diff --git a/.gitattributes b/.gitattributes index ee2aa99597a22854eae01da9abbfdf2b09839604..8a37a903fc0178a24da8db2de0c3d75195c2cbe3 100644 --- a/.gitattributes +++ b/.gitattributes @@ -59,3 +59,8 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text *.mp4 filter=lfs diff=lfs merge=lfs -text *.webm filter=lfs diff=lfs merge=lfs -text plots/all-task-progression.pdf filter=lfs diff=lfs merge=lfs -text +shared/package-files/00/0023a9045c7afbcf2ba8cc23f8b4b492ac32204bf9c367d18d9a3b5b6d802e28/blob filter=lfs diff=lfs merge=lfs -text +shared/package-files/00/007c7273f4f4d627c319bd19a7be1e7c291bf3de21e62e9ea14cb159d8dda003/blob filter=lfs diff=lfs merge=lfs -text +shared/package-files/00/00a16df76cb2ba5d643c2536ffa3a63735da528cc101cbfd3f87ec553ae37efe/blob filter=lfs diff=lfs merge=lfs -text +shared/package-files/01/01b20c23e9ca7c868b86b6bd109e153f4e21bd6aeec88522ef93976c6f4c2e7d/blob filter=lfs diff=lfs merge=lfs -text +shared/package-files/01/01e0d376352c8f8de9e5e13cf97756480f3a3a3244ea4d681b96c966af352e17/blob filter=lfs diff=lfs merge=lfs -text diff --git a/shared/package-files/00/001cf5f5504a7c67b0758dfd4089c6f5071c827d4c4d85776d3e4f87b4c2cb66/blob b/shared/package-files/00/001cf5f5504a7c67b0758dfd4089c6f5071c827d4c4d85776d3e4f87b4c2cb66/blob new file mode 100644 index 0000000000000000000000000000000000000000..75a534951d60ef83ede2da26aec25747fbfb95b3 --- /dev/null +++ b/shared/package-files/00/001cf5f5504a7c67b0758dfd4089c6f5071c827d4c4d85776d3e4f87b4c2cb66/blob @@ -0,0 +1,2 @@ +This is the sample data needed for some of matplotlib's examples and +docs. See matplotlib.cbook.get_sample_data for more info. diff --git a/shared/package-files/00/001df83b40d5ec09447fd6786eb9c269d790539fae030856470e4565ab3ae430/blob b/shared/package-files/00/001df83b40d5ec09447fd6786eb9c269d790539fae030856470e4565ab3ae430/blob new file mode 100644 index 0000000000000000000000000000000000000000..6a18a7964d746561dfd5f81177cd78ccc46d2a5d --- /dev/null +++ b/shared/package-files/00/001df83b40d5ec09447fd6786eb9c269d790539fae030856470e4565ab3ae430/blob @@ -0,0 +1,698 @@ +from mpmath import * +from mpmath.libmp import round_up, from_float, mpf_zeta_int + +def test_zeta_int_bug(): + assert mpf_zeta_int(0, 10) == from_float(-0.5) + +def test_bernoulli(): + assert bernfrac(0) == (1,1) + assert bernfrac(1) == (-1,2) + assert bernfrac(2) == (1,6) + assert bernfrac(3) == (0,1) + assert bernfrac(4) == (-1,30) + assert bernfrac(5) == (0,1) + assert bernfrac(6) == (1,42) + assert bernfrac(8) == (-1,30) + assert bernfrac(10) == (5,66) + assert bernfrac(12) == (-691,2730) + assert bernfrac(18) == (43867,798) + p, q = bernfrac(228) + assert p % 10**10 == 164918161 + assert q == 625170 + p, q = bernfrac(1000) + assert p % 10**10 == 7950421099 + assert q == 342999030 + mp.dps = 15 + assert bernoulli(0) == 1 + assert bernoulli(1) == -0.5 + assert bernoulli(2).ae(1./6) + assert bernoulli(3) == 0 + assert bernoulli(4).ae(-1./30) + assert bernoulli(5) == 0 + assert bernoulli(6).ae(1./42) + assert str(bernoulli(10)) == '0.0757575757575758' + assert str(bernoulli(234)) == '7.62772793964344e+267' + assert str(bernoulli(10**5)) == '-5.82229431461335e+376755' + assert str(bernoulli(10**8+2)) == '1.19570355039953e+676752584' + + mp.dps = 50 + assert str(bernoulli(10)) == '0.075757575757575757575757575757575757575757575757576' + assert str(bernoulli(234)) == '7.6277279396434392486994969020496121553385863373331e+267' + assert str(bernoulli(10**5)) == '-5.8222943146133508236497045360612887555320691004308e+376755' + assert str(bernoulli(10**8+2)) == '1.1957035503995297272263047884604346914602088317782e+676752584' + + mp.dps = 1000 + assert bernoulli(10).ae(mpf(5)/66) + + mp.dps = 50000 + assert bernoulli(10).ae(mpf(5)/66) + + mp.dps = 15 + +def test_bernpoly_eulerpoly(): + mp.dps = 15 + assert bernpoly(0,-1).ae(1) + assert bernpoly(0,0).ae(1) + assert bernpoly(0,'1/2').ae(1) + assert bernpoly(0,'3/4').ae(1) + assert bernpoly(0,1).ae(1) + assert bernpoly(0,2).ae(1) + assert bernpoly(1,-1).ae('-3/2') + assert bernpoly(1,0).ae('-1/2') + assert bernpoly(1,'1/2').ae(0) + assert bernpoly(1,'3/4').ae('1/4') + assert bernpoly(1,1).ae('1/2') + assert bernpoly(1,2).ae('3/2') + assert bernpoly(2,-1).ae('13/6') + assert bernpoly(2,0).ae('1/6') + assert bernpoly(2,'1/2').ae('-1/12') + assert bernpoly(2,'3/4').ae('-1/48') + assert bernpoly(2,1).ae('1/6') + assert bernpoly(2,2).ae('13/6') + assert bernpoly(3,-1).ae(-3) + assert bernpoly(3,0).ae(0) + assert bernpoly(3,'1/2').ae(0) + assert bernpoly(3,'3/4').ae('-3/64') + assert bernpoly(3,1).ae(0) + assert bernpoly(3,2).ae(3) + assert bernpoly(4,-1).ae('119/30') + assert bernpoly(4,0).ae('-1/30') + assert bernpoly(4,'1/2').ae('7/240') + assert bernpoly(4,'3/4').ae('7/3840') + assert bernpoly(4,1).ae('-1/30') + assert bernpoly(4,2).ae('119/30') + assert bernpoly(5,-1).ae(-5) + assert bernpoly(5,0).ae(0) + assert bernpoly(5,'1/2').ae(0) + assert bernpoly(5,'3/4').ae('25/1024') + assert bernpoly(5,1).ae(0) + assert bernpoly(5,2).ae(5) + assert bernpoly(10,-1).ae('665/66') + assert bernpoly(10,0).ae('5/66') + assert bernpoly(10,'1/2').ae('-2555/33792') + assert bernpoly(10,'3/4').ae('-2555/34603008') + assert bernpoly(10,1).ae('5/66') + assert bernpoly(10,2).ae('665/66') + assert bernpoly(11,-1).ae(-11) + assert bernpoly(11,0).ae(0) + assert bernpoly(11,'1/2').ae(0) + assert bernpoly(11,'3/4').ae('-555731/4194304') + assert bernpoly(11,1).ae(0) + assert bernpoly(11,2).ae(11) + assert eulerpoly(0,-1).ae(1) + assert eulerpoly(0,0).ae(1) + assert eulerpoly(0,'1/2').ae(1) + assert eulerpoly(0,'3/4').ae(1) + assert eulerpoly(0,1).ae(1) + assert eulerpoly(0,2).ae(1) + assert eulerpoly(1,-1).ae('-3/2') + assert eulerpoly(1,0).ae('-1/2') + assert eulerpoly(1,'1/2').ae(0) + assert eulerpoly(1,'3/4').ae('1/4') + assert eulerpoly(1,1).ae('1/2') + assert eulerpoly(1,2).ae('3/2') + assert eulerpoly(2,-1).ae(2) + assert eulerpoly(2,0).ae(0) + assert eulerpoly(2,'1/2').ae('-1/4') + assert eulerpoly(2,'3/4').ae('-3/16') + assert eulerpoly(2,1).ae(0) + assert eulerpoly(2,2).ae(2) + assert eulerpoly(3,-1).ae('-9/4') + assert eulerpoly(3,0).ae('1/4') + assert eulerpoly(3,'1/2').ae(0) + assert eulerpoly(3,'3/4').ae('-11/64') + assert eulerpoly(3,1).ae('-1/4') + assert eulerpoly(3,2).ae('9/4') + assert eulerpoly(4,-1).ae(2) + assert eulerpoly(4,0).ae(0) + assert eulerpoly(4,'1/2').ae('5/16') + assert eulerpoly(4,'3/4').ae('57/256') + assert eulerpoly(4,1).ae(0) + assert eulerpoly(4,2).ae(2) + assert eulerpoly(5,-1).ae('-3/2') + assert eulerpoly(5,0).ae('-1/2') + assert eulerpoly(5,'1/2').ae(0) + assert eulerpoly(5,'3/4').ae('361/1024') + assert eulerpoly(5,1).ae('1/2') + assert eulerpoly(5,2).ae('3/2') + assert eulerpoly(10,-1).ae(2) + assert eulerpoly(10,0).ae(0) + assert eulerpoly(10,'1/2').ae('-50521/1024') + assert eulerpoly(10,'3/4').ae('-36581523/1048576') + assert eulerpoly(10,1).ae(0) + assert eulerpoly(10,2).ae(2) + assert eulerpoly(11,-1).ae('-699/4') + assert eulerpoly(11,0).ae('691/4') + assert eulerpoly(11,'1/2').ae(0) + assert eulerpoly(11,'3/4').ae('-512343611/4194304') + assert eulerpoly(11,1).ae('-691/4') + assert eulerpoly(11,2).ae('699/4') + # Potential accuracy issues + assert bernpoly(10000,10000).ae('5.8196915936323387117e+39999') + assert bernpoly(200,17.5).ae(3.8048418524583064909e244) + assert eulerpoly(200,17.5).ae(-3.7309911582655785929e275) + +def test_gamma(): + mp.dps = 15 + assert gamma(0.25).ae(3.6256099082219083119) + assert gamma(0.0001).ae(9999.4228832316241908) + assert gamma(300).ae('1.0201917073881354535e612') + assert gamma(-0.5).ae(-3.5449077018110320546) + assert gamma(-7.43).ae(0.00026524416464197007186) + #assert gamma(Rational(1,2)) == gamma(0.5) + #assert gamma(Rational(-7,3)).ae(gamma(mpf(-7)/3)) + assert gamma(1+1j).ae(0.49801566811835604271 - 0.15494982830181068512j) + assert gamma(-1+0.01j).ae(-0.422733904013474115 + 99.985883082635367436j) + assert gamma(20+30j).ae(-1453876687.5534810 + 1163777777.8031573j) + # Should always give exact factorials when they can + # be represented as mpfs under the current working precision + fact = 1 + for i in range(1, 18): + assert gamma(i) == fact + fact *= i + for dps in [170, 600]: + fact = 1 + mp.dps = dps + for i in range(1, 105): + assert gamma(i) == fact + fact *= i + mp.dps = 100 + assert gamma(0.5).ae(sqrt(pi)) + mp.dps = 15 + assert factorial(0) == fac(0) == 1 + assert factorial(3) == 6 + assert isnan(gamma(nan)) + assert gamma(1100).ae('4.8579168073569433667e2866') + assert rgamma(0) == 0 + assert rgamma(-1) == 0 + assert rgamma(2) == 1.0 + assert rgamma(3) == 0.5 + assert loggamma(2+8j).ae(-8.5205176753667636926 + 10.8569497125597429366j) + assert loggamma('1e10000').ae('2.302485092994045684017991e10004') + assert loggamma('1e10000j').ae(mpc('-1.570796326794896619231322e10000','2.302485092994045684017991e10004')) + +def test_fac2(): + mp.dps = 15 + assert [fac2(n) for n in range(10)] == [1,1,2,3,8,15,48,105,384,945] + assert fac2(-5).ae(1./3) + assert fac2(-11).ae(-1./945) + assert fac2(50).ae(5.20469842636666623e32) + assert fac2(0.5+0.75j).ae(0.81546769394688069176-0.34901016085573266889j) + assert fac2(inf) == inf + assert isnan(fac2(-inf)) + +def test_gamma_quotients(): + mp.dps = 15 + h = 1e-8 + ep = 1e-4 + G = gamma + assert gammaprod([-1],[-3,-4]) == 0 + assert gammaprod([-1,0],[-5]) == inf + assert abs(gammaprod([-1],[-2]) - G(-1+h)/G(-2+h)) < 1e-4 + assert abs(gammaprod([-4,-3],[-2,0]) - G(-4+h)*G(-3+h)/G(-2+h)/G(0+h)) < 1e-4 + assert rf(3,0) == 1 + assert rf(2.5,1) == 2.5 + assert rf(-5,2) == 20 + assert rf(j,j).ae(gamma(2*j)/gamma(j)) + assert rf('-255.5815971722918','-0.5119253100282322').ae('-0.1952720278805729485') # issue 421 + assert ff(-2,0) == 1 + assert ff(-2,1) == -2 + assert ff(4,3) == 24 + assert ff(3,4) == 0 + assert binomial(0,0) == 1 + assert binomial(1,0) == 1 + assert binomial(0,-1) == 0 + assert binomial(3,2) == 3 + assert binomial(5,2) == 10 + assert binomial(5,3) == 10 + assert binomial(5,5) == 1 + assert binomial(-1,0) == 1 + assert binomial(-2,-4) == 3 + assert binomial(4.5, 1.5) == 6.5625 + assert binomial(1100,1) == 1100 + assert binomial(1100,2) == 604450 + assert beta(1,1) == 1 + assert beta(0,0) == inf + assert beta(3,0) == inf + assert beta(-1,-1) == inf + assert beta(1.5,1).ae(2/3.) + assert beta(1.5,2.5).ae(pi/16) + assert (10**15*beta(10,100)).ae(2.3455339739604649879) + assert beta(inf,inf) == 0 + assert isnan(beta(-inf,inf)) + assert isnan(beta(-3,inf)) + assert isnan(beta(0,inf)) + assert beta(inf,0.5) == beta(0.5,inf) == 0 + assert beta(inf,-1.5) == inf + assert beta(inf,-0.5) == -inf + assert beta(1+2j,-1-j/2).ae(1.16396542451069943086+0.08511695947832914640j) + assert beta(-0.5,0.5) == 0 + assert beta(-3,3).ae(-1/3.) + assert beta('-255.5815971722918','-0.5119253100282322').ae('18.157330562703710339') # issue 421 + +def test_zeta(): + mp.dps = 15 + assert zeta(2).ae(pi**2 / 6) + assert zeta(2.0).ae(pi**2 / 6) + assert zeta(mpc(2)).ae(pi**2 / 6) + assert zeta(100).ae(1) + assert zeta(0).ae(-0.5) + assert zeta(0.5).ae(-1.46035450880958681) + assert zeta(-1).ae(-mpf(1)/12) + assert zeta(-2) == 0 + assert zeta(-3).ae(mpf(1)/120) + assert zeta(-4) == 0 + assert zeta(-100) == 0 + assert isnan(zeta(nan)) + assert zeta(1e-30).ae(-0.5) + assert zeta(-1e-30).ae(-0.5) + # Zeros in the critical strip + assert zeta(mpc(0.5, 14.1347251417346937904)).ae(0) + assert zeta(mpc(0.5, 21.0220396387715549926)).ae(0) + assert zeta(mpc(0.5, 25.0108575801456887632)).ae(0) + assert zeta(mpc(1e-30,1e-40)).ae(-0.5) + assert zeta(mpc(-1e-30,1e-40)).ae(-0.5) + mp.dps = 50 + im = '236.5242296658162058024755079556629786895294952121891237' + assert zeta(mpc(0.5, im)).ae(0, 1e-46) + mp.dps = 15 + # Complex reflection formula + assert (zeta(-60+3j) / 10**34).ae(8.6270183987866146+15.337398548226238j) + # issue #358 + assert zeta(0,0.5) == 0 + assert zeta(0,0) == 0.5 + assert zeta(0,0.5,1).ae(-0.34657359027997265) + # see issue #390 + assert zeta(-1.5,0.5j).ae(-0.13671400162512768475 + 0.11411333638426559139j) + +def test_altzeta(): + mp.dps = 15 + assert altzeta(-2) == 0 + assert altzeta(-4) == 0 + assert altzeta(-100) == 0 + assert altzeta(0) == 0.5 + assert altzeta(-1) == 0.25 + assert altzeta(-3) == -0.125 + assert altzeta(-5) == 0.25 + assert altzeta(-21) == 1180529130.25 + assert altzeta(1).ae(log(2)) + assert altzeta(2).ae(pi**2/12) + assert altzeta(10).ae(73*pi**10/6842880) + assert altzeta(50) < 1 + assert altzeta(60, rounding='d') < 1 + assert altzeta(60, rounding='u') == 1 + assert altzeta(10000, rounding='d') < 1 + assert altzeta(10000, rounding='u') == 1 + assert altzeta(3+0j) == altzeta(3) + s = 3+4j + assert altzeta(s).ae((1-2**(1-s))*zeta(s)) + s = -3+4j + assert altzeta(s).ae((1-2**(1-s))*zeta(s)) + assert altzeta(-100.5).ae(4.58595480083585913e+108) + assert altzeta(1.3).ae(0.73821404216623045) + assert altzeta(1e-30).ae(0.5) + assert altzeta(-1e-30).ae(0.5) + assert altzeta(mpc(1e-30,1e-40)).ae(0.5) + assert altzeta(mpc(-1e-30,1e-40)).ae(0.5) + +def test_zeta_huge(): + mp.dps = 15 + assert zeta(inf) == 1 + mp.dps = 50 + assert zeta(100).ae('1.0000000000000000000000000000007888609052210118073522') + assert zeta(40*pi).ae('1.0000000000000000000000000000000000000148407238666182') + mp.dps = 10000 + v = zeta(33000) + mp.dps = 15 + assert str(v-1) == '1.02363019598118e-9934' + assert zeta(pi*1000, rounding=round_up) > 1 + assert zeta(3000, rounding=round_up) > 1 + assert zeta(pi*1000) == 1 + assert zeta(3000) == 1 + +def test_zeta_negative(): + mp.dps = 150 + a = -pi*10**40 + mp.dps = 15 + assert str(zeta(a)) == '2.55880492708712e+1233536161668617575553892558646631323374078' + mp.dps = 50 + assert str(zeta(a)) == '2.5588049270871154960875033337384432038436330847333e+1233536161668617575553892558646631323374078' + mp.dps = 15 + +def test_polygamma(): + mp.dps = 15 + psi0 = lambda z: psi(0,z) + psi1 = lambda z: psi(1,z) + assert psi0(3) == psi(0,3) == digamma(3) + #assert psi2(3) == psi(2,3) == tetragamma(3) + #assert psi3(3) == psi(3,3) == pentagamma(3) + assert psi0(pi).ae(0.97721330794200673) + assert psi0(-pi).ae(7.8859523853854902) + assert psi0(-pi+1).ae(7.5676424992016996) + assert psi0(pi+j).ae(1.04224048313859376 + 0.35853686544063749j) + assert psi0(-pi-j).ae(1.3404026194821986 - 2.8824392476809402j) + assert findroot(psi0, 1).ae(1.4616321449683622) + assert psi0(1e-10).ae(-10000000000.57722) + assert psi0(1e-40).ae(-1.000000000000000e+40) + assert psi0(1e-10+1e-10j).ae(-5000000000.577215 + 5000000000.000000j) + assert psi0(1e-40+1e-40j).ae(-5.000000000000000e+39 + 5.000000000000000e+39j) + assert psi0(inf) == inf + assert psi1(inf) == 0 + assert psi(2,inf) == 0 + assert psi1(pi).ae(0.37424376965420049) + assert psi1(-pi).ae(53.030438740085385) + assert psi1(pi+j).ae(0.32935710377142464 - 0.12222163911221135j) + assert psi1(-pi-j).ae(-0.30065008356019703 + 0.01149892486928227j) + assert (10**6*psi(4,1+10*pi*j)).ae(-6.1491803479004446 - 0.3921316371664063j) + assert psi0(1+10*pi*j).ae(3.4473994217222650 + 1.5548808324857071j) + assert isnan(psi0(nan)) + assert isnan(psi0(-inf)) + assert psi0(-100.5).ae(4.615124601338064) + assert psi0(3+0j).ae(psi0(3)) + assert psi0(-100+3j).ae(4.6106071768714086321+3.1117510556817394626j) + assert isnan(psi(2,mpc(0,inf))) + assert isnan(psi(2,mpc(0,nan))) + assert isnan(psi(2,mpc(0,-inf))) + assert isnan(psi(2,mpc(1,inf))) + assert isnan(psi(2,mpc(1,nan))) + assert isnan(psi(2,mpc(1,-inf))) + assert isnan(psi(2,mpc(inf,inf))) + assert isnan(psi(2,mpc(nan,nan))) + assert isnan(psi(2,mpc(-inf,-inf))) + mp.dps = 30 + # issue #534 + assert digamma(-0.75+1j).ae(mpc('0.46317279488182026118963809283042317', '2.4821070143037957102007677817351115')) + mp.dps = 15 + +def test_polygamma_high_prec(): + mp.dps = 100 + assert str(psi(0,pi)) == "0.9772133079420067332920694864061823436408346099943256380095232865318105924777141317302075654362928734" + assert str(psi(10,pi)) == "-12.98876181434889529310283769414222588307175962213707170773803550518307617769657562747174101900659238" + +def test_polygamma_identities(): + mp.dps = 15 + psi0 = lambda z: psi(0,z) + psi1 = lambda z: psi(1,z) + psi2 = lambda z: psi(2,z) + assert psi0(0.5).ae(-euler-2*log(2)) + assert psi0(1).ae(-euler) + assert psi1(0.5).ae(0.5*pi**2) + assert psi1(1).ae(pi**2/6) + assert psi1(0.25).ae(pi**2 + 8*catalan) + assert psi2(1).ae(-2*apery) + mp.dps = 20 + u = -182*apery+4*sqrt(3)*pi**3 + mp.dps = 15 + assert psi(2,5/6.).ae(u) + assert psi(3,0.5).ae(pi**4) + +def test_foxtrot_identity(): + # A test of the complex digamma function. + # See http://mathworld.wolfram.com/FoxTrotSeries.html and + # http://mathworld.wolfram.com/DigammaFunction.html + psi0 = lambda z: psi(0,z) + mp.dps = 50 + a = (-1)**fraction(1,3) + b = (-1)**fraction(2,3) + x = -psi0(0.5*a) - psi0(-0.5*b) + psi0(0.5*(1+a)) + psi0(0.5*(1-b)) + y = 2*pi*sech(0.5*sqrt(3)*pi) + assert x.ae(y) + mp.dps = 15 + +def test_polygamma_high_order(): + mp.dps = 100 + assert str(psi(50, pi)) == "-1344100348958402765749252447726432491812.641985273160531055707095989227897753035823152397679626136483" + assert str(psi(50, pi + 14*e)) == "-0.00000000000000000189793739550804321623512073101895801993019919886375952881053090844591920308111549337295143780341396" + assert str(psi(50, pi + 14*e*j)) == ("(-0.0000000000000000522516941152169248975225472155683565752375889510631513244785" + "9377385233700094871256507814151956624433 - 0.00000000000000001813157041407010184" + "702414110218205348527862196327980417757665282244728963891298080199341480881811613j)") + mp.dps = 15 + assert str(psi(50, pi)) == "-1.34410034895841e+39" + assert str(psi(50, pi + 14*e)) == "-1.89793739550804e-18" + assert str(psi(50, pi + 14*e*j)) == "(-5.2251694115217e-17 - 1.81315704140701e-17j)" + +def test_harmonic(): + mp.dps = 15 + assert harmonic(0) == 0 + assert harmonic(1) == 1 + assert harmonic(2) == 1.5 + assert harmonic(3).ae(1. + 1./2 + 1./3) + assert harmonic(10**10).ae(23.603066594891989701) + assert harmonic(10**1000).ae(2303.162308658947) + assert harmonic(0.5).ae(2-2*log(2)) + assert harmonic(inf) == inf + assert harmonic(2+0j) == 1.5+0j + assert harmonic(1+2j).ae(1.4918071802755104+0.92080728264223022j) + +def test_gamma_huge_1(): + mp.dps = 500 + x = mpf(10**10) / 7 + mp.dps = 15 + assert str(gamma(x)) == "6.26075321389519e+12458010678" + mp.dps = 50 + assert str(gamma(x)) == "6.2607532138951929201303779291707455874010420783933e+12458010678" + mp.dps = 15 + +def test_gamma_huge_2(): + mp.dps = 500 + x = mpf(10**100) / 19 + mp.dps = 15 + assert str(gamma(x)) == (\ + "1.82341134776679e+5172997469323364168990133558175077136829182824042201886051511" + "9656908623426021308685461258226190190661") + mp.dps = 50 + assert str(gamma(x)) == (\ + "1.82341134776678875374414910350027596939980412984e+5172997469323364168990133558" + "1750771368291828240422018860515119656908623426021308685461258226190190661") + +def test_gamma_huge_3(): + mp.dps = 500 + x = 10**80 // 3 + 10**70*j / 7 + mp.dps = 15 + y = gamma(x) + assert str(y.real) == (\ + "-6.82925203918106e+2636286142112569524501781477865238132302397236429627932441916" + "056964386399485392600") + assert str(y.imag) == (\ + "8.54647143678418e+26362861421125695245017814778652381323023972364296279324419160" + "56964386399485392600") + mp.dps = 50 + y = gamma(x) + assert str(y.real) == (\ + "-6.8292520391810548460682736226799637356016538421817e+26362861421125695245017814" + "77865238132302397236429627932441916056964386399485392600") + assert str(y.imag) == (\ + "8.5464714367841748507479306948130687511711420234015e+263628614211256952450178147" + "7865238132302397236429627932441916056964386399485392600") + +def test_gamma_huge_4(): + x = 3200+11500j + mp.dps = 15 + assert str(gamma(x)) == \ + "(8.95783268539713e+5164 - 1.94678798329735e+5164j)" + mp.dps = 50 + assert str(gamma(x)) == (\ + "(8.9578326853971339570292952697675570822206567327092e+5164" + " - 1.9467879832973509568895402139429643650329524144794e+51" + "64j)") + mp.dps = 15 + +def test_gamma_huge_5(): + mp.dps = 500 + x = 10**60 * j / 3 + mp.dps = 15 + y = gamma(x) + assert str(y.real) == "-3.27753899634941e-227396058973640224580963937571892628368354580620654233316839" + assert str(y.imag) == "-7.1519888950416e-227396058973640224580963937571892628368354580620654233316841" + mp.dps = 50 + y = gamma(x) + assert str(y.real) == (\ + "-3.2775389963494132168950056995974690946983219123935e-22739605897364022458096393" + "7571892628368354580620654233316839") + assert str(y.imag) == (\ + "-7.1519888950415979749736749222530209713136588885897e-22739605897364022458096393" + "7571892628368354580620654233316841") + mp.dps = 15 + +def test_gamma_huge_7(): + mp.dps = 100 + a = 3 + j/mpf(10)**1000 + mp.dps = 15 + y = gamma(a) + assert str(y.real) == "2.0" + # wrong + #assert str(y.imag) == "2.16735365342606e-1000" + assert str(y.imag) == "1.84556867019693e-1000" + mp.dps = 50 + y = gamma(a) + assert str(y.real) == "2.0" + #assert str(y.imag) == "2.1673536534260596065418805612488708028522563689298e-1000" + assert str(y.imag) == "1.8455686701969342787869758198351951379156813281202e-1000" + +def test_stieltjes(): + mp.dps = 15 + assert stieltjes(0).ae(+euler) + mp.dps = 25 + assert stieltjes(1).ae('-0.07281584548367672486058637587') + assert stieltjes(2).ae('-0.009690363192872318484530386035') + assert stieltjes(3).ae('0.002053834420303345866160046543') + assert stieltjes(4).ae('0.002325370065467300057468170178') + mp.dps = 15 + assert stieltjes(1).ae(-0.07281584548367672486058637587) + assert stieltjes(2).ae(-0.009690363192872318484530386035) + assert stieltjes(3).ae(0.002053834420303345866160046543) + assert stieltjes(4).ae(0.0023253700654673000574681701775) + +def test_barnesg(): + mp.dps = 15 + assert barnesg(0) == barnesg(-1) == 0 + assert [superfac(i) for i in range(8)] == [1, 1, 2, 12, 288, 34560, 24883200, 125411328000] + assert str(superfac(1000)) == '3.24570818422368e+1177245' + assert isnan(barnesg(nan)) + assert isnan(superfac(nan)) + assert isnan(hyperfac(nan)) + assert barnesg(inf) == inf + assert superfac(inf) == inf + assert hyperfac(inf) == inf + assert isnan(superfac(-inf)) + assert barnesg(0.7).ae(0.8068722730141471) + assert barnesg(2+3j).ae(-0.17810213864082169+0.04504542715447838j) + assert [hyperfac(n) for n in range(7)] == [1, 1, 4, 108, 27648, 86400000, 4031078400000] + assert [hyperfac(n) for n in range(0,-7,-1)] == [1,1,-1,-4,108,27648,-86400000] + a = barnesg(-3+0j) + assert a == 0 and isinstance(a, mpc) + a = hyperfac(-3+0j) + assert a == -4 and isinstance(a, mpc) + +def test_polylog(): + mp.dps = 15 + zs = [mpmathify(z) for z in [0, 0.5, 0.99, 4, -0.5, -4, 1j, 3+4j]] + for z in zs: assert polylog(1, z).ae(-log(1-z)) + for z in zs: assert polylog(0, z).ae(z/(1-z)) + for z in zs: assert polylog(-1, z).ae(z/(1-z)**2) + for z in zs: assert polylog(-2, z).ae(z*(1+z)/(1-z)**3) + for z in zs: assert polylog(-3, z).ae(z*(1+4*z+z**2)/(1-z)**4) + assert polylog(3, 7).ae(5.3192579921456754382-5.9479244480803301023j) + assert polylog(3, -7).ae(-4.5693548977219423182) + assert polylog(2, 0.9).ae(1.2997147230049587252) + assert polylog(2, -0.9).ae(-0.75216317921726162037) + assert polylog(2, 0.9j).ae(-0.17177943786580149299+0.83598828572550503226j) + assert polylog(2, 1.1).ae(1.9619991013055685931-0.2994257606855892575j) + assert polylog(2, -1.1).ae(-0.89083809026228260587) + assert polylog(2, 1.1*sqrt(j)).ae(0.58841571107611387722+1.09962542118827026011j) + assert polylog(-2, 0.9).ae(1710) + assert polylog(-2, -0.9).ae(-90/6859.) + assert polylog(3, 0.9).ae(1.0496589501864398696) + assert polylog(-3, 0.9).ae(48690) + assert polylog(-3, -4).ae(-0.0064) + assert polylog(0.5+j/3, 0.5+j/2).ae(0.31739144796565650535 + 0.99255390416556261437j) + assert polylog(3+4j,1).ae(zeta(3+4j)) + assert polylog(3+4j,-1).ae(-altzeta(3+4j)) + # issue 390 + assert polylog(1.5, -48.910886523731889).ae(-6.272992229311817) + assert polylog(1.5, 200).ae(-8.349608319033686529 - 8.159694826434266042j) + assert polylog(-2+0j, -2).ae(mpf(1)/13.5) + assert polylog(-2+0j, 1.25).ae(-180) + +def test_bell_polyexp(): + mp.dps = 15 + # TODO: more tests for polyexp + assert (polyexp(0,1e-10)*10**10).ae(1.00000000005) + assert (polyexp(1,1e-10)*10**10).ae(1.0000000001) + assert polyexp(5,3j).ae(-607.7044517476176454+519.962786482001476087j) + assert polyexp(-1,3.5).ae(12.09537536175543444) + # bell(0,x) = 1 + assert bell(0,0) == 1 + assert bell(0,1) == 1 + assert bell(0,2) == 1 + assert bell(0,inf) == 1 + assert bell(0,-inf) == 1 + assert isnan(bell(0,nan)) + # bell(1,x) = x + assert bell(1,4) == 4 + assert bell(1,0) == 0 + assert bell(1,inf) == inf + assert bell(1,-inf) == -inf + assert isnan(bell(1,nan)) + # bell(2,x) = x*(1+x) + assert bell(2,-1) == 0 + assert bell(2,0) == 0 + # large orders / arguments + assert bell(10) == 115975 + assert bell(10,1) == 115975 + assert bell(10, -8) == 11054008 + assert bell(5,-50) == -253087550 + assert bell(50,-50).ae('3.4746902914629720259e74') + mp.dps = 80 + assert bell(50,-50) == 347469029146297202586097646631767227177164818163463279814268368579055777450 + assert bell(40,50) == 5575520134721105844739265207408344706846955281965031698187656176321717550 + assert bell(74) == 5006908024247925379707076470957722220463116781409659160159536981161298714301202 + mp.dps = 15 + assert bell(10,20j) == 7504528595600+15649605360020j + # continuity of the generalization + assert bell(0.5,0).ae(sinc(pi*0.5)) + +def test_primezeta(): + mp.dps = 15 + assert primezeta(0.9).ae(1.8388316154446882243 + 3.1415926535897932385j) + assert primezeta(4).ae(0.076993139764246844943) + assert primezeta(1) == inf + assert primezeta(inf) == 0 + assert isnan(primezeta(nan)) + +def test_rs_zeta(): + mp.dps = 15 + assert zeta(0.5+100000j).ae(1.0730320148577531321 + 5.7808485443635039843j) + assert zeta(0.75+100000j).ae(1.837852337251873704 + 1.9988492668661145358j) + assert zeta(0.5+1000000j, derivative=3).ae(1647.7744105852674733 - 1423.1270943036622097j) + assert zeta(1+1000000j, derivative=3).ae(3.4085866124523582894 - 18.179184721525947301j) + assert zeta(1+1000000j, derivative=1).ae(-0.10423479366985452134 - 0.74728992803359056244j) + assert zeta(0.5-1000000j, derivative=1).ae(11.636804066002521459 + 17.127254072212996004j) + # Additional sanity tests using fp arithmetic. + # Some more high-precision tests are found in the docstrings + def ae(x, y, tol=1e-6): + return abs(x-y) < tol*abs(y) + assert ae(fp.zeta(0.5-100000j), 1.0730320148577531321 - 5.7808485443635039843j) + assert ae(fp.zeta(0.75-100000j), 1.837852337251873704 - 1.9988492668661145358j) + assert ae(fp.zeta(0.5+1e6j), 0.076089069738227100006 + 2.8051021010192989554j) + assert ae(fp.zeta(0.5+1e6j, derivative=1), 11.636804066002521459 - 17.127254072212996004j) + assert ae(fp.zeta(1+1e6j), 0.94738726251047891048 + 0.59421999312091832833j) + assert ae(fp.zeta(1+1e6j, derivative=1), -0.10423479366985452134 - 0.74728992803359056244j) + assert ae(fp.zeta(0.5+100000j, derivative=1), 10.766962036817482375 - 30.92705282105996714j) + assert ae(fp.zeta(0.5+100000j, derivative=2), -119.40515625740538429 + 217.14780631141830251j) + assert ae(fp.zeta(0.5+100000j, derivative=3), 1129.7550282628460881 - 1685.4736895169690346j) + assert ae(fp.zeta(0.5+100000j, derivative=4), -10407.160819314958615 + 13777.786698628045085j) + assert ae(fp.zeta(0.75+100000j, derivative=1), -0.41742276699594321475 - 6.4453816275049955949j) + assert ae(fp.zeta(0.75+100000j, derivative=2), -9.214314279161977266 + 35.07290795337967899j) + assert ae(fp.zeta(0.75+100000j, derivative=3), 110.61331857820103469 - 236.87847130518129926j) + assert ae(fp.zeta(0.75+100000j, derivative=4), -1054.334275898559401 + 1769.9177890161596383j) + +def test_siegelz(): + mp.dps = 15 + assert siegelz(100000).ae(5.87959246868176504171) + assert siegelz(100000, derivative=2).ae(-54.1172711010126452832) + assert siegelz(100000, derivative=3).ae(-278.930831343966552538) + assert siegelz(100000+j,derivative=1).ae(678.214511857070283307-379.742160779916375413j) + + + +def test_zeta_near_1(): + # Test for a former bug in mpf_zeta and mpc_zeta + mp.dps = 15 + s1 = fadd(1, '1e-10', exact=True) + s2 = fadd(1, '-1e-10', exact=True) + s3 = fadd(1, '1e-10j', exact=True) + assert zeta(s1).ae(1.000000000057721566490881444e10) + assert zeta(s2).ae(-9.99999999942278433510574872e9) + z = zeta(s3) + assert z.real.ae(0.57721566490153286060) + assert z.imag.ae(-9.9999999999999999999927184e9) + mp.dps = 30 + s1 = fadd(1, '1e-50', exact=True) + s2 = fadd(1, '-1e-50', exact=True) + s3 = fadd(1, '1e-50j', exact=True) + assert zeta(s1).ae('1e50') + assert zeta(s2).ae('-1e50') + z = zeta(s3) + assert z.real.ae('0.57721566490153286060651209008240243104215933593992') + assert z.imag.ae('-1e50') diff --git a/shared/package-files/00/0023a9045c7afbcf2ba8cc23f8b4b492ac32204bf9c367d18d9a3b5b6d802e28/blob b/shared/package-files/00/0023a9045c7afbcf2ba8cc23f8b4b492ac32204bf9c367d18d9a3b5b6d802e28/blob new file mode 100644 index 0000000000000000000000000000000000000000..a1a870c83f0bdf75cfeb29b1cbf0b8902e4aade6 --- /dev/null +++ b/shared/package-files/00/0023a9045c7afbcf2ba8cc23f8b4b492ac32204bf9c367d18d9a3b5b6d802e28/blob @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:0023a9045c7afbcf2ba8cc23f8b4b492ac32204bf9c367d18d9a3b5b6d802e28 +size 354880 diff --git a/shared/package-files/00/0024252ffc037f100c09dddc0581ca67e8dbc7f57d367bf0c44fee2990462cc6/blob b/shared/package-files/00/0024252ffc037f100c09dddc0581ca67e8dbc7f57d367bf0c44fee2990462cc6/blob new file mode 100644 index 0000000000000000000000000000000000000000..8a676c7e16c780b52f156cece3a7b7347c6f465b --- /dev/null +++ b/shared/package-files/00/0024252ffc037f100c09dddc0581ca67e8dbc7f57d367bf0c44fee2990462cc6/blob @@ -0,0 +1,323 @@ +# mypy: ignore-errors + +# Torch +import torch +import torch.cuda +import torch.jit +import torch.jit._logging +import torch.jit.frontend +import torch.jit.quantized + +# Testing utils +from torch.testing._internal.common_dtype import floating_and_complex_types_and +from torch.testing._internal.common_utils import TestCase, \ + freeze_rng_state, TemporaryFileName, enable_profiling_mode_for_profiling_tests, is_iterable_of_tensors +from torch.testing._internal.common_utils import enable_profiling_mode # noqa: F401 + +# Standard library +from itertools import chain +from typing import List, Union +from torch._C import TensorType + +import io + +def check_output_types(self, func, ref_outputs, args, kwargs): + graph = getattr(func, 'last_graph', None) + types = [o.type() for o in graph.outputs()] + self.assertTrue(len(types) == 1) + t = types[0] + torch._C._jit_assert_is_instance(ref_outputs, t) + +# Test names in this set are only checked for a single derivative +nn_functional_single_grad = frozenset('test_nn_' + name for name in [ + 'pdist', + 'multilabel_margin_loss', + 'max_unpool3d', + 'multi_margin_loss', + 'binary_cross_entropy', + 'binary_cross_entropy_size_average', + 'ctc_loss', + 'grid_sample', +]) + +def check_against_reference(self, func, reference_func, output_func, args, kwargs=None, + allow_unused=True, check_types=True, no_grad=False, no_gradgrad=False): + """Verifies a function performs identically to some reference implementation. + + Commonly, this is used to verify that a JIT implementation + (output_func) matches the behavior of the eager implementation + (reference_func). + """ + kwargs = kwargs if kwargs else {} + + def allSum(vs): + if isinstance(vs, torch.Tensor): + vs = (vs,) + return sum((i + 1) * v.sum().abs() if v.dtype.is_complex else (i + 1) * v.sum() + for i, v in enumerate(vs) + if v is not None and v.dtype in floating_and_complex_types_and(torch.half, torch.bfloat16)) + + def clone_tensor(t, preserve_requires_grad): + require_grad = preserve_requires_grad and t.requires_grad + return t.detach().clone().requires_grad_(require_grad) + + def clone_inputs(preserve_requires_grad: bool): + inputs: List[Union[torch.Tensor, List[torch.Tensor]]] = [] + + for arg in args: + if isinstance(arg, torch.Tensor): + inputs.append(clone_tensor(arg, preserve_requires_grad)) + elif is_iterable_of_tensors(arg): + inputs.append([clone_tensor(t, preserve_requires_grad) for t in arg]) + else: + inputs.append(arg) + + return inputs + + # Returns tensors in args that requires_grad, including tensors in TensorList args + def get_recording_tensors(args): + recording_tensors: List[torch.Tensor] = [] + + for arg in args: + if isinstance(arg, torch.Tensor) and arg.requires_grad: + recording_tensors.append(arg) + elif is_iterable_of_tensors(arg): + recording_tensors.extend(filter(lambda t: t.requires_grad, arg)) + + return recording_tensors + + # test no gradients case + nograd_inputs = clone_inputs(preserve_requires_grad=False) + outputs = self.runAndSaveRNG(reference_func, nograd_inputs, kwargs) + with enable_profiling_mode_for_profiling_tests(): + outputs_test = self.runAndSaveRNG(func, nograd_inputs, kwargs) + self.assertEqual(outputs, outputs_test) + + if check_types: + check_output_types(self, func, outputs_test, nograd_inputs, kwargs) + + if no_grad: + # skip grad tests + return + + with enable_profiling_mode_for_profiling_tests(): + # test single grad case + recording_inputs = clone_inputs(preserve_requires_grad=True) + recording_tensors = get_recording_tensors(recording_inputs) + outputs = output_func(self.runAndSaveRNG(reference_func, recording_inputs, kwargs)) + grads = torch.autograd.grad(allSum(outputs), recording_tensors, + allow_unused=allow_unused) + outputs_test = output_func(self.runAndSaveRNG(func, recording_inputs, kwargs)) + grads_test = torch.autograd.grad(allSum(outputs_test), recording_tensors, + allow_unused=allow_unused) + self.assertEqual(outputs, outputs_test) + self.assertEqual(grads, grads_test) + # test the grad grad case + if self._testMethodName in nn_functional_single_grad or no_gradgrad: + return + + outputs = output_func(self.runAndSaveRNG(reference_func, recording_inputs, kwargs)) + l1 = allSum(outputs) + grads = torch.autograd.grad(l1, recording_tensors, create_graph=True, + allow_unused=allow_unused) + + l2 = (allSum(grads) * l1) + grads2 = torch.autograd.grad(l2, recording_tensors, allow_unused=allow_unused) + recording_inputs = clone_inputs(preserve_requires_grad=True) + recording_tensors = get_recording_tensors(recording_inputs) + outputs_test = output_func(self.runAndSaveRNG(func, recording_inputs, kwargs)) + l1_test = allSum(outputs_test) + grads_test = torch.autograd.grad( + l1_test, recording_tensors, create_graph=True, allow_unused=allow_unused) + + l2_test = (allSum(grads_test) * l1_test) + grads2_test = torch.autograd.grad(l2_test, recording_tensors, allow_unused=allow_unused) + + self.assertEqual(outputs, outputs_test) + self.assertEqual(grads, grads_test) + for g2, g2_test in zip(grads2, grads2_test): + if g2 is None and g2_test is None: + continue + self.assertEqual(g2, g2_test, atol=5e-4, rtol=1e-4) + +class JitCommonTestCase(TestCase): + def createFunctionFromGraph(self, trace): + graph = trace if isinstance(trace, torch._C.Graph) else trace.graph() + return torch._C._create_function_from_graph("forward", graph) + + def assertExportImport(self, trace, inputs): + m = self.createFunctionFromGraph(trace) + self.assertExportImportModule(m, inputs) + + def assertExportImportModule(self, m, inputs): + m_import = self.getExportImportCopy(m) + a = self.runAndSaveRNG(m, inputs) + b = self.runAndSaveRNG(m_import, inputs) + self.assertEqual(a, b, "Results of original model and " + "exported/imported version of model differed") + + def runAndSaveRNG(self, func, inputs, kwargs=None): + kwargs = kwargs if kwargs else {} + with freeze_rng_state(): + results = func(*inputs, **kwargs) + return results + + def getExportImportCopy(self, m, also_test_file=True, map_location=None): + buffer = io.BytesIO() + torch.jit.save(m, buffer) + buffer.seek(0) + imported = torch.jit.load(buffer, map_location=map_location) + + if not also_test_file: + return imported + + with TemporaryFileName() as fname: + torch.jit.save(imported, fname) + return torch.jit.load(fname, map_location=map_location) + + def autoDiffErrorMessage(self, should_autodiff_node, nodes_not_in_diff_graph, + fusion_nodes_not_found, non_fusible_nodes_being_fused, + fusion_nodes_found, nodes_in_diff_graph): + err_msg = "\nFailure in testing nodes' autodifferentiation. " + if should_autodiff_node: + err_msg += "One or more nodes were expected to be autodiffed, " \ + "but were not found in specified fusible/nonfusible " \ + "DifferentiableGraph groups. \nSpecifically:" + # The node is intended to appear in a differentiable graph but doesn't + diff_nodes_missing = [] + # The node is intended to appear in a differentiable graph + # outside of a fusion group but instead is in a fusion group + diff_nodes_in_fusion = [] + # The node is intended to appear in a fusion group but doesn't + fusion_nodes_missing = [] + # The node is intended to appear in a fusion group but instead + # is just in an outer differentiable graph + fusion_nodes_in_diff = [] + for node in nodes_not_in_diff_graph: + if node in non_fusible_nodes_being_fused: + diff_nodes_in_fusion.append(node) + else: + diff_nodes_missing.append(node) + for node in fusion_nodes_not_found: + if node in nodes_in_diff_graph: + fusion_nodes_in_diff.append(node) + else: + fusion_nodes_missing.append(node) + if len(diff_nodes_missing) > 0: + err_msg += f"\n {diff_nodes_missing} were not in one of the " \ + "DifferentiableGraphs when they were expected to be. " \ + "Did you intend for these nodes to be autodiffed? " \ + "If not, remove them from the list of nonfusible nodes." + if len(diff_nodes_in_fusion) > 0: + err_msg += f"\n {diff_nodes_in_fusion} were found in one of the FusionGroups " \ + "when they were expected to be just in a DifferentiableGraph. If it was " \ + "intended for these nodes to be in FusionGroups, reclassify these nodes as " \ + "fusible nodes. If these nodes were not intended to be fused, your " \ + "autodifferentiation logic might be wrong." + if len(fusion_nodes_missing) > 0: + err_msg += f"\n {fusion_nodes_missing} were not in one of the FusionGroups " \ + "of the DifferentiableGraphs when they were expected to be. " \ + "They were also not found in an outer DifferentiableGraph. Did you " \ + "intend for these nodes to be autodifferentiated? If not, you should " \ + "remove these nodes from the test's fusible nodes. Otherwise your " \ + "autodifferentiation logic might be wrong." + if len(fusion_nodes_in_diff) > 0: + err_msg += f"\n {fusion_nodes_in_diff} were not in one of the FusionGroups " \ + "of the DifferentiableGraphs when they were expected to be, " \ + "instead they were found just in an outer DifferentiableGraph. " \ + "Did you intend for these nodes to be fused? If not, you should " \ + "move these nodes into the test's nonfusible nodes. Otherwise your " \ + "autodifferentiation logic might be wrong." + else: + err_msg += "One or more nodes were not expected to be autodiffed " \ + "but were found in a DifferentiableGraph or in a FusionGroup " \ + "of a DifferentiableGraph. Did you intend for these nodes to be " \ + "autodiffed? If so, change this test to expect autodifferentiation. " \ + "\nSpecifically:" + if len(fusion_nodes_found) > 0: + err_msg += f"\n {fusion_nodes_found} were not expected to be in " \ + "one of the DifferentiableGraphs, but appeared in a FusionGroup " \ + "of a DifferentiableGraph. " + if len(nodes_in_diff_graph) > 0: + err_msg += f"\n {nodes_in_diff_graph} were not expected to " \ + "be in one of the DifferentiableGraphs but were." + return err_msg + + def assertAutodiffNode(self, graph, should_autodiff_node, nonfusible_nodes, fusible_nodes): + diff_nodes = graph.findAllNodes('prim::DifferentiableGraph') + diff_subgraphs = [node.g('Subgraph') for node in diff_nodes] + + # Note: currently no tests have fusible_nodes + fusion_nodes = list(chain.from_iterable([g.findAllNodes('prim::FusionGroup') for g in diff_subgraphs])) + fusion_subgraphs = [node.g('Subgraph') for node in fusion_nodes] + + # For any non-fusible node, it must show up in one of the DifferentiableGraphs. + nodes_in_diff_graph = [] + nodes_not_in_diff_graph = [] + non_fusible_nodes_being_fused = [] + for node in nonfusible_nodes: + if any(g.findNode(node) is not None for g in diff_subgraphs): + nodes_in_diff_graph.append(node) + else: + nodes_not_in_diff_graph.append(node) + if any(g.findNode(node) is not None for g in fusion_subgraphs): + non_fusible_nodes_being_fused.append(node) + found_all_nonfusible_nodes = len(nodes_in_diff_graph) == len(nonfusible_nodes) + + # For any fusible node, it must show up in one of the FusionGroups in one of the DifferentiableGraphs. + fusion_nodes_found = [] + fusion_nodes_not_found = [] + for node in fusible_nodes: + if any(g.findNode(node) is not None for g in fusion_subgraphs): + fusion_nodes_found.append(node) + else: + fusion_nodes_not_found.append(node) + found_all_fusible_nodes = len(fusion_nodes_found) == len(fusible_nodes) + + if should_autodiff_node is not None: + err_msg = self.autoDiffErrorMessage(should_autodiff_node, + nodes_not_in_diff_graph, + fusion_nodes_not_found, + non_fusible_nodes_being_fused, + fusion_nodes_found, + nodes_in_diff_graph) + self.assertEqual(should_autodiff_node, + found_all_nonfusible_nodes and found_all_fusible_nodes, err_msg) + + def checkShapeAnalysis(self, out_sizes: Union[List[int], List[List[int]]], + traced_graph, assert_propagation, constant_prop=True): + # repropagte input shapes provided by tracing, + prev_symbolic_shapes_test_enabled = torch._C._jit_symbolic_shapes_test_mode_enabled() + for enable_test_mode in [True, False]: + # here we are testing allowing/disallowing substituting in complete shapes as constants, + # disallowing constants helps stress test partial eval and substitution pipeline + torch._C._jit_set_symbolic_shapes_test_mode(enable_test_mode) + torch._C._jit_erase_non_input_shape_information(traced_graph) + if constant_prop: + torch._C._jit_pass_constant_propagation(traced_graph) + torch._C._jit_pass_propagate_shapes_on_graph(traced_graph) + # Add sizes to default tensor type to avoid checking something out of scope + # and difficulties with tracer leaving in other parts of tensor type + output = next(traced_graph.outputs()).type() + + def test_type(type, actual_size): + sizes = type.symbolic_sizes() + out_type = TensorType.get().with_sizes(sizes) + actual_type = TensorType.get().with_sizes(actual_size) + + # always check actual shape is a subtype of the output + self.assertTrue(actual_type.isSubtypeOf(out_type)) + + # and then if assertion flag is provided, check shape analysis + # is successful + if assert_propagation: + self.assertEqual(out_type.sizes(), actual_size) + + if output.isSubtypeOf(torch._C.TensorType.get()): + test_type(output, out_sizes) + else: + tuple_elements = output.elements() + for i in range(len(tuple_elements)): + test_type(tuple_elements[i], out_sizes[i]) + + torch._C._jit_set_symbolic_shapes_test_mode(prev_symbolic_shapes_test_enabled) diff --git a/shared/package-files/00/002490ed9be1b821e7bd5e069af46e2966796c12d5ceaee7719ef9a225b22dd3/blob b/shared/package-files/00/002490ed9be1b821e7bd5e069af46e2966796c12d5ceaee7719ef9a225b22dd3/blob new file mode 100644 index 0000000000000000000000000000000000000000..eaaa2884a0d2380015b6a4f11177e2fcaaa7f51d --- /dev/null +++ b/shared/package-files/00/002490ed9be1b821e7bd5e069af46e2966796c12d5ceaee7719ef9a225b22dd3/blob @@ -0,0 +1,6 @@ +class CudaSupportError(RuntimeError): + pass + + +class NvrtcError(Exception): + pass diff --git a/shared/package-files/00/00276baf2735e9b1915b1901993d86dd2ed9542921648c08e66b97019299e174/blob b/shared/package-files/00/00276baf2735e9b1915b1901993d86dd2ed9542921648c08e66b97019299e174/blob new file mode 100644 index 0000000000000000000000000000000000000000..f21ab29178e5ca46777b873fc5c1ef12f32f6443 --- /dev/null +++ b/shared/package-files/00/00276baf2735e9b1915b1901993d86dd2ed9542921648c08e66b97019299e174/blob @@ -0,0 +1,423 @@ +from dataclasses import dataclass + +from typing import Iterator, List, Optional, Sequence, Set, Tuple, Union + +from torchgen.model import ( + BackendIndex, + FunctionSchema, + NativeFunction, + NativeFunctionsGroup, + NativeFunctionsViewGroup, +) + +from .types_base import Binding, CType, Expr + + +@dataclass(frozen=True) +class CppSignature: + """ + A CppSignature represents a single overload in the C++ API. For + any given function schema, there may be multiple CppSignatures + corresponding to it, based on how we desugar to C++. See also + CppSignatureGroup. + """ + + # The schema this signature is derived from + func: FunctionSchema + + # Is this a C++ signature for a method, i.e. Tensor::my_op(...)? + method: bool + + # Is this a faithful C++ signature (i.e. following the JIT schema) or a convenience API + # (i.e. with a potential TensorOptions argument and out arguments in the front) + faithful: bool + + # Is this a symint C++ signature. For BC reasons, functions that take + # SymInts still present as int64_t in C++, and the SymInt variant is + # offered at a different overload name + # + # NB: If a function RETURNS a SymInt, this is ALWAYS false + symint: bool + + # The set of C++ arguments which should not have defaults applied to them + cpp_no_default_args: Set[str] + + # Is this a fallback C++ binding? Fallback bindings are enabled by + # manual_cpp_binding: True and are alternate, non-public API that + # lets manual C++ binding implementors access the binding that would + # have been automatically generated + fallback_binding: bool = False + + # Return the unpacked argument structure of this signature, + # discarding information about which arguments are semantically + # related to each other. + def arguments(self) -> Sequence[Binding]: + return cpp.arguments( + self.func.arguments, + faithful=self.faithful, + symint=self.symint, + method=self.method, + cpp_no_default_args=self.cpp_no_default_args, + ) + + def name(self, *, suppress_symint_suffix: bool = False) -> str: + n = cpp.name( + self.func, + faithful_name_for_out_overloads=self.faithful, + symint_overload=False if suppress_symint_suffix else self.symint, + ) + if self.fallback_binding: + n = f"__dispatch_{n}" + return n + + # Render the C++ declaration for this signature + def decl( + self, + *, + name: Optional[str] = None, + prefix: str = "", + is_redispatching_fn: bool = False, + suppress_symint_suffix: bool = False, + ) -> str: + returns_type = cpp.returns_type( + self.func.returns, symint=self.symint + ).cpp_type() + cpp_args = [a.decl() for a in self.arguments()] + if is_redispatching_fn: + cpp_args = ["c10::DispatchKeySet dispatchKeySet"] + cpp_args + cpp_args_str = ", ".join(cpp_args) + if name is None: + name = prefix + self.name(suppress_symint_suffix=suppress_symint_suffix) + return f"{returns_type} {name}({cpp_args_str})" + + # Render the C++ definition for this signature, not including + # the body (with curly braces) + def defn( + self, + *, + name: Optional[str] = None, + prefix: str = "", + is_redispatching_fn: bool = False, + ) -> str: + returns_type = cpp.returns_type( + self.func.returns, symint=self.symint + ).cpp_type() + cpp_args = [a.defn() for a in self.arguments()] + if is_redispatching_fn: + cpp_args = ["c10::DispatchKeySet dispatchKeySet"] + cpp_args + cpp_args_str = ", ".join(cpp_args) + if name is None: + name = prefix + self.name() + return f"{returns_type} {name}({cpp_args_str})" + + def ptr_type(self) -> str: + args_types_str = ", ".join(a.type for a in self.arguments()) + return f"{cpp.returns_type(self.func.returns, symint=self.symint).cpp_type()} (*)({args_types_str})" + + # Return the C++ function type, e.g., something like int(bool) + def type(self) -> str: + args_types_str = ", ".join(a.type for a in self.arguments()) + return f"{cpp.returns_type(self.func.returns, symint=self.symint).cpp_type()} ({args_types_str})" + + +# Represents group of all CppSignatures associated with a +# FunctionSchema. Right now, that's the regular, user-visible +# signature, as well as a "faithful" signature which doesn't +# have grouping. +@dataclass(frozen=True) +class CppSignatureGroup: + func: FunctionSchema + signature: CppSignature + faithful_signature: Optional[CppSignature] + symint_signature: Optional[CppSignature] + symint_faithful_signature: Optional[CppSignature] + + def most_faithful_signature(self) -> CppSignature: + if self.faithful_signature: + return self.faithful_signature + else: + return self.signature + + def signatures(self, *, symint: bool = True) -> Iterator[CppSignature]: + yield self.signature + if self.faithful_signature: + yield self.faithful_signature + if symint: + if self.symint_signature: + yield self.symint_signature + if self.symint_faithful_signature: + yield self.symint_faithful_signature + + @staticmethod + def from_native_function( + f: NativeFunction, *, method: bool, fallback_binding: bool = False + ) -> "CppSignatureGroup": + func = f.func + + def make_sig(*, faithful: bool, symint: bool) -> CppSignature: + return CppSignature( + func=func, + faithful=faithful, + symint=symint, + method=method, + fallback_binding=fallback_binding, + cpp_no_default_args=f.cpp_no_default_args, + ) + + def make_sigs(*, symint: bool) -> Tuple[CppSignature, Optional[CppSignature]]: + faithful_signature: Optional[CppSignature] = None + if func.arguments.tensor_options is not None or len(func.arguments.out) > 0: + faithful_signature = make_sig(faithful=True, symint=symint) + signature = make_sig(faithful=False, symint=symint) + return signature, faithful_signature + + signature, faithful_signature = make_sigs(symint=False) + symint_signature: Optional[CppSignature] = None + symint_faithful_signature: Optional[CppSignature] = None + if func.has_symint(): + symint_signature, symint_faithful_signature = make_sigs(symint=True) + + return CppSignatureGroup( + func=func, + signature=signature, + faithful_signature=faithful_signature, + symint_signature=symint_signature, + symint_faithful_signature=symint_faithful_signature, + ) + + +@dataclass(frozen=True) +class DispatcherSignature: + # The schema this signature is derived from + func: FunctionSchema + + # Allows you to prepend an arbitrary prefix to the signature name. + # This is useful for parts of the codegen that generate wrappers around kernels, + # and need to avoid naming collisions. + prefix: str = "" + + symint: bool = True + + def arguments(self) -> List[Binding]: + return dispatcher.arguments(self.func, symint=self.symint) + + def name(self) -> str: + return self.prefix + dispatcher.name(self.func) + + def decl(self, name: Optional[str] = None) -> str: + args_str = ", ".join(a.decl() for a in self.arguments()) + if name is None: + name = self.name() + return f"{self.returns_type().cpp_type()} {name}({args_str})" + + def defn( + self, name: Optional[str] = None, *, is_redispatching_fn: bool = False + ) -> str: + args = [a.defn() for a in self.arguments()] + if is_redispatching_fn: + args = ["c10::DispatchKeySet dispatchKeySet"] + args + args_str = ", ".join(args) + if name is None: + name = self.name() + return f"{self.returns_type().cpp_type()} {name}({args_str})" + + def exprs(self) -> List[Expr]: + return [Expr(a.name, a.nctype) for a in self.arguments()] + + def returns_type(self) -> CType: + return dispatcher.returns_type(self.func.returns, symint=self.symint) + + def ptr_type(self) -> str: + dispatcher_args_types_str = ", ".join(a.type for a in self.arguments()) + return f"{self.returns_type().cpp_type()} (*)({dispatcher_args_types_str})" + + # Return the C++ function type, e.g., something like int(bool) + def type(self) -> str: + dispatcher_args_types_str = ", ".join(a.type for a in self.arguments()) + return f"{self.returns_type().cpp_type()} ({dispatcher_args_types_str})" + + @staticmethod + def from_schema( + func: FunctionSchema, *, prefix: str = "", symint: bool = True + ) -> "DispatcherSignature": + return DispatcherSignature(func, prefix, symint) + + +@dataclass(frozen=True) +class NativeSignature: + # The schema this signature is derived from + func: FunctionSchema + + symint: bool + + prefix: str = "" + + def name(self) -> str: + return self.prefix + native.name(self.func) + + def decl(self, name: Optional[str] = None) -> str: + args_str = ", ".join(a.decl() for a in self.arguments()) + if name is None: + name = self.name() + return f"{native.returns_type(self.func.returns, symint=self.symint).cpp_type()} {name}({args_str})" + + def defn(self, name: Optional[str] = None) -> str: + args_str = ", ".join(a.defn() for a in self.arguments()) + if name is None: + name = self.name() + return f"{native.returns_type(self.func.returns, symint=self.symint).cpp_type()} {name}({args_str})" + + def ptr_type(self) -> str: + # don't include defaults in type signature! + args_str = ", ".join(a.defn() for a in self.arguments()) + return f"{native.returns_type(self.func.returns, symint=self.symint).cpp_type()} (*)({args_str})" + + def arguments(self) -> List[Binding]: + return native.arguments(self.func, symint=self.symint) + + def returns_type(self) -> CType: + return native.returns_type(self.func.returns, symint=self.symint) + + def dispatcher_exprs(self) -> List[Expr]: + return translate.translate( + self.arguments(), dispatcher.arguments(self.func), method=False + ) + + +@dataclass(frozen=True) +class ViewInverseSignature: + g: NativeFunctionsViewGroup + + def name(self) -> str: + return functionalization.reverse_name(self.g.view, include_namespace=False) + + def decl(self) -> str: + return_type = functionalization.returns_type(self.g.view.func) + decls = [ + a.decl() + for a in functionalization.inner_arguments( + self.g.view.func, is_reverse=True + ) + ] + return f"static {return_type.cpp_type()} {self.name()}({', '.join(decls)});" + + +@dataclass(frozen=True) +class FunctionalizationLambda: + g: NativeFunctionsViewGroup + + # are we generating the forward lambda or the reverse lambda? + is_reverse: bool + + def captures(self) -> List[Expr]: + # The lambda lives inside of a kernel following the dispatcher API, so its outer context is the dispatcher arguments + # We also need to read the "reapply views" TLS at the time that the functionalization kernel was executed, + # and plumb it into the lambda. + outer_ctx = dispatcher.arguments(self.g.view.func) + [ + functionalization.reapply_views_binding, + functionalization.inverse_return_mode_binding, + ] + capture_bindings = functionalization.capture_arguments( + self.g.view.func, is_reverse=self.is_reverse + ) + # allow_expensive_conversions is set because we want to convert + # some reference types (IntArrayRef) to value types (vector). + capture_exprs = translate.translate( + outer_ctx, capture_bindings, method=False, allow_expensive_conversions=True + ) + return capture_exprs + + def decl(self) -> str: + return_type = functionalization.returns_type(self.g.view.func) + capture_str = ", ".join( + f"{val.type.name} = {val.expr}" for val in self.captures() + ) + decls = [ + a.decl() + for a in functionalization.outer_arguments(is_reverse=self.is_reverse) + ] + return f"[{capture_str}]({', '.join(decls)}) -> {return_type.cpp_type()}" + + def inner_call(self, *, reapply_views: Optional[bool] = None) -> str: + inner_call_name = functionalization.name( + self.g, + is_reverse=self.is_reverse, + include_namespace=True, + reapply_views=reapply_views, + ) + + arg_ctx = functionalization.outer_arguments(is_reverse=self.is_reverse) + capture_ctx = functionalization.capture_arguments( + self.g.view.func, is_reverse=self.is_reverse + ) + full_ctx = arg_ctx + capture_ctx + + assert self.g.view_copy is not None + call_bindings = functionalization.inner_arguments( + self.g.view_copy.func, is_reverse=self.is_reverse + ) + maybe_index = functionalization.inner_call_index(self.g.view_copy.func) + call_exprs = [ + e.expr for e in translate.translate(full_ctx, call_bindings, method=False) + ] + if not self.is_reverse and maybe_index is not None: + return f'{inner_call_name}({", ".join(call_exprs)})[{maybe_index.name}];' + else: + return f'{inner_call_name}({", ".join(call_exprs)});' + + @staticmethod + def from_func( + g: NativeFunctionsViewGroup, *, is_reverse: bool + ) -> "FunctionalizationLambda": + return FunctionalizationLambda(g, is_reverse) + + +@dataclass(frozen=True) +class StructuredImplSignature: + g: NativeFunctionsGroup + name: str + + def defn(self, name: Optional[str] = None) -> str: + args_str = ", ".join(a.defn() for a in self.arguments()) + return f"TORCH_IMPL_FUNC({self.name})({args_str})" + + def arguments(self) -> List[Binding]: + return structured.impl_arguments(self.g) + + +# Helper functions + + +def kernel_signature( + f: NativeFunction, backend_index: BackendIndex, *, prefix: str = "" +) -> Union["NativeSignature", "DispatcherSignature"]: + # Note [External Backends Follow Dispatcher API] + # Kernel signatures for in-tree backends follow the "native" API, + # while kernels for out-of-tree backends follow the dispatcher API. + # See the comments in `native.py` for details, but historically there have been + # some small differences in schema convention between them and the Dispatcher API. + # Any differences that require translating between the two will results in a runtime cost, + # so we'd like to keep the differences as small as possible. + # With external backends, we'd like to enforce that they write their kernels with schemas + # that match the Dispatcher API directly, if they can. + meta = backend_index.get_kernel(f) + symint = meta is not None and meta.supports_symint() + if symint: + assert ( + f.func.has_symint() + ), f"attempted to define symint kernel for {backend_index.dispatch_key} without SymInt in schema" + if backend_index.external: + return DispatcherSignature.from_schema(f.func, prefix=prefix, symint=symint) + else: + return NativeSignature(f.func, prefix=prefix, symint=symint) + + +# Functions only, no types +from torchgen.api import ( + cpp, + dispatcher, + functionalization, + native, + structured, + translate, +) diff --git a/shared/package-files/00/00296106cebefe5167bdd513b6e0ca2a6369d5175ffc26cb3a8f816423c9a142/blob b/shared/package-files/00/00296106cebefe5167bdd513b6e0ca2a6369d5175ffc26cb3a8f816423c9a142/blob new file mode 100644 index 0000000000000000000000000000000000000000..e28289745ae525fa3cda22373e509700ba62a6bd --- /dev/null +++ b/shared/package-files/00/00296106cebefe5167bdd513b6e0ca2a6369d5175ffc26cb3a8f816423c9a142/blob @@ -0,0 +1,20 @@ +#pragma once + +#include + +namespace c10 { + +// RAII thread local guard that tracks whether code is being executed in +// `at::parallel_for` or `at::parallel_reduce` loop function. +class C10_API ParallelGuard { + public: + static bool is_enabled(); + + ParallelGuard(bool state); + ~ParallelGuard(); + + private: + bool previous_state_; +}; + +} // namespace c10 diff --git a/shared/package-files/00/002c55da2ea23c393e6ba2ff06ce23af254a6093041944e2b442184e36c97ace/blob b/shared/package-files/00/002c55da2ea23c393e6ba2ff06ce23af254a6093041944e2b442184e36c97ace/blob new file mode 100644 index 0000000000000000000000000000000000000000..f8f076172ab48ca4834d631b362f47ca374db5e4 --- /dev/null +++ b/shared/package-files/00/002c55da2ea23c393e6ba2ff06ce23af254a6093041944e2b442184e36c97ace/blob @@ -0,0 +1,9 @@ +MODULE string_test + + character(len=8) :: string + character string77 * 8 + + character(len=12), dimension(5,7) :: strarr + character strarr77(5,7) * 12 + +END MODULE string_test diff --git a/shared/package-files/00/002c817cb823dff5c6fa2039a26103ad7a833347102b38bc87c1d10489f31ba4/blob b/shared/package-files/00/002c817cb823dff5c6fa2039a26103ad7a833347102b38bc87c1d10489f31ba4/blob new file mode 100644 index 0000000000000000000000000000000000000000..3f4d300cef077e698989245562375a9444d983fa --- /dev/null +++ b/shared/package-files/00/002c817cb823dff5c6fa2039a26103ad7a833347102b38bc87c1d10489f31ba4/blob @@ -0,0 +1,63 @@ +"""Stuff that differs in different Python versions and platform +distributions.""" + +import logging +import os +import sys + +__all__ = ["get_path_uid", "stdlib_pkgs", "WINDOWS"] + + +logger = logging.getLogger(__name__) + + +def has_tls() -> bool: + try: + import _ssl # noqa: F401 # ignore unused + + return True + except ImportError: + pass + + from pip._vendor.urllib3.util import IS_PYOPENSSL + + return IS_PYOPENSSL + + +def get_path_uid(path: str) -> int: + """ + Return path's uid. + + Does not follow symlinks: + https://github.com/pypa/pip/pull/935#discussion_r5307003 + + Placed this function in compat due to differences on AIX and + Jython, that should eventually go away. + + :raises OSError: When path is a symlink or can't be read. + """ + if hasattr(os, "O_NOFOLLOW"): + fd = os.open(path, os.O_RDONLY | os.O_NOFOLLOW) + file_uid = os.fstat(fd).st_uid + os.close(fd) + else: # AIX and Jython + # WARNING: time of check vulnerability, but best we can do w/o NOFOLLOW + if not os.path.islink(path): + # older versions of Jython don't have `os.fstat` + file_uid = os.stat(path).st_uid + else: + # raise OSError for parity with os.O_NOFOLLOW above + raise OSError(f"{path} is a symlink; Will not return uid for symlinks") + return file_uid + + +# packages in the stdlib that may have installation metadata, but should not be +# considered 'installed'. this theoretically could be determined based on +# dist.location (py27:`sysconfig.get_paths()['stdlib']`, +# py26:sysconfig.get_config_vars('LIBDEST')), but fear platform variation may +# make this ineffective, so hard-coding +stdlib_pkgs = {"python", "wsgiref", "argparse"} + + +# windows detection, covers cpython and ironpython +WINDOWS = sys.platform.startswith("win") or (sys.platform == "cli" and os.name == "nt") diff --git a/shared/package-files/00/002cd5b3d209638942d9241be9fac755ee1d19de982c5203e54030e01b996bb7/blob b/shared/package-files/00/002cd5b3d209638942d9241be9fac755ee1d19de982c5203e54030e01b996bb7/blob new file mode 100644 index 0000000000000000000000000000000000000000..e177b5275d855fffbede91280d9ee7fb61ece2cd --- /dev/null +++ b/shared/package-files/00/002cd5b3d209638942d9241be9fac755ee1d19de982c5203e54030e01b996bb7/blob @@ -0,0 +1,77 @@ +import numpy as np +import pytest + +from pandas import ( + NA, + Categorical, + Series, +) +import pandas._testing as tm + + +@pytest.mark.parametrize( + "keep, expected", + [ + ("first", Series([False, False, True, False, True], name="name")), + ("last", Series([True, True, False, False, False], name="name")), + (False, Series([True, True, True, False, True], name="name")), + ], +) +def test_duplicated_keep(keep, expected): + ser = Series(["a", "b", "b", "c", "a"], name="name") + + result = ser.duplicated(keep=keep) + tm.assert_series_equal(result, expected) + + +@pytest.mark.parametrize( + "keep, expected", + [ + ("first", Series([False, False, True, False, True])), + ("last", Series([True, True, False, False, False])), + (False, Series([True, True, True, False, True])), + ], +) +def test_duplicated_nan_none(keep, expected): + ser = Series([np.nan, 3, 3, None, np.nan], dtype=object) + + result = ser.duplicated(keep=keep) + tm.assert_series_equal(result, expected) + + +def test_duplicated_categorical_bool_na(nulls_fixture): + # GH#44351 + ser = Series( + Categorical( + [True, False, True, False, nulls_fixture], + categories=[True, False], + ordered=True, + ) + ) + result = ser.duplicated() + expected = Series([False, False, True, True, False]) + tm.assert_series_equal(result, expected) + + +@pytest.mark.parametrize( + "keep, vals", + [ + ("last", [True, True, False]), + ("first", [False, True, True]), + (False, [True, True, True]), + ], +) +def test_duplicated_mask(keep, vals): + # GH#48150 + ser = Series([1, 2, NA, NA, NA], dtype="Int64") + result = ser.duplicated(keep=keep) + expected = Series([False, False] + vals) + tm.assert_series_equal(result, expected) + + +def test_duplicated_mask_no_duplicated_na(keep): + # GH#48150 + ser = Series([1, 2, NA], dtype="Int64") + result = ser.duplicated(keep=keep) + expected = Series([False, False, False]) + tm.assert_series_equal(result, expected) diff --git a/shared/package-files/00/00314591621e2b81b12f88e07c416168c2f9e6bf1406d10c076bc586bf6f3dd5/blob b/shared/package-files/00/00314591621e2b81b12f88e07c416168c2f9e6bf1406d10c076bc586bf6f3dd5/blob new file mode 100644 index 0000000000000000000000000000000000000000..d8c74fdb0724f2abe55cdc2e27c554a8dcf545c1 --- /dev/null +++ b/shared/package-files/00/00314591621e2b81b12f88e07c416168c2f9e6bf1406d10c076bc586bf6f3dd5/blob @@ -0,0 +1,113 @@ +#pragma once + +// @generated by torchgen/gen.py from Function.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + + +#include + +namespace at { + + +// aten::upsample_bilinear2d.vec(Tensor input, SymInt[]? output_size, bool align_corners, float[]? scale_factors) -> Tensor +inline at::Tensor upsample_bilinear2d(const at::Tensor & input, at::OptionalIntArrayRef output_size, bool align_corners, c10::optional> scale_factors) { + return at::_ops::upsample_bilinear2d_vec::call(input, output_size.has_value() ? c10::make_optional(c10::fromIntArrayRefSlow(*output_size)) : c10::nullopt, align_corners, scale_factors); +} +namespace symint { + template ::value>> + at::Tensor upsample_bilinear2d(const at::Tensor & input, at::OptionalIntArrayRef output_size, bool align_corners, c10::optional> scale_factors) { + return at::_ops::upsample_bilinear2d_vec::call(input, output_size.has_value() ? c10::make_optional(c10::fromIntArrayRefSlow(*output_size)) : c10::nullopt, align_corners, scale_factors); + } +} + +// aten::upsample_bilinear2d.vec(Tensor input, SymInt[]? output_size, bool align_corners, float[]? scale_factors) -> Tensor +inline at::Tensor upsample_bilinear2d_symint(const at::Tensor & input, at::OptionalSymIntArrayRef output_size, bool align_corners, c10::optional> scale_factors) { + return at::_ops::upsample_bilinear2d_vec::call(input, output_size, align_corners, scale_factors); +} +namespace symint { + template ::value>> + at::Tensor upsample_bilinear2d(const at::Tensor & input, at::OptionalSymIntArrayRef output_size, bool align_corners, c10::optional> scale_factors) { + return at::_ops::upsample_bilinear2d_vec::call(input, output_size, align_corners, scale_factors); + } +} + +// aten::upsample_bilinear2d.out(Tensor self, SymInt[2] output_size, bool align_corners, float? scales_h=None, float? scales_w=None, *, Tensor(a!) out) -> Tensor(a!) +inline at::Tensor & upsample_bilinear2d_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) { + return at::_ops::upsample_bilinear2d_out::call(self, c10::fromIntArrayRefSlow(output_size), align_corners, scales_h, scales_w, out); +} +namespace symint { + template ::value>> + at::Tensor & upsample_bilinear2d_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) { + return at::_ops::upsample_bilinear2d_out::call(self, c10::fromIntArrayRefSlow(output_size), align_corners, scales_h, scales_w, out); + } +} + +// aten::upsample_bilinear2d.out(Tensor self, SymInt[2] output_size, bool align_corners, float? scales_h=None, float? scales_w=None, *, Tensor(a!) out) -> Tensor(a!) +inline at::Tensor & upsample_bilinear2d_outf(const at::Tensor & self, at::IntArrayRef output_size, bool align_corners, c10::optional scales_h, c10::optional scales_w, at::Tensor & out) { + return at::_ops::upsample_bilinear2d_out::call(self, c10::fromIntArrayRefSlow(output_size), align_corners, scales_h, scales_w, out); +} +namespace symint { + template ::value>> + at::Tensor & upsample_bilinear2d_outf(const at::Tensor & self, at::IntArrayRef output_size, bool align_corners, c10::optional scales_h, c10::optional scales_w, at::Tensor & out) { + return at::_ops::upsample_bilinear2d_out::call(self, c10::fromIntArrayRefSlow(output_size), align_corners, scales_h, scales_w, out); + } +} + +// aten::upsample_bilinear2d.out(Tensor self, SymInt[2] output_size, bool align_corners, float? scales_h=None, float? scales_w=None, *, Tensor(a!) out) -> Tensor(a!) +inline at::Tensor & upsample_bilinear2d_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) { + return at::_ops::upsample_bilinear2d_out::call(self, output_size, align_corners, scales_h, scales_w, out); +} +namespace symint { + template ::value>> + at::Tensor & upsample_bilinear2d_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) { + return at::_ops::upsample_bilinear2d_out::call(self, output_size, align_corners, scales_h, scales_w, out); + } +} + +// aten::upsample_bilinear2d.out(Tensor self, SymInt[2] output_size, bool align_corners, float? scales_h=None, float? scales_w=None, *, Tensor(a!) out) -> Tensor(a!) +inline at::Tensor & upsample_bilinear2d_symint_outf(const at::Tensor & self, c10::SymIntArrayRef output_size, bool align_corners, c10::optional scales_h, c10::optional scales_w, at::Tensor & out) { + return at::_ops::upsample_bilinear2d_out::call(self, output_size, align_corners, scales_h, scales_w, out); +} +namespace symint { + template ::value>> + at::Tensor & upsample_bilinear2d_outf(const at::Tensor & self, c10::SymIntArrayRef output_size, bool align_corners, c10::optional scales_h, c10::optional scales_w, at::Tensor & out) { + return at::_ops::upsample_bilinear2d_out::call(self, output_size, align_corners, scales_h, scales_w, out); + } +} + +// aten::upsample_bilinear2d(Tensor self, SymInt[2] output_size, bool align_corners, float? scales_h=None, float? scales_w=None) -> Tensor +inline at::Tensor upsample_bilinear2d(const at::Tensor & self, at::IntArrayRef output_size, bool align_corners, c10::optional scales_h=c10::nullopt, c10::optional scales_w=c10::nullopt) { + return at::_ops::upsample_bilinear2d::call(self, c10::fromIntArrayRefSlow(output_size), align_corners, scales_h, scales_w); +} +namespace symint { + template ::value>> + at::Tensor upsample_bilinear2d(const at::Tensor & self, at::IntArrayRef output_size, bool align_corners, c10::optional scales_h=c10::nullopt, c10::optional scales_w=c10::nullopt) { + return at::_ops::upsample_bilinear2d::call(self, c10::fromIntArrayRefSlow(output_size), align_corners, scales_h, scales_w); + } +} + +// aten::upsample_bilinear2d(Tensor self, SymInt[2] output_size, bool align_corners, float? scales_h=None, float? scales_w=None) -> Tensor +inline at::Tensor upsample_bilinear2d_symint(const at::Tensor & self, c10::SymIntArrayRef output_size, bool align_corners, c10::optional scales_h=c10::nullopt, c10::optional scales_w=c10::nullopt) { + return at::_ops::upsample_bilinear2d::call(self, output_size, align_corners, scales_h, scales_w); +} +namespace symint { + template ::value>> + at::Tensor upsample_bilinear2d(const at::Tensor & self, c10::SymIntArrayRef output_size, bool align_corners, c10::optional scales_h=c10::nullopt, c10::optional scales_w=c10::nullopt) { + return at::_ops::upsample_bilinear2d::call(self, output_size, align_corners, scales_h, scales_w); + } +} + +} diff --git a/shared/package-files/00/0031606ea5313c5e9b70243b8c97945a8592388e70f333037cc63eeb21e6416e/blob b/shared/package-files/00/0031606ea5313c5e9b70243b8c97945a8592388e70f333037cc63eeb21e6416e/blob new file mode 100644 index 0000000000000000000000000000000000000000..ed2346c2a408c9bf895a5853f8878c5c457c4d52 --- /dev/null +++ b/shared/package-files/00/0031606ea5313c5e9b70243b8c97945a8592388e70f333037cc63eeb21e6416e/blob @@ -0,0 +1,164 @@ +""" +Utilities for generating random numbers, random sequences, and +random selections. +""" + +import networkx as nx +from networkx.utils import py_random_state + +__all__ = [ + "powerlaw_sequence", + "zipf_rv", + "cumulative_distribution", + "discrete_sequence", + "random_weighted_sample", + "weighted_choice", +] + + +# The same helpers for choosing random sequences from distributions +# uses Python's random module +# https://docs.python.org/3/library/random.html + + +@py_random_state(2) +def powerlaw_sequence(n, exponent=2.0, seed=None): + """ + Return sample sequence of length n from a power law distribution. + """ + return [seed.paretovariate(exponent - 1) for i in range(n)] + + +@py_random_state(2) +def zipf_rv(alpha, xmin=1, seed=None): + r"""Returns a random value chosen from the Zipf distribution. + + The return value is an integer drawn from the probability distribution + + .. math:: + + p(x)=\frac{x^{-\alpha}}{\zeta(\alpha, x_{\min})}, + + where $\zeta(\alpha, x_{\min})$ is the Hurwitz zeta function. + + Parameters + ---------- + alpha : float + Exponent value of the distribution + xmin : int + Minimum value + seed : integer, random_state, or None (default) + Indicator of random number generation state. + See :ref:`Randomness`. + + Returns + ------- + x : int + Random value from Zipf distribution + + Raises + ------ + ValueError: + If xmin < 1 or + If alpha <= 1 + + Notes + ----- + The rejection algorithm generates random values for a the power-law + distribution in uniformly bounded expected time dependent on + parameters. See [1]_ for details on its operation. + + Examples + -------- + >>> nx.utils.zipf_rv(alpha=2, xmin=3, seed=42) + 8 + + References + ---------- + .. [1] Luc Devroye, Non-Uniform Random Variate Generation, + Springer-Verlag, New York, 1986. + """ + if xmin < 1: + raise ValueError("xmin < 1") + if alpha <= 1: + raise ValueError("a <= 1.0") + a1 = alpha - 1.0 + b = 2**a1 + while True: + u = 1.0 - seed.random() # u in (0,1] + v = seed.random() # v in [0,1) + x = int(xmin * u ** -(1.0 / a1)) + t = (1.0 + (1.0 / x)) ** a1 + if v * x * (t - 1.0) / (b - 1.0) <= t / b: + break + return x + + +def cumulative_distribution(distribution): + """Returns normalized cumulative distribution from discrete distribution.""" + + cdf = [0.0] + psum = sum(distribution) + for i in range(0, len(distribution)): + cdf.append(cdf[i] + distribution[i] / psum) + return cdf + + +@py_random_state(3) +def discrete_sequence(n, distribution=None, cdistribution=None, seed=None): + """ + Return sample sequence of length n from a given discrete distribution + or discrete cumulative distribution. + + One of the following must be specified. + + distribution = histogram of values, will be normalized + + cdistribution = normalized discrete cumulative distribution + + """ + import bisect + + if cdistribution is not None: + cdf = cdistribution + elif distribution is not None: + cdf = cumulative_distribution(distribution) + else: + raise nx.NetworkXError( + "discrete_sequence: distribution or cdistribution missing" + ) + + # get a uniform random number + inputseq = [seed.random() for i in range(n)] + + # choose from CDF + seq = [bisect.bisect_left(cdf, s) - 1 for s in inputseq] + return seq + + +@py_random_state(2) +def random_weighted_sample(mapping, k, seed=None): + """Returns k items without replacement from a weighted sample. + + The input is a dictionary of items with weights as values. + """ + if k > len(mapping): + raise ValueError("sample larger than population") + sample = set() + while len(sample) < k: + sample.add(weighted_choice(mapping, seed)) + return list(sample) + + +@py_random_state(1) +def weighted_choice(mapping, seed=None): + """Returns a single element from a weighted sample. + + The input is a dictionary of items with weights as values. + """ + # use roulette method + rnd = seed.random() * sum(mapping.values()) + for k, w in mapping.items(): + rnd -= w + if rnd < 0: + return k diff --git a/shared/package-files/00/00323b115fc2338ced202a6a1ea7aaf0b23e59d07a717d2db5ab5d45d8dbb140/blob b/shared/package-files/00/00323b115fc2338ced202a6a1ea7aaf0b23e59d07a717d2db5ab5d45d8dbb140/blob new file mode 100644 index 0000000000000000000000000000000000000000..2f620eaa0722338a39807f91f2d6a3e61ea68ca9 --- /dev/null +++ b/shared/package-files/00/00323b115fc2338ced202a6a1ea7aaf0b23e59d07a717d2db5ab5d45d8dbb140/blob @@ -0,0 +1,112 @@ +import os +import pytest + +import numpy as np + +from . import util + + +class TestParameters(util.F2PyTest): + # Check that intent(in out) translates as intent(inout) + sources = [ + util.getpath("tests", "src", "parameter", "constant_real.f90"), + util.getpath("tests", "src", "parameter", "constant_integer.f90"), + util.getpath("tests", "src", "parameter", "constant_both.f90"), + util.getpath("tests", "src", "parameter", "constant_compound.f90"), + util.getpath("tests", "src", "parameter", "constant_non_compound.f90"), + ] + + @pytest.mark.slow + def test_constant_real_single(self): + # non-contiguous should raise error + x = np.arange(6, dtype=np.float32)[::2] + pytest.raises(ValueError, self.module.foo_single, x) + + # check values with contiguous array + x = np.arange(3, dtype=np.float32) + self.module.foo_single(x) + assert np.allclose(x, [0 + 1 + 2 * 3, 1, 2]) + + @pytest.mark.slow + def test_constant_real_double(self): + # non-contiguous should raise error + x = np.arange(6, dtype=np.float64)[::2] + pytest.raises(ValueError, self.module.foo_double, x) + + # check values with contiguous array + x = np.arange(3, dtype=np.float64) + self.module.foo_double(x) + assert np.allclose(x, [0 + 1 + 2 * 3, 1, 2]) + + @pytest.mark.slow + def test_constant_compound_int(self): + # non-contiguous should raise error + x = np.arange(6, dtype=np.int32)[::2] + pytest.raises(ValueError, self.module.foo_compound_int, x) + + # check values with contiguous array + x = np.arange(3, dtype=np.int32) + self.module.foo_compound_int(x) + assert np.allclose(x, [0 + 1 + 2 * 6, 1, 2]) + + @pytest.mark.slow + def test_constant_non_compound_int(self): + # check values + x = np.arange(4, dtype=np.int32) + self.module.foo_non_compound_int(x) + assert np.allclose(x, [0 + 1 + 2 + 3 * 4, 1, 2, 3]) + + @pytest.mark.slow + def test_constant_integer_int(self): + # non-contiguous should raise error + x = np.arange(6, dtype=np.int32)[::2] + pytest.raises(ValueError, self.module.foo_int, x) + + # check values with contiguous array + x = np.arange(3, dtype=np.int32) + self.module.foo_int(x) + assert np.allclose(x, [0 + 1 + 2 * 3, 1, 2]) + + @pytest.mark.slow + def test_constant_integer_long(self): + # non-contiguous should raise error + x = np.arange(6, dtype=np.int64)[::2] + pytest.raises(ValueError, self.module.foo_long, x) + + # check values with contiguous array + x = np.arange(3, dtype=np.int64) + self.module.foo_long(x) + assert np.allclose(x, [0 + 1 + 2 * 3, 1, 2]) + + @pytest.mark.slow + def test_constant_both(self): + # non-contiguous should raise error + x = np.arange(6, dtype=np.float64)[::2] + pytest.raises(ValueError, self.module.foo, x) + + # check values with contiguous array + x = np.arange(3, dtype=np.float64) + self.module.foo(x) + assert np.allclose(x, [0 + 1 * 3 * 3 + 2 * 3 * 3, 1 * 3, 2 * 3]) + + @pytest.mark.slow + def test_constant_no(self): + # non-contiguous should raise error + x = np.arange(6, dtype=np.float64)[::2] + pytest.raises(ValueError, self.module.foo_no, x) + + # check values with contiguous array + x = np.arange(3, dtype=np.float64) + self.module.foo_no(x) + assert np.allclose(x, [0 + 1 * 3 * 3 + 2 * 3 * 3, 1 * 3, 2 * 3]) + + @pytest.mark.slow + def test_constant_sum(self): + # non-contiguous should raise error + x = np.arange(6, dtype=np.float64)[::2] + pytest.raises(ValueError, self.module.foo_sum, x) + + # check values with contiguous array + x = np.arange(3, dtype=np.float64) + self.module.foo_sum(x) + assert np.allclose(x, [0 + 1 * 3 * 3 + 2 * 3 * 3, 1 * 3, 2 * 3]) diff --git a/shared/package-files/00/00329ec9a1b2285e43c01344d2c444e69bd6f9b4a414c25f06e873677adc78fe/blob b/shared/package-files/00/00329ec9a1b2285e43c01344d2c444e69bd6f9b4a414c25f06e873677adc78fe/blob new file mode 100644 index 0000000000000000000000000000000000000000..6d38aa0601b31c7f4c47ff3016173426df4e1d53 --- /dev/null +++ b/shared/package-files/00/00329ec9a1b2285e43c01344d2c444e69bd6f9b4a414c25f06e873677adc78fe/blob @@ -0,0 +1,6 @@ +Wheel-Version: 1.0 +Generator: bdist_wheel (0.35.1) +Root-Is-Purelib: true +Tag: py2-none-any +Tag: py3-none-any + diff --git a/shared/package-files/00/0035359859fbca5f644ed4233a47cfb63a6690147f8bfea1c1b5645a1e6a666c/blob b/shared/package-files/00/0035359859fbca5f644ed4233a47cfb63a6690147f8bfea1c1b5645a1e6a666c/blob new file mode 100644 index 0000000000000000000000000000000000000000..a31d9a8051e2e4362d214a0e2ac1d79694eca127 --- /dev/null +++ b/shared/package-files/00/0035359859fbca5f644ed4233a47cfb63a6690147f8bfea1c1b5645a1e6a666c/blob @@ -0,0 +1,84 @@ +"""Unit tests for the :mod:`networkx.algorithms.community.centrality` +module. + +""" +from operator import itemgetter + +import networkx as nx + + +def set_of_sets(iterable): + return set(map(frozenset, iterable)) + + +def validate_communities(result, expected): + assert set_of_sets(result) == set_of_sets(expected) + + +def validate_possible_communities(result, *expected): + assert any(set_of_sets(result) == set_of_sets(p) for p in expected) + + +class TestGirvanNewman: + """Unit tests for the + :func:`networkx.algorithms.community.centrality.girvan_newman` + function. + + """ + + def test_no_edges(self): + G = nx.empty_graph(3) + communities = list(nx.community.girvan_newman(G)) + assert len(communities) == 1 + validate_communities(communities[0], [{0}, {1}, {2}]) + + def test_undirected(self): + # Start with the graph .-.-.-. + G = nx.path_graph(4) + communities = list(nx.community.girvan_newman(G)) + assert len(communities) == 3 + # After one removal, we get the graph .-. .-. + validate_communities(communities[0], [{0, 1}, {2, 3}]) + # After the next, we get the graph .-. . ., but there are two + # symmetric possible versions. + validate_possible_communities( + communities[1], [{0}, {1}, {2, 3}], [{0, 1}, {2}, {3}] + ) + # After the last removal, we always get the empty graph. + validate_communities(communities[2], [{0}, {1}, {2}, {3}]) + + def test_directed(self): + G = nx.DiGraph(nx.path_graph(4)) + communities = list(nx.community.girvan_newman(G)) + assert len(communities) == 3 + validate_communities(communities[0], [{0, 1}, {2, 3}]) + validate_possible_communities( + communities[1], [{0}, {1}, {2, 3}], [{0, 1}, {2}, {3}] + ) + validate_communities(communities[2], [{0}, {1}, {2}, {3}]) + + def test_selfloops(self): + G = nx.path_graph(4) + G.add_edge(0, 0) + G.add_edge(2, 2) + communities = list(nx.community.girvan_newman(G)) + assert len(communities) == 3 + validate_communities(communities[0], [{0, 1}, {2, 3}]) + validate_possible_communities( + communities[1], [{0}, {1}, {2, 3}], [{0, 1}, {2}, {3}] + ) + validate_communities(communities[2], [{0}, {1}, {2}, {3}]) + + def test_most_valuable_edge(self): + G = nx.Graph() + G.add_weighted_edges_from([(0, 1, 3), (1, 2, 2), (2, 3, 1)]) + # Let the most valuable edge be the one with the highest weight. + + def heaviest(G): + return max(G.edges(data="weight"), key=itemgetter(2))[:2] + + communities = list(nx.community.girvan_newman(G, heaviest)) + assert len(communities) == 3 + validate_communities(communities[0], [{0}, {1, 2, 3}]) + validate_communities(communities[1], [{0}, {1}, {2, 3}]) + validate_communities(communities[2], [{0}, {1}, {2}, {3}]) diff --git a/shared/package-files/00/0035e986d00e45897712abc4e6ab3fbb7d81fd300b2923ad178de338b9a8c51c/blob b/shared/package-files/00/0035e986d00e45897712abc4e6ab3fbb7d81fd300b2923ad178de338b9a8c51c/blob new file mode 100644 index 0000000000000000000000000000000000000000..1ac6fc7d91c868ba077235b8229cd00869386660 --- /dev/null +++ b/shared/package-files/00/0035e986d00e45897712abc4e6ab3fbb7d81fd300b2923ad178de338b9a8c51c/blob @@ -0,0 +1,85 @@ +from typing import ( + Literal as L, + Any, + overload, + TypeVar, + Protocol, +) + +from numpy import generic + +from numpy._typing import ( + ArrayLike, + NDArray, + _ArrayLikeInt, + _ArrayLike, +) + +_SCT = TypeVar("_SCT", bound=generic) + +class _ModeFunc(Protocol): + def __call__( + self, + vector: NDArray[Any], + iaxis_pad_width: tuple[int, int], + iaxis: int, + kwargs: dict[str, Any], + /, + ) -> None: ... + +_ModeKind = L[ + "constant", + "edge", + "linear_ramp", + "maximum", + "mean", + "median", + "minimum", + "reflect", + "symmetric", + "wrap", + "empty", +] + +__all__: list[str] + +# TODO: In practice each keyword argument is exclusive to one or more +# specific modes. Consider adding more overloads to express this in the future. + +# Expand `**kwargs` into explicit keyword-only arguments +@overload +def pad( + array: _ArrayLike[_SCT], + pad_width: _ArrayLikeInt, + mode: _ModeKind = ..., + *, + stat_length: None | _ArrayLikeInt = ..., + constant_values: ArrayLike = ..., + end_values: ArrayLike = ..., + reflect_type: L["odd", "even"] = ..., +) -> NDArray[_SCT]: ... +@overload +def pad( + array: ArrayLike, + pad_width: _ArrayLikeInt, + mode: _ModeKind = ..., + *, + stat_length: None | _ArrayLikeInt = ..., + constant_values: ArrayLike = ..., + end_values: ArrayLike = ..., + reflect_type: L["odd", "even"] = ..., +) -> NDArray[Any]: ... +@overload +def pad( + array: _ArrayLike[_SCT], + pad_width: _ArrayLikeInt, + mode: _ModeFunc, + **kwargs: Any, +) -> NDArray[_SCT]: ... +@overload +def pad( + array: ArrayLike, + pad_width: _ArrayLikeInt, + mode: _ModeFunc, + **kwargs: Any, +) -> NDArray[Any]: ... diff --git a/shared/package-files/00/003919ccfac5d0d91a0e489eaa5788f5497f09903fd2ae8319145ba82d6df63c/blob b/shared/package-files/00/003919ccfac5d0d91a0e489eaa5788f5497f09903fd2ae8319145ba82d6df63c/blob new file mode 100644 index 0000000000000000000000000000000000000000..9909c5200e914982d07a4ff30ed076e5836fe185 --- /dev/null +++ b/shared/package-files/00/003919ccfac5d0d91a0e489eaa5788f5497f09903fd2ae8319145ba82d6df63c/blob @@ -0,0 +1,23 @@ +#pragma once +// @generated by torchgen/gen.py from DispatchKeyFunction.h + +// NB: The implementing C++ file is RegisterDispatchKey.cpp + +// The only #includes we need are for custom classes that have defaults in the C++ API +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { + +namespace compositeimplicitautograd { + +TORCH_API int64_t output_nr(const at::Tensor & self); + +} // namespace compositeimplicitautograd +} // namespace at diff --git a/shared/package-files/00/003a32bd1889775f1c7405d2d01cdef524ebe07e4347fcd5dd8ba009920ea628/blob b/shared/package-files/00/003a32bd1889775f1c7405d2d01cdef524ebe07e4347fcd5dd8ba009920ea628/blob new file mode 100644 index 0000000000000000000000000000000000000000..fa16a552675b499c3c2295b09f8f085a807e4803 --- /dev/null +++ b/shared/package-files/00/003a32bd1889775f1c7405d2d01cdef524ebe07e4347fcd5dd8ba009920ea628/blob @@ -0,0 +1,27 @@ +#pragma once + +// @generated by torchgen/gen.py from NativeMetaFunction.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace at { +namespace meta { + +struct TORCH_API structured_igammac : public TensorIteratorBase { + + + void meta(const at::Tensor & self, const at::Tensor & other); +}; + +} // namespace native +} // namespace at diff --git a/shared/package-files/00/003dc07b4b624fd9a7dab96312bbdf0847c41b44e50197cbfe7b9f42e8670c17/blob b/shared/package-files/00/003dc07b4b624fd9a7dab96312bbdf0847c41b44e50197cbfe7b9f42e8670c17/blob new file mode 100644 index 0000000000000000000000000000000000000000..63052f748befc7b30cdf6609490092b1d1d062e0 --- /dev/null +++ b/shared/package-files/00/003dc07b4b624fd9a7dab96312bbdf0847c41b44e50197cbfe7b9f42e8670c17/blob @@ -0,0 +1,433 @@ +import pytest +import warnings +import numpy as np +from numpy.testing import (assert_array_equal, assert_allclose, + suppress_warnings) +from copy import deepcopy +from scipy.stats.sampling import FastGeneratorInversion +from scipy import stats + + +def test_bad_args(): + # loc and scale must be scalar + with pytest.raises(ValueError, match="loc must be scalar"): + FastGeneratorInversion(stats.norm(loc=(1.2, 1.3))) + with pytest.raises(ValueError, match="scale must be scalar"): + FastGeneratorInversion(stats.norm(scale=[1.5, 5.7])) + + with pytest.raises(ValueError, match="'test' cannot be used to seed"): + FastGeneratorInversion(stats.norm(), random_state="test") + + msg = "Each of the 1 shape parameters must be a scalar" + with pytest.raises(ValueError, match=msg): + FastGeneratorInversion(stats.gamma([1.3, 2.5])) + + with pytest.raises(ValueError, match="`dist` must be a frozen"): + FastGeneratorInversion("xy") + + with pytest.raises(ValueError, match="Distribution 'truncnorm' is not"): + FastGeneratorInversion(stats.truncnorm(1.3, 4.5)) + + +def test_random_state(): + # fixed seed + gen = FastGeneratorInversion(stats.norm(), random_state=68734509) + x1 = gen.rvs(size=10) + gen.random_state = 68734509 + x2 = gen.rvs(size=10) + assert_array_equal(x1, x2) + + # Generator + urng = np.random.default_rng(20375857) + gen = FastGeneratorInversion(stats.norm(), random_state=urng) + x1 = gen.rvs(size=10) + gen.random_state = np.random.default_rng(20375857) + x2 = gen.rvs(size=10) + assert_array_equal(x1, x2) + + # RandomState + urng = np.random.RandomState(2364) + gen = FastGeneratorInversion(stats.norm(), random_state=urng) + x1 = gen.rvs(size=10) + gen.random_state = np.random.RandomState(2364) + x2 = gen.rvs(size=10) + assert_array_equal(x1, x2) + + # if evaluate_error is called, it must not interfere with the random_state + # used by rvs + gen = FastGeneratorInversion(stats.norm(), random_state=68734509) + x1 = gen.rvs(size=10) + _ = gen.evaluate_error(size=5) # this will generate 5 uniform rvs + x2 = gen.rvs(size=10) + gen.random_state = 68734509 + x3 = gen.rvs(size=20) + assert_array_equal(x2, x3[10:]) + + +dists_with_params = [ + ("alpha", (3.5,)), + ("anglit", ()), + ("argus", (3.5,)), + ("argus", (5.1,)), + ("beta", (1.5, 0.9)), + ("cosine", ()), + ("betaprime", (2.5, 3.3)), + ("bradford", (1.2,)), + ("burr", (1.3, 2.4)), + ("burr12", (0.7, 1.2)), + ("cauchy", ()), + ("chi2", (3.5,)), + ("chi", (4.5,)), + ("crystalball", (0.7, 1.2)), + ("expon", ()), + ("gamma", (1.5,)), + ("gennorm", (2.7,)), + ("gumbel_l", ()), + ("gumbel_r", ()), + ("hypsecant", ()), + ("invgauss", (3.1,)), + ("invweibull", (1.5,)), + ("laplace", ()), + ("logistic", ()), + ("maxwell", ()), + ("moyal", ()), + ("norm", ()), + ("pareto", (1.3,)), + ("powerlaw", (7.6,)), + ("rayleigh", ()), + ("semicircular", ()), + ("t", (5.7,)), + ("wald", ()), + ("weibull_max", (2.4,)), + ("weibull_min", (1.2,)), +] + + +@pytest.mark.parametrize(("distname, args"), dists_with_params) +def test_rvs_and_ppf(distname, args): + # check sample against rvs generated by rv_continuous + urng = np.random.default_rng(9807324628097097) + rng1 = getattr(stats, distname)(*args) + rvs1 = rng1.rvs(size=500, random_state=urng) + rng2 = FastGeneratorInversion(rng1, random_state=urng) + rvs2 = rng2.rvs(size=500) + assert stats.cramervonmises_2samp(rvs1, rvs2).pvalue > 0.01 + + # check ppf + q = [0.001, 0.1, 0.5, 0.9, 0.999] + assert_allclose(rng1.ppf(q), rng2.ppf(q), atol=1e-10) + + +@pytest.mark.parametrize(("distname, args"), dists_with_params) +def test_u_error(distname, args): + # check sample against rvs generated by rv_continuous + dist = getattr(stats, distname)(*args) + with suppress_warnings() as sup: + # filter the warnings thrown by UNU.RAN + sup.filter(RuntimeWarning) + rng = FastGeneratorInversion(dist) + u_error, x_error = rng.evaluate_error( + size=10_000, random_state=9807324628097097, x_error=False + ) + assert u_error <= 1e-10 + + +@pytest.mark.xslow +@pytest.mark.xfail(reason="geninvgauss CDF is not accurate") +def test_geninvgauss_uerror(): + dist = stats.geninvgauss(3.2, 1.5) + rng = FastGeneratorInversion(dist) + err = rng.evaluate_error(size=10_000, random_state=67982) + assert err[0] < 1e-10 + + +# TODO: add more distributions +@pytest.mark.fail_slow(5) +@pytest.mark.parametrize(("distname, args"), [("beta", (0.11, 0.11))]) +def test_error_extreme_params(distname, args): + # take extreme parameters where u-error might not be below the tolerance + # due to limitations of floating point arithmetic + with suppress_warnings() as sup: + # filter the warnings thrown by UNU.RAN for such extreme parameters + sup.filter(RuntimeWarning) + dist = getattr(stats, distname)(*args) + rng = FastGeneratorInversion(dist) + u_error, x_error = rng.evaluate_error( + size=10_000, random_state=980732462809709732623, x_error=True + ) + if u_error >= 2.5 * 1e-10: + assert x_error < 1e-9 + + +def test_evaluate_error_inputs(): + gen = FastGeneratorInversion(stats.norm()) + with pytest.raises(ValueError, match="size must be an integer"): + gen.evaluate_error(size=3.5) + with pytest.raises(ValueError, match="size must be an integer"): + gen.evaluate_error(size=(3, 3)) + + +def test_rvs_ppf_loc_scale(): + loc, scale = 3.5, 2.3 + dist = stats.norm(loc=loc, scale=scale) + rng = FastGeneratorInversion(dist, random_state=1234) + r = rng.rvs(size=1000) + r_rescaled = (r - loc) / scale + assert stats.cramervonmises(r_rescaled, "norm").pvalue > 0.01 + q = [0.001, 0.1, 0.5, 0.9, 0.999] + assert_allclose(rng._ppf(q), rng.ppf(q), atol=1e-10) + + +def test_domain(): + # only a basic check that the domain argument is passed to the + # UNU.RAN generators + rng = FastGeneratorInversion(stats.norm(), domain=(-1, 1)) + r = rng.rvs(size=100) + assert -1 <= r.min() < r.max() <= 1 + + # if loc and scale are used, new domain is loc + scale*domain + loc, scale = 3.5, 1.3 + dist = stats.norm(loc=loc, scale=scale) + rng = FastGeneratorInversion(dist, domain=(-1.5, 2)) + r = rng.rvs(size=100) + lb, ub = loc - scale * 1.5, loc + scale * 2 + assert lb <= r.min() < r.max() <= ub + + +@pytest.mark.parametrize(("distname, args, expected"), + [("beta", (3.5, 2.5), (0, 1)), + ("norm", (), (-np.inf, np.inf))]) +def test_support(distname, args, expected): + # test that the support is updated if truncation and loc/scale are applied + # use beta distribution since it is a transformed betaprime distribution, + # so it is important that the correct support is considered + # (i.e., the support of beta is (0,1), while betaprime is (0, inf)) + dist = getattr(stats, distname)(*args) + rng = FastGeneratorInversion(dist) + assert_array_equal(rng.support(), expected) + rng.loc = 1 + rng.scale = 2 + assert_array_equal(rng.support(), 1 + 2*np.array(expected)) + + +@pytest.mark.parametrize(("distname, args"), + [("beta", (3.5, 2.5)), ("norm", ())]) +def test_support_truncation(distname, args): + # similar test for truncation + dist = getattr(stats, distname)(*args) + rng = FastGeneratorInversion(dist, domain=(0.5, 0.7)) + assert_array_equal(rng.support(), (0.5, 0.7)) + rng.loc = 1 + rng.scale = 2 + assert_array_equal(rng.support(), (1 + 2 * 0.5, 1 + 2 * 0.7)) + + +def test_domain_shift_truncation(): + # center of norm is zero, it should be shifted to the left endpoint of + # domain. if this was not the case, PINV in UNURAN would raise a warning + # as the center is not inside the domain + with warnings.catch_warnings(): + warnings.simplefilter("error") + rng = FastGeneratorInversion(stats.norm(), domain=(1, 2)) + r = rng.rvs(size=100) + assert 1 <= r.min() < r.max() <= 2 + + +def test_non_rvs_methods_with_domain(): + # as a first step, compare truncated normal against stats.truncnorm + rng = FastGeneratorInversion(stats.norm(), domain=(2.3, 3.2)) + trunc_norm = stats.truncnorm(2.3, 3.2) + # take values that are inside and outside the domain + x = (2.0, 2.4, 3.0, 3.4) + p = (0.01, 0.5, 0.99) + assert_allclose(rng._cdf(x), trunc_norm.cdf(x)) + assert_allclose(rng._ppf(p), trunc_norm.ppf(p)) + loc, scale = 2, 3 + rng.loc = 2 + rng.scale = 3 + trunc_norm = stats.truncnorm(2.3, 3.2, loc=loc, scale=scale) + x = np.array(x) * scale + loc + assert_allclose(rng._cdf(x), trunc_norm.cdf(x)) + assert_allclose(rng._ppf(p), trunc_norm.ppf(p)) + + # do another sanity check with beta distribution + # in that case, it is important to use the correct domain since beta + # is a transformation of betaprime which has a different support + rng = FastGeneratorInversion(stats.beta(2.5, 3.5), domain=(0.3, 0.7)) + rng.loc = 2 + rng.scale = 2.5 + # the support is 2.75, , 3.75 (2 + 2.5 * 0.3, 2 + 2.5 * 0.7) + assert_array_equal(rng.support(), (2.75, 3.75)) + x = np.array([2.74, 2.76, 3.74, 3.76]) + # the cdf needs to be zero outside of the domain + y_cdf = rng._cdf(x) + assert_array_equal((y_cdf[0], y_cdf[3]), (0, 1)) + assert np.min(y_cdf[1:3]) > 0 + # ppf needs to map 0 and 1 to the boundaries + assert_allclose(rng._ppf(y_cdf), (2.75, 2.76, 3.74, 3.75)) + + +def test_non_rvs_methods_without_domain(): + norm_dist = stats.norm() + rng = FastGeneratorInversion(norm_dist) + x = np.linspace(-3, 3, num=10) + p = (0.01, 0.5, 0.99) + assert_allclose(rng._cdf(x), norm_dist.cdf(x)) + assert_allclose(rng._ppf(p), norm_dist.ppf(p)) + loc, scale = 0.5, 1.3 + rng.loc = loc + rng.scale = scale + norm_dist = stats.norm(loc=loc, scale=scale) + assert_allclose(rng._cdf(x), norm_dist.cdf(x)) + assert_allclose(rng._ppf(p), norm_dist.ppf(p)) + +@pytest.mark.parametrize(("domain, x"), + [(None, 0.5), + ((0, 1), 0.5), + ((0, 1), 1.5)]) +def test_scalar_inputs(domain, x): + """ pdf, cdf etc should map scalar values to scalars. check with and + w/o domain since domain impacts pdf, cdf etc + Take x inside and outside of domain """ + rng = FastGeneratorInversion(stats.norm(), domain=domain) + assert np.isscalar(rng._cdf(x)) + assert np.isscalar(rng._ppf(0.5)) + + +def test_domain_argus_large_chi(): + # for large chi, the Gamma distribution is used and the domain has to be + # transformed. this is a test to ensure that the transformation works + chi, lb, ub = 5.5, 0.25, 0.75 + rng = FastGeneratorInversion(stats.argus(chi), domain=(lb, ub)) + rng.random_state = 4574 + r = rng.rvs(size=500) + assert lb <= r.min() < r.max() <= ub + # perform goodness of fit test with conditional cdf + cdf = stats.argus(chi).cdf + prob = cdf(ub) - cdf(lb) + assert stats.cramervonmises(r, lambda x: cdf(x) / prob).pvalue > 0.05 + + +def test_setting_loc_scale(): + rng = FastGeneratorInversion(stats.norm(), random_state=765765864) + r1 = rng.rvs(size=1000) + rng.loc = 3.0 + rng.scale = 2.5 + r2 = rng.rvs(1000) + # rescaled r2 should be again standard normal + assert stats.cramervonmises_2samp(r1, (r2 - 3) / 2.5).pvalue > 0.05 + # reset values to default loc=0, scale=1 + rng.loc = 0 + rng.scale = 1 + r2 = rng.rvs(1000) + assert stats.cramervonmises_2samp(r1, r2).pvalue > 0.05 + + +def test_ignore_shape_range(): + msg = "No generator is defined for the shape parameters" + with pytest.raises(ValueError, match=msg): + rng = FastGeneratorInversion(stats.t(0.03)) + rng = FastGeneratorInversion(stats.t(0.03), ignore_shape_range=True) + # we can ignore the recommended range of shape parameters + # but u-error can be expected to be too large in that case + u_err, _ = rng.evaluate_error(size=1000, random_state=234) + assert u_err >= 1e-6 + +@pytest.mark.xfail_on_32bit( + "NumericalInversePolynomial.qrvs fails for Win 32-bit" +) +class TestQRVS: + def test_input_validation(self): + gen = FastGeneratorInversion(stats.norm()) + + match = "`qmc_engine` must be an instance of..." + with pytest.raises(ValueError, match=match): + gen.qrvs(qmc_engine=0) + + match = "`d` must be consistent with dimension of `qmc_engine`." + with pytest.raises(ValueError, match=match): + gen.qrvs(d=3, qmc_engine=stats.qmc.Halton(2)) + + qrngs = [None, stats.qmc.Sobol(1, seed=0), stats.qmc.Halton(3, seed=0)] + # `size=None` should not add anything to the shape, `size=1` should + sizes = [ + (None, tuple()), + (1, (1,)), + (4, (4,)), + ((4,), (4,)), + ((2, 4), (2, 4)), + ] + # Neither `d=None` nor `d=1` should add anything to the shape + ds = [(None, tuple()), (1, tuple()), (3, (3,))] + + @pytest.mark.parametrize("qrng", qrngs) + @pytest.mark.parametrize("size_in, size_out", sizes) + @pytest.mark.parametrize("d_in, d_out", ds) + def test_QRVS_shape_consistency(self, qrng, size_in, size_out, + d_in, d_out): + gen = FastGeneratorInversion(stats.norm()) + + # If d and qrng.d are inconsistent, an error is raised + if d_in is not None and qrng is not None and qrng.d != d_in: + match = "`d` must be consistent with dimension of `qmc_engine`." + with pytest.raises(ValueError, match=match): + gen.qrvs(size_in, d=d_in, qmc_engine=qrng) + return + + # Sometimes d is really determined by qrng + if d_in is None and qrng is not None and qrng.d != 1: + d_out = (qrng.d,) + + shape_expected = size_out + d_out + + qrng2 = deepcopy(qrng) + qrvs = gen.qrvs(size=size_in, d=d_in, qmc_engine=qrng) + if size_in is not None: + assert qrvs.shape == shape_expected + + if qrng2 is not None: + uniform = qrng2.random(np.prod(size_in) or 1) + qrvs2 = stats.norm.ppf(uniform).reshape(shape_expected) + assert_allclose(qrvs, qrvs2, atol=1e-12) + + def test_QRVS_size_tuple(self): + # QMCEngine samples are always of shape (n, d). When `size` is a tuple, + # we set `n = prod(size)` in the call to qmc_engine.random, transform + # the sample, and reshape it to the final dimensions. When we reshape, + # we need to be careful, because the _columns_ of the sample returned + # by a QMCEngine are "independent"-ish, but the elements within the + # columns are not. We need to make sure that this doesn't get mixed up + # by reshaping: qrvs[..., i] should remain "independent"-ish of + # qrvs[..., i+1], but the elements within qrvs[..., i] should be + # transformed from the same low-discrepancy sequence. + + gen = FastGeneratorInversion(stats.norm()) + + size = (3, 4) + d = 5 + qrng = stats.qmc.Halton(d, seed=0) + qrng2 = stats.qmc.Halton(d, seed=0) + + uniform = qrng2.random(np.prod(size)) + + qrvs = gen.qrvs(size=size, d=d, qmc_engine=qrng) + qrvs2 = stats.norm.ppf(uniform) + + for i in range(d): + sample = qrvs[..., i] + sample2 = qrvs2[:, i].reshape(size) + assert_allclose(sample, sample2, atol=1e-12) + + +def test_burr_overflow(): + # this case leads to an overflow error if math.exp is used + # in the definition of the burr pdf instead of np.exp + # a direct implementation of the PDF as x**(-c-1) / (1+x**(-c))**(d+1) + # also leads to an overflow error in the setup + args = (1.89128135, 0.30195177) + with suppress_warnings() as sup: + # filter potential overflow warning + sup.filter(RuntimeWarning) + gen = FastGeneratorInversion(stats.burr(*args)) + u_error, _ = gen.evaluate_error(random_state=4326) + assert u_error <= 1e-10 diff --git a/shared/package-files/00/00416a0d488c68cdaa9f2f1ff590f227807dda2acd8fba1254b8d076cc2c6fdd/blob b/shared/package-files/00/00416a0d488c68cdaa9f2f1ff590f227807dda2acd8fba1254b8d076cc2c6fdd/blob new file mode 100644 index 0000000000000000000000000000000000000000..4299fabddb76a284091f854ba1edc6240c61874d --- /dev/null +++ b/shared/package-files/00/00416a0d488c68cdaa9f2f1ff590f227807dda2acd8fba1254b8d076cc2c6fdd/blob @@ -0,0 +1,28 @@ +#pragma once +// @generated by torchgen/gen.py from DispatchKeyFunction.h + +// NB: The implementing C++ file is RegisterDispatchKey.cpp + +// The only #includes we need are for custom classes that have defaults in the C++ API +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { + +namespace cpu { + +TORCH_API at::Tensor reflection_pad1d_backward(const at::Tensor & grad_output, const at::Tensor & self, at::IntArrayRef padding); +TORCH_API at::Tensor reflection_pad1d_backward_symint(const at::Tensor & grad_output, const at::Tensor & self, c10::SymIntArrayRef padding); +TORCH_API at::Tensor & reflection_pad1d_backward_out(at::Tensor & grad_input, const at::Tensor & grad_output, const at::Tensor & self, at::IntArrayRef padding); +TORCH_API at::Tensor & reflection_pad1d_backward_outf(const at::Tensor & grad_output, const at::Tensor & self, at::IntArrayRef padding, at::Tensor & grad_input); +TORCH_API at::Tensor & reflection_pad1d_backward_symint_out(at::Tensor & grad_input, const at::Tensor & grad_output, const at::Tensor & self, c10::SymIntArrayRef padding); +TORCH_API at::Tensor & reflection_pad1d_backward_symint_outf(const at::Tensor & grad_output, const at::Tensor & self, c10::SymIntArrayRef padding, at::Tensor & grad_input); + +} // namespace cpu +} // namespace at diff --git a/shared/package-files/00/0041d46d458301b27ecb872c1b017dfb423a8cc7f355bd0076fbcf02d81b09f5/blob b/shared/package-files/00/0041d46d458301b27ecb872c1b017dfb423a8cc7f355bd0076fbcf02d81b09f5/blob new file mode 100644 index 0000000000000000000000000000000000000000..4a9d01cf9cde74e5252c8e796659a46af93de1f6 --- /dev/null +++ b/shared/package-files/00/0041d46d458301b27ecb872c1b017dfb423a8cc7f355bd0076fbcf02d81b09f5/blob @@ -0,0 +1,78 @@ +# mypy: ignore-errors + +import contextlib +import functools +import inspect + +import torch + + +# Test whether hardware BF32 math mode enabled. It is enabled only on: +# - MKLDNN is available +# - BF16 is supported by MKLDNN +def bf32_is_not_fp32(): + if not torch.backends.mkldnn.is_available(): + return False + if not torch.ops.mkldnn._is_mkldnn_bf16_supported(): + return False + return True + + +@contextlib.contextmanager +def bf32_off(): + old_matmul_precision = torch.get_float32_matmul_precision() + try: + torch.set_float32_matmul_precision("highest") + yield + finally: + torch.set_float32_matmul_precision(old_matmul_precision) + + +@contextlib.contextmanager +def bf32_on(self, bf32_precision=1e-5): + old_matmul_precision = torch.get_float32_matmul_precision() + old_precision = self.precision + try: + torch.set_float32_matmul_precision("medium") + self.precision = bf32_precision + yield + finally: + torch.set_float32_matmul_precision(old_matmul_precision) + self.precision = old_precision + + +# This is a wrapper that wraps a test to run this test twice, one with +# allow_bf32=True, another with allow_bf32=False. When running with +# allow_bf32=True, it will use reduced precision as specified by the +# argument +def bf32_on_and_off(bf32_precision=1e-5): + def with_bf32_disabled(self, function_call): + with bf32_off(): + function_call() + + def with_bf32_enabled(self, function_call): + with bf32_on(self, bf32_precision): + function_call() + + def wrapper(f): + params = inspect.signature(f).parameters + arg_names = tuple(params.keys()) + + @functools.wraps(f) + def wrapped(*args, **kwargs): + for k, v in zip(arg_names, args): + kwargs[k] = v + cond = bf32_is_not_fp32() + if "device" in kwargs: + cond = cond and (torch.device(kwargs["device"]).type == "cpu") + if "dtype" in kwargs: + cond = cond and (kwargs["dtype"] == torch.float) + if cond: + with_bf32_disabled(kwargs["self"], lambda: f(**kwargs)) + with_bf32_enabled(kwargs["self"], lambda: f(**kwargs)) + else: + f(**kwargs) + + return wrapped + + return wrapper diff --git a/shared/package-files/00/0043db8cea50b491a93a3c2bae2fbac15da0cd422f359e44215255b1312eb219/blob b/shared/package-files/00/0043db8cea50b491a93a3c2bae2fbac15da0cd422f359e44215255b1312eb219/blob new file mode 100644 index 0000000000000000000000000000000000000000..3badf23ebac8f08bda5af32392305569141b04ba --- /dev/null +++ b/shared/package-files/00/0043db8cea50b491a93a3c2bae2fbac15da0cd422f359e44215255b1312eb219/blob @@ -0,0 +1,20 @@ +from typing import Any, Callable, Iterable, Optional, Type, Union, TypeVar + +from django.utils.deprecation import MiddlewareMixin +from django.views.generic.base import View + +_T = TypeVar("_T", bound=Union[View, Callable]) # Any callable + +class classonlymethod(classmethod): ... + +def method_decorator(decorator: Union[Callable, Iterable[Callable]], name: str = ...) -> Callable[[_T], _T]: ... +def decorator_from_middleware_with_args(middleware_class: type) -> Callable: ... +def decorator_from_middleware(middleware_class: type) -> Callable: ... +def available_attrs(fn: Callable): ... +def make_middleware_decorator(middleware_class: Type[MiddlewareMixin]) -> Callable: ... + +class classproperty: + fget: Optional[Callable] = ... + def __init__(self, method: Optional[Callable] = ...) -> None: ... + def __get__(self, instance: Any, cls: Optional[type] = ...) -> Any: ... + def getter(self, method: Callable) -> classproperty: ... diff --git a/shared/package-files/00/0044e23094d2e3a3ff97226409f39e7547a72fbb333129ef0ece163b42789de5/blob b/shared/package-files/00/0044e23094d2e3a3ff97226409f39e7547a72fbb333129ef0ece163b42789de5/blob new file mode 100644 index 0000000000000000000000000000000000000000..2e89a769eff0c8dc82d8f003ac62b18e9e78624e --- /dev/null +++ b/shared/package-files/00/0044e23094d2e3a3ff97226409f39e7547a72fbb333129ef0ece163b42789de5/blob @@ -0,0 +1,113 @@ +from contextlib import contextmanager +from typing import Any, List, Tuple, cast +import random +import torch +import time +from torch.utils.benchmark import Timer + +def extract_ir(filename: str) -> List[str]: + BEGIN = "" + END = "" + pfx = None + current = "" + graphs = [] + with open(filename) as f: + split_strs = f.read().split(BEGIN) + for i, split_str in enumerate(split_strs): + if i == 0: + continue + end_loc = split_str.find(END) + if end_loc == -1: + continue + s = split_str[:end_loc] + pfx = split_strs[i - 1].splitlines()[-1] + lines = [x[len(pfx):] for x in s.splitlines(keepends=True)] + graphs.append(''.join(lines)) + + return graphs + + +def make_tensor_from_type(inp_type: torch._C.TensorType): + size = inp_type.sizes() + stride = inp_type.strides() + device = inp_type.device() + dtype = inp_type.dtype() + assert size is not None + assert stride is not None + assert device is not None + assert dtype is not None + return torch.empty_strided(size=size, stride=stride, device=device, dtype=dtype) + +def load_graph_and_inputs(ir: str) -> Tuple[Any, List[Any]]: + graph = torch._C.parse_ir(ir, parse_tensor_constants=True) + graph.makeMultiOutputIntoTuple() + inputs = [] + for inp in graph.inputs(): + if isinstance(inp.type(), torch._C.FloatType): + inputs.append(random.uniform(.1, 100)) + elif isinstance(inp.type(), torch._C.IntType): + inputs.append(random.randint(1, 100)) + elif isinstance(inp.type(), torch._C.TensorType): + tensorType = cast(torch._C.TensorType, inp.type()) + inputs.append(make_tensor_from_type(tensorType)) + elif isinstance(inp.type(), torch._C.BoolType): + inputs.append(random.randint(0, 1) == 1) + else: + raise NotImplementedError(f"A default value is not implemented for type {inp.type()}") + + func = torch._C._create_function_from_graph("forward", graph) + torch._C._jit_pass_erase_shape_information(func.graph) + return (func, inputs) + +def time_cuda(fn, inputs, test_runs): + t = Timer(stmt="fn(*inputs)", globals={"fn": fn, "inputs" : inputs}) + times = t.blocked_autorange() + return times.median * 1000 # time in ms + +def time_cpu(fn, inputs, test_runs): + s = time.perf_counter() + for _ in range(test_runs): + fn(*inputs) + e = time.perf_counter() + return (e - s) / test_runs * 1000 # time in ms + +def run_test(ir, inputs, *, warmup_runs=10, test_runs=20) -> float: + graph, _ = load_graph_and_inputs(ir) + for _ in range(warmup_runs): + graph(*inputs) + + is_cpu = None + for input in inputs: + if isinstance(input, torch.Tensor): + is_cpu = input.device.type == "cpu" + break + assert is_cpu is not None + + out = time_cpu(graph, inputs, test_runs) if is_cpu else time_cuda(graph, inputs, test_runs) + return out + +@contextmanager +def no_fuser(*args, **kwargs): + old_optimize = torch._C._get_graph_executor_optimize(False) + try: + yield + finally: + torch._C._get_graph_executor_optimize(old_optimize) + +def run_baseline_no_fusion(ir, inputs) -> float: + with no_fuser(): + return run_test(ir, inputs) + + +def run_nnc(ir, inputs, dynamic) -> float: + try: + strat = [("DYNAMIC", 10)] if dynamic else [("STATIC", 10)] + old_strat = torch.jit.set_fusion_strategy(strat) + with torch.jit.fuser("fuser1"): + return run_test(ir, inputs) + finally: + torch.jit.set_fusion_strategy(old_strat) + +def run_nvfuser(ir, inputs) -> float: + with torch.jit.fuser("fuser2"): + return run_test(ir, inputs) diff --git a/shared/package-files/00/004558d2aa27cb210c82fe03a3674836baea500c149365d84aa1cceb9d2ecde9/blob b/shared/package-files/00/004558d2aa27cb210c82fe03a3674836baea500c149365d84aa1cceb9d2ecde9/blob new file mode 100644 index 0000000000000000000000000000000000000000..941fdb9ec7a9699c1f4de8077eb681751446956e --- /dev/null +++ b/shared/package-files/00/004558d2aa27cb210c82fe03a3674836baea500c149365d84aa1cceb9d2ecde9/blob @@ -0,0 +1,330 @@ +""" + pygments.util + ~~~~~~~~~~~~~ + + Utility functions. + + :copyright: Copyright 2006-2023 by the Pygments team, see AUTHORS. + :license: BSD, see LICENSE for details. +""" + +import re +from io import TextIOWrapper + + +split_path_re = re.compile(r'[/\\ ]') +doctype_lookup_re = re.compile(r''' + ]*> +''', re.DOTALL | re.MULTILINE | re.VERBOSE) +tag_re = re.compile(r'<(.+?)(\s.*?)?>.*?', + re.IGNORECASE | re.DOTALL | re.MULTILINE) +xml_decl_re = re.compile(r'\s*<\?xml[^>]*\?>', re.I) + + +class ClassNotFound(ValueError): + """Raised if one of the lookup functions didn't find a matching class.""" + + +class OptionError(Exception): + """ + This exception will be raised by all option processing functions if + the type or value of the argument is not correct. + """ + +def get_choice_opt(options, optname, allowed, default=None, normcase=False): + """ + If the key `optname` from the dictionary is not in the sequence + `allowed`, raise an error, otherwise return it. + """ + string = options.get(optname, default) + if normcase: + string = string.lower() + if string not in allowed: + raise OptionError('Value for option %s must be one of %s' % + (optname, ', '.join(map(str, allowed)))) + return string + + +def get_bool_opt(options, optname, default=None): + """ + Intuitively, this is `options.get(optname, default)`, but restricted to + Boolean value. The Booleans can be represented as string, in order to accept + Boolean value from the command line arguments. If the key `optname` is + present in the dictionary `options` and is not associated with a Boolean, + raise an `OptionError`. If it is absent, `default` is returned instead. + + The valid string values for ``True`` are ``1``, ``yes``, ``true`` and + ``on``, the ones for ``False`` are ``0``, ``no``, ``false`` and ``off`` + (matched case-insensitively). + """ + string = options.get(optname, default) + if isinstance(string, bool): + return string + elif isinstance(string, int): + return bool(string) + elif not isinstance(string, str): + raise OptionError('Invalid type %r for option %s; use ' + '1/0, yes/no, true/false, on/off' % ( + string, optname)) + elif string.lower() in ('1', 'yes', 'true', 'on'): + return True + elif string.lower() in ('0', 'no', 'false', 'off'): + return False + else: + raise OptionError('Invalid value %r for option %s; use ' + '1/0, yes/no, true/false, on/off' % ( + string, optname)) + + +def get_int_opt(options, optname, default=None): + """As :func:`get_bool_opt`, but interpret the value as an integer.""" + string = options.get(optname, default) + try: + return int(string) + except TypeError: + raise OptionError('Invalid type %r for option %s; you ' + 'must give an integer value' % ( + string, optname)) + except ValueError: + raise OptionError('Invalid value %r for option %s; you ' + 'must give an integer value' % ( + string, optname)) + +def get_list_opt(options, optname, default=None): + """ + If the key `optname` from the dictionary `options` is a string, + split it at whitespace and return it. If it is already a list + or a tuple, it is returned as a list. + """ + val = options.get(optname, default) + if isinstance(val, str): + return val.split() + elif isinstance(val, (list, tuple)): + return list(val) + else: + raise OptionError('Invalid type %r for option %s; you ' + 'must give a list value' % ( + val, optname)) + + +def docstring_headline(obj): + if not obj.__doc__: + return '' + res = [] + for line in obj.__doc__.strip().splitlines(): + if line.strip(): + res.append(" " + line.strip()) + else: + break + return ''.join(res).lstrip() + + +def make_analysator(f): + """Return a static text analyser function that returns float values.""" + def text_analyse(text): + try: + rv = f(text) + except Exception: + return 0.0 + if not rv: + return 0.0 + try: + return min(1.0, max(0.0, float(rv))) + except (ValueError, TypeError): + return 0.0 + text_analyse.__doc__ = f.__doc__ + return staticmethod(text_analyse) + + +def shebang_matches(text, regex): + r"""Check if the given regular expression matches the last part of the + shebang if one exists. + + >>> from pygments.util import shebang_matches + >>> shebang_matches('#!/usr/bin/env python', r'python(2\.\d)?') + True + >>> shebang_matches('#!/usr/bin/python2.4', r'python(2\.\d)?') + True + >>> shebang_matches('#!/usr/bin/python-ruby', r'python(2\.\d)?') + False + >>> shebang_matches('#!/usr/bin/python/ruby', r'python(2\.\d)?') + False + >>> shebang_matches('#!/usr/bin/startsomethingwith python', + ... r'python(2\.\d)?') + True + + It also checks for common windows executable file extensions:: + + >>> shebang_matches('#!C:\\Python2.4\\Python.exe', r'python(2\.\d)?') + True + + Parameters (``'-f'`` or ``'--foo'`` are ignored so ``'perl'`` does + the same as ``'perl -e'``) + + Note that this method automatically searches the whole string (eg: + the regular expression is wrapped in ``'^$'``) + """ + index = text.find('\n') + if index >= 0: + first_line = text[:index].lower() + else: + first_line = text.lower() + if first_line.startswith('#!'): + try: + found = [x for x in split_path_re.split(first_line[2:].strip()) + if x and not x.startswith('-')][-1] + except IndexError: + return False + regex = re.compile(r'^%s(\.(exe|cmd|bat|bin))?$' % regex, re.IGNORECASE) + if regex.search(found) is not None: + return True + return False + + +def doctype_matches(text, regex): + """Check if the doctype matches a regular expression (if present). + + Note that this method only checks the first part of a DOCTYPE. + eg: 'html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"' + """ + m = doctype_lookup_re.search(text) + if m is None: + return False + doctype = m.group(1) + return re.compile(regex, re.I).match(doctype.strip()) is not None + + +def html_doctype_matches(text): + """Check if the file looks like it has a html doctype.""" + return doctype_matches(text, r'html') + + +_looks_like_xml_cache = {} + + +def looks_like_xml(text): + """Check if a doctype exists or if we have some tags.""" + if xml_decl_re.match(text): + return True + key = hash(text) + try: + return _looks_like_xml_cache[key] + except KeyError: + m = doctype_lookup_re.search(text) + if m is not None: + return True + rv = tag_re.search(text[:1000]) is not None + _looks_like_xml_cache[key] = rv + return rv + + +def surrogatepair(c): + """Given a unicode character code with length greater than 16 bits, + return the two 16 bit surrogate pair. + """ + # From example D28 of: + # http://www.unicode.org/book/ch03.pdf + return (0xd7c0 + (c >> 10), (0xdc00 + (c & 0x3ff))) + + +def format_lines(var_name, seq, raw=False, indent_level=0): + """Formats a sequence of strings for output.""" + lines = [] + base_indent = ' ' * indent_level * 4 + inner_indent = ' ' * (indent_level + 1) * 4 + lines.append(base_indent + var_name + ' = (') + if raw: + # These should be preformatted reprs of, say, tuples. + for i in seq: + lines.append(inner_indent + i + ',') + else: + for i in seq: + # Force use of single quotes + r = repr(i + '"') + lines.append(inner_indent + r[:-2] + r[-1] + ',') + lines.append(base_indent + ')') + return '\n'.join(lines) + + +def duplicates_removed(it, already_seen=()): + """ + Returns a list with duplicates removed from the iterable `it`. + + Order is preserved. + """ + lst = [] + seen = set() + for i in it: + if i in seen or i in already_seen: + continue + lst.append(i) + seen.add(i) + return lst + + +class Future: + """Generic class to defer some work. + + Handled specially in RegexLexerMeta, to support regex string construction at + first use. + """ + def get(self): + raise NotImplementedError + + +def guess_decode(text): + """Decode *text* with guessed encoding. + + First try UTF-8; this should fail for non-UTF-8 encodings. + Then try the preferred locale encoding. + Fall back to latin-1, which always works. + """ + try: + text = text.decode('utf-8') + return text, 'utf-8' + except UnicodeDecodeError: + try: + import locale + prefencoding = locale.getpreferredencoding() + text = text.decode() + return text, prefencoding + except (UnicodeDecodeError, LookupError): + text = text.decode('latin1') + return text, 'latin1' + + +def guess_decode_from_terminal(text, term): + """Decode *text* coming from terminal *term*. + + First try the terminal encoding, if given. + Then try UTF-8. Then try the preferred locale encoding. + Fall back to latin-1, which always works. + """ + if getattr(term, 'encoding', None): + try: + text = text.decode(term.encoding) + except UnicodeDecodeError: + pass + else: + return text, term.encoding + return guess_decode(text) + + +def terminal_encoding(term): + """Return our best guess of encoding for the given *term*.""" + if getattr(term, 'encoding', None): + return term.encoding + import locale + return locale.getpreferredencoding() + + +class UnclosingTextIOWrapper(TextIOWrapper): + # Don't close underlying buffer on destruction. + def close(self): + self.flush() diff --git a/shared/package-files/00/00463fe3819a889b13c931e466a1b6246895a053a9369301f786520f69c9f1f0/blob b/shared/package-files/00/00463fe3819a889b13c931e466a1b6246895a053a9369301f786520f69c9f1f0/blob new file mode 100644 index 0000000000000000000000000000000000000000..82f237a2de1b781cb7a69975fed157b615f09060 --- /dev/null +++ b/shared/package-files/00/00463fe3819a889b13c931e466a1b6246895a053a9369301f786520f69c9f1f0/blob @@ -0,0 +1,228 @@ +/* Adapted from CPython3.7 Objects/dict-common.h */ +#include "cext.h" + +#ifndef NUMBA_DICT_COMMON_H +#define NUMBA_DICT_COMMON_H + +typedef struct { + /* Uses Py_ssize_t instead of Py_hash_t to guarantee word size alignment */ + Py_ssize_t hash; + char keyvalue[]; +} NB_DictEntry; + + +typedef int (*dict_key_comparator_t)(const char *lhs, const char *rhs); +typedef void (*dict_refcount_op_t)(const void*); + + +typedef struct { + dict_key_comparator_t key_equal; + dict_refcount_op_t key_incref; + dict_refcount_op_t key_decref; + dict_refcount_op_t value_incref; + dict_refcount_op_t value_decref; +} type_based_methods_table; + + +typedef struct { + /* hash table size */ + Py_ssize_t size; + /* Usable size of the hash table. + Also, size of the entries */ + Py_ssize_t usable; + /* hash table used entries */ + Py_ssize_t nentries; + /* Entry info + - key_size is the sizeof key type + - val_size is the sizeof value type + - entry_size is key_size + val_size + alignment + */ + Py_ssize_t key_size, val_size, entry_size; + /* Byte offset from indices to the first entry. */ + Py_ssize_t entry_offset; + + /* Method table for type-dependent operations. */ + type_based_methods_table methods; + + /* hash table */ + char indices[]; +} NB_DictKeys; + + +typedef struct { + /* num of elements in the hashtable */ + Py_ssize_t used; + NB_DictKeys *keys; +} NB_Dict; + + +typedef struct { + /* parent dictionary */ + NB_Dict *parent; + /* parent keys object */ + NB_DictKeys *parent_keys; + /* dict size */ + Py_ssize_t size; + /* iterator position; indicates the next position to read */ + Py_ssize_t pos; +} NB_DictIter; + + + +/* A test function for the dict +Returns 0 for OK; 1 for failure. +*/ +NUMBA_EXPORT_FUNC(int) +numba_test_dict(void); + +/* Allocate a new dict +Parameters +- NB_Dict **out + Output for the new dictionary. +- Py_ssize_t size + Hashtable size. Must be power of two. +- Py_ssize_t key_size + Size of a key entry. +- Py_ssize_t val_size + Size of a value entry. +*/ +NUMBA_EXPORT_FUNC(int) +numba_dict_new(NB_Dict **out, Py_ssize_t size, Py_ssize_t key_size, Py_ssize_t val_size); + +/* Allocate a new dict with enough space to hold n_keys without resizing. +Parameters +- NB_Dict **out + Output for the new dictionary. +- Py_ssize_t n_keys + The number of keys to fit without needing resize. +- Py_ssize_t key_size + Size of a key entry. +- Py_ssize_t val_size + Size of a value entry. +*/ +NUMBA_EXPORT_FUNC(int) +numba_dict_new_sized(NB_Dict** out, Py_ssize_t n_keys, Py_ssize_t key_size, Py_ssize_t val_size); + +/* Free a dict */ +NUMBA_EXPORT_FUNC(void) +numba_dict_free(NB_Dict *d); + +/* Returns length of a dict */ +NUMBA_EXPORT_FUNC(Py_ssize_t) +numba_dict_length(NB_Dict *d); + +/* Set the method table for type specific operations +*/ +NUMBA_EXPORT_FUNC(void) +numba_dict_set_method_table(NB_Dict *d, type_based_methods_table *methods); + +/* Lookup a key + +Parameters +- NB_Dict *d + The dictionary object. +- const char *key_bytes + The key as a byte buffer. +- Py_hash_t hash + The precomputed hash of the key. +- char *oldval_bytes + An output parameter to store the associated value if the key is found. + Must point to memory of sufficient size to store the value. +*/ +NUMBA_EXPORT_FUNC(Py_ssize_t) +numba_dict_lookup(NB_Dict *d, const char *key_bytes, Py_hash_t hash, char *oldval_bytes); + +/* Resize the dict to at least *minsize*. +*/ +NUMBA_EXPORT_FUNC(int) +numba_dict_resize(NB_Dict *d, Py_ssize_t minsize); + +/* Insert to the dict + +Parameters +- NB_Dict *d + The dictionary object. +- const char *key_bytes + The key as a byte buffer. +- Py_hash_t hash + The precomputed hash of key. +- const char *val_bytes + The value as a byte buffer. +- char *oldval_bytes + An output buffer to store the replaced value. + Must point to memory of sufficient size to store the value. + +Returns +- < 0 for error +- 0 for ok +- 1 for ok and oldval_bytes has a copy of the replaced value. +*/ +NUMBA_EXPORT_FUNC(int) +numba_dict_insert(NB_Dict *d, const char *key_bytes, Py_hash_t hash, const char *val_bytes, char *oldval_bytes); + +/* Same as numba_dict_insert() but oldval_bytes is not needed */ +NUMBA_EXPORT_FUNC(int) +numba_dict_insert_ez(NB_Dict *d, const char *key_bytes, Py_hash_t hash, const char *val_bytes); + +/* Delete an entry from the dict +Parameters +- NB_Dict *d + The dictionary +- Py_hash_t hash + Precomputed hash of the key to be deleted +- Py_ssize_t ix + Precomputed entry index of the key to be deleted. + Usually results of numba_dict_lookup(). +*/ +NUMBA_EXPORT_FUNC(int) +numba_dict_delitem(NB_Dict *d, Py_hash_t hash, Py_ssize_t ix); + +/* Remove an item from the dict +Parameters +- NB_Dict *d + The dictionary +- char *key_bytes + Output. The key as a byte buffer +- char *val_bytes + Output. The value as a byte buffer +*/ +NUMBA_EXPORT_FUNC(int) +numba_dict_popitem(NB_Dict *d, char *key_bytes, char *val_bytes); + +/* Returns the sizeof a dictionary iterator +*/ +NUMBA_EXPORT_FUNC(size_t) +numba_dict_iter_sizeof(void); + +/* Fill a NB_DictIter for a dictionary to begin iteration +Parameters +- NB_DictIter *it + Output. Must points to memory of size at least `numba_dict_iter_sizeof()`. +- NB_Dict *d + The dictionary to be iterated. +*/ +NUMBA_EXPORT_FUNC(void) +numba_dict_iter(NB_DictIter *it, NB_Dict *d); + +/* Advance the iterator +Parameters +- NB_DictIter *it + The iterator +- const char **key_ptr + Output pointer for the key. Points to data in the dictionary. +- const char **val_ptr + Output pointer for the key. Points to data in the dictionary. + +Returns +- 0 for success; valid key_ptr and val_ptr +- ERR_ITER_EXHAUSTED for end of iterator. +- ERR_DICT_MUTATED for detected dictionary mutation. +*/ +NUMBA_EXPORT_FUNC(int) +numba_dict_iter_next(NB_DictIter *it, const char **key_ptr, const char **val_ptr); + + +NUMBA_EXPORT_FUNC(void) +numba_dict_dump(NB_Dict *); + +#endif diff --git a/shared/package-files/00/0047fd967fa3e4c988310d094d03e19d9c1b361f36ca749446c58f68a68d8a78/blob b/shared/package-files/00/0047fd967fa3e4c988310d094d03e19d9c1b361f36ca749446c58f68a68d8a78/blob new file mode 100644 index 0000000000000000000000000000000000000000..80d119a48530d4285e0009cb71e40b3cc0feb33b --- /dev/null +++ b/shared/package-files/00/0047fd967fa3e4c988310d094d03e19d9c1b361f36ca749446c58f68a68d8a78/blob @@ -0,0 +1,434 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. + +import datetime +import pytest + +import pyarrow as pa + + +@pytest.mark.gandiva +def test_tree_exp_builder(): + import pyarrow.gandiva as gandiva + + builder = gandiva.TreeExprBuilder() + + field_a = pa.field('a', pa.int32()) + field_b = pa.field('b', pa.int32()) + + schema = pa.schema([field_a, field_b]) + + field_result = pa.field('res', pa.int32()) + + node_a = builder.make_field(field_a) + node_b = builder.make_field(field_b) + + assert node_a.return_type() == field_a.type + + condition = builder.make_function("greater_than", [node_a, node_b], + pa.bool_()) + if_node = builder.make_if(condition, node_a, node_b, pa.int32()) + + expr = builder.make_expression(if_node, field_result) + + assert expr.result().type == pa.int32() + + config = gandiva.Configuration(dump_ir=True) + projector = gandiva.make_projector( + schema, [expr], pa.default_memory_pool(), "NONE", config) + + # Gandiva generates compute kernel function named `@expr_X` + assert projector.llvm_ir.find("@expr_") != -1 + + a = pa.array([10, 12, -20, 5], type=pa.int32()) + b = pa.array([5, 15, 15, 17], type=pa.int32()) + e = pa.array([10, 15, 15, 17], type=pa.int32()) + input_batch = pa.RecordBatch.from_arrays([a, b], names=['a', 'b']) + + r, = projector.evaluate(input_batch) + assert r.equals(e) + + +@pytest.mark.gandiva +def test_table(): + import pyarrow.gandiva as gandiva + + table = pa.Table.from_arrays([pa.array([1.0, 2.0]), pa.array([3.0, 4.0])], + ['a', 'b']) + + builder = gandiva.TreeExprBuilder() + node_a = builder.make_field(table.schema.field("a")) + node_b = builder.make_field(table.schema.field("b")) + + sum = builder.make_function("add", [node_a, node_b], pa.float64()) + + field_result = pa.field("c", pa.float64()) + expr = builder.make_expression(sum, field_result) + + projector = gandiva.make_projector( + table.schema, [expr], pa.default_memory_pool()) + + # TODO: Add .evaluate function which can take Tables instead of + # RecordBatches + r, = projector.evaluate(table.to_batches()[0]) + + e = pa.array([4.0, 6.0]) + assert r.equals(e) + + +@pytest.mark.gandiva +def test_filter(): + import pyarrow.gandiva as gandiva + + table = pa.Table.from_arrays([pa.array([1.0 * i for i in range(10000)])], + ['a']) + + builder = gandiva.TreeExprBuilder() + node_a = builder.make_field(table.schema.field("a")) + thousand = builder.make_literal(1000.0, pa.float64()) + cond = builder.make_function("less_than", [node_a, thousand], pa.bool_()) + condition = builder.make_condition(cond) + + assert condition.result().type == pa.bool_() + + config = gandiva.Configuration(dump_ir=True) + filter = gandiva.make_filter(table.schema, condition, config) + # Gandiva generates compute kernel function named `@expr_X` + assert filter.llvm_ir.find("@expr_") != -1 + + result = filter.evaluate(table.to_batches()[0], pa.default_memory_pool()) + assert result.to_array().equals(pa.array(range(1000), type=pa.uint32())) + + +@pytest.mark.gandiva +def test_in_expr(): + import pyarrow.gandiva as gandiva + + arr = pa.array(["ga", "an", "nd", "di", "iv", "va"]) + table = pa.Table.from_arrays([arr], ["a"]) + + # string + builder = gandiva.TreeExprBuilder() + node_a = builder.make_field(table.schema.field("a")) + cond = builder.make_in_expression(node_a, ["an", "nd"], pa.string()) + condition = builder.make_condition(cond) + filter = gandiva.make_filter(table.schema, condition) + result = filter.evaluate(table.to_batches()[0], pa.default_memory_pool()) + assert result.to_array().equals(pa.array([1, 2], type=pa.uint32())) + + # int32 + arr = pa.array([3, 1, 4, 1, 5, 9, 2, 6, 5, 4]) + table = pa.Table.from_arrays([arr.cast(pa.int32())], ["a"]) + node_a = builder.make_field(table.schema.field("a")) + cond = builder.make_in_expression(node_a, [1, 5], pa.int32()) + condition = builder.make_condition(cond) + filter = gandiva.make_filter(table.schema, condition) + result = filter.evaluate(table.to_batches()[0], pa.default_memory_pool()) + assert result.to_array().equals(pa.array([1, 3, 4, 8], type=pa.uint32())) + + # int64 + arr = pa.array([3, 1, 4, 1, 5, 9, 2, 6, 5, 4]) + table = pa.Table.from_arrays([arr], ["a"]) + node_a = builder.make_field(table.schema.field("a")) + cond = builder.make_in_expression(node_a, [1, 5], pa.int64()) + condition = builder.make_condition(cond) + filter = gandiva.make_filter(table.schema, condition) + result = filter.evaluate(table.to_batches()[0], pa.default_memory_pool()) + assert result.to_array().equals(pa.array([1, 3, 4, 8], type=pa.uint32())) + + +@pytest.mark.skip(reason="Gandiva C++ did not have *real* binary, " + "time and date support.") +def test_in_expr_todo(): + import pyarrow.gandiva as gandiva + # TODO: Implement reasonable support for timestamp, time & date. + # Current exceptions: + # pyarrow.lib.ArrowException: ExpressionValidationError: + # Evaluation expression for IN clause returns XXXX values are of typeXXXX + + # binary + arr = pa.array([b"ga", b"an", b"nd", b"di", b"iv", b"va"]) + table = pa.Table.from_arrays([arr], ["a"]) + + builder = gandiva.TreeExprBuilder() + node_a = builder.make_field(table.schema.field("a")) + cond = builder.make_in_expression(node_a, [b'an', b'nd'], pa.binary()) + condition = builder.make_condition(cond) + + filter = gandiva.make_filter(table.schema, condition) + result = filter.evaluate(table.to_batches()[0], pa.default_memory_pool()) + assert result.to_array().equals(pa.array([1, 2], type=pa.uint32())) + + # timestamp + datetime_1 = datetime.datetime.utcfromtimestamp(1542238951.621877) + datetime_2 = datetime.datetime.utcfromtimestamp(1542238911.621877) + datetime_3 = datetime.datetime.utcfromtimestamp(1542238051.621877) + + arr = pa.array([datetime_1, datetime_2, datetime_3]) + table = pa.Table.from_arrays([arr], ["a"]) + + builder = gandiva.TreeExprBuilder() + node_a = builder.make_field(table.schema.field("a")) + cond = builder.make_in_expression(node_a, [datetime_2], pa.timestamp('ms')) + condition = builder.make_condition(cond) + + filter = gandiva.make_filter(table.schema, condition) + result = filter.evaluate(table.to_batches()[0], pa.default_memory_pool()) + assert list(result.to_array()) == [1] + + # time + time_1 = datetime_1.time() + time_2 = datetime_2.time() + time_3 = datetime_3.time() + + arr = pa.array([time_1, time_2, time_3]) + table = pa.Table.from_arrays([arr], ["a"]) + + builder = gandiva.TreeExprBuilder() + node_a = builder.make_field(table.schema.field("a")) + cond = builder.make_in_expression(node_a, [time_2], pa.time64('ms')) + condition = builder.make_condition(cond) + + filter = gandiva.make_filter(table.schema, condition) + result = filter.evaluate(table.to_batches()[0], pa.default_memory_pool()) + assert list(result.to_array()) == [1] + + # date + date_1 = datetime_1.date() + date_2 = datetime_2.date() + date_3 = datetime_3.date() + + arr = pa.array([date_1, date_2, date_3]) + table = pa.Table.from_arrays([arr], ["a"]) + + builder = gandiva.TreeExprBuilder() + node_a = builder.make_field(table.schema.field("a")) + cond = builder.make_in_expression(node_a, [date_2], pa.date32()) + condition = builder.make_condition(cond) + + filter = gandiva.make_filter(table.schema, condition) + result = filter.evaluate(table.to_batches()[0], pa.default_memory_pool()) + assert list(result.to_array()) == [1] + + +@pytest.mark.gandiva +def test_boolean(): + import pyarrow.gandiva as gandiva + + table = pa.Table.from_arrays([ + pa.array([1., 31., 46., 3., 57., 44., 22.]), + pa.array([5., 45., 36., 73., 83., 23., 76.])], + ['a', 'b']) + + builder = gandiva.TreeExprBuilder() + node_a = builder.make_field(table.schema.field("a")) + node_b = builder.make_field(table.schema.field("b")) + fifty = builder.make_literal(50.0, pa.float64()) + eleven = builder.make_literal(11.0, pa.float64()) + + cond_1 = builder.make_function("less_than", [node_a, fifty], pa.bool_()) + cond_2 = builder.make_function("greater_than", [node_a, node_b], + pa.bool_()) + cond_3 = builder.make_function("less_than", [node_b, eleven], pa.bool_()) + cond = builder.make_or([builder.make_and([cond_1, cond_2]), cond_3]) + condition = builder.make_condition(cond) + + filter = gandiva.make_filter(table.schema, condition) + result = filter.evaluate(table.to_batches()[0], pa.default_memory_pool()) + assert result.to_array().equals(pa.array([0, 2, 5], type=pa.uint32())) + + +@pytest.mark.gandiva +def test_literals(): + import pyarrow.gandiva as gandiva + + builder = gandiva.TreeExprBuilder() + + builder.make_literal(True, pa.bool_()) + builder.make_literal(0, pa.uint8()) + builder.make_literal(1, pa.uint16()) + builder.make_literal(2, pa.uint32()) + builder.make_literal(3, pa.uint64()) + builder.make_literal(4, pa.int8()) + builder.make_literal(5, pa.int16()) + builder.make_literal(6, pa.int32()) + builder.make_literal(7, pa.int64()) + builder.make_literal(8.0, pa.float32()) + builder.make_literal(9.0, pa.float64()) + builder.make_literal("hello", pa.string()) + builder.make_literal(b"world", pa.binary()) + + builder.make_literal(True, "bool") + builder.make_literal(0, "uint8") + builder.make_literal(1, "uint16") + builder.make_literal(2, "uint32") + builder.make_literal(3, "uint64") + builder.make_literal(4, "int8") + builder.make_literal(5, "int16") + builder.make_literal(6, "int32") + builder.make_literal(7, "int64") + builder.make_literal(8.0, "float32") + builder.make_literal(9.0, "float64") + builder.make_literal("hello", "string") + builder.make_literal(b"world", "binary") + + with pytest.raises(TypeError): + builder.make_literal("hello", pa.int64()) + with pytest.raises(TypeError): + builder.make_literal(True, None) + + +@pytest.mark.gandiva +def test_regex(): + import pyarrow.gandiva as gandiva + + elements = ["park", "sparkle", "bright spark and fire", "spark"] + data = pa.array(elements, type=pa.string()) + table = pa.Table.from_arrays([data], names=['a']) + + builder = gandiva.TreeExprBuilder() + node_a = builder.make_field(table.schema.field("a")) + regex = builder.make_literal("%spark%", pa.string()) + like = builder.make_function("like", [node_a, regex], pa.bool_()) + + field_result = pa.field("b", pa.bool_()) + expr = builder.make_expression(like, field_result) + + projector = gandiva.make_projector( + table.schema, [expr], pa.default_memory_pool()) + + r, = projector.evaluate(table.to_batches()[0]) + b = pa.array([False, True, True, True], type=pa.bool_()) + assert r.equals(b) + + +@pytest.mark.gandiva +def test_get_registered_function_signatures(): + import pyarrow.gandiva as gandiva + signatures = gandiva.get_registered_function_signatures() + + assert type(signatures[0].return_type()) is pa.DataType + assert type(signatures[0].param_types()) is list + assert hasattr(signatures[0], "name") + + +@pytest.mark.gandiva +def test_filter_project(): + import pyarrow.gandiva as gandiva + mpool = pa.default_memory_pool() + # Create a table with some sample data + array0 = pa.array([10, 12, -20, 5, 21, 29], pa.int32()) + array1 = pa.array([5, 15, 15, 17, 12, 3], pa.int32()) + array2 = pa.array([1, 25, 11, 30, -21, None], pa.int32()) + + table = pa.Table.from_arrays([array0, array1, array2], ['a', 'b', 'c']) + + field_result = pa.field("res", pa.int32()) + + builder = gandiva.TreeExprBuilder() + node_a = builder.make_field(table.schema.field("a")) + node_b = builder.make_field(table.schema.field("b")) + node_c = builder.make_field(table.schema.field("c")) + + greater_than_function = builder.make_function("greater_than", + [node_a, node_b], pa.bool_()) + filter_condition = builder.make_condition( + greater_than_function) + + project_condition = builder.make_function("less_than", + [node_b, node_c], pa.bool_()) + if_node = builder.make_if(project_condition, + node_b, node_c, pa.int32()) + expr = builder.make_expression(if_node, field_result) + + # Build a filter for the expressions. + filter = gandiva.make_filter(table.schema, filter_condition) + + # Build a projector for the expressions. + projector = gandiva.make_projector( + table.schema, [expr], mpool, "UINT32") + + # Evaluate filter + selection_vector = filter.evaluate(table.to_batches()[0], mpool) + + # Evaluate project + r, = projector.evaluate( + table.to_batches()[0], selection_vector) + + exp = pa.array([1, -21, None], pa.int32()) + assert r.equals(exp) + + +@pytest.mark.gandiva +def test_to_string(): + import pyarrow.gandiva as gandiva + builder = gandiva.TreeExprBuilder() + + assert str(builder.make_literal(2.0, pa.float64()) + ).startswith('(const double) 2 raw(') + assert str(builder.make_literal(2, pa.int64())) == '(const int64) 2' + assert str(builder.make_field(pa.field('x', pa.float64()))) == '(double) x' + assert str(builder.make_field(pa.field('y', pa.string()))) == '(string) y' + + field_z = builder.make_field(pa.field('z', pa.bool_())) + func_node = builder.make_function('not', [field_z], pa.bool_()) + assert str(func_node) == 'bool not((bool) z)' + + field_y = builder.make_field(pa.field('y', pa.bool_())) + and_node = builder.make_and([func_node, field_y]) + assert str(and_node) == 'bool not((bool) z) && (bool) y' + + +@pytest.mark.gandiva +def test_rejects_none(): + import pyarrow.gandiva as gandiva + + builder = gandiva.TreeExprBuilder() + + field_x = pa.field('x', pa.int32()) + schema = pa.schema([field_x]) + literal_true = builder.make_literal(True, pa.bool_()) + + with pytest.raises(TypeError): + builder.make_field(None) + + with pytest.raises(TypeError): + builder.make_if(literal_true, None, None, None) + + with pytest.raises(TypeError): + builder.make_and([literal_true, None]) + + with pytest.raises(TypeError): + builder.make_or([None, literal_true]) + + with pytest.raises(TypeError): + builder.make_in_expression(None, [1, 2, 3], pa.int32()) + + with pytest.raises(TypeError): + builder.make_expression(None, field_x) + + with pytest.raises(TypeError): + builder.make_condition(None) + + with pytest.raises(TypeError): + builder.make_function('less_than', [literal_true, None], pa.bool_()) + + with pytest.raises(TypeError): + gandiva.make_projector(schema, [None]) + + with pytest.raises(TypeError): + gandiva.make_filter(schema, None) diff --git a/shared/package-files/00/004ee94fea0838b1b92b372c5e2b12f832662b273d321a2910be2c135afa92f9/blob b/shared/package-files/00/004ee94fea0838b1b92b372c5e2b12f832662b273d321a2910be2c135afa92f9/blob new file mode 100644 index 0000000000000000000000000000000000000000..861984a21e1c436ef738c71b96fb1b4534f61583 --- /dev/null +++ b/shared/package-files/00/004ee94fea0838b1b92b372c5e2b12f832662b273d321a2910be2c135afa92f9/blob @@ -0,0 +1,21 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates + +from .core import MaskedTensor + +__all__ = [ + "as_masked_tensor", + "masked_tensor", +] + + +"""" +These two factory functions are intended to mirror + torch.tensor - guaranteed to be a leaf node + torch.as_tensor - differentiable constructor that preserves the autograd history +""" + +def masked_tensor(data, mask, requires_grad=False): + return MaskedTensor(data, mask, requires_grad) + +def as_masked_tensor(data, mask): + return MaskedTensor._from_values(data, mask) diff --git a/shared/package-files/00/00595c205d02a130f617f8f98b500778e149cefc849fb678c30d9ac5d4f40f71/blob b/shared/package-files/00/00595c205d02a130f617f8f98b500778e149cefc849fb678c30d9ac5d4f40f71/blob new file mode 100644 index 0000000000000000000000000000000000000000..27abbb0e61ad509230582c8b57c84e3a9edc2025 --- /dev/null +++ b/shared/package-files/00/00595c205d02a130f617f8f98b500778e149cefc849fb678c30d9ac5d4f40f71/blob @@ -0,0 +1,104 @@ +import pytest + +import networkx as nx + + +class TestAverageNeighbor: + def test_degree_p4(self): + G = nx.path_graph(4) + answer = {0: 2, 1: 1.5, 2: 1.5, 3: 2} + nd = nx.average_neighbor_degree(G) + assert nd == answer + + D = G.to_directed() + nd = nx.average_neighbor_degree(D) + assert nd == answer + + D = nx.DiGraph(G.edges(data=True)) + nd = nx.average_neighbor_degree(D) + assert nd == {0: 1, 1: 1, 2: 0, 3: 0} + nd = nx.average_neighbor_degree(D, "in", "out") + assert nd == {0: 0, 1: 1, 2: 1, 3: 1} + nd = nx.average_neighbor_degree(D, "out", "in") + assert nd == {0: 1, 1: 1, 2: 1, 3: 0} + nd = nx.average_neighbor_degree(D, "in", "in") + assert nd == {0: 0, 1: 0, 2: 1, 3: 1} + + def test_degree_p4_weighted(self): + G = nx.path_graph(4) + G[1][2]["weight"] = 4 + answer = {0: 2, 1: 1.8, 2: 1.8, 3: 2} + nd = nx.average_neighbor_degree(G, weight="weight") + assert nd == answer + + D = G.to_directed() + nd = nx.average_neighbor_degree(D, weight="weight") + assert nd == answer + + D = nx.DiGraph(G.edges(data=True)) + print(D.edges(data=True)) + nd = nx.average_neighbor_degree(D, weight="weight") + assert nd == {0: 1, 1: 1, 2: 0, 3: 0} + nd = nx.average_neighbor_degree(D, "out", "out", weight="weight") + assert nd == {0: 1, 1: 1, 2: 0, 3: 0} + nd = nx.average_neighbor_degree(D, "in", "in", weight="weight") + assert nd == {0: 0, 1: 0, 2: 1, 3: 1} + nd = nx.average_neighbor_degree(D, "in", "out", weight="weight") + assert nd == {0: 0, 1: 1, 2: 1, 3: 1} + nd = nx.average_neighbor_degree(D, "out", "in", weight="weight") + assert nd == {0: 1, 1: 1, 2: 1, 3: 0} + + D = G.to_directed() + nd = nx.average_neighbor_degree(D, weight="weight") + assert nd == answer + nd = nx.average_neighbor_degree(D, source="out", target="out", weight="weight") + assert nd == answer + + D = G.to_directed() + nd = nx.average_neighbor_degree(D, source="in", target="in", weight="weight") + assert nd == answer + + def test_degree_k4(self): + G = nx.complete_graph(4) + answer = {0: 3, 1: 3, 2: 3, 3: 3} + nd = nx.average_neighbor_degree(G) + assert nd == answer + + D = G.to_directed() + nd = nx.average_neighbor_degree(D) + assert nd == answer + + D = G.to_directed() + nd = nx.average_neighbor_degree(D) + assert nd == answer + + D = G.to_directed() + nd = nx.average_neighbor_degree(D, source="in", target="in") + assert nd == answer + + def test_degree_k4_nodes(self): + G = nx.complete_graph(4) + answer = {1: 3.0, 2: 3.0} + nd = nx.average_neighbor_degree(G, nodes=[1, 2]) + assert nd == answer + + def test_degree_barrat(self): + G = nx.star_graph(5) + G.add_edges_from([(5, 6), (5, 7), (5, 8), (5, 9)]) + G[0][5]["weight"] = 5 + nd = nx.average_neighbor_degree(G)[5] + assert nd == 1.8 + nd = nx.average_neighbor_degree(G, weight="weight")[5] + assert nd == pytest.approx(3.222222, abs=1e-5) + + def test_error_invalid_source_target(self): + G = nx.path_graph(4) + with pytest.raises(nx.NetworkXError): + nx.average_neighbor_degree(G, "error") + with pytest.raises(nx.NetworkXError): + nx.average_neighbor_degree(G, "in", "error") + G = G.to_directed() + with pytest.raises(nx.NetworkXError): + nx.average_neighbor_degree(G, "error") + with pytest.raises(nx.NetworkXError): + nx.average_neighbor_degree(G, "in", "error") diff --git a/shared/package-files/00/00599b73d4a67e0a505743c3f61097ba4b5109190dbc31794b567bcf7d44db11/blob b/shared/package-files/00/00599b73d4a67e0a505743c3f61097ba4b5109190dbc31794b567bcf7d44db11/blob new file mode 100644 index 0000000000000000000000000000000000000000..d0b9d96cafa0db15203cb3057517571a178b25db --- /dev/null +++ b/shared/package-files/00/00599b73d4a67e0a505743c3f61097ba4b5109190dbc31794b567bcf7d44db11/blob @@ -0,0 +1,85 @@ +import numpy as np + +from pandas import ( + DataFrame, + date_range, +) +import pandas._testing as tm + + +class TestEquals: + def test_dataframe_not_equal(self): + # see GH#28839 + df1 = DataFrame({"a": [1, 2], "b": ["s", "d"]}) + df2 = DataFrame({"a": ["s", "d"], "b": [1, 2]}) + assert df1.equals(df2) is False + + def test_equals_different_blocks(self, using_array_manager, using_infer_string): + # GH#9330 + df0 = DataFrame({"A": ["x", "y"], "B": [1, 2], "C": ["w", "z"]}) + df1 = df0.reset_index()[["A", "B", "C"]] + if not using_array_manager and not using_infer_string: + # this assert verifies that the above operations have + # induced a block rearrangement + assert df0._mgr.blocks[0].dtype != df1._mgr.blocks[0].dtype + + # do the real tests + tm.assert_frame_equal(df0, df1) + assert df0.equals(df1) + assert df1.equals(df0) + + def test_equals(self): + # Add object dtype column with nans + index = np.random.default_rng(2).random(10) + df1 = DataFrame( + np.random.default_rng(2).random(10), index=index, columns=["floats"] + ) + df1["text"] = "the sky is so blue. we could use more chocolate.".split() + df1["start"] = date_range("2000-1-1", periods=10, freq="min") + df1["end"] = date_range("2000-1-1", periods=10, freq="D") + df1["diff"] = df1["end"] - df1["start"] + # Explicitly cast to object, to avoid implicit cast when setting np.nan + df1["bool"] = (np.arange(10) % 3 == 0).astype(object) + df1.loc[::2] = np.nan + df2 = df1.copy() + assert df1["text"].equals(df2["text"]) + assert df1["start"].equals(df2["start"]) + assert df1["end"].equals(df2["end"]) + assert df1["diff"].equals(df2["diff"]) + assert df1["bool"].equals(df2["bool"]) + assert df1.equals(df2) + assert not df1.equals(object) + + # different dtype + different = df1.copy() + different["floats"] = different["floats"].astype("float32") + assert not df1.equals(different) + + # different index + different_index = -index + different = df2.set_index(different_index) + assert not df1.equals(different) + + # different columns + different = df2.copy() + different.columns = df2.columns[::-1] + assert not df1.equals(different) + + # DatetimeIndex + index = date_range("2000-1-1", periods=10, freq="min") + df1 = df1.set_index(index) + df2 = df1.copy() + assert df1.equals(df2) + + # MultiIndex + df3 = df1.set_index(["text"], append=True) + df2 = df1.set_index(["text"], append=True) + assert df3.equals(df2) + + df2 = df1.set_index(["floats"], append=True) + assert not df3.equals(df2) + + # NaN in index + df3 = df1.set_index(["floats"], append=True) + df2 = df1.set_index(["floats"], append=True) + assert df3.equals(df2) diff --git a/shared/package-files/00/0060dbf4b6a0e180e9e33d2c0120e7f9ac20fa61d3882e7349a21958775ec7f8/blob b/shared/package-files/00/0060dbf4b6a0e180e9e33d2c0120e7f9ac20fa61d3882e7349a21958775ec7f8/blob new file mode 100644 index 0000000000000000000000000000000000000000..c8d1125641da24227830042c5fa010460c47440f --- /dev/null +++ b/shared/package-files/00/0060dbf4b6a0e180e9e33d2c0120e7f9ac20fa61d3882e7349a21958775ec7f8/blob @@ -0,0 +1,22 @@ +#pragma once + +// @generated by torchgen/gen.py from NativeFunction.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + +namespace at { +namespace native { +TORCH_API at::Tensor relu6(const at::Tensor & self); +TORCH_API at::Tensor & relu6_(at::Tensor & self); +} // namespace native +} // namespace at diff --git a/shared/package-files/00/0063fed96e58e85fa8878f6acdd4a75b947f82e6018d06d17411858b1bea968e/blob b/shared/package-files/00/0063fed96e58e85fa8878f6acdd4a75b947f82e6018d06d17411858b1bea968e/blob new file mode 100644 index 0000000000000000000000000000000000000000..40ec377f29f8723501238f2794ca670abbe28a46 --- /dev/null +++ b/shared/package-files/00/0063fed96e58e85fa8878f6acdd4a75b947f82e6018d06d17411858b1bea968e/blob @@ -0,0 +1,50 @@ +#pragma once + +// @generated by torchgen/gen.py from Operator.h + +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { +namespace _ops { + + +struct TORCH_API scatter_reduce_two { + using schema = at::Tensor (const at::Tensor &, int64_t, const at::Tensor &, const at::Tensor &, c10::string_view, bool); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::scatter_reduce") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "two") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "scatter_reduce.two(Tensor self, int dim, Tensor index, Tensor src, str reduce, *, bool include_self=True) -> Tensor") + static at::Tensor call(const at::Tensor & self, int64_t dim, const at::Tensor & index, const at::Tensor & src, c10::string_view reduce, bool include_self); + static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, int64_t dim, const at::Tensor & index, const at::Tensor & src, c10::string_view reduce, bool include_self); +}; + +struct TORCH_API scatter_reduce__two { + using schema = at::Tensor & (at::Tensor &, int64_t, const at::Tensor &, const at::Tensor &, c10::string_view, bool); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::scatter_reduce_") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "two") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "scatter_reduce_.two(Tensor(a!) self, int dim, Tensor index, Tensor src, str reduce, *, bool include_self=True) -> Tensor(a!)") + static at::Tensor & call(at::Tensor & self, int64_t dim, const at::Tensor & index, const at::Tensor & src, c10::string_view reduce, bool include_self); + static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, at::Tensor & self, int64_t dim, const at::Tensor & index, const at::Tensor & src, c10::string_view reduce, bool include_self); +}; + +struct TORCH_API scatter_reduce_two_out { + using schema = at::Tensor & (const at::Tensor &, int64_t, const at::Tensor &, const at::Tensor &, c10::string_view, 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::scatter_reduce") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "two_out") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "scatter_reduce.two_out(Tensor self, int dim, Tensor index, Tensor src, str reduce, *, bool include_self=True, Tensor(a!) out) -> Tensor(a!)") + static at::Tensor & call(const at::Tensor & self, int64_t dim, const at::Tensor & index, const at::Tensor & src, c10::string_view reduce, bool include_self, at::Tensor & out); + static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, int64_t dim, const at::Tensor & index, const at::Tensor & src, c10::string_view reduce, bool include_self, at::Tensor & out); +}; + +}} // namespace at::_ops diff --git a/shared/package-files/00/006942ebd5efa62509d8a788b3de96a2880017919d405bf8f1cd41527391e2d9/blob b/shared/package-files/00/006942ebd5efa62509d8a788b3de96a2880017919d405bf8f1cd41527391e2d9/blob new file mode 100644 index 0000000000000000000000000000000000000000..4e0de99f5e7e37bb92643ad29f3c859c689d4918 --- /dev/null +++ b/shared/package-files/00/006942ebd5efa62509d8a788b3de96a2880017919d405bf8f1cd41527391e2d9/blob @@ -0,0 +1,42 @@ +"""The k-nearest neighbors algorithms.""" + +# Authors: The scikit-learn developers +# SPDX-License-Identifier: BSD-3-Clause + +from ._ball_tree import BallTree +from ._base import VALID_METRICS, VALID_METRICS_SPARSE, sort_graph_by_row_values +from ._classification import KNeighborsClassifier, RadiusNeighborsClassifier +from ._graph import ( + KNeighborsTransformer, + RadiusNeighborsTransformer, + kneighbors_graph, + radius_neighbors_graph, +) +from ._kd_tree import KDTree +from ._kde import KernelDensity +from ._lof import LocalOutlierFactor +from ._nca import NeighborhoodComponentsAnalysis +from ._nearest_centroid import NearestCentroid +from ._regression import KNeighborsRegressor, RadiusNeighborsRegressor +from ._unsupervised import NearestNeighbors + +__all__ = [ + "VALID_METRICS", + "VALID_METRICS_SPARSE", + "BallTree", + "KDTree", + "KNeighborsClassifier", + "KNeighborsRegressor", + "KNeighborsTransformer", + "KernelDensity", + "LocalOutlierFactor", + "NearestCentroid", + "NearestNeighbors", + "NeighborhoodComponentsAnalysis", + "RadiusNeighborsClassifier", + "RadiusNeighborsRegressor", + "RadiusNeighborsTransformer", + "kneighbors_graph", + "radius_neighbors_graph", + "sort_graph_by_row_values", +] diff --git a/shared/package-files/00/006d3a694562d4bb7fdc50f26e67a97d55937270221dff7328a0803d0b011074/blob b/shared/package-files/00/006d3a694562d4bb7fdc50f26e67a97d55937270221dff7328a0803d0b011074/blob new file mode 100644 index 0000000000000000000000000000000000000000..7eedd1498c94be9d09922cd33c0191ae5bb354d0 --- /dev/null +++ b/shared/package-files/00/006d3a694562d4bb7fdc50f26e67a97d55937270221dff7328a0803d0b011074/blob @@ -0,0 +1,231 @@ +import math +import operator +import traceback +from functools import partial +from typing import Callable, Dict, List, NamedTuple, Set + +import sympy + +import torch +import torch.fx +from torch._export.pass_base import _ExportPassBaseDeprecatedDoNotUse, ProxyValue, PassResult +from torch.utils._sympy.value_ranges import ValueRanges +from torch.fx.experimental.symbolic_shapes import free_unbacked_symbols + + +__all__ = ["InputDim"] + + +class InputDim(NamedTuple): + input_name: str + dim: int + + +def _convert_to_int(val): + # Convert simple sympy Integers into concrete int + if val == sympy.oo: + return math.inf + if val == -sympy.oo: + return -math.inf + if isinstance(val, sympy.Integer): + return int(val) + raise RuntimeError( + "Export constraints cannot be non-integer expressions" + ) + + +def _convert_range_to_int(range: ValueRanges): + assert isinstance(range, ValueRanges) + min_val = _convert_to_int(range.lower) + max_val = _convert_to_int(range.upper) + return min_val, max_val + + +class _AddRuntimeAssertionsForInlineConstraintsPass(_ExportPassBaseDeprecatedDoNotUse): + def __init__( + self, + range_constraints: Dict[sympy.Symbol, ValueRanges], + ): + super().__init__() + self.range_constraints: Dict[sympy.Symbol, ValueRanges] = range_constraints + self._asserts_generated_unbacked_symbols: Set[sympy.Symbol] = set() + self.counter = 0 + + def _assert_range_constraint(self, proxy, lower, upper, assert_msg): + if lower > -math.inf: + self._insert_assert_async(operator.ge, proxy, lower, assert_msg) + + if upper < math.inf: + self._insert_assert_async(operator.le, proxy, upper, assert_msg) + + def _insert_assert_async(self, operator, lower, upper, assert_msg): + """ + Inserts assert_async call_function nodes in the graph. This function is + called **during** the interpreter-based pass. + """ + self.counter += 1 + cmp = super().call_operator(operator, (lower, upper), {}, self._create_dummy_node_metadata()) + cmp_tensor = super().call_operator(torch.ops.aten.scalar_tensor.default, (cmp,), {}, self._create_dummy_node_metadata()) + super().call_operator( + torch.ops.aten._assert_async.msg, + (cmp_tensor, assert_msg), + {}, + self._create_dummy_node_metadata(), + ) + + def call_operator(self, op, args, kwargs, meta) -> ProxyValue: + ret = super().call_operator(op, args, kwargs, meta) + if "val" not in meta: + return ret + + val = meta["val"] + + # In general, we may have to deal the case such as: ret[1].shape[0]. + # We need first find out what symbols require assertion, then we need to follow the path + # from ret to the symbol, construct the proxies along the way and construct the messages + # piece-wise at the same time. + # + # We use post-order traversal to collect all the proxies callbacks needed, construct + # the error message callbacks, and at the top-level traversal tree we execute all the callbacks. + # We need the callbacks because, in order to call the function to create a proxy for shape[0], we + # need the proxy for shape, which further requires the proxy for ret[1], etc. + def add_assertions(val): + call_backs: List[Callable] = [] + messages: List[str] = [] + if isinstance(val, (torch.SymInt, torch.SymFloat, torch.SymBool)): + symbol = val.node.expr + if symbol in self.existing_inline_assertions: + return call_backs, messages + if isinstance(symbol, sympy.Symbol) and free_unbacked_symbols(symbol): + if symbol in self._asserts_generated_unbacked_symbols: + return call_backs, messages + # We only care about unbacked symints for these inline + # constraints, which are prefixed with 'u' + constraint = self.range_constraints[symbol] + min_val, max_val = _convert_range_to_int(constraint) + assert_msg = f" is outside of inline constraint [{min_val}, {max_val}]." + call_backs.append( + partial(self._assert_range_constraint, lower=min_val, upper=max_val) + ) + messages.append(assert_msg) + self._asserts_generated_unbacked_symbols.add(symbol) + + elif isinstance(val, torch.Tensor): + for i, sym in enumerate(val.shape): + cbs, msgs = add_assertions(sym) + for cb, msg in zip(cbs, msgs): + def sym_size_cb(proxy, assert_msg, dim): + dim_proxy = super( + _AddRuntimeAssertionsForInlineConstraintsPass, + self + ).call_operator( + torch.ops.aten.sym_size.int, + (proxy, dim), + {}, + self._create_dummy_node_metadata(), + ) + cb(proxy=dim_proxy, assert_msg=assert_msg) + call_backs.append(partial(sym_size_cb, dim=i)) + messages.append(f".shape[{i}]" + msg) + return call_backs, messages + + callbacks, messages = add_assertions(val) + for cb, msg in zip(callbacks, messages): + cb(proxy=ret, assert_msg=f"{ret.node}" + msg) + return ret + + def call(self, graph_module): + self.existing_inline_assertions = _get_existing_inline_assertions( + graph_module, self.range_constraints + ) + + # Add runtime asserts for inline constraints + val = super().call(graph_module) + + # Sometimes this pass would return a wrong graph where we have mismatched + # node names in signature. Before we fix it, let's just skip it. + if self.counter == 0 and type(self) is _AddRuntimeAssertionsForInlineConstraintsPass: + return PassResult(graph_module, False) + + # Populate the stack trace with dummy vals to respect IR + for node in val.graph_module.graph.nodes: + if not node.meta.get("stack_trace", None): + node.meta["stack_trace"] = "".join(traceback.format_stack(limit=1)) + + return PassResult(val.graph_module, val.modified) + + +def _get_existing_inline_assertions( + graph_module: torch.fx.GraphModule, + range_constraints: Dict[sympy.Symbol, ValueRanges], +) -> Dict[sympy.Symbol, ValueRanges]: + existing_inline_assertions: Dict[sympy.Symbol, ValueRanges] = {} + + for module in graph_module.modules(): + if not isinstance(module, torch.fx.GraphModule): + continue + + # Find all the existing inline assertions. They will look something like: + # %_local_scalar_dense = call_function[target=torch.ops.aten._local_scalar_dense.default](args = (%arg1_1,), kwargs = {}) + # %ge = call_function[target=operator.ge](args = (%_local_scalar_dense, 0), kwargs = {}) + # %scalar_tensor = call_function[target=torch.ops.aten.scalar_tensor.default](args = (%ge,), kwargs = {}) + # %_assert_async = call_function[target=torch.ops.aten._assert_async.msg](args = (%scalar_tensor, "..."), kwargs = {}) + for node in module.graph.nodes: + if node.target != torch.ops.aten._assert_async.msg: + continue + + scalar_tensor_arg = node.args[0] + if not ( + scalar_tensor_arg.op == "call_function" and + scalar_tensor_arg.target == torch.ops.aten.scalar_tensor.default + ): + continue + + compare_arg = scalar_tensor_arg.args[0] + if not ( + compare_arg.op == "call_function" and + compare_arg.target in (operator.le, operator.ge) and + len(compare_arg.args) == 2 + ): + continue + + compare_op = compare_arg.target + maybe_symint_arg, compare_int = compare_arg.args + + # x >= 0 will sometimes be canonicalized to -x <= 0, so in some + # cases the operation before the comparison is to multiply by -1. We + # can undo the canonicalization here + if ( + maybe_symint_arg.op == "call_function" and + maybe_symint_arg.target == operator.mul and + maybe_symint_arg.args[0] == -1 + ): + maybe_symint_arg = maybe_symint_arg.args[1] + compare_op = operator.ge + compare_int = -1 * compare_int + + if not ( + "val" in maybe_symint_arg.meta and + isinstance(maybe_symint_arg.meta["val"], torch.SymInt) + ): + continue + + symint = maybe_symint_arg.meta["val"].node.expr + if not isinstance(symint, sympy.Symbol): + continue + + if symint not in range_constraints: + raise RuntimeError(f"Unable to find symint {symint} in {range_constraints}") + + found_range = existing_inline_assertions.get(symint, ValueRanges(-math.inf, math.inf)) + + if compare_arg.target == operator.le: + existing_inline_assertions[symint] = ValueRanges( + lower=found_range.lower, upper=compare_int + ) + elif compare_arg.target == operator.ge: + existing_inline_assertions[symint] = ValueRanges( + lower=compare_int, upper=found_range.upper + ) + + return existing_inline_assertions diff --git a/shared/package-files/00/006e4ddaad8ae86e219508336081d540eb437d60b514d215f76a64ba973b1b73/blob b/shared/package-files/00/006e4ddaad8ae86e219508336081d540eb437d60b514d215f76a64ba973b1b73/blob new file mode 100644 index 0000000000000000000000000000000000000000..16e5d746cfc413a539b18244f3c23633ca97403f --- /dev/null +++ b/shared/package-files/00/006e4ddaad8ae86e219508336081d540eb437d60b514d215f76a64ba973b1b73/blob @@ -0,0 +1,974 @@ +# -*- 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. + +"""\ + +The :class:`set` type brings the practical expressiveness of +set theory to Python. It has a very rich API overall, but lacks a +couple of fundamental features. For one, sets are not ordered. On top +of this, sets are not indexable, i.e, ``my_set[8]`` will raise an +:exc:`TypeError`. The :class:`IndexedSet` type remedies both of these +issues without compromising on the excellent complexity +characteristics of Python's built-in set implementation. +""" + +from __future__ import print_function + +from bisect import bisect_left +from itertools import chain, islice +import operator + +try: + from collections.abc import MutableSet +except ImportError: + from collections import MutableSet + +try: + from typeutils import make_sentinel + _MISSING = make_sentinel(var_name='_MISSING') +except ImportError: + _MISSING = object() + + +__all__ = ['IndexedSet', 'complement'] + + +_COMPACTION_FACTOR = 8 + +# TODO: inherit from set() +# TODO: .discard_many(), .remove_many() +# TODO: raise exception on non-set params? +# TODO: technically reverse operators should probably reverse the +# order of the 'other' inputs and put self last (to try and maintain +# insertion order) + + +class IndexedSet(MutableSet): + """``IndexedSet`` is a :class:`collections.MutableSet` that maintains + insertion order and uniqueness of inserted elements. It's a hybrid + type, mostly like an OrderedSet, but also :class:`list`-like, in + that it supports indexing and slicing. + + Args: + other (iterable): An optional iterable used to initialize the set. + + >>> x = IndexedSet(list(range(4)) + list(range(8))) + >>> x + IndexedSet([0, 1, 2, 3, 4, 5, 6, 7]) + >>> x - set(range(2)) + IndexedSet([2, 3, 4, 5, 6, 7]) + >>> x[-1] + 7 + >>> fcr = IndexedSet('freecreditreport.com') + >>> ''.join(fcr[:fcr.index('.')]) + 'frecditpo' + + Standard set operators and interoperation with :class:`set` are + all supported: + + >>> fcr & set('cash4gold.com') + IndexedSet(['c', 'd', 'o', '.', 'm']) + + As you can see, the ``IndexedSet`` is almost like a ``UniqueList``, + retaining only one copy of a given value, in the order it was + first added. For the curious, the reason why IndexedSet does not + support setting items based on index (i.e, ``__setitem__()``), + consider the following dilemma:: + + my_indexed_set = [A, B, C, D] + my_indexed_set[2] = A + + At this point, a set requires only one *A*, but a :class:`list` would + overwrite *C*. Overwriting *C* would change the length of the list, + meaning that ``my_indexed_set[2]`` would not be *A*, as expected with a + list, but rather *D*. So, no ``__setitem__()``. + + Otherwise, the API strives to be as complete a union of the + :class:`list` and :class:`set` APIs as possible. + """ + def __init__(self, other=None): + self.item_index_map = dict() + self.item_list = [] + self.dead_indices = [] + self._compactions = 0 + self._c_max_size = 0 + if other: + self.update(other) + + # internal functions + @property + def _dead_index_count(self): + return len(self.item_list) - len(self.item_index_map) + + def _compact(self): + if not self.dead_indices: + return + self._compactions += 1 + dead_index_count = self._dead_index_count + items, index_map = self.item_list, self.item_index_map + self._c_max_size = max(self._c_max_size, len(items)) + for i, item in enumerate(self): + items[i] = item + index_map[item] = i + del items[-dead_index_count:] + del self.dead_indices[:] + + def _cull(self): + ded = self.dead_indices + if not ded: + return + items, ii_map = self.item_list, self.item_index_map + if not ii_map: + del items[:] + del ded[:] + elif len(ded) > 384: + self._compact() + elif self._dead_index_count > (len(items) / _COMPACTION_FACTOR): + self._compact() + elif items[-1] is _MISSING: # get rid of dead right hand side + num_dead = 1 + while items[-(num_dead + 1)] is _MISSING: + num_dead += 1 + if ded and ded[-1][1] == len(items): + del ded[-1] + del items[-num_dead:] + + def _get_real_index(self, index): + if index < 0: + index += len(self) + if not self.dead_indices: + return index + real_index = index + for d_start, d_stop in self.dead_indices: + if real_index < d_start: + break + real_index += d_stop - d_start + return real_index + + def _get_apparent_index(self, index): + if index < 0: + index += len(self) + if not self.dead_indices: + return index + apparent_index = index + for d_start, d_stop in self.dead_indices: + if index < d_start: + break + apparent_index -= d_stop - d_start + return apparent_index + + def _add_dead(self, start, stop=None): + # TODO: does not handle when the new interval subsumes + # multiple existing intervals + dints = self.dead_indices + if stop is None: + stop = start + 1 + cand_int = [start, stop] + if not dints: + dints.append(cand_int) + return + int_idx = bisect_left(dints, cand_int) + dint = dints[int_idx - 1] + d_start, d_stop = dint + if start <= d_start <= stop: + dint[0] = start + elif start <= d_stop <= stop: + dint[1] = stop + else: + dints.insert(int_idx, cand_int) + return + + # common operations (shared by set and list) + def __len__(self): + return len(self.item_index_map) + + def __contains__(self, item): + return item in self.item_index_map + + def __iter__(self): + return (item for item in self.item_list if item is not _MISSING) + + def __reversed__(self): + item_list = self.item_list + return (item for item in reversed(item_list) if item is not _MISSING) + + def __repr__(self): + return '%s(%r)' % (self.__class__.__name__, list(self)) + + def __eq__(self, other): + if isinstance(other, IndexedSet): + return len(self) == len(other) and list(self) == list(other) + return set(self) == set(other) + + @classmethod + def from_iterable(cls, it): + "from_iterable(it) -> create a set from an iterable" + return cls(it) + + # set operations + def add(self, item): + "add(item) -> add item to the set" + if item not in self.item_index_map: + self.item_index_map[item] = len(self.item_list) + self.item_list.append(item) + + def remove(self, item): + "remove(item) -> remove item from the set, raises if not present" + try: + didx = self.item_index_map.pop(item) + except KeyError: + raise KeyError(item) + self.item_list[didx] = _MISSING + self._add_dead(didx) + self._cull() + + def discard(self, item): + "discard(item) -> discard item from the set (does not raise)" + try: + self.remove(item) + except KeyError: + pass + + def clear(self): + "clear() -> empty the set" + del self.item_list[:] + del self.dead_indices[:] + self.item_index_map.clear() + + def isdisjoint(self, other): + "isdisjoint(other) -> return True if no overlap with other" + iim = self.item_index_map + for k in other: + if k in iim: + return False + return True + + def issubset(self, other): + "issubset(other) -> return True if other contains this set" + if len(other) < len(self): + return False + for k in self.item_index_map: + if k not in other: + return False + return True + + def issuperset(self, other): + "issuperset(other) -> return True if set contains other" + if len(other) > len(self): + return False + iim = self.item_index_map + for k in other: + if k not in iim: + return False + return True + + def union(self, *others): + "union(*others) -> return a new set containing this set and others" + return self.from_iterable(chain(self, *others)) + + def iter_intersection(self, *others): + "iter_intersection(*others) -> iterate over elements also in others" + for k in self: + for other in others: + if k not in other: + break + else: + yield k + return + + def intersection(self, *others): + "intersection(*others) -> get a set with overlap of this and others" + if len(others) == 1: + other = others[0] + return self.from_iterable(k for k in self if k in other) + return self.from_iterable(self.iter_intersection(*others)) + + def iter_difference(self, *others): + "iter_difference(*others) -> iterate over elements not in others" + for k in self: + for other in others: + if k in other: + break + else: + yield k + return + + def difference(self, *others): + "difference(*others) -> get a new set with elements not in others" + if len(others) == 1: + other = others[0] + return self.from_iterable(k for k in self if k not in other) + return self.from_iterable(self.iter_difference(*others)) + + def symmetric_difference(self, *others): + "symmetric_difference(*others) -> XOR set of this and others" + ret = self.union(*others) + return ret.difference(self.intersection(*others)) + + __or__ = __ror__ = union + __and__ = __rand__ = intersection + __sub__ = difference + __xor__ = __rxor__ = symmetric_difference + + def __rsub__(self, other): + vals = [x for x in other if x not in self] + return type(other)(vals) + + # in-place set operations + def update(self, *others): + "update(*others) -> add values from one or more iterables" + if not others: + return # raise? + elif len(others) == 1: + other = others[0] + else: + other = chain(others) + for o in other: + self.add(o) + + def intersection_update(self, *others): + "intersection_update(*others) -> discard self.difference(*others)" + for val in self.difference(*others): + self.discard(val) + + def difference_update(self, *others): + "difference_update(*others) -> discard self.intersection(*others)" + if self in others: + self.clear() + for val in self.intersection(*others): + self.discard(val) + + def symmetric_difference_update(self, other): # note singular 'other' + "symmetric_difference_update(other) -> in-place XOR with other" + if self is other: + self.clear() + for val in other: + if val in self: + self.discard(val) + else: + self.add(val) + + def __ior__(self, *others): + self.update(*others) + return self + + def __iand__(self, *others): + self.intersection_update(*others) + return self + + def __isub__(self, *others): + self.difference_update(*others) + return self + + def __ixor__(self, *others): + self.symmetric_difference_update(*others) + return self + + def iter_slice(self, start, stop, step=None): + "iterate over a slice of the set" + iterable = self + if start is not None: + start = self._get_real_index(start) + if stop is not None: + stop = self._get_real_index(stop) + if step is not None and step < 0: + step = -step + iterable = reversed(self) + return islice(iterable, start, stop, step) + + # list operations + def __getitem__(self, index): + try: + start, stop, step = index.start, index.stop, index.step + except AttributeError: + index = operator.index(index) + else: + iter_slice = self.iter_slice(start, stop, step) + return self.from_iterable(iter_slice) + if index < 0: + index += len(self) + real_index = self._get_real_index(index) + try: + ret = self.item_list[real_index] + except IndexError: + raise IndexError('IndexedSet index out of range') + return ret + + def pop(self, index=None): + "pop(index) -> remove the item at a given index (-1 by default)" + item_index_map = self.item_index_map + len_self = len(item_index_map) + if index is None or index == -1 or index == len_self - 1: + ret = self.item_list.pop() + del item_index_map[ret] + else: + real_index = self._get_real_index(index) + ret = self.item_list[real_index] + self.item_list[real_index] = _MISSING + del item_index_map[ret] + self._add_dead(real_index) + self._cull() + return ret + + def count(self, val): + "count(val) -> count number of instances of value (0 or 1)" + if val in self.item_index_map: + return 1 + return 0 + + def reverse(self): + "reverse() -> reverse the contents of the set in-place" + reversed_list = list(reversed(self)) + self.item_list[:] = reversed_list + for i, item in enumerate(self.item_list): + self.item_index_map[item] = i + del self.dead_indices[:] + + def sort(self, **kwargs): + "sort() -> sort the contents of the set in-place" + sorted_list = sorted(self, **kwargs) + if sorted_list == self.item_list: + return + self.item_list[:] = sorted_list + for i, item in enumerate(self.item_list): + self.item_index_map[item] = i + del self.dead_indices[:] + + def index(self, val): + "index(val) -> get the index of a value, raises if not present" + try: + return self._get_apparent_index(self.item_index_map[val]) + except KeyError: + cn = self.__class__.__name__ + raise ValueError('%r is not in %s' % (val, cn)) + + +def complement(wrapped): + """Given a :class:`set`, convert it to a **complement set**. + + Whereas a :class:`set` keeps track of what it contains, a + `complement set + `_ keeps + track of what it does *not* contain. For example, look what + happens when we intersect a normal set with a complement set:: + + >>> list(set(range(5)) & complement(set([2, 3]))) + [0, 1, 4] + + We get the everything in the left that wasn't in the right, + because intersecting with a complement is the same as subtracting + a normal set. + + Args: + wrapped (set): A set or any other iterable which should be + turned into a complement set. + + All set methods and operators are supported by complement sets, + between other :func:`complement`-wrapped sets and/or regular + :class:`set` objects. + + Because a complement set only tracks what elements are *not* in + the set, functionality based on set contents is unavailable: + :func:`len`, :func:`iter` (and for loops), and ``.pop()``. But a + complement set can always be turned back into a regular set by + complementing it again: + + >>> s = set(range(5)) + >>> complement(complement(s)) == s + True + + .. note:: + + An empty complement set corresponds to the concept of a + `universal set `_ + from mathematics. + + Complement sets by example + ^^^^^^^^^^^^^^^^^^^^^^^^^^ + + Many uses of sets can be expressed more simply by using a + complement. Rather than trying to work out in your head the proper + way to invert an expression, you can just throw a complement on + the set. Consider this example of a name filter:: + + >>> class NamesFilter(object): + ... def __init__(self, allowed): + ... self._allowed = allowed + ... + ... def filter(self, names): + ... return [name for name in names if name in self._allowed] + >>> NamesFilter(set(['alice', 'bob'])).filter(['alice', 'bob', 'carol']) + ['alice', 'bob'] + + What if we want to just express "let all the names through"? + + We could try to enumerate all of the expected names:: + + ``NamesFilter({'alice', 'bob', 'carol'})`` + + But this is very brittle -- what if at some point over this + object is changed to filter ``['alice', 'bob', 'carol', 'dan']``? + + Even worse, what about the poor programmer who next works + on this piece of code? They cannot tell whether the purpose + of the large allowed set was "allow everything", or if 'dan' + was excluded for some subtle reason. + + A complement set lets the programmer intention be expressed + succinctly and directly:: + + NamesFilter(complement(set())) + + Not only is this code short and robust, it is easy to understand + the intention. + + """ + if type(wrapped) is _ComplementSet: + return wrapped.complemented() + if type(wrapped) is frozenset: + return _ComplementSet(excluded=wrapped) + return _ComplementSet(excluded=set(wrapped)) + + +def _norm_args_typeerror(other): + '''normalize args and raise type-error if there is a problem''' + if type(other) in (set, frozenset): + inc, exc = other, None + elif type(other) is _ComplementSet: + inc, exc = other._included, other._excluded + else: + raise TypeError('argument must be another set or complement(set)') + return inc, exc + + +def _norm_args_notimplemented(other): + '''normalize args and return NotImplemented (for overloaded operators)''' + if type(other) in (set, frozenset): + inc, exc = other, None + elif type(other) is _ComplementSet: + inc, exc = other._included, other._excluded + else: + return NotImplemented, None + return inc, exc + + +class _ComplementSet(object): + """ + helper class for complement() that implements the set methods + """ + __slots__ = ('_included', '_excluded') + + def __init__(self, included=None, excluded=None): + if included is None: + assert type(excluded) in (set, frozenset) + elif excluded is None: + assert type(included) in (set, frozenset) + else: + raise ValueError('one of included or excluded must be a set') + self._included, self._excluded = included, excluded + + def __repr__(self): + if self._included is None: + return 'complement({0})'.format(repr(self._excluded)) + return 'complement(complement({0}))'.format(repr(self._included)) + + def complemented(self): + '''return a complement of the current set''' + if type(self._included) is frozenset or type(self._excluded) is frozenset: + return _ComplementSet(included=self._excluded, excluded=self._included) + return _ComplementSet( + included=None if self._excluded is None else set(self._excluded), + excluded=None if self._included is None else set(self._included)) + + __invert__ = complemented + + def complement(self): + '''convert the current set to its complement in-place''' + self._included, self._excluded = self._excluded, self._included + + def __contains__(self, item): + if self._included is None: + return not item in self._excluded + return item in self._included + + def add(self, item): + if self._included is None: + if item in self._excluded: + self._excluded.remove(item) + else: + self._included.add(item) + + def remove(self, item): + if self._included is None: + self._excluded.add(item) + else: + self._included.remove(item) + + def pop(self): + if self._included is None: + raise NotImplementedError # self.missing.add(random.choice(gc.objects())) + return self._included.pop() + + def intersection(self, other): + try: + return self & other + except NotImplementedError: + raise TypeError('argument must be another set or complement(set)') + + def __and__(self, other): + inc, exc = _norm_args_notimplemented(other) + if inc is NotImplemented: + return NotImplemented + if self._included is None: + if exc is None: # - + + return _ComplementSet(included=inc - self._excluded) + else: # - - + return _ComplementSet(excluded=self._excluded.union(other._excluded)) + else: + if inc is None: # + - + return _ComplementSet(included=exc - self._included) + else: # + + + return _ComplementSet(included=self._included.intersection(inc)) + + __rand__ = __and__ + + def __iand__(self, other): + inc, exc = _norm_args_notimplemented(other) + if inc is NotImplemented: + return NotImplemented + if self._included is None: + if exc is None: # - + + self._excluded = inc - self._excluded # TODO: do this in place? + else: # - - + self._excluded |= exc + else: + if inc is None: # + - + self._included -= exc + self._included, self._excluded = None, self._included + else: # + + + self._included &= inc + return self + + def union(self, other): + try: + return self | other + except NotImplementedError: + raise TypeError('argument must be another set or complement(set)') + + def __or__(self, other): + inc, exc = _norm_args_notimplemented(other) + if inc is NotImplemented: + return NotImplemented + if self._included is None: + if exc is None: # - + + return _ComplementSet(excluded=self._excluded - inc) + else: # - - + return _ComplementSet(excluded=self._excluded.intersection(exc)) + else: + if inc is None: # + - + return _ComplementSet(excluded=exc - self._included) + else: # + + + return _ComplementSet(included=self._included.union(inc)) + + __ror__ = __or__ + + def __ior__(self, other): + inc, exc = _norm_args_notimplemented(other) + if inc is NotImplemented: + return NotImplemented + if self._included is None: + if exc is None: # - + + self._excluded -= inc + else: # - - + self._excluded &= exc + else: + if inc is None: # + - + self._included, self._excluded = None, exc - self._included # TODO: do this in place? + else: # + + + self._included |= inc + return self + + def update(self, items): + if type(items) in (set, frozenset): + inc, exc = items, None + elif type(items) is _ComplementSet: + inc, exc = items._included, items._excluded + else: + inc, exc = frozenset(items), None + if self._included is None: + if exc is None: # - + + self._excluded &= inc + else: # - - + self._excluded.discard(exc) + else: + if inc is None: # + - + self._included &= exc + self._included, self._excluded = None, self._excluded + else: # + + + self._included.update(inc) + + def discard(self, items): + if type(items) in (set, frozenset): + inc, exc = items, None + elif type(items) is _ComplementSet: + inc, exc = items._included, items._excluded + else: + inc, exc = frozenset(items), None + if self._included is None: + if exc is None: # - + + self._excluded.update(inc) + else: # - - + self._included, self._excluded = exc - self._excluded, None + else: + if inc is None: # + - + self._included &= exc + else: # + + + self._included.discard(inc) + + def symmetric_difference(self, other): + try: + return self ^ other + except NotImplementedError: + raise TypeError('argument must be another set or complement(set)') + + def __xor__(self, other): + inc, exc = _norm_args_notimplemented(other) + if inc is NotImplemented: + return NotImplemented + if inc is NotImplemented: + return NotImplemented + if self._included is None: + if exc is None: # - + + return _ComplementSet(excluded=self._excluded - inc) + else: # - - + return _ComplementSet(included=self._excluded.symmetric_difference(exc)) + else: + if inc is None: # + - + return _ComplementSet(excluded=exc - self._included) + else: # + + + return _ComplementSet(included=self._included.symmetric_difference(inc)) + + __rxor__ = __xor__ + + def symmetric_difference_update(self, other): + inc, exc = _norm_args_typeerror(other) + if self._included is None: + if exc is None: # - + + self._excluded |= inc + else: # - - + self._excluded.symmetric_difference_update(exc) + self._included, self._excluded = self._excluded, None + else: + if inc is None: # + - + self._included |= exc + self._included, self._excluded = None, self._included + else: # + + + self._included.symmetric_difference_update(inc) + + def isdisjoint(self, other): + inc, exc = _norm_args_typeerror(other) + if inc is NotImplemented: + return NotImplemented + if self._included is None: + if exc is None: # - + + return inc.issubset(self._excluded) + else: # - - + return False + else: + if inc is None: # + - + return self._included.issubset(exc) + else: # + + + return self._included.isdisjoint(inc) + + def issubset(self, other): + '''everything missing from other is also missing from self''' + try: + return self <= other + except NotImplementedError: + raise TypeError('argument must be another set or complement(set)') + + def __le__(self, other): + inc, exc = _norm_args_notimplemented(other) + if inc is NotImplemented: + return NotImplemented + if inc is NotImplemented: + return NotImplemented + if self._included is None: + if exc is None: # - + + return False + else: # - - + return self._excluded.issupserset(exc) + else: + if inc is None: # + - + return self._included.isdisjoint(exc) + else: # + + + return self._included.issubset(inc) + + def __lt__(self, other): + inc, exc = _norm_args_notimplemented(other) + if inc is NotImplemented: + return NotImplemented + if inc is NotImplemented: + return NotImplemented + if self._included is None: + if exc is None: # - + + return False + else: # - - + return self._excluded > exc + else: + if inc is None: # + - + return self._included.isdisjoint(exc) + else: # + + + return self._included < inc + + def issuperset(self, other): + '''everything missing from self is also missing from super''' + try: + return self >= other + except NotImplementedError: + raise TypeError('argument must be another set or complement(set)') + + def __ge__(self, other): + inc, exc = _norm_args_notimplemented(other) + if inc is NotImplemented: + return NotImplemented + if self._included is None: + if exc is None: # - + + return not self._excluded.intersection(inc) + else: # - - + return self._excluded.issubset(exc) + else: + if inc is None: # + - + return False + else: # + + + return self._included.issupserset(inc) + + def __gt__(self, other): + inc, exc = _norm_args_notimplemented(other) + if inc is NotImplemented: + return NotImplemented + if self._included is None: + if exc is None: # - + + return not self._excluded.intersection(inc) + else: # - - + return self._excluded < exc + else: + if inc is None: # + - + return False + else: # + + + return self._included > inc + + def difference(self, other): + try: + return self - other + except NotImplementedError: + raise TypeError('argument must be another set or complement(set)') + + def __sub__(self, other): + inc, exc = _norm_args_notimplemented(other) + if inc is NotImplemented: + return NotImplemented + if self._included is None: + if exc is None: # - + + return _ComplementSet(excluded=self._excluded | inc) + else: # - - + return _ComplementSet(included=exc - self._excluded) + else: + if inc is None: # + - + return _ComplementSet(included=self._included & exc) + else: # + + + return _ComplementSet(included=self._included.difference(inc)) + + def __rsub__(self, other): + inc, exc = _norm_args_notimplemented(other) + if inc is NotImplemented: + return NotImplemented + # rsub, so the expression being evaluated is "other - self" + if self._included is None: + if exc is None: # - + + return _ComplementSet(included=inc & self._excluded) + else: # - - + return _ComplementSet(included=self._excluded - exc) + else: + if inc is None: # + - + return _ComplementSet(excluded=exc | self._included) + else: # + + + return _ComplementSet(included=inc.difference(self._included)) + + def difference_update(self, other): + try: + self -= other + except NotImplementedError: + raise TypeError('argument must be another set or complement(set)') + + def __isub__(self, other): + inc, exc = _norm_args_notimplemented(other) + if inc is NotImplemented: + return NotImplemented + if self._included is None: + if exc is None: # - + + self._excluded |= inc + else: # - - + self._included, self._excluded = exc - self._excluded, None + else: + if inc is None: # + - + self._included &= exc + else: # + + + self._included.difference_update(inc) + return self + + def __eq__(self, other): + return ( + type(self) is type(other) + and self._included == other._included + and self._excluded == other._excluded) or ( + type(other) in (set, frozenset) and self._included == other) + + def __hash__(self): + return hash(self._included) ^ hash(self._excluded) + + def __len__(self): + if self._included is not None: + return len(self._included) + raise NotImplementedError('complemented sets have undefined length') + + def __iter__(self): + if self._included is not None: + return iter(self._included) + raise NotImplementedError('complemented sets have undefined contents') + + def __bool__(self): + if self._included is not None: + return bool(self._included) + return True + + __nonzero__ = __bool__ # py2 compat diff --git a/shared/package-files/00/006fc7f4bc50db6692f9823d09a03031dc6f3881feb24da82d3ee690ea645382/blob b/shared/package-files/00/006fc7f4bc50db6692f9823d09a03031dc6f3881feb24da82d3ee690ea645382/blob new file mode 100644 index 0000000000000000000000000000000000000000..ff00aaa2c54ea729e7115e4febd79b130801ac2a --- /dev/null +++ b/shared/package-files/00/006fc7f4bc50db6692f9823d09a03031dc6f3881feb24da82d3ee690ea645382/blob @@ -0,0 +1,26 @@ +#pragma once +// @generated by torchgen/gen.py from DispatchKeyFunction.h + +// NB: The implementing C++ file is RegisterDispatchKey.cpp + +// The only #includes we need are for custom classes that have defaults in the C++ API +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { + +namespace cuda { + +TORCH_API at::Tensor sqrt(const at::Tensor & self); +TORCH_API at::Tensor & sqrt_out(at::Tensor & out, const at::Tensor & self); +TORCH_API at::Tensor & sqrt_outf(const at::Tensor & self, at::Tensor & out); +TORCH_API at::Tensor & sqrt_(at::Tensor & self); + +} // namespace cuda +} // namespace at diff --git a/shared/package-files/00/00747ae5e774dcd581ea82bc6284d062ddc08029347cc935efd351704e567e64/blob b/shared/package-files/00/00747ae5e774dcd581ea82bc6284d062ddc08029347cc935efd351704e567e64/blob new file mode 100644 index 0000000000000000000000000000000000000000..87dd3481ec8b23259c5b2c4f209e75bb31aca5da --- /dev/null +++ b/shared/package-files/00/00747ae5e774dcd581ea82bc6284d062ddc08029347cc935efd351704e567e64/blob @@ -0,0 +1,79 @@ +from abc import ABCMeta, abstractmethod +from typing import Optional + +from cryptography.hazmat.backends.interfaces import DHBackend +from cryptography.hazmat.primitives.serialization import ( + Encoding, + KeySerializationEncryption, + ParameterFormat, + PrivateFormat, + PublicFormat, +) + +class DHParameters(metaclass=ABCMeta): + @abstractmethod + def generate_private_key(self) -> DHPrivateKey: ... + @abstractmethod + def parameter_bytes(self, encoding: Encoding, format: ParameterFormat) -> bytes: ... + @abstractmethod + def parameter_numbers(self) -> DHParameterNumbers: ... + +DHParametersWithSerialization = DHParameters + +class DHParameterNumbers(object): + @property + def p(self) -> int: ... + @property + def g(self) -> int: ... + @property + def q(self) -> int: ... + def __init__(self, p: int, g: int, q: Optional[int]) -> None: ... + def parameters(self, backend: Optional[DHBackend] = ...) -> DHParameters: ... + +class DHPrivateKey(metaclass=ABCMeta): + key_size: int + @abstractmethod + def exchange(self, peer_public_key: DHPublicKey) -> bytes: ... + @abstractmethod + def parameters(self) -> DHParameters: ... + @abstractmethod + def public_key(self) -> DHPublicKey: ... + +class DHPrivateKeyWithSerialization(DHPrivateKey): + @abstractmethod + def private_bytes( + self, encoding: Encoding, format: PrivateFormat, encryption_algorithm: KeySerializationEncryption + ) -> bytes: ... + @abstractmethod + def private_numbers(self) -> DHPrivateNumbers: ... + +class DHPrivateNumbers(object): + @property + def public_numbers(self) -> DHPublicNumbers: ... + @property + def x(self) -> int: ... + def __init__(self, x: int, public_numbers: DHPublicNumbers) -> None: ... + def private_key(self, backend: Optional[DHBackend] = ...) -> DHPrivateKey: ... + +class DHPublicKey(metaclass=ABCMeta): + @property + @abstractmethod + def key_size(self) -> int: ... + @abstractmethod + def parameters(self) -> DHParameters: ... + @abstractmethod + def public_bytes(self, encoding: Encoding, format: PublicFormat) -> bytes: ... + @abstractmethod + def public_numbers(self) -> DHPublicNumbers: ... + +DHPublicKeyWithSerialization = DHPublicKey + +class DHPublicNumbers(object): + @property + def parameter_numbers(self) -> DHParameterNumbers: ... + @property + def y(self) -> int: ... + def __init__(self, y: int, parameter_numbers: DHParameterNumbers) -> None: ... + def public_key(self, backend: Optional[DHBackend] = ...) -> DHPublicKey: ... + +def generate_parameters(generator: int, key_size: int, backend: Optional[DHBackend] = ...) -> DHParameters: ... diff --git a/shared/package-files/00/0074a85fc2e4588b7b4469490e693ae290ef996aba18287e0fb5f0136977f360/blob b/shared/package-files/00/0074a85fc2e4588b7b4469490e693ae290ef996aba18287e0fb5f0136977f360/blob new file mode 100644 index 0000000000000000000000000000000000000000..669d6e86ef482b43e05c2d31220421b4b3d80c15 --- /dev/null +++ b/shared/package-files/00/0074a85fc2e4588b7b4469490e693ae290ef996aba18287e0fb5f0136977f360/blob @@ -0,0 +1,146 @@ +from ._optical_flow import FlyingChairs, FlyingThings3D, HD1K, KittiFlow, Sintel +from ._stereo_matching import ( + CarlaStereo, + CREStereo, + ETH3DStereo, + FallingThingsStereo, + InStereo2k, + Kitti2012Stereo, + Kitti2015Stereo, + Middlebury2014Stereo, + SceneFlowStereo, + SintelStereo, +) +from .caltech import Caltech101, Caltech256 +from .celeba import CelebA +from .cifar import CIFAR10, CIFAR100 +from .cityscapes import Cityscapes +from .clevr import CLEVRClassification +from .coco import CocoCaptions, CocoDetection +from .country211 import Country211 +from .dtd import DTD +from .eurosat import EuroSAT +from .fakedata import FakeData +from .fer2013 import FER2013 +from .fgvc_aircraft import FGVCAircraft +from .flickr import Flickr30k, Flickr8k +from .flowers102 import Flowers102 +from .folder import DatasetFolder, ImageFolder +from .food101 import Food101 +from .gtsrb import GTSRB +from .hmdb51 import HMDB51 +from .imagenet import ImageNet +from .imagenette import Imagenette +from .inaturalist import INaturalist +from .kinetics import Kinetics +from .kitti import Kitti +from .lfw import LFWPairs, LFWPeople +from .lsun import LSUN, LSUNClass +from .mnist import EMNIST, FashionMNIST, KMNIST, MNIST, QMNIST +from .moving_mnist import MovingMNIST +from .omniglot import Omniglot +from .oxford_iiit_pet import OxfordIIITPet +from .pcam import PCAM +from .phototour import PhotoTour +from .places365 import Places365 +from .rendered_sst2 import RenderedSST2 +from .sbd import SBDataset +from .sbu import SBU +from .semeion import SEMEION +from .stanford_cars import StanfordCars +from .stl10 import STL10 +from .sun397 import SUN397 +from .svhn import SVHN +from .ucf101 import UCF101 +from .usps import USPS +from .vision import VisionDataset +from .voc import VOCDetection, VOCSegmentation +from .widerface import WIDERFace + +__all__ = ( + "LSUN", + "LSUNClass", + "ImageFolder", + "DatasetFolder", + "FakeData", + "CocoCaptions", + "CocoDetection", + "CIFAR10", + "CIFAR100", + "EMNIST", + "FashionMNIST", + "QMNIST", + "MNIST", + "KMNIST", + "StanfordCars", + "STL10", + "SUN397", + "SVHN", + "PhotoTour", + "SEMEION", + "Omniglot", + "SBU", + "Flickr8k", + "Flickr30k", + "Flowers102", + "VOCSegmentation", + "VOCDetection", + "Cityscapes", + "ImageNet", + "Caltech101", + "Caltech256", + "CelebA", + "WIDERFace", + "SBDataset", + "VisionDataset", + "USPS", + "Kinetics", + "HMDB51", + "UCF101", + "Places365", + "Kitti", + "INaturalist", + "LFWPeople", + "LFWPairs", + "KittiFlow", + "Sintel", + "FlyingChairs", + "FlyingThings3D", + "HD1K", + "Food101", + "DTD", + "FER2013", + "GTSRB", + "CLEVRClassification", + "OxfordIIITPet", + "PCAM", + "Country211", + "FGVCAircraft", + "EuroSAT", + "RenderedSST2", + "Kitti2012Stereo", + "Kitti2015Stereo", + "CarlaStereo", + "Middlebury2014Stereo", + "CREStereo", + "FallingThingsStereo", + "SceneFlowStereo", + "SintelStereo", + "InStereo2k", + "ETH3DStereo", + "wrap_dataset_for_transforms_v2", + "Imagenette", +) + + +# We override current module's attributes to handle the import: +# from torchvision.datasets import wrap_dataset_for_transforms_v2 +# without a cyclic error. +# Ref: https://peps.python.org/pep-0562/ +def __getattr__(name): + if name in ("wrap_dataset_for_transforms_v2",): + from torchvision.tv_tensors._dataset_wrapper import wrap_dataset_for_transforms_v2 + + return wrap_dataset_for_transforms_v2 + + raise AttributeError(f"module {__name__!r} has no attribute {name!r}") diff --git a/shared/package-files/00/0076fa231bdbcf039b03630c36c86000136ac8ccf3e41aa6080b9e8bbb993e0b/blob b/shared/package-files/00/0076fa231bdbcf039b03630c36c86000136ac8ccf3e41aa6080b9e8bbb993e0b/blob new file mode 100644 index 0000000000000000000000000000000000000000..486d41c5bd3a153f9f914fc2b5f7a765c5b916ed --- /dev/null +++ b/shared/package-files/00/0076fa231bdbcf039b03630c36c86000136ac8ccf3e41aa6080b9e8bbb993e0b/blob @@ -0,0 +1,24 @@ +#pragma once +// @generated by torchgen/gen.py from DispatchKeyFunction.h + +// NB: The implementing C++ file is RegisterDispatchKey.cpp + +// The only #includes we need are for custom classes that have defaults in the C++ API +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { + +namespace compositeimplicitautograd { + +TORCH_API at::Tensor conv_transpose2d(const at::Tensor & input, const at::Tensor & weight, const c10::optional & bias={}, at::IntArrayRef stride=1, at::IntArrayRef padding=0, at::IntArrayRef output_padding=0, int64_t groups=1, at::IntArrayRef dilation=1); +TORCH_API at::Tensor conv_transpose2d_symint(const at::Tensor & input, const at::Tensor & weight, const c10::optional & bias={}, c10::SymIntArrayRef stride=c10::SymInt(1), c10::SymIntArrayRef padding=c10::SymInt(0), c10::SymIntArrayRef output_padding=c10::SymInt(0), c10::SymInt groups=1, c10::SymIntArrayRef dilation=c10::SymInt(1)); + +} // namespace compositeimplicitautograd +} // namespace at diff --git a/shared/package-files/00/007879f48b3ee1689559ddbaca8be73ccde15ea292fb2c7b2167d7492d0d6611/blob b/shared/package-files/00/007879f48b3ee1689559ddbaca8be73ccde15ea292fb2c7b2167d7492d0d6611/blob new file mode 100644 index 0000000000000000000000000000000000000000..2e6a7e7e528aeb9f0c5c0f3b421559abbf9727ac --- /dev/null +++ b/shared/package-files/00/007879f48b3ee1689559ddbaca8be73ccde15ea292fb2c7b2167d7492d0d6611/blob @@ -0,0 +1,71 @@ +# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license + +# Copyright (C) 2003-2007, 2009-2011 Nominum, Inc. +# +# Permission to use, copy, modify, and distribute this software and its +# documentation for any purpose with or without fee is hereby granted, +# provided that the above copyright notice and this permission notice +# appear in all copies. +# +# THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES +# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR +# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT +# OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + +import struct + +import dns.exception +import dns.immutable +import dns.rdata +import dns.tokenizer + + +@dns.immutable.immutable +class CAA(dns.rdata.Rdata): + """CAA (Certification Authority Authorization) record""" + + # see: RFC 6844 + + __slots__ = ["flags", "tag", "value"] + + def __init__(self, rdclass, rdtype, flags, tag, value): + super().__init__(rdclass, rdtype) + self.flags = self._as_uint8(flags) + self.tag = self._as_bytes(tag, True, 255) + if not tag.isalnum(): + raise ValueError("tag is not alphanumeric") + self.value = self._as_bytes(value) + + def to_text(self, origin=None, relativize=True, **kw): + return '%u %s "%s"' % ( + self.flags, + dns.rdata._escapify(self.tag), + dns.rdata._escapify(self.value), + ) + + @classmethod + def from_text( + cls, rdclass, rdtype, tok, origin=None, relativize=True, relativize_to=None + ): + flags = tok.get_uint8() + tag = tok.get_string().encode() + value = tok.get_string().encode() + return cls(rdclass, rdtype, flags, tag, value) + + def _to_wire(self, file, compress=None, origin=None, canonicalize=False): + file.write(struct.pack("!B", self.flags)) + l = len(self.tag) + assert l < 256 + file.write(struct.pack("!B", l)) + file.write(self.tag) + file.write(self.value) + + @classmethod + def from_wire_parser(cls, rdclass, rdtype, parser, origin=None): + flags = parser.get_uint8() + tag = parser.get_counted_bytes() + value = parser.get_remaining() + return cls(rdclass, rdtype, flags, tag, value) diff --git a/shared/package-files/00/007a806377cd7d6f29e3152ee2d4b79ae360ee897c6bbe75bfbb58ca2eecadda/blob b/shared/package-files/00/007a806377cd7d6f29e3152ee2d4b79ae360ee897c6bbe75bfbb58ca2eecadda/blob new file mode 100644 index 0000000000000000000000000000000000000000..08378e1f2fb460041193e078fc8a56bd39cb9874 --- /dev/null +++ b/shared/package-files/00/007a806377cd7d6f29e3152ee2d4b79ae360ee897c6bbe75bfbb58ca2eecadda/blob @@ -0,0 +1,1158 @@ +from datetime import ( + date, + datetime, + timedelta, +) +import re + +import numpy as np +import pytest + +from pandas._libs.tslibs import iNaT +from pandas._libs.tslibs.ccalendar import ( + DAYS, + MONTHS, +) +from pandas._libs.tslibs.np_datetime import OutOfBoundsDatetime +from pandas._libs.tslibs.parsing import DateParseError +from pandas._libs.tslibs.period import INVALID_FREQ_ERR_MSG +from pandas.compat import PY314 + +from pandas import ( + NaT, + Period, + Timedelta, + Timestamp, + offsets, +) +import pandas._testing as tm + +bday_msg = "Period with BDay freq is deprecated" + + +class TestPeriodDisallowedFreqs: + @pytest.mark.parametrize( + "freq, freq_msg", + [ + (offsets.BYearBegin(), "BYearBegin"), + (offsets.YearBegin(2), "YearBegin"), + (offsets.QuarterBegin(startingMonth=12), "QuarterBegin"), + (offsets.BusinessMonthEnd(2), "BusinessMonthEnd"), + ], + ) + def test_offsets_not_supported(self, freq, freq_msg): + # GH#55785 + msg = re.escape(f"{freq} is not supported as period frequency") + with pytest.raises(ValueError, match=msg): + Period(year=2014, freq=freq) + + def test_custom_business_day_freq_raises(self): + # GH#52534 + msg = "C is not supported as period frequency" + with pytest.raises(ValueError, match=msg): + Period("2023-04-10", freq="C") + msg = f"{offsets.CustomBusinessDay().base} is not supported as period frequency" + with pytest.raises(ValueError, match=msg): + Period("2023-04-10", freq=offsets.CustomBusinessDay()) + + def test_invalid_frequency_error_message(self): + msg = "WOM-1MON is not supported as period frequency" + with pytest.raises(ValueError, match=msg): + Period("2012-01-02", freq="WOM-1MON") + + def test_invalid_frequency_period_error_message(self): + msg = "for Period, please use 'M' instead of 'ME'" + with pytest.raises(ValueError, match=msg): + Period("2012-01-02", freq="ME") + + +class TestPeriodConstruction: + def test_from_td64nat_raises(self): + # GH#44507 + td = NaT.to_numpy("m8[ns]") + + msg = "Value must be Period, string, integer, or datetime" + with pytest.raises(ValueError, match=msg): + Period(td) + + with pytest.raises(ValueError, match=msg): + Period(td, freq="D") + + def test_construction(self): + i1 = Period("1/1/2005", freq="M") + i2 = Period("Jan 2005") + + assert i1 == i2 + + # GH#54105 - Period can be confusingly instantiated with lowercase freq + # TODO: raise in the future an error when passing lowercase freq + i1 = Period("2005", freq="Y") + i2 = Period("2005") + + assert i1 == i2 + + i4 = Period("2005", freq="M") + assert i1 != i4 + + i1 = Period.now(freq="Q") + i2 = Period(datetime.now(), freq="Q") + + assert i1 == i2 + + # Pass in freq as a keyword argument sometimes as a test for + # https://github.com/pandas-dev/pandas/issues/53369 + i1 = Period.now(freq="D") + i2 = Period(datetime.now(), freq="D") + i3 = Period.now(offsets.Day()) + + assert i1 == i2 + assert i1 == i3 + + i1 = Period("1982", freq="min") + msg = "'MIN' is deprecated and will be removed in a future version." + with tm.assert_produces_warning(FutureWarning, match=msg): + i2 = Period("1982", freq="MIN") + assert i1 == i2 + + i1 = Period(year=2005, month=3, day=1, freq="D") + i2 = Period("3/1/2005", freq="D") + assert i1 == i2 + + i3 = Period(year=2005, month=3, day=1, freq="d") + assert i1 == i3 + + i1 = Period("2007-01-01 09:00:00.001") + expected = Period(datetime(2007, 1, 1, 9, 0, 0, 1000), freq="ms") + assert i1 == expected + + expected = Period("2007-01-01 09:00:00.001", freq="ms") + assert i1 == expected + + i1 = Period("2007-01-01 09:00:00.00101") + expected = Period(datetime(2007, 1, 1, 9, 0, 0, 1010), freq="us") + assert i1 == expected + + expected = Period("2007-01-01 09:00:00.00101", freq="us") + assert i1 == expected + + msg = "Must supply freq for ordinal value" + with pytest.raises(ValueError, match=msg): + Period(ordinal=200701) + + msg = "Invalid frequency: X" + with pytest.raises(ValueError, match=msg): + Period("2007-1-1", freq="X") + + def test_tuple_freq_disallowed(self): + # GH#34703 tuple freq disallowed + with pytest.raises(TypeError, match="pass as a string instead"): + Period("1982", freq=("Min", 1)) + + with pytest.raises(TypeError, match="pass as a string instead"): + Period("2006-12-31", ("w", 1)) + + def test_construction_from_timestamp_nanos(self): + # GH#46811 don't drop nanos from Timestamp + ts = Timestamp("2022-04-20 09:23:24.123456789") + per = Period(ts, freq="ns") + + # should losslessly round-trip, not lose the 789 + rt = per.to_timestamp() + assert rt == ts + + # same thing but from a datetime64 object + dt64 = ts.asm8 + per2 = Period(dt64, freq="ns") + rt2 = per2.to_timestamp() + assert rt2.asm8 == dt64 + + def test_construction_bday(self): + # Biz day construction, roll forward if non-weekday + with tm.assert_produces_warning(FutureWarning, match=bday_msg): + i1 = Period("3/10/12", freq="B") + i2 = Period("3/10/12", freq="D") + assert i1 == i2.asfreq("B") + i2 = Period("3/11/12", freq="D") + assert i1 == i2.asfreq("B") + i2 = Period("3/12/12", freq="D") + assert i1 == i2.asfreq("B") + + i3 = Period("3/10/12", freq="b") + assert i1 == i3 + + i1 = Period(year=2012, month=3, day=10, freq="B") + i2 = Period("3/12/12", freq="B") + assert i1 == i2 + + def test_construction_quarter(self): + i1 = Period(year=2005, quarter=1, freq="Q") + i2 = Period("1/1/2005", freq="Q") + assert i1 == i2 + + i1 = Period(year=2005, quarter=3, freq="Q") + i2 = Period("9/1/2005", freq="Q") + assert i1 == i2 + + i1 = Period("2005Q1") + i2 = Period(year=2005, quarter=1, freq="Q") + i3 = Period("2005q1") + assert i1 == i2 + assert i1 == i3 + + i1 = Period("05Q1") + assert i1 == i2 + lower = Period("05q1") + assert i1 == lower + + i1 = Period("1Q2005") + assert i1 == i2 + lower = Period("1q2005") + assert i1 == lower + + i1 = Period("1Q05") + assert i1 == i2 + lower = Period("1q05") + assert i1 == lower + + i1 = Period("4Q1984") + assert i1.year == 1984 + lower = Period("4q1984") + assert i1 == lower + + def test_construction_month(self): + expected = Period("2007-01", freq="M") + i1 = Period("200701", freq="M") + assert i1 == expected + + i1 = Period("200701", freq="M") + assert i1 == expected + + i1 = Period(200701, freq="M") + assert i1 == expected + + i1 = Period(ordinal=200701, freq="M") + assert i1.year == 18695 + + i1 = Period(datetime(2007, 1, 1), freq="M") + i2 = Period("200701", freq="M") + assert i1 == i2 + + i1 = Period(date(2007, 1, 1), freq="M") + i2 = Period(datetime(2007, 1, 1), freq="M") + i3 = Period(np.datetime64("2007-01-01"), freq="M") + i4 = Period("2007-01-01 00:00:00", freq="M") + i5 = Period("2007-01-01 00:00:00.000", freq="M") + assert i1 == i2 + assert i1 == i3 + assert i1 == i4 + assert i1 == i5 + + def test_period_constructor_offsets(self): + assert Period("1/1/2005", freq=offsets.MonthEnd()) == Period( + "1/1/2005", freq="M" + ) + assert Period("2005", freq=offsets.YearEnd()) == Period("2005", freq="Y") + assert Period("2005", freq=offsets.MonthEnd()) == Period("2005", freq="M") + with tm.assert_produces_warning(FutureWarning, match=bday_msg): + assert Period("3/10/12", freq=offsets.BusinessDay()) == Period( + "3/10/12", freq="B" + ) + assert Period("3/10/12", freq=offsets.Day()) == Period("3/10/12", freq="D") + + assert Period( + year=2005, quarter=1, freq=offsets.QuarterEnd(startingMonth=12) + ) == Period(year=2005, quarter=1, freq="Q") + assert Period( + year=2005, quarter=2, freq=offsets.QuarterEnd(startingMonth=12) + ) == Period(year=2005, quarter=2, freq="Q") + + assert Period(year=2005, month=3, day=1, freq=offsets.Day()) == Period( + year=2005, month=3, day=1, freq="D" + ) + with tm.assert_produces_warning(FutureWarning, match=bday_msg): + assert Period(year=2012, month=3, day=10, freq=offsets.BDay()) == Period( + year=2012, month=3, day=10, freq="B" + ) + + expected = Period("2005-03-01", freq="3D") + assert Period(year=2005, month=3, day=1, freq=offsets.Day(3)) == expected + assert Period(year=2005, month=3, day=1, freq="3D") == expected + + with tm.assert_produces_warning(FutureWarning, match=bday_msg): + assert Period(year=2012, month=3, day=10, freq=offsets.BDay(3)) == Period( + year=2012, month=3, day=10, freq="3B" + ) + + assert Period(200701, freq=offsets.MonthEnd()) == Period(200701, freq="M") + + i1 = Period(ordinal=200701, freq=offsets.MonthEnd()) + i2 = Period(ordinal=200701, freq="M") + assert i1 == i2 + assert i1.year == 18695 + assert i2.year == 18695 + + i1 = Period(datetime(2007, 1, 1), freq="M") + i2 = Period("200701", freq="M") + assert i1 == i2 + + i1 = Period(date(2007, 1, 1), freq="M") + i2 = Period(datetime(2007, 1, 1), freq="M") + i3 = Period(np.datetime64("2007-01-01"), freq="M") + i4 = Period("2007-01-01 00:00:00", freq="M") + i5 = Period("2007-01-01 00:00:00.000", freq="M") + assert i1 == i2 + assert i1 == i3 + assert i1 == i4 + assert i1 == i5 + + i1 = Period("2007-01-01 09:00:00.001") + expected = Period(datetime(2007, 1, 1, 9, 0, 0, 1000), freq="ms") + assert i1 == expected + + expected = Period("2007-01-01 09:00:00.001", freq="ms") + assert i1 == expected + + i1 = Period("2007-01-01 09:00:00.00101") + expected = Period(datetime(2007, 1, 1, 9, 0, 0, 1010), freq="us") + assert i1 == expected + + expected = Period("2007-01-01 09:00:00.00101", freq="us") + assert i1 == expected + + def test_invalid_arguments(self): + msg = "Must supply freq for datetime value" + with pytest.raises(ValueError, match=msg): + Period(datetime.now()) + with pytest.raises(ValueError, match=msg): + Period(datetime.now().date()) + + msg = "Value must be Period, string, integer, or datetime" + with pytest.raises(ValueError, match=msg): + Period(1.6, freq="D") + msg = "Ordinal must be an integer" + with pytest.raises(ValueError, match=msg): + Period(ordinal=1.6, freq="D") + msg = "Only value or ordinal but not both should be given but not both" + with pytest.raises(ValueError, match=msg): + Period(ordinal=2, value=1, freq="D") + + msg = "If value is None, freq cannot be None" + with pytest.raises(ValueError, match=msg): + Period(month=1) + + msg = '^Given date string "-2000" not likely a datetime$' + with pytest.raises(ValueError, match=msg): + Period("-2000", "Y") + if PY314: + msg = "day 0 must be in range 1..31 for month 1 in year 1: 0" + else: + msg = "day is out of range for month" + with pytest.raises(DateParseError, match=msg): + Period("0", "Y") + msg = "Unknown datetime string format, unable to parse" + with pytest.raises(DateParseError, match=msg): + Period("1/1/-2000", "Y") + + def test_constructor_corner(self): + expected = Period("2007-01", freq="2M") + assert Period(year=2007, month=1, freq="2M") == expected + + assert Period(None) is NaT + + p = Period("2007-01-01", freq="D") + + result = Period(p, freq="Y") + exp = Period("2007", freq="Y") + assert result == exp + + def test_constructor_infer_freq(self): + p = Period("2007-01-01") + assert p.freq == "D" + + p = Period("2007-01-01 07") + assert p.freq == "h" + + p = Period("2007-01-01 07:10") + assert p.freq == "min" + + p = Period("2007-01-01 07:10:15") + assert p.freq == "s" + + p = Period("2007-01-01 07:10:15.123") + assert p.freq == "ms" + + # We see that there are 6 digits after the decimal, so get microsecond + # even though they are all zeros. + p = Period("2007-01-01 07:10:15.123000") + assert p.freq == "us" + + p = Period("2007-01-01 07:10:15.123400") + assert p.freq == "us" + + def test_multiples(self): + result1 = Period("1989", freq="2Y") + result2 = Period("1989", freq="Y") + assert result1.ordinal == result2.ordinal + assert result1.freqstr == "2Y-DEC" + assert result2.freqstr == "Y-DEC" + assert result1.freq == offsets.YearEnd(2) + assert result2.freq == offsets.YearEnd() + + assert (result1 + 1).ordinal == result1.ordinal + 2 + assert (1 + result1).ordinal == result1.ordinal + 2 + assert (result1 - 1).ordinal == result2.ordinal - 2 + assert (-1 + result1).ordinal == result2.ordinal - 2 + + @pytest.mark.parametrize("month", MONTHS) + def test_period_cons_quarterly(self, month): + # bugs in scikits.timeseries + freq = f"Q-{month}" + exp = Period("1989Q3", freq=freq) + assert "1989Q3" in str(exp) + stamp = exp.to_timestamp("D", how="end") + p = Period(stamp, freq=freq) + assert p == exp + + stamp = exp.to_timestamp("3D", how="end") + p = Period(stamp, freq=freq) + assert p == exp + + @pytest.mark.parametrize("month", MONTHS) + def test_period_cons_annual(self, month): + # bugs in scikits.timeseries + freq = f"Y-{month}" + exp = Period("1989", freq=freq) + stamp = exp.to_timestamp("D", how="end") + timedelta(days=30) + p = Period(stamp, freq=freq) + + assert p == exp + 1 + assert isinstance(p, Period) + + @pytest.mark.parametrize("day", DAYS) + @pytest.mark.parametrize("num", range(10, 17)) + def test_period_cons_weekly(self, num, day): + daystr = f"2011-02-{num}" + freq = f"W-{day}" + + result = Period(daystr, freq=freq) + expected = Period(daystr, freq="D").asfreq(freq) + assert result == expected + assert isinstance(result, Period) + + def test_parse_week_str_roundstrip(self): + # GH#50803 + per = Period("2017-01-23/2017-01-29") + assert per.freq.freqstr == "W-SUN" + + per = Period("2017-01-24/2017-01-30") + assert per.freq.freqstr == "W-MON" + + msg = "Could not parse as weekly-freq Period" + with pytest.raises(ValueError, match=msg): + # not 6 days apart + Period("2016-01-23/2017-01-29") + + def test_period_from_ordinal(self): + p = Period("2011-01", freq="M") + res = Period._from_ordinal(p.ordinal, freq=p.freq) + assert p == res + assert isinstance(res, Period) + + @pytest.mark.parametrize("freq", ["Y", "M", "D", "h"]) + def test_construct_from_nat_string_and_freq(self, freq): + per = Period("NaT", freq=freq) + assert per is NaT + + per = Period("NaT", freq="2" + freq) + assert per is NaT + + per = Period("NaT", freq="3" + freq) + assert per is NaT + + def test_period_cons_nat(self): + p = Period("nat", freq="W-SUN") + assert p is NaT + + p = Period(iNaT, freq="D") + assert p is NaT + + p = Period(iNaT, freq="3D") + assert p is NaT + + p = Period(iNaT, freq="1D1h") + assert p is NaT + + p = Period("NaT") + assert p is NaT + + p = Period(iNaT) + assert p is NaT + + def test_period_cons_mult(self): + p1 = Period("2011-01", freq="3M") + p2 = Period("2011-01", freq="M") + assert p1.ordinal == p2.ordinal + + assert p1.freq == offsets.MonthEnd(3) + assert p1.freqstr == "3M" + + assert p2.freq == offsets.MonthEnd() + assert p2.freqstr == "M" + + result = p1 + 1 + assert result.ordinal == (p2 + 3).ordinal + + assert result.freq == p1.freq + assert result.freqstr == "3M" + + result = p1 - 1 + assert result.ordinal == (p2 - 3).ordinal + assert result.freq == p1.freq + assert result.freqstr == "3M" + + msg = "Frequency must be positive, because it represents span: -3M" + with pytest.raises(ValueError, match=msg): + Period("2011-01", freq="-3M") + + msg = "Frequency must be positive, because it represents span: 0M" + with pytest.raises(ValueError, match=msg): + Period("2011-01", freq="0M") + + def test_period_cons_combined(self): + p = [ + ( + Period("2011-01", freq="1D1h"), + Period("2011-01", freq="1h1D"), + Period("2011-01", freq="h"), + ), + ( + Period(ordinal=1, freq="1D1h"), + Period(ordinal=1, freq="1h1D"), + Period(ordinal=1, freq="h"), + ), + ] + + for p1, p2, p3 in p: + assert p1.ordinal == p3.ordinal + assert p2.ordinal == p3.ordinal + + assert p1.freq == offsets.Hour(25) + assert p1.freqstr == "25h" + + assert p2.freq == offsets.Hour(25) + assert p2.freqstr == "25h" + + assert p3.freq == offsets.Hour() + assert p3.freqstr == "h" + + result = p1 + 1 + assert result.ordinal == (p3 + 25).ordinal + assert result.freq == p1.freq + assert result.freqstr == "25h" + + result = p2 + 1 + assert result.ordinal == (p3 + 25).ordinal + assert result.freq == p2.freq + assert result.freqstr == "25h" + + result = p1 - 1 + assert result.ordinal == (p3 - 25).ordinal + assert result.freq == p1.freq + assert result.freqstr == "25h" + + result = p2 - 1 + assert result.ordinal == (p3 - 25).ordinal + assert result.freq == p2.freq + assert result.freqstr == "25h" + + msg = "Frequency must be positive, because it represents span: -25h" + with pytest.raises(ValueError, match=msg): + Period("2011-01", freq="-1D1h") + with pytest.raises(ValueError, match=msg): + Period("2011-01", freq="-1h1D") + with pytest.raises(ValueError, match=msg): + Period(ordinal=1, freq="-1D1h") + with pytest.raises(ValueError, match=msg): + Period(ordinal=1, freq="-1h1D") + + msg = "Frequency must be positive, because it represents span: 0D" + with pytest.raises(ValueError, match=msg): + Period("2011-01", freq="0D0h") + with pytest.raises(ValueError, match=msg): + Period(ordinal=1, freq="0D0h") + + # You can only combine together day and intraday offsets + msg = "Invalid frequency: 1W1D" + with pytest.raises(ValueError, match=msg): + Period("2011-01", freq="1W1D") + msg = "Invalid frequency: 1D1W" + with pytest.raises(ValueError, match=msg): + Period("2011-01", freq="1D1W") + + @pytest.mark.parametrize("day", ["1970/01/01 ", "2020-12-31 ", "1981/09/13 "]) + @pytest.mark.parametrize("hour", ["00:00:00", "00:00:01", "23:59:59", "12:00:59"]) + @pytest.mark.parametrize( + "sec_float, expected", + [ + (".000000001", 1), + (".000000999", 999), + (".123456789", 789), + (".999999999", 999), + (".999999000", 0), + # Test femtoseconds, attoseconds, picoseconds are dropped like Timestamp + (".999999001123", 1), + (".999999001123456", 1), + (".999999001123456789", 1), + ], + ) + def test_period_constructor_nanosecond(self, day, hour, sec_float, expected): + # GH 34621 + + assert Period(day + hour + sec_float).start_time.nanosecond == expected + + @pytest.mark.parametrize("hour", range(24)) + def test_period_large_ordinal(self, hour): + # Issue #36430 + # Integer overflow for Period over the maximum timestamp + p = Period(ordinal=2562048 + hour, freq="1h") + assert p.hour == hour + + +class TestPeriodMethods: + def test_round_trip(self): + p = Period("2000Q1") + new_p = tm.round_trip_pickle(p) + assert new_p == p + + def test_hash(self): + assert hash(Period("2011-01", freq="M")) == hash(Period("2011-01", freq="M")) + + assert hash(Period("2011-01-01", freq="D")) != hash(Period("2011-01", freq="M")) + + assert hash(Period("2011-01", freq="3M")) != hash(Period("2011-01", freq="2M")) + + assert hash(Period("2011-01", freq="M")) != hash(Period("2011-02", freq="M")) + + # -------------------------------------------------------------- + # to_timestamp + + def test_to_timestamp_mult(self): + p = Period("2011-01", freq="M") + assert p.to_timestamp(how="S") == Timestamp("2011-01-01") + expected = Timestamp("2011-02-01") - Timedelta(1, "ns") + assert p.to_timestamp(how="E") == expected + + p = Period("2011-01", freq="3M") + assert p.to_timestamp(how="S") == Timestamp("2011-01-01") + expected = Timestamp("2011-04-01") - Timedelta(1, "ns") + assert p.to_timestamp(how="E") == expected + + @pytest.mark.filterwarnings( + "ignore:Period with BDay freq is deprecated:FutureWarning" + ) + def test_to_timestamp(self): + p = Period("1982", freq="Y") + start_ts = p.to_timestamp(how="S") + aliases = ["s", "StarT", "BEGIn"] + for a in aliases: + assert start_ts == p.to_timestamp("D", how=a) + # freq with mult should not affect to the result + assert start_ts == p.to_timestamp("3D", how=a) + + end_ts = p.to_timestamp(how="E") + aliases = ["e", "end", "FINIsH"] + for a in aliases: + assert end_ts == p.to_timestamp("D", how=a) + assert end_ts == p.to_timestamp("3D", how=a) + + from_lst = ["Y", "Q", "M", "W", "B", "D", "h", "Min", "s"] + + def _ex(p): + if p.freq == "B": + return p.start_time + Timedelta(days=1, nanoseconds=-1) + return Timestamp((p + p.freq).start_time._value - 1) + + for fcode in from_lst: + p = Period("1982", freq=fcode) + result = p.to_timestamp().to_period(fcode) + assert result == p + + assert p.start_time == p.to_timestamp(how="S") + + assert p.end_time == _ex(p) + + # Frequency other than daily + + p = Period("1985", freq="Y") + + result = p.to_timestamp("h", how="end") + expected = Timestamp(1986, 1, 1) - Timedelta(1, "ns") + assert result == expected + result = p.to_timestamp("3h", how="end") + assert result == expected + + result = p.to_timestamp("min", how="end") + expected = Timestamp(1986, 1, 1) - Timedelta(1, "ns") + assert result == expected + result = p.to_timestamp("2min", how="end") + assert result == expected + + result = p.to_timestamp(how="end") + expected = Timestamp(1986, 1, 1) - Timedelta(1, "ns") + assert result == expected + + expected = datetime(1985, 1, 1) + result = p.to_timestamp("h", how="start") + assert result == expected + result = p.to_timestamp("min", how="start") + assert result == expected + result = p.to_timestamp("s", how="start") + assert result == expected + result = p.to_timestamp("3h", how="start") + assert result == expected + result = p.to_timestamp("5s", how="start") + assert result == expected + + def test_to_timestamp_business_end(self): + with tm.assert_produces_warning(FutureWarning, match=bday_msg): + per = Period("1990-01-05", "B") # Friday + result = per.to_timestamp("B", how="E") + + expected = Timestamp("1990-01-06") - Timedelta(nanoseconds=1) + assert result == expected + + @pytest.mark.parametrize( + "ts, expected", + [ + ("1970-01-01 00:00:00", 0), + ("1970-01-01 00:00:00.000001", 1), + ("1970-01-01 00:00:00.00001", 10), + ("1970-01-01 00:00:00.499", 499000), + ("1999-12-31 23:59:59.999", 999000), + ("1999-12-31 23:59:59.999999", 999999), + ("2050-12-31 23:59:59.5", 500000), + ("2050-12-31 23:59:59.500001", 500001), + ("2050-12-31 23:59:59.123456", 123456), + ], + ) + @pytest.mark.parametrize("freq", [None, "us", "ns"]) + def test_to_timestamp_microsecond(self, ts, expected, freq): + # GH 24444 + result = Period(ts).to_timestamp(freq=freq).microsecond + assert result == expected + + # -------------------------------------------------------------- + # Rendering: __repr__, strftime, etc + + @pytest.mark.parametrize( + "str_ts,freq,str_res,str_freq", + ( + ("Jan-2000", None, "2000-01", "M"), + ("2000-12-15", None, "2000-12-15", "D"), + ( + "2000-12-15 13:45:26.123456789", + "ns", + "2000-12-15 13:45:26.123456789", + "ns", + ), + ("2000-12-15 13:45:26.123456789", "us", "2000-12-15 13:45:26.123456", "us"), + ("2000-12-15 13:45:26.123456", None, "2000-12-15 13:45:26.123456", "us"), + ("2000-12-15 13:45:26.123456789", "ms", "2000-12-15 13:45:26.123", "ms"), + ("2000-12-15 13:45:26.123", None, "2000-12-15 13:45:26.123", "ms"), + ("2000-12-15 13:45:26", "s", "2000-12-15 13:45:26", "s"), + ("2000-12-15 13:45:26", "min", "2000-12-15 13:45", "min"), + ("2000-12-15 13:45:26", "h", "2000-12-15 13:00", "h"), + ("2000-12-15", "Y", "2000", "Y-DEC"), + ("2000-12-15", "Q", "2000Q4", "Q-DEC"), + ("2000-12-15", "M", "2000-12", "M"), + ("2000-12-15", "W", "2000-12-11/2000-12-17", "W-SUN"), + ("2000-12-15", "D", "2000-12-15", "D"), + ("2000-12-15", "B", "2000-12-15", "B"), + ), + ) + @pytest.mark.filterwarnings( + "ignore:Period with BDay freq is deprecated:FutureWarning" + ) + def test_repr(self, str_ts, freq, str_res, str_freq): + p = Period(str_ts, freq=freq) + assert str(p) == str_res + assert repr(p) == f"Period('{str_res}', '{str_freq}')" + + def test_repr_nat(self): + p = Period("nat", freq="M") + assert repr(NaT) in repr(p) + + def test_strftime(self): + # GH#3363 + p = Period("2000-1-1 12:34:12", freq="s") + res = p.strftime("%Y-%m-%d %H:%M:%S") + assert res == "2000-01-01 12:34:12" + assert isinstance(res, str) + + +class TestPeriodProperties: + """Test properties such as year, month, weekday, etc....""" + + @pytest.mark.parametrize("freq", ["Y", "M", "D", "h"]) + def test_is_leap_year(self, freq): + # GH 13727 + p = Period("2000-01-01 00:00:00", freq=freq) + assert p.is_leap_year + assert isinstance(p.is_leap_year, bool) + + p = Period("1999-01-01 00:00:00", freq=freq) + assert not p.is_leap_year + + p = Period("2004-01-01 00:00:00", freq=freq) + assert p.is_leap_year + + p = Period("2100-01-01 00:00:00", freq=freq) + assert not p.is_leap_year + + def test_quarterly_negative_ordinals(self): + p = Period(ordinal=-1, freq="Q-DEC") + assert p.year == 1969 + assert p.quarter == 4 + assert isinstance(p, Period) + + p = Period(ordinal=-2, freq="Q-DEC") + assert p.year == 1969 + assert p.quarter == 3 + assert isinstance(p, Period) + + p = Period(ordinal=-2, freq="M") + assert p.year == 1969 + assert p.month == 11 + assert isinstance(p, Period) + + def test_freq_str(self): + i1 = Period("1982", freq="Min") + assert i1.freq == offsets.Minute() + assert i1.freqstr == "min" + + @pytest.mark.filterwarnings( + "ignore:Period with BDay freq is deprecated:FutureWarning" + ) + def test_period_deprecated_freq(self): + cases = { + "M": ["MTH", "MONTH", "MONTHLY", "Mth", "month", "monthly"], + "B": ["BUS", "BUSINESS", "BUSINESSLY", "WEEKDAY", "bus"], + "D": ["DAY", "DLY", "DAILY", "Day", "Dly", "Daily"], + "h": ["HR", "HOUR", "HRLY", "HOURLY", "hr", "Hour", "HRly"], + "min": ["minute", "MINUTE", "MINUTELY", "minutely"], + "s": ["sec", "SEC", "SECOND", "SECONDLY", "second"], + "ms": ["MILLISECOND", "MILLISECONDLY", "millisecond"], + "us": ["MICROSECOND", "MICROSECONDLY", "microsecond"], + "ns": ["NANOSECOND", "NANOSECONDLY", "nanosecond"], + } + + msg = INVALID_FREQ_ERR_MSG + for exp, freqs in cases.items(): + for freq in freqs: + with pytest.raises(ValueError, match=msg): + Period("2016-03-01 09:00", freq=freq) + with pytest.raises(ValueError, match=msg): + Period(ordinal=1, freq=freq) + + # check supported freq-aliases still works + p1 = Period("2016-03-01 09:00", freq=exp) + p2 = Period(ordinal=1, freq=exp) + assert isinstance(p1, Period) + assert isinstance(p2, Period) + + @staticmethod + def _period_constructor(bound, offset): + return Period( + year=bound.year, + month=bound.month, + day=bound.day, + hour=bound.hour, + minute=bound.minute, + second=bound.second + offset, + freq="us", + ) + + @pytest.mark.parametrize("bound, offset", [(Timestamp.min, -1), (Timestamp.max, 1)]) + @pytest.mark.parametrize("period_property", ["start_time", "end_time"]) + def test_outer_bounds_start_and_end_time(self, bound, offset, period_property): + # GH #13346 + period = TestPeriodProperties._period_constructor(bound, offset) + with pytest.raises(OutOfBoundsDatetime, match="Out of bounds nanosecond"): + getattr(period, period_property) + + @pytest.mark.parametrize("bound, offset", [(Timestamp.min, -1), (Timestamp.max, 1)]) + @pytest.mark.parametrize("period_property", ["start_time", "end_time"]) + def test_inner_bounds_start_and_end_time(self, bound, offset, period_property): + # GH #13346 + period = TestPeriodProperties._period_constructor(bound, -offset) + expected = period.to_timestamp().round(freq="s") + assert getattr(period, period_property).round(freq="s") == expected + expected = (bound - offset * Timedelta(1, unit="s")).floor("s") + assert getattr(period, period_property).floor("s") == expected + + def test_start_time(self): + freq_lst = ["Y", "Q", "M", "D", "h", "min", "s"] + xp = datetime(2012, 1, 1) + for f in freq_lst: + p = Period("2012", freq=f) + assert p.start_time == xp + with tm.assert_produces_warning(FutureWarning, match=bday_msg): + assert Period("2012", freq="B").start_time == datetime(2012, 1, 2) + assert Period("2012", freq="W").start_time == datetime(2011, 12, 26) + + def test_end_time(self): + p = Period("2012", freq="Y") + + def _ex(*args): + return Timestamp(Timestamp(datetime(*args)).as_unit("ns")._value - 1) + + xp = _ex(2013, 1, 1) + assert xp == p.end_time + + p = Period("2012", freq="Q") + xp = _ex(2012, 4, 1) + assert xp == p.end_time + + p = Period("2012", freq="M") + xp = _ex(2012, 2, 1) + assert xp == p.end_time + + p = Period("2012", freq="D") + xp = _ex(2012, 1, 2) + assert xp == p.end_time + + p = Period("2012", freq="h") + xp = _ex(2012, 1, 1, 1) + assert xp == p.end_time + + with tm.assert_produces_warning(FutureWarning, match=bday_msg): + p = Period("2012", freq="B") + xp = _ex(2012, 1, 3) + assert xp == p.end_time + + p = Period("2012", freq="W") + xp = _ex(2012, 1, 2) + assert xp == p.end_time + + # Test for GH 11738 + p = Period("2012", freq="15D") + xp = _ex(2012, 1, 16) + assert xp == p.end_time + + p = Period("2012", freq="1D1h") + xp = _ex(2012, 1, 2, 1) + assert xp == p.end_time + + p = Period("2012", freq="1h1D") + xp = _ex(2012, 1, 2, 1) + assert xp == p.end_time + + def test_end_time_business_friday(self): + # GH#34449 + with tm.assert_produces_warning(FutureWarning, match=bday_msg): + per = Period("1990-01-05", "B") + result = per.end_time + + expected = Timestamp("1990-01-06") - Timedelta(nanoseconds=1) + assert result == expected + + def test_anchor_week_end_time(self): + def _ex(*args): + return Timestamp(Timestamp(datetime(*args)).as_unit("ns")._value - 1) + + p = Period("2013-1-1", "W-SAT") + xp = _ex(2013, 1, 6) + assert p.end_time == xp + + def test_properties_annually(self): + # Test properties on Periods with annually frequency. + a_date = Period(freq="Y", year=2007) + assert a_date.year == 2007 + + def test_properties_quarterly(self): + # Test properties on Periods with daily frequency. + qedec_date = Period(freq="Q-DEC", year=2007, quarter=1) + qejan_date = Period(freq="Q-JAN", year=2007, quarter=1) + qejun_date = Period(freq="Q-JUN", year=2007, quarter=1) + # + for x in range(3): + for qd in (qedec_date, qejan_date, qejun_date): + assert (qd + x).qyear == 2007 + assert (qd + x).quarter == x + 1 + + def test_properties_monthly(self): + # Test properties on Periods with daily frequency. + m_date = Period(freq="M", year=2007, month=1) + for x in range(11): + m_ival_x = m_date + x + assert m_ival_x.year == 2007 + if 1 <= x + 1 <= 3: + assert m_ival_x.quarter == 1 + elif 4 <= x + 1 <= 6: + assert m_ival_x.quarter == 2 + elif 7 <= x + 1 <= 9: + assert m_ival_x.quarter == 3 + elif 10 <= x + 1 <= 12: + assert m_ival_x.quarter == 4 + assert m_ival_x.month == x + 1 + + def test_properties_weekly(self): + # Test properties on Periods with daily frequency. + w_date = Period(freq="W", year=2007, month=1, day=7) + # + assert w_date.year == 2007 + assert w_date.quarter == 1 + assert w_date.month == 1 + assert w_date.week == 1 + assert (w_date - 1).week == 52 + assert w_date.days_in_month == 31 + assert Period(freq="W", year=2012, month=2, day=1).days_in_month == 29 + + def test_properties_weekly_legacy(self): + # Test properties on Periods with daily frequency. + w_date = Period(freq="W", year=2007, month=1, day=7) + assert w_date.year == 2007 + assert w_date.quarter == 1 + assert w_date.month == 1 + assert w_date.week == 1 + assert (w_date - 1).week == 52 + assert w_date.days_in_month == 31 + + exp = Period(freq="W", year=2012, month=2, day=1) + assert exp.days_in_month == 29 + + msg = INVALID_FREQ_ERR_MSG + with pytest.raises(ValueError, match=msg): + Period(freq="WK", year=2007, month=1, day=7) + + def test_properties_daily(self): + # Test properties on Periods with daily frequency. + with tm.assert_produces_warning(FutureWarning, match=bday_msg): + b_date = Period(freq="B", year=2007, month=1, day=1) + # + assert b_date.year == 2007 + assert b_date.quarter == 1 + assert b_date.month == 1 + assert b_date.day == 1 + assert b_date.weekday == 0 + assert b_date.dayofyear == 1 + assert b_date.days_in_month == 31 + with tm.assert_produces_warning(FutureWarning, match=bday_msg): + assert Period(freq="B", year=2012, month=2, day=1).days_in_month == 29 + + d_date = Period(freq="D", year=2007, month=1, day=1) + + assert d_date.year == 2007 + assert d_date.quarter == 1 + assert d_date.month == 1 + assert d_date.day == 1 + assert d_date.weekday == 0 + assert d_date.dayofyear == 1 + assert d_date.days_in_month == 31 + assert Period(freq="D", year=2012, month=2, day=1).days_in_month == 29 + + def test_properties_hourly(self): + # Test properties on Periods with hourly frequency. + h_date1 = Period(freq="h", year=2007, month=1, day=1, hour=0) + h_date2 = Period(freq="2h", year=2007, month=1, day=1, hour=0) + + for h_date in [h_date1, h_date2]: + assert h_date.year == 2007 + assert h_date.quarter == 1 + assert h_date.month == 1 + assert h_date.day == 1 + assert h_date.weekday == 0 + assert h_date.dayofyear == 1 + assert h_date.hour == 0 + assert h_date.days_in_month == 31 + assert ( + Period(freq="h", year=2012, month=2, day=1, hour=0).days_in_month == 29 + ) + + def test_properties_minutely(self): + # Test properties on Periods with minutely frequency. + t_date = Period(freq="Min", year=2007, month=1, day=1, hour=0, minute=0) + # + assert t_date.quarter == 1 + assert t_date.month == 1 + assert t_date.day == 1 + assert t_date.weekday == 0 + assert t_date.dayofyear == 1 + assert t_date.hour == 0 + assert t_date.minute == 0 + assert t_date.days_in_month == 31 + assert ( + Period(freq="D", year=2012, month=2, day=1, hour=0, minute=0).days_in_month + == 29 + ) + + def test_properties_secondly(self): + # Test properties on Periods with secondly frequency. + s_date = Period( + freq="Min", year=2007, month=1, day=1, hour=0, minute=0, second=0 + ) + # + assert s_date.year == 2007 + assert s_date.quarter == 1 + assert s_date.month == 1 + assert s_date.day == 1 + assert s_date.weekday == 0 + assert s_date.dayofyear == 1 + assert s_date.hour == 0 + assert s_date.minute == 0 + assert s_date.second == 0 + assert s_date.days_in_month == 31 + assert ( + Period( + freq="Min", year=2012, month=2, day=1, hour=0, minute=0, second=0 + ).days_in_month + == 29 + ) + + +class TestPeriodComparisons: + def test_sort_periods(self): + jan = Period("2000-01", "M") + feb = Period("2000-02", "M") + mar = Period("2000-03", "M") + periods = [mar, jan, feb] + correctPeriods = [jan, feb, mar] + assert sorted(periods) == correctPeriods + + +def test_period_immutable(): + # see gh-17116 + msg = "not writable" + + per = Period("2014Q1") + with pytest.raises(AttributeError, match=msg): + per.ordinal = 14 + + freq = per.freq + with pytest.raises(AttributeError, match=msg): + per.freq = 2 * freq + + +def test_small_year_parsing(): + per1 = Period("0001-01-07", "D") + assert per1.year == 1 + assert per1.day == 7 + + +def test_negone_ordinals(): + freqs = ["Y", "M", "Q", "D", "h", "min", "s"] + + period = Period(ordinal=-1, freq="D") + for freq in freqs: + repr(period.asfreq(freq)) + + for freq in freqs: + period = Period(ordinal=-1, freq=freq) + repr(period) + assert period.year == 1969 + + with tm.assert_produces_warning(FutureWarning, match=bday_msg): + period = Period(ordinal=-1, freq="B") + repr(period) + period = Period(ordinal=-1, freq="W") + repr(period) diff --git a/shared/package-files/00/007b4b4429d075e6397d074c248b6780debb3c1565c569f612aff4b9ae159492/blob b/shared/package-files/00/007b4b4429d075e6397d074c248b6780debb3c1565c569f612aff4b9ae159492/blob new file mode 100644 index 0000000000000000000000000000000000000000..4b043c3ddb01f22aaa500a37314f7f74b94ff6a0 --- /dev/null +++ b/shared/package-files/00/007b4b4429d075e6397d074c248b6780debb3c1565c569f612aff4b9ae159492/blob @@ -0,0 +1,105 @@ +""" + pygments.lexers.graph + ~~~~~~~~~~~~~~~~~~~~~ + + Lexers for graph query languages. + + :copyright: Copyright 2006-2023 by the Pygments team, see AUTHORS. + :license: BSD, see LICENSE for details. +""" + +import re + +from pygments.lexer import RegexLexer, include, bygroups, using, this, words +from pygments.token import Keyword, Punctuation, Comment, Operator, Name,\ + String, Number, Whitespace + + +__all__ = ['CypherLexer'] + + +class CypherLexer(RegexLexer): + """ + For Cypher Query Language + + For the Cypher version in Neo4j 3.3 + + .. versionadded:: 2.0 + """ + name = 'Cypher' + url = 'https://neo4j.com/docs/developer-manual/3.3/cypher/' + aliases = ['cypher'] + filenames = ['*.cyp', '*.cypher'] + + flags = re.MULTILINE | re.IGNORECASE + + tokens = { + 'root': [ + include('comment'), + include('clauses'), + include('keywords'), + include('relations'), + include('strings'), + include('whitespace'), + include('barewords'), + ], + 'comment': [ + (r'^.*//.*$', Comment.Single), + ], + 'keywords': [ + (r'(create|order|match|limit|set|skip|start|return|with|where|' + r'delete|foreach|not|by|true|false)\b', Keyword), + ], + 'clauses': [ + # based on https://neo4j.com/docs/cypher-refcard/3.3/ + (r'(create)(\s+)(index|unique)\b', + bygroups(Keyword, Whitespace, Keyword)), + (r'(drop)(\s+)(contraint|index)(\s+)(on)\b', + bygroups(Keyword, Whitespace, Keyword, Whitespace, Keyword)), + (r'(ends)(\s+)(with)\b', + bygroups(Keyword, Whitespace, Keyword)), + (r'(is)(\s+)(node)(\s+)(key)\b', + bygroups(Keyword, Whitespace, Keyword, Whitespace, Keyword)), + (r'(is)(\s+)(null|unique)\b', + bygroups(Keyword, Whitespace, Keyword)), + (r'(load)(\s+)(csv)(\s+)(from)\b', + bygroups(Keyword, Whitespace, Keyword, Whitespace, Keyword)), + (r'(on)(\s+)(match|create)\b', + bygroups(Keyword, Whitespace, Keyword)), + (r'(optional)(\s+)(match)\b', + bygroups(Keyword, Whitespace, Keyword)), + (r'(order)(\s+)(by)\b', + bygroups(Keyword, Whitespace, Keyword)), + (r'(starts)(\s+)(with)\b', + bygroups(Keyword, Whitespace, Keyword)), + (r'(union)(\s+)(all)\b', + bygroups(Keyword, Whitespace, Keyword)), + (r'(using)(\s+)(periodic)(\s+)(commit)\b', + bygroups(Keyword, Whitespace, Keyword, Whitespace, Keyword)), + (words(( + 'all', 'any', 'as', 'asc', 'ascending', 'assert', 'call', 'case', 'create', + 'delete', 'desc', 'descending', 'distinct', 'end', 'fieldterminator', + 'foreach', 'in', 'limit', 'match', 'merge', 'none', 'not', 'null', + 'remove', 'return', 'set', 'skip', 'single', 'start', 'then', 'union', + 'unwind', 'yield', 'where', 'when', 'with'), suffix=r'\b'), Keyword), + ], + 'relations': [ + (r'(-\[)(.*?)(\]->)', bygroups(Operator, using(this), Operator)), + (r'(<-\[)(.*?)(\]-)', bygroups(Operator, using(this), Operator)), + (r'(-\[)(.*?)(\]-)', bygroups(Operator, using(this), Operator)), + (r'-->|<--|\[|\]', Operator), + (r'<|>|<>|=|<=|=>|\(|\)|\||:|,|;', Punctuation), + (r'[.*{}]', Punctuation), + ], + 'strings': [ + (r'"(?:\\[tbnrf\'"\\]|[^\\"])*"', String), + (r'`(?:``|[^`])+`', Name.Variable), + ], + 'whitespace': [ + (r'\s+', Whitespace), + ], + 'barewords': [ + (r'[a-z]\w*', Name), + (r'\d+', Number), + ], + } diff --git a/shared/package-files/00/007bc30a58fa40a996e772047120de4eaf31f5110e4f9c3b5f93fcdfbe2eaca1/blob b/shared/package-files/00/007bc30a58fa40a996e772047120de4eaf31f5110e4f9c3b5f93fcdfbe2eaca1/blob new file mode 100644 index 0000000000000000000000000000000000000000..6bbfda911b2afada41a568218e31a6502dc68f44 --- /dev/null +++ b/shared/package-files/00/007bc30a58fa40a996e772047120de4eaf31f5110e4f9c3b5f93fcdfbe2eaca1/blob @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright 2016, latex2sympy + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/shared/package-files/00/007c7273f4f4d627c319bd19a7be1e7c291bf3de21e62e9ea14cb159d8dda003/blob b/shared/package-files/00/007c7273f4f4d627c319bd19a7be1e7c291bf3de21e62e9ea14cb159d8dda003/blob new file mode 100644 index 0000000000000000000000000000000000000000..7d2d5053f7ca307b84cf7e3989ceb3cff12ed45a --- /dev/null +++ b/shared/package-files/00/007c7273f4f4d627c319bd19a7be1e7c291bf3de21e62e9ea14cb159d8dda003/blob @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:007c7273f4f4d627c319bd19a7be1e7c291bf3de21e62e9ea14cb159d8dda003 +size 458840 diff --git a/shared/package-files/00/007c797f91b0f387ba6c88c56859ecebbbb6a888d34644952179c8dcd9859cfb/blob b/shared/package-files/00/007c797f91b0f387ba6c88c56859ecebbbb6a888d34644952179c8dcd9859cfb/blob new file mode 100644 index 0000000000000000000000000000000000000000..6d931d3333a5dd7bde69c05f4e61719159f1202f --- /dev/null +++ b/shared/package-files/00/007c797f91b0f387ba6c88c56859ecebbbb6a888d34644952179c8dcd9859cfb/blob @@ -0,0 +1,28 @@ +#pragma once + +// @generated by torchgen/gen.py from Operator.h + +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { +namespace _ops { + + +struct TORCH_API _has_compatible_shallow_copy_type { + using schema = bool (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::_has_compatible_shallow_copy_type") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "_has_compatible_shallow_copy_type(Tensor self, Tensor from) -> bool") + static bool call(const at::Tensor & self, const at::Tensor & from); + static bool redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, const at::Tensor & from); +}; + +}} // namespace at::_ops diff --git a/shared/package-files/00/007c7f5b6c46e0911ccf5c4aa0de53c021d513af943b63e2301cb29e47784cf1/blob b/shared/package-files/00/007c7f5b6c46e0911ccf5c4aa0de53c021d513af943b63e2301cb29e47784cf1/blob new file mode 100644 index 0000000000000000000000000000000000000000..6c6af680031b4f30fc6da946d0344b5c27e5f05e Binary files /dev/null and b/shared/package-files/00/007c7f5b6c46e0911ccf5c4aa0de53c021d513af943b63e2301cb29e47784cf1/blob differ diff --git a/shared/package-files/00/00802e742f5fefce24704cee868f0689753adef8f64e1462b4ace797b22692ae/blob b/shared/package-files/00/00802e742f5fefce24704cee868f0689753adef8f64e1462b4ace797b22692ae/blob new file mode 100644 index 0000000000000000000000000000000000000000..317730745b6e3a0278a48b7bb810cf43e718e787 --- /dev/null +++ b/shared/package-files/00/00802e742f5fefce24704cee868f0689753adef8f64e1462b4ace797b22692ae/blob @@ -0,0 +1,3 @@ +from pandas.io.sas.sasreader import read_sas + +__all__ = ["read_sas"] diff --git a/shared/package-files/00/0081cfe13348b3509eaa122039b1f26344b69cd181a3a70808bff78694738fda/blob b/shared/package-files/00/0081cfe13348b3509eaa122039b1f26344b69cd181a3a70808bff78694738fda/blob new file mode 100644 index 0000000000000000000000000000000000000000..0ccf14137096c862a0644cdb229cb98b4556e5d7 --- /dev/null +++ b/shared/package-files/00/0081cfe13348b3509eaa122039b1f26344b69cd181a3a70808bff78694738fda/blob @@ -0,0 +1,521 @@ +from typing import Any + +import numpy as np + +__all__ = [ + 'geterr', + 'seterr', + 'errstate', + 'agm', + 'airy', + 'airye', + 'bdtr', + 'bdtrc', + 'bdtri', + 'bdtrik', + 'bdtrin', + 'bei', + 'beip', + 'ber', + 'berp', + 'besselpoly', + 'beta', + 'betainc', + 'betaincc', + 'betainccinv', + 'betaincinv', + 'betaln', + 'binom', + 'boxcox', + 'boxcox1p', + 'btdtria', + 'btdtrib', + 'cbrt', + 'chdtr', + 'chdtrc', + 'chdtri', + 'chdtriv', + 'chndtr', + 'chndtridf', + 'chndtrinc', + 'chndtrix', + 'cosdg', + 'cosm1', + 'cotdg', + 'dawsn', + 'ellipe', + 'ellipeinc', + 'ellipj', + 'ellipk', + 'ellipkinc', + 'ellipkm1', + 'elliprc', + 'elliprd', + 'elliprf', + 'elliprg', + 'elliprj', + 'entr', + 'erf', + 'erfc', + 'erfcinv', + 'erfcx', + 'erfi', + 'erfinv', + 'eval_chebyc', + 'eval_chebys', + 'eval_chebyt', + 'eval_chebyu', + 'eval_gegenbauer', + 'eval_genlaguerre', + 'eval_hermite', + 'eval_hermitenorm', + 'eval_jacobi', + 'eval_laguerre', + 'eval_legendre', + 'eval_sh_chebyt', + 'eval_sh_chebyu', + 'eval_sh_jacobi', + 'eval_sh_legendre', + 'exp1', + 'exp10', + 'exp2', + 'expi', + 'expit', + 'expm1', + 'expn', + 'exprel', + 'fdtr', + 'fdtrc', + 'fdtri', + 'fdtridfd', + 'fresnel', + 'gamma', + 'gammainc', + 'gammaincc', + 'gammainccinv', + 'gammaincinv', + 'gammaln', + 'gammasgn', + 'gdtr', + 'gdtrc', + 'gdtria', + 'gdtrib', + 'gdtrix', + 'hankel1', + 'hankel1e', + 'hankel2', + 'hankel2e', + 'huber', + 'hyp0f1', + 'hyp1f1', + 'hyp2f1', + 'hyperu', + 'i0', + 'i0e', + 'i1', + 'i1e', + 'inv_boxcox', + 'inv_boxcox1p', + 'it2i0k0', + 'it2j0y0', + 'it2struve0', + 'itairy', + 'iti0k0', + 'itj0y0', + 'itmodstruve0', + 'itstruve0', + 'iv', + 'ive', + 'j0', + 'j1', + 'jn', + 'jv', + 'jve', + 'k0', + 'k0e', + 'k1', + 'k1e', + 'kei', + 'keip', + 'kelvin', + 'ker', + 'kerp', + 'kl_div', + 'kn', + 'kolmogi', + 'kolmogorov', + 'kv', + 'kve', + 'log1p', + 'log_expit', + 'log_ndtr', + 'log_wright_bessel', + 'loggamma', + 'logit', + 'lpmv', + 'mathieu_a', + 'mathieu_b', + 'mathieu_cem', + 'mathieu_modcem1', + 'mathieu_modcem2', + 'mathieu_modsem1', + 'mathieu_modsem2', + 'mathieu_sem', + 'modfresnelm', + 'modfresnelp', + 'modstruve', + 'nbdtr', + 'nbdtrc', + 'nbdtri', + 'nbdtrik', + 'nbdtrin', + 'ncfdtr', + 'ncfdtri', + 'ncfdtridfd', + 'ncfdtridfn', + 'ncfdtrinc', + 'nctdtr', + 'nctdtridf', + 'nctdtrinc', + 'nctdtrit', + 'ndtr', + 'ndtri', + 'ndtri_exp', + 'nrdtrimn', + 'nrdtrisd', + 'obl_ang1', + 'obl_ang1_cv', + 'obl_cv', + 'obl_rad1', + 'obl_rad1_cv', + 'obl_rad2', + 'obl_rad2_cv', + 'owens_t', + 'pbdv', + 'pbvv', + 'pbwa', + 'pdtr', + 'pdtrc', + 'pdtri', + 'pdtrik', + 'poch', + 'powm1', + 'pro_ang1', + 'pro_ang1_cv', + 'pro_cv', + 'pro_rad1', + 'pro_rad1_cv', + 'pro_rad2', + 'pro_rad2_cv', + 'pseudo_huber', + 'psi', + 'radian', + 'rel_entr', + 'rgamma', + 'round', + 'shichi', + 'sici', + 'sindg', + 'smirnov', + 'smirnovi', + 'spence', + 'sph_harm', + 'stdtr', + 'stdtridf', + 'stdtrit', + 'struve', + 'tandg', + 'tklmbda', + 'voigt_profile', + 'wofz', + 'wright_bessel', + 'wrightomega', + 'xlog1py', + 'xlogy', + 'y0', + 'y1', + 'yn', + 'yv', + 'yve', + 'zetac' +] + +def geterr() -> dict[str, str]: ... +def seterr(**kwargs: str) -> dict[str, str]: ... + +class errstate: + def __init__(self, **kargs: str) -> None: ... + def __enter__(self) -> None: ... + def __exit__( + self, + exc_type: Any, # Unused + exc_value: Any, # Unused + traceback: Any, # Unused + ) -> None: ... + +_cosine_cdf: np.ufunc +_cosine_invcdf: np.ufunc +_cospi: np.ufunc +_ellip_harm: np.ufunc +_factorial: np.ufunc +_igam_fac: np.ufunc +_kolmogc: np.ufunc +_kolmogci: np.ufunc +_kolmogp: np.ufunc +_lambertw: np.ufunc +_lanczos_sum_expg_scaled: np.ufunc +_lgam1p: np.ufunc +_log1pmx: np.ufunc +_riemann_zeta: np.ufunc +_scaled_exp1: np.ufunc +_sf_error_test_function: np.ufunc +_sinpi: np.ufunc +_smirnovc: np.ufunc +_smirnovci: np.ufunc +_smirnovp: np.ufunc +_spherical_in: np.ufunc +_spherical_in_d: np.ufunc +_spherical_jn: np.ufunc +_spherical_jn_d: np.ufunc +_spherical_kn: np.ufunc +_spherical_kn_d: np.ufunc +_spherical_yn: np.ufunc +_spherical_yn_d: np.ufunc +_stirling2_inexact: np.ufunc +_struve_asymp_large_z: np.ufunc +_struve_bessel_series: np.ufunc +_struve_power_series: np.ufunc +_zeta: np.ufunc +agm: np.ufunc +airy: np.ufunc +airye: np.ufunc +bdtr: np.ufunc +bdtrc: np.ufunc +bdtri: np.ufunc +bdtrik: np.ufunc +bdtrin: np.ufunc +bei: np.ufunc +beip: np.ufunc +ber: np.ufunc +berp: np.ufunc +besselpoly: np.ufunc +beta: np.ufunc +betainc: np.ufunc +betaincc: np.ufunc +betainccinv: np.ufunc +betaincinv: np.ufunc +betaln: np.ufunc +binom: np.ufunc +boxcox1p: np.ufunc +boxcox: np.ufunc +btdtria: np.ufunc +btdtrib: np.ufunc +cbrt: np.ufunc +chdtr: np.ufunc +chdtrc: np.ufunc +chdtri: np.ufunc +chdtriv: np.ufunc +chndtr: np.ufunc +chndtridf: np.ufunc +chndtrinc: np.ufunc +chndtrix: np.ufunc +cosdg: np.ufunc +cosm1: np.ufunc +cotdg: np.ufunc +dawsn: np.ufunc +ellipe: np.ufunc +ellipeinc: np.ufunc +ellipj: np.ufunc +ellipk: np.ufunc +ellipkinc: np.ufunc +ellipkm1: np.ufunc +elliprc: np.ufunc +elliprd: np.ufunc +elliprf: np.ufunc +elliprg: np.ufunc +elliprj: np.ufunc +entr: np.ufunc +erf: np.ufunc +erfc: np.ufunc +erfcinv: np.ufunc +erfcx: np.ufunc +erfi: np.ufunc +erfinv: np.ufunc +eval_chebyc: np.ufunc +eval_chebys: np.ufunc +eval_chebyt: np.ufunc +eval_chebyu: np.ufunc +eval_gegenbauer: np.ufunc +eval_genlaguerre: np.ufunc +eval_hermite: np.ufunc +eval_hermitenorm: np.ufunc +eval_jacobi: np.ufunc +eval_laguerre: np.ufunc +eval_legendre: np.ufunc +eval_sh_chebyt: np.ufunc +eval_sh_chebyu: np.ufunc +eval_sh_jacobi: np.ufunc +eval_sh_legendre: np.ufunc +exp10: np.ufunc +exp1: np.ufunc +exp2: np.ufunc +expi: np.ufunc +expit: np.ufunc +expm1: np.ufunc +expn: np.ufunc +exprel: np.ufunc +fdtr: np.ufunc +fdtrc: np.ufunc +fdtri: np.ufunc +fdtridfd: np.ufunc +fresnel: np.ufunc +gamma: np.ufunc +gammainc: np.ufunc +gammaincc: np.ufunc +gammainccinv: np.ufunc +gammaincinv: np.ufunc +gammaln: np.ufunc +gammasgn: np.ufunc +gdtr: np.ufunc +gdtrc: np.ufunc +gdtria: np.ufunc +gdtrib: np.ufunc +gdtrix: np.ufunc +hankel1: np.ufunc +hankel1e: np.ufunc +hankel2: np.ufunc +hankel2e: np.ufunc +huber: np.ufunc +hyp0f1: np.ufunc +hyp1f1: np.ufunc +hyp2f1: np.ufunc +hyperu: np.ufunc +i0: np.ufunc +i0e: np.ufunc +i1: np.ufunc +i1e: np.ufunc +inv_boxcox1p: np.ufunc +inv_boxcox: np.ufunc +it2i0k0: np.ufunc +it2j0y0: np.ufunc +it2struve0: np.ufunc +itairy: np.ufunc +iti0k0: np.ufunc +itj0y0: np.ufunc +itmodstruve0: np.ufunc +itstruve0: np.ufunc +iv: np.ufunc +ive: np.ufunc +j0: np.ufunc +j1: np.ufunc +jn: np.ufunc +jv: np.ufunc +jve: np.ufunc +k0: np.ufunc +k0e: np.ufunc +k1: np.ufunc +k1e: np.ufunc +kei: np.ufunc +keip: np.ufunc +kelvin: np.ufunc +ker: np.ufunc +kerp: np.ufunc +kl_div: np.ufunc +kn: np.ufunc +kolmogi: np.ufunc +kolmogorov: np.ufunc +kv: np.ufunc +kve: np.ufunc +log1p: np.ufunc +log_expit: np.ufunc +log_ndtr: np.ufunc +log_wright_bessel: np.ufunc +loggamma: np.ufunc +logit: np.ufunc +lpmv: np.ufunc +mathieu_a: np.ufunc +mathieu_b: np.ufunc +mathieu_cem: np.ufunc +mathieu_modcem1: np.ufunc +mathieu_modcem2: np.ufunc +mathieu_modsem1: np.ufunc +mathieu_modsem2: np.ufunc +mathieu_sem: np.ufunc +modfresnelm: np.ufunc +modfresnelp: np.ufunc +modstruve: np.ufunc +nbdtr: np.ufunc +nbdtrc: np.ufunc +nbdtri: np.ufunc +nbdtrik: np.ufunc +nbdtrin: np.ufunc +ncfdtr: np.ufunc +ncfdtri: np.ufunc +ncfdtridfd: np.ufunc +ncfdtridfn: np.ufunc +ncfdtrinc: np.ufunc +nctdtr: np.ufunc +nctdtridf: np.ufunc +nctdtrinc: np.ufunc +nctdtrit: np.ufunc +ndtr: np.ufunc +ndtri: np.ufunc +ndtri_exp: np.ufunc +nrdtrimn: np.ufunc +nrdtrisd: np.ufunc +obl_ang1: np.ufunc +obl_ang1_cv: np.ufunc +obl_cv: np.ufunc +obl_rad1: np.ufunc +obl_rad1_cv: np.ufunc +obl_rad2: np.ufunc +obl_rad2_cv: np.ufunc +owens_t: np.ufunc +pbdv: np.ufunc +pbvv: np.ufunc +pbwa: np.ufunc +pdtr: np.ufunc +pdtrc: np.ufunc +pdtri: np.ufunc +pdtrik: np.ufunc +poch: np.ufunc +powm1: np.ufunc +pro_ang1: np.ufunc +pro_ang1_cv: np.ufunc +pro_cv: np.ufunc +pro_rad1: np.ufunc +pro_rad1_cv: np.ufunc +pro_rad2: np.ufunc +pro_rad2_cv: np.ufunc +pseudo_huber: np.ufunc +psi: np.ufunc +radian: np.ufunc +rel_entr: np.ufunc +rgamma: np.ufunc +round: np.ufunc +shichi: np.ufunc +sici: np.ufunc +sindg: np.ufunc +smirnov: np.ufunc +smirnovi: np.ufunc +spence: np.ufunc +sph_harm: np.ufunc +stdtr: np.ufunc +stdtridf: np.ufunc +stdtrit: np.ufunc +struve: np.ufunc +tandg: np.ufunc +tklmbda: np.ufunc +voigt_profile: np.ufunc +wofz: np.ufunc +wright_bessel: np.ufunc +wrightomega: np.ufunc +xlog1py: np.ufunc +xlogy: np.ufunc +y0: np.ufunc +y1: np.ufunc +yn: np.ufunc +yv: np.ufunc +yve: np.ufunc +zetac: np.ufunc + diff --git a/shared/package-files/00/00846343a0d9b42f0a65d83ae1122c698f533ef9883999234e7dc130c74e99fc/blob b/shared/package-files/00/00846343a0d9b42f0a65d83ae1122c698f533ef9883999234e7dc130c74e99fc/blob new file mode 100644 index 0000000000000000000000000000000000000000..4082d3aff0206002224885858718fcb9def9ddf8 --- /dev/null +++ b/shared/package-files/00/00846343a0d9b42f0a65d83ae1122c698f533ef9883999234e7dc130c74e99fc/blob @@ -0,0 +1,22 @@ +#pragma once + +// @generated by torchgen/gen.py from NativeFunction.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + +namespace at { +namespace native { +TORCH_API at::Tensor smooth_l1_loss_backward(const at::Tensor & grad_output, const at::Tensor & self, const at::Tensor & target, int64_t reduction, double beta); +TORCH_API at::Tensor & smooth_l1_loss_backward_out(const at::Tensor & grad_output, const at::Tensor & self, const at::Tensor & target, int64_t reduction, double beta, at::Tensor & grad_input); +} // namespace native +} // namespace at diff --git a/shared/package-files/00/00861efb625e1476b20218687baea5dc22afeb7d05aa1012f468c5ff6deb8784/blob b/shared/package-files/00/00861efb625e1476b20218687baea5dc22afeb7d05aa1012f468c5ff6deb8784/blob new file mode 100644 index 0000000000000000000000000000000000000000..fc6a04132d83fceadcdd92d1709acbd8f7a72f66 --- /dev/null +++ b/shared/package-files/00/00861efb625e1476b20218687baea5dc22afeb7d05aa1012f468c5ff6deb8784/blob @@ -0,0 +1,39 @@ +#pragma once + +// @generated by torchgen/gen.py from Operator.h + +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { +namespace _ops { + + +struct TORCH_API special_airy_ai { + using schema = at::Tensor (const at::Tensor &); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::special_airy_ai") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "special_airy_ai(Tensor x) -> Tensor") + static at::Tensor call(const at::Tensor & x); + static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & x); +}; + +struct TORCH_API special_airy_ai_out { + using schema = at::Tensor & (const at::Tensor &, at::Tensor &); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::special_airy_ai") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "out") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "special_airy_ai.out(Tensor x, *, Tensor(a!) out) -> Tensor(a!)") + static at::Tensor & call(const at::Tensor & x, at::Tensor & out); + static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & x, at::Tensor & out); +}; + +}} // namespace at::_ops diff --git a/shared/package-files/00/0086fee1e20b0641b01e33d835771212955f02ee6f1a5749785ddb3a456e4521/blob b/shared/package-files/00/0086fee1e20b0641b01e33d835771212955f02ee6f1a5749785ddb3a456e4521/blob new file mode 100644 index 0000000000000000000000000000000000000000..622ee1df1b105ea84f43aba4503cb9238f899fc4 Binary files /dev/null and b/shared/package-files/00/0086fee1e20b0641b01e33d835771212955f02ee6f1a5749785ddb3a456e4521/blob differ diff --git a/shared/package-files/00/008a8d7cac2c1d84f13e85a7d8ef64680bb614ea3c251f0455d35f5791630e3f/blob b/shared/package-files/00/008a8d7cac2c1d84f13e85a7d8ef64680bb614ea3c251f0455d35f5791630e3f/blob new file mode 100644 index 0000000000000000000000000000000000000000..68da8d0bf7334f9883c269b9322c67306d7ce4c8 --- /dev/null +++ b/shared/package-files/00/008a8d7cac2c1d84f13e85a7d8ef64680bb614ea3c251f0455d35f5791630e3f/blob @@ -0,0 +1,28 @@ +#pragma once +// @generated by torchgen/gen.py from DispatchKeyFunction.h + +// NB: The implementing C++ file is RegisterDispatchKey.cpp + +// The only #includes we need are for custom classes that have defaults in the C++ API +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { + +namespace compositeexplicitautograd { + +TORCH_API at::Tensor _convolution(const at::Tensor & input, const at::Tensor & weight, const c10::optional & bias, at::IntArrayRef stride, at::IntArrayRef padding, at::IntArrayRef dilation, bool transposed, at::IntArrayRef output_padding, int64_t groups, bool benchmark, bool deterministic, bool cudnn_enabled, bool allow_tf32); +TORCH_API at::Tensor _convolution_symint(const at::Tensor & input, const at::Tensor & weight, const c10::optional & bias, c10::SymIntArrayRef stride, c10::SymIntArrayRef padding, c10::SymIntArrayRef dilation, bool transposed, c10::SymIntArrayRef output_padding, c10::SymInt groups, bool benchmark, bool deterministic, bool cudnn_enabled, bool allow_tf32); +TORCH_API at::Tensor & _convolution_out(at::Tensor & out, const at::Tensor & input, const at::Tensor & weight, const c10::optional & bias, at::IntArrayRef stride, at::IntArrayRef padding, at::IntArrayRef dilation, bool transposed, at::IntArrayRef output_padding, int64_t groups, bool benchmark, bool deterministic, bool cudnn_enabled, bool allow_tf32); +TORCH_API at::Tensor & _convolution_outf(const at::Tensor & input, const at::Tensor & weight, const c10::optional & bias, at::IntArrayRef stride, at::IntArrayRef padding, at::IntArrayRef dilation, bool transposed, at::IntArrayRef output_padding, int64_t groups, bool benchmark, bool deterministic, bool cudnn_enabled, bool allow_tf32, at::Tensor & out); +TORCH_API at::Tensor & _convolution_symint_out(at::Tensor & out, const at::Tensor & input, const at::Tensor & weight, const c10::optional & bias, c10::SymIntArrayRef stride, c10::SymIntArrayRef padding, c10::SymIntArrayRef dilation, bool transposed, c10::SymIntArrayRef output_padding, c10::SymInt groups, bool benchmark, bool deterministic, bool cudnn_enabled, bool allow_tf32); +TORCH_API at::Tensor & _convolution_symint_outf(const at::Tensor & input, const at::Tensor & weight, const c10::optional & bias, c10::SymIntArrayRef stride, c10::SymIntArrayRef padding, c10::SymIntArrayRef dilation, bool transposed, c10::SymIntArrayRef output_padding, c10::SymInt groups, bool benchmark, bool deterministic, bool cudnn_enabled, bool allow_tf32, at::Tensor & out); + +} // namespace compositeexplicitautograd +} // namespace at diff --git a/shared/package-files/00/008aebf96e567aa0e3e4a6c42ea8c79b7fa1aaac77abc63106bbf5cf6a1ca3de/blob b/shared/package-files/00/008aebf96e567aa0e3e4a6c42ea8c79b7fa1aaac77abc63106bbf5cf6a1ca3de/blob new file mode 100644 index 0000000000000000000000000000000000000000..a8353f301a3c39a50b2a0c5541722551ff660e30 --- /dev/null +++ b/shared/package-files/00/008aebf96e567aa0e3e4a6c42ea8c79b7fa1aaac77abc63106bbf5cf6a1ca3de/blob @@ -0,0 +1,96 @@ +import numpy as np +import pytest + +from pandas import ( + Categorical, + CategoricalIndex, + Index, + MultiIndex, +) + + +class TestEquals: + def test_equals_categorical(self): + ci1 = CategoricalIndex(["a", "b"], categories=["a", "b"], ordered=True) + ci2 = CategoricalIndex(["a", "b"], categories=["a", "b", "c"], ordered=True) + + assert ci1.equals(ci1) + assert not ci1.equals(ci2) + assert ci1.equals(ci1.astype(object)) + assert ci1.astype(object).equals(ci1) + + assert (ci1 == ci1).all() + assert not (ci1 != ci1).all() + assert not (ci1 > ci1).all() + assert not (ci1 < ci1).all() + assert (ci1 <= ci1).all() + assert (ci1 >= ci1).all() + + assert not (ci1 == 1).all() + assert (ci1 == Index(["a", "b"])).all() + assert (ci1 == ci1.values).all() + + # invalid comparisons + with pytest.raises(ValueError, match="Lengths must match"): + ci1 == Index(["a", "b", "c"]) + + msg = "Categoricals can only be compared if 'categories' are the same" + with pytest.raises(TypeError, match=msg): + ci1 == ci2 + with pytest.raises(TypeError, match=msg): + ci1 == Categorical(ci1.values, ordered=False) + with pytest.raises(TypeError, match=msg): + ci1 == Categorical(ci1.values, categories=list("abc")) + + # tests + # make sure that we are testing for category inclusion properly + ci = CategoricalIndex(list("aabca"), categories=["c", "a", "b"]) + assert not ci.equals(list("aabca")) + # Same categories, but different order + # Unordered + assert ci.equals(CategoricalIndex(list("aabca"))) + # Ordered + assert not ci.equals(CategoricalIndex(list("aabca"), ordered=True)) + assert ci.equals(ci.copy()) + + ci = CategoricalIndex(list("aabca") + [np.nan], categories=["c", "a", "b"]) + assert not ci.equals(list("aabca")) + assert not ci.equals(CategoricalIndex(list("aabca"))) + assert ci.equals(ci.copy()) + + ci = CategoricalIndex(list("aabca") + [np.nan], categories=["c", "a", "b"]) + assert not ci.equals(list("aabca") + [np.nan]) + assert ci.equals(CategoricalIndex(list("aabca") + [np.nan])) + assert not ci.equals(CategoricalIndex(list("aabca") + [np.nan], ordered=True)) + assert ci.equals(ci.copy()) + + def test_equals_categorical_unordered(self): + # https://github.com/pandas-dev/pandas/issues/16603 + a = CategoricalIndex(["A"], categories=["A", "B"]) + b = CategoricalIndex(["A"], categories=["B", "A"]) + c = CategoricalIndex(["C"], categories=["B", "A"]) + assert a.equals(b) + assert not a.equals(c) + assert not b.equals(c) + + def test_equals_non_category(self): + # GH#37667 Case where other contains a value not among ci's + # categories ("D") and also contains np.nan + ci = CategoricalIndex(["A", "B", np.nan, np.nan]) + other = Index(["A", "B", "D", np.nan]) + + assert not ci.equals(other) + + def test_equals_multiindex(self): + # dont raise NotImplementedError when calling is_dtype_compat + + mi = MultiIndex.from_arrays([["A", "B", "C", "D"], range(4)]) + ci = mi.to_flat_index().astype("category") + + assert not ci.equals(mi) + + def test_equals_string_dtype(self, any_string_dtype): + # GH#55364 + idx = CategoricalIndex(list("abc"), name="B") + other = Index(["a", "b", "c"], name="B", dtype=any_string_dtype) + assert idx.equals(other) diff --git a/shared/package-files/00/008d8696d03cd263cdce11f163272e13021b3b500d5f222a05064ca63a8aa9d4/blob b/shared/package-files/00/008d8696d03cd263cdce11f163272e13021b3b500d5f222a05064ca63a8aa9d4/blob new file mode 100644 index 0000000000000000000000000000000000000000..f3e185c3ab516065c52557aaceaaeacae1f8b221 Binary files /dev/null and b/shared/package-files/00/008d8696d03cd263cdce11f163272e13021b3b500d5f222a05064ca63a8aa9d4/blob differ diff --git a/shared/package-files/00/008df3db96fee0e246fb7c3856aadccc29fd22e8cc53be2808d92ea2ad1862e5/blob b/shared/package-files/00/008df3db96fee0e246fb7c3856aadccc29fd22e8cc53be2808d92ea2ad1862e5/blob new file mode 100644 index 0000000000000000000000000000000000000000..f28021d51970084a6e1ffdbb61eaf597e975d172 --- /dev/null +++ b/shared/package-files/00/008df3db96fee0e246fb7c3856aadccc29fd22e8cc53be2808d92ea2ad1862e5/blob @@ -0,0 +1,25 @@ +#pragma once + +// @generated by torchgen/gen.py from NativeFunction.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + +namespace at { +namespace native { +TORCH_API void _foreach_tanh_out(at::TensorList self, at::TensorList out); +TORCH_API ::std::vector foreach_tensor_tanh_slow(at::TensorList self); +TORCH_API void foreach_tensor_tanh_slow_(at::TensorList self); +TORCH_API ::std::vector foreach_tensor_tanh_cuda(at::TensorList self); +TORCH_API void foreach_tensor_tanh_cuda_(at::TensorList self); +} // namespace native +} // namespace at diff --git a/shared/package-files/00/008e5929fd806cb3710fc957c8b0e9299cb3799da87c5b5d2b565616afde7357/blob b/shared/package-files/00/008e5929fd806cb3710fc957c8b0e9299cb3799da87c5b5d2b565616afde7357/blob new file mode 100644 index 0000000000000000000000000000000000000000..20280f0ca354a691861ab6f17821bbeb04632003 --- /dev/null +++ b/shared/package-files/00/008e5929fd806cb3710fc957c8b0e9299cb3799da87c5b5d2b565616afde7357/blob @@ -0,0 +1,14 @@ +"""Compatibility module. + +It can be necessary to load files generated by previous versions of cloudpickle +that rely on symbols being defined under the `cloudpickle.cloudpickle_fast` +namespace. + +See: tests/test_backward_compat.py +""" + +from . import cloudpickle + + +def __getattr__(name): + return getattr(cloudpickle, name) diff --git a/shared/package-files/00/00904e718f0eab4918739ef42aeb8f4e4beeaa302586e7da13673db0251b9bae/blob b/shared/package-files/00/00904e718f0eab4918739ef42aeb8f4e4beeaa302586e7da13673db0251b9bae/blob new file mode 100644 index 0000000000000000000000000000000000000000..540e7a4dc79d02a820e291b57c43335d5aa25a41 --- /dev/null +++ b/shared/package-files/00/00904e718f0eab4918739ef42aeb8f4e4beeaa302586e7da13673db0251b9bae/blob @@ -0,0 +1,304 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. + +import operator +import os +import platform +import sys +from typing import Any, Callable, Dict, List, Optional, Tuple, Union + +from pip._vendor.pyparsing import ( # noqa: N817 + Forward, + Group, + Literal as L, + ParseException, + ParseResults, + QuotedString, + ZeroOrMore, + stringEnd, + stringStart, +) + +from .specifiers import InvalidSpecifier, Specifier + +__all__ = [ + "InvalidMarker", + "UndefinedComparison", + "UndefinedEnvironmentName", + "Marker", + "default_environment", +] + +Operator = Callable[[str, str], bool] + + +class InvalidMarker(ValueError): + """ + An invalid marker was found, users should refer to PEP 508. + """ + + +class UndefinedComparison(ValueError): + """ + An invalid operation was attempted on a value that doesn't support it. + """ + + +class UndefinedEnvironmentName(ValueError): + """ + A name was attempted to be used that does not exist inside of the + environment. + """ + + +class Node: + def __init__(self, value: Any) -> None: + self.value = value + + def __str__(self) -> str: + return str(self.value) + + def __repr__(self) -> str: + return f"<{self.__class__.__name__}('{self}')>" + + def serialize(self) -> str: + raise NotImplementedError + + +class Variable(Node): + def serialize(self) -> str: + return str(self) + + +class Value(Node): + def serialize(self) -> str: + return f'"{self}"' + + +class Op(Node): + def serialize(self) -> str: + return str(self) + + +VARIABLE = ( + L("implementation_version") + | L("platform_python_implementation") + | L("implementation_name") + | L("python_full_version") + | L("platform_release") + | L("platform_version") + | L("platform_machine") + | L("platform_system") + | L("python_version") + | L("sys_platform") + | L("os_name") + | L("os.name") # PEP-345 + | L("sys.platform") # PEP-345 + | L("platform.version") # PEP-345 + | L("platform.machine") # PEP-345 + | L("platform.python_implementation") # PEP-345 + | L("python_implementation") # undocumented setuptools legacy + | L("extra") # PEP-508 +) +ALIASES = { + "os.name": "os_name", + "sys.platform": "sys_platform", + "platform.version": "platform_version", + "platform.machine": "platform_machine", + "platform.python_implementation": "platform_python_implementation", + "python_implementation": "platform_python_implementation", +} +VARIABLE.setParseAction(lambda s, l, t: Variable(ALIASES.get(t[0], t[0]))) + +VERSION_CMP = ( + L("===") | L("==") | L(">=") | L("<=") | L("!=") | L("~=") | L(">") | L("<") +) + +MARKER_OP = VERSION_CMP | L("not in") | L("in") +MARKER_OP.setParseAction(lambda s, l, t: Op(t[0])) + +MARKER_VALUE = QuotedString("'") | QuotedString('"') +MARKER_VALUE.setParseAction(lambda s, l, t: Value(t[0])) + +BOOLOP = L("and") | L("or") + +MARKER_VAR = VARIABLE | MARKER_VALUE + +MARKER_ITEM = Group(MARKER_VAR + MARKER_OP + MARKER_VAR) +MARKER_ITEM.setParseAction(lambda s, l, t: tuple(t[0])) + +LPAREN = L("(").suppress() +RPAREN = L(")").suppress() + +MARKER_EXPR = Forward() +MARKER_ATOM = MARKER_ITEM | Group(LPAREN + MARKER_EXPR + RPAREN) +MARKER_EXPR << MARKER_ATOM + ZeroOrMore(BOOLOP + MARKER_EXPR) + +MARKER = stringStart + MARKER_EXPR + stringEnd + + +def _coerce_parse_result(results: Union[ParseResults, List[Any]]) -> List[Any]: + if isinstance(results, ParseResults): + return [_coerce_parse_result(i) for i in results] + else: + return results + + +def _format_marker( + marker: Union[List[str], Tuple[Node, ...], str], first: Optional[bool] = True +) -> str: + + assert isinstance(marker, (list, tuple, str)) + + # Sometimes we have a structure like [[...]] which is a single item list + # where the single item is itself it's own list. In that case we want skip + # the rest of this function so that we don't get extraneous () on the + # outside. + if ( + isinstance(marker, list) + and len(marker) == 1 + and isinstance(marker[0], (list, tuple)) + ): + return _format_marker(marker[0]) + + if isinstance(marker, list): + inner = (_format_marker(m, first=False) for m in marker) + if first: + return " ".join(inner) + else: + return "(" + " ".join(inner) + ")" + elif isinstance(marker, tuple): + return " ".join([m.serialize() for m in marker]) + else: + return marker + + +_operators: Dict[str, Operator] = { + "in": lambda lhs, rhs: lhs in rhs, + "not in": lambda lhs, rhs: lhs not in rhs, + "<": operator.lt, + "<=": operator.le, + "==": operator.eq, + "!=": operator.ne, + ">=": operator.ge, + ">": operator.gt, +} + + +def _eval_op(lhs: str, op: Op, rhs: str) -> bool: + try: + spec = Specifier("".join([op.serialize(), rhs])) + except InvalidSpecifier: + pass + else: + return spec.contains(lhs) + + oper: Optional[Operator] = _operators.get(op.serialize()) + if oper is None: + raise UndefinedComparison(f"Undefined {op!r} on {lhs!r} and {rhs!r}.") + + return oper(lhs, rhs) + + +class Undefined: + pass + + +_undefined = Undefined() + + +def _get_env(environment: Dict[str, str], name: str) -> str: + value: Union[str, Undefined] = environment.get(name, _undefined) + + if isinstance(value, Undefined): + raise UndefinedEnvironmentName( + f"{name!r} does not exist in evaluation environment." + ) + + return value + + +def _evaluate_markers(markers: List[Any], environment: Dict[str, str]) -> bool: + groups: List[List[bool]] = [[]] + + for marker in markers: + assert isinstance(marker, (list, tuple, str)) + + if isinstance(marker, list): + groups[-1].append(_evaluate_markers(marker, environment)) + elif isinstance(marker, tuple): + lhs, op, rhs = marker + + if isinstance(lhs, Variable): + lhs_value = _get_env(environment, lhs.value) + rhs_value = rhs.value + else: + lhs_value = lhs.value + rhs_value = _get_env(environment, rhs.value) + + groups[-1].append(_eval_op(lhs_value, op, rhs_value)) + else: + assert marker in ["and", "or"] + if marker == "or": + groups.append([]) + + return any(all(item) for item in groups) + + +def format_full_version(info: "sys._version_info") -> str: + version = "{0.major}.{0.minor}.{0.micro}".format(info) + kind = info.releaselevel + if kind != "final": + version += kind[0] + str(info.serial) + return version + + +def default_environment() -> Dict[str, str]: + iver = format_full_version(sys.implementation.version) + implementation_name = sys.implementation.name + return { + "implementation_name": implementation_name, + "implementation_version": iver, + "os_name": os.name, + "platform_machine": platform.machine(), + "platform_release": platform.release(), + "platform_system": platform.system(), + "platform_version": platform.version(), + "python_full_version": platform.python_version(), + "platform_python_implementation": platform.python_implementation(), + "python_version": ".".join(platform.python_version_tuple()[:2]), + "sys_platform": sys.platform, + } + + +class Marker: + def __init__(self, marker: str) -> None: + try: + self._markers = _coerce_parse_result(MARKER.parseString(marker)) + except ParseException as e: + raise InvalidMarker( + f"Invalid marker: {marker!r}, parse error at " + f"{marker[e.loc : e.loc + 8]!r}" + ) + + def __str__(self) -> str: + return _format_marker(self._markers) + + def __repr__(self) -> str: + return f"" + + def evaluate(self, environment: Optional[Dict[str, str]] = None) -> bool: + """Evaluate a marker. + + Return the boolean from evaluating the given marker against the + environment. environment is an optional argument to override all or + part of the determined environment. + + The environment is determined from the current Python process. + """ + current_environment = default_environment() + if environment is not None: + current_environment.update(environment) + + return _evaluate_markers(self._markers, current_environment) diff --git a/shared/package-files/00/0095664dcd8887527886cc4bc84e4448af2beb5d4ea2a935b61877f5c5b6f2fd/blob b/shared/package-files/00/0095664dcd8887527886cc4bc84e4448af2beb5d4ea2a935b61877f5c5b6f2fd/blob new file mode 100644 index 0000000000000000000000000000000000000000..ef98c9c8ceac82b7d5bf39ee2c87b02ffcf37dc5 --- /dev/null +++ b/shared/package-files/00/0095664dcd8887527886cc4bc84e4448af2beb5d4ea2a935b61877f5c5b6f2fd/blob @@ -0,0 +1,110 @@ +from email._policybase import Policy # type: ignore +from email.message import Message +from email.mime.base import MIMEBase +from email.mime.message import MIMEMessage +from email.mime.multipart import MIMEMultipart +from email.mime.text import MIMEText +from typing import Any, Dict, List, Optional, Sequence, Tuple, Union, overload + +utf8_charset: Any +utf8_charset_qp: Any +DEFAULT_ATTACHMENT_MIME_TYPE: str +RFC5322_EMAIL_LINE_LENGTH_LIMIT: int + +class BadHeaderError(ValueError): ... + +ADDRESS_HEADERS: Any + +def forbid_multi_line_headers(name: str, val: str, encoding: str) -> Tuple[str, str]: ... +def split_addr(addr: str, encoding: str) -> Tuple[str, str]: ... +def sanitize_address(addr: Union[Tuple[str, str], str], encoding: str) -> str: ... + +class MIMEMixin: ... + +class SafeMIMEMessage(MIMEMixin, MIMEMessage): + defects: List[Any] + epilogue: None + policy: Policy + preamble: None + +class SafeMIMEText(MIMEMixin, MIMEText): + defects: List[Any] + epilogue: None + policy: Policy + preamble: None + encoding: str = ... + def __init__(self, _text: str, _subtype: str = ..., _charset: str = ...) -> None: ... + +class SafeMIMEMultipart(MIMEMixin, MIMEMultipart): + defects: List[Any] + epilogue: None + policy: Policy + preamble: None + encoding: str = ... + def __init__( + self, _subtype: str = ..., boundary: None = ..., _subparts: None = ..., encoding: str = ..., **_params: Any + ) -> None: ... + +_AttachmentContent = Union[bytes, EmailMessage, Message, SafeMIMEText, str] +_AttachmentTuple = Union[ + Tuple[str, _AttachmentContent], Tuple[Optional[str], _AttachmentContent, str], Tuple[str, _AttachmentContent, None] +] + +class EmailMessage: + content_subtype: str = ... + mixed_subtype: str = ... + encoding: Any = ... + to: List[str] = ... + cc: List[Any] = ... + bcc: List[Any] = ... + reply_to: List[Any] = ... + from_email: str = ... + subject: str = ... + body: str = ... + attachments: List[Any] = ... + extra_headers: Dict[Any, Any] = ... + connection: Any = ... + def __init__( + self, + subject: str = ..., + body: Optional[str] = ..., + from_email: Optional[str] = ..., + to: Optional[Sequence[str]] = ..., + bcc: Optional[Sequence[str]] = ..., + connection: Optional[Any] = ..., + attachments: Optional[Sequence[Union[MIMEBase, _AttachmentTuple]]] = ..., + headers: Optional[Dict[str, str]] = ..., + cc: Optional[Sequence[str]] = ..., + reply_to: Optional[Sequence[str]] = ..., + ) -> None: ... + def get_connection(self, fail_silently: bool = ...) -> Any: ... + # TODO: when typeshed gets more types for email.Message, move it to MIMEMessage, now it has too many false-positives + def message(self) -> Any: ... + def recipients(self) -> List[str]: ... + def send(self, fail_silently: bool = ...) -> int: ... + @overload + def attach(self, filename: MIMEText = ...) -> None: ... + @overload + def attach(self, filename: None = ..., content: _AttachmentContent = ..., mimetype: str = ...) -> None: ... + @overload + def attach(self, filename: str = ..., content: _AttachmentContent = ..., mimetype: Optional[str] = ...) -> None: ... + def attach_file(self, path: str, mimetype: Optional[str] = ...) -> None: ... + +class EmailMultiAlternatives(EmailMessage): + alternative_subtype: str = ... + alternatives: Sequence[Tuple[_AttachmentContent, str]] = ... + def __init__( + self, + subject: str = ..., + body: str = ..., + from_email: Optional[str] = ..., + to: Optional[Sequence[str]] = ..., + bcc: Optional[Sequence[str]] = ..., + connection: Optional[Any] = ..., + attachments: Optional[Sequence[Union[MIMEBase, _AttachmentTuple]]] = ..., + headers: Optional[Dict[str, str]] = ..., + alternatives: Optional[Sequence[Tuple[_AttachmentContent, str]]] = ..., + cc: Optional[Sequence[str]] = ..., + reply_to: Optional[Sequence[str]] = ..., + ) -> None: ... + def attach_alternative(self, content: _AttachmentContent, mimetype: str) -> None: ... diff --git a/shared/package-files/00/00987aa252715d0cc231628e139c9ee231df820d5503ef7e80267931bad7ffc1/blob b/shared/package-files/00/00987aa252715d0cc231628e139c9ee231df820d5503ef7e80267931bad7ffc1/blob new file mode 100644 index 0000000000000000000000000000000000000000..8a4ba4d30a6b7da8399f20a8b98c91169e04ae40 Binary files /dev/null and b/shared/package-files/00/00987aa252715d0cc231628e139c9ee231df820d5503ef7e80267931bad7ffc1/blob differ diff --git a/shared/package-files/00/009a34153c87e01b949d4b2fd7be8b0fde7aa26df4f0a1989ddcbe6f9e0a1b13/blob b/shared/package-files/00/009a34153c87e01b949d4b2fd7be8b0fde7aa26df4f0a1989ddcbe6f9e0a1b13/blob new file mode 100644 index 0000000000000000000000000000000000000000..99f3759c3071c4d55e0481472f3d16c1f5df1fef --- /dev/null +++ b/shared/package-files/00/009a34153c87e01b949d4b2fd7be8b0fde7aa26df4f0a1989ddcbe6f9e0a1b13/blob @@ -0,0 +1,1671 @@ +""" +Easy-to-use test-generating code: + +cases = ''' +exp 2.25 +log 2.25 +''' + +from mpmath import * +mp.dps = 20 +for test in cases.splitlines(): + if not test: + continue + words = test.split() + fname = words[0] + args = words[1:] + argstr = ", ".join(args) + testline = "%s(%s)" % (fname, argstr) + ans = str(eval(testline)) + print " assert ae(fp.%s, %s)" % (testline, ans) + +""" + +from mpmath import fp + +def ae(x, y, tol=1e-12): + if x == y: + return True + return abs(x-y) <= tol*abs(y) + +def test_conj(): + assert fp.conj(4) == 4 + assert fp.conj(3+4j) == 3-4j + assert fp.fdot([1,2],[3,2+1j], conjugate=True) == 7-2j + +def test_fp_number_parts(): + assert ae(fp.arg(3), 0.0) + assert ae(fp.arg(-3), 3.1415926535897932385) + assert ae(fp.arg(3j), 1.5707963267948966192) + assert ae(fp.arg(-3j), -1.5707963267948966192) + assert ae(fp.arg(2+3j), 0.98279372324732906799) + assert ae(fp.arg(-1-1j), -2.3561944901923449288) + assert ae(fp.re(2.5), 2.5) + assert ae(fp.re(2.5+3j), 2.5) + assert ae(fp.im(2.5), 0.0) + assert ae(fp.im(2.5+3j), 3.0) + assert ae(fp.floor(2.5), 2.0) + assert ae(fp.floor(2), 2.0) + assert ae(fp.floor(2.0+0j), (2.0 + 0.0j)) + assert ae(fp.floor(-1.5-0.5j), (-2.0 - 1.0j)) + assert ae(fp.ceil(2.5), 3.0) + assert ae(fp.ceil(2), 2.0) + assert ae(fp.ceil(2.0+0j), (2.0 + 0.0j)) + assert ae(fp.ceil(-1.5-0.5j), (-1.0 + 0.0j)) + +def test_fp_cospi_sinpi(): + assert ae(fp.sinpi(0), 0.0) + assert ae(fp.sinpi(0.25), 0.7071067811865475244) + assert ae(fp.sinpi(0.5), 1.0) + assert ae(fp.sinpi(0.75), 0.7071067811865475244) + assert ae(fp.sinpi(1), 0.0) + assert ae(fp.sinpi(1.25), -0.7071067811865475244) + assert ae(fp.sinpi(1.5), -1.0) + assert ae(fp.sinpi(1.75), -0.7071067811865475244) + assert ae(fp.sinpi(2), 0.0) + assert ae(fp.sinpi(2.25), 0.7071067811865475244) + assert ae(fp.sinpi(0+3j), (0.0 + 6195.8238636085899556j)) + assert ae(fp.sinpi(0.25+3j), (4381.1091260582448033 + 4381.1090689950686908j)) + assert ae(fp.sinpi(0.5+3j), (6195.8239443081075259 + 0.0j)) + assert ae(fp.sinpi(0.75+3j), (4381.1091260582448033 - 4381.1090689950686908j)) + assert ae(fp.sinpi(1+3j), (0.0 - 6195.8238636085899556j)) + assert ae(fp.sinpi(1.25+3j), (-4381.1091260582448033 - 4381.1090689950686908j)) + assert ae(fp.sinpi(1.5+3j), (-6195.8239443081075259 + 0.0j)) + assert ae(fp.sinpi(1.75+3j), (-4381.1091260582448033 + 4381.1090689950686908j)) + assert ae(fp.sinpi(2+3j), (0.0 + 6195.8238636085899556j)) + assert ae(fp.sinpi(2.25+3j), (4381.1091260582448033 + 4381.1090689950686908j)) + assert ae(fp.sinpi(-0.75), -0.7071067811865475244) + assert ae(fp.sinpi(-1e-10), -3.1415926535897933529e-10) + assert ae(fp.sinpi(1e-10), 3.1415926535897933529e-10) + assert ae(fp.sinpi(1e-10+1e-10j), (3.141592653589793353e-10 + 3.1415926535897933528e-10j)) + assert ae(fp.sinpi(1e-10-1e-10j), (3.141592653589793353e-10 - 3.1415926535897933528e-10j)) + assert ae(fp.sinpi(-1e-10+1e-10j), (-3.141592653589793353e-10 + 3.1415926535897933528e-10j)) + assert ae(fp.sinpi(-1e-10-1e-10j), (-3.141592653589793353e-10 - 3.1415926535897933528e-10j)) + assert ae(fp.cospi(0), 1.0) + assert ae(fp.cospi(0.25), 0.7071067811865475244) + assert ae(fp.cospi(0.5), 0.0) + assert ae(fp.cospi(0.75), -0.7071067811865475244) + assert ae(fp.cospi(1), -1.0) + assert ae(fp.cospi(1.25), -0.7071067811865475244) + assert ae(fp.cospi(1.5), 0.0) + assert ae(fp.cospi(1.75), 0.7071067811865475244) + assert ae(fp.cospi(2), 1.0) + assert ae(fp.cospi(2.25), 0.7071067811865475244) + assert ae(fp.cospi(0+3j), (6195.8239443081075259 + 0.0j)) + assert ae(fp.cospi(0.25+3j), (4381.1091260582448033 - 4381.1090689950686908j)) + assert ae(fp.cospi(0.5+3j), (0.0 - 6195.8238636085899556j)) + assert ae(fp.cospi(0.75+3j), (-4381.1091260582448033 - 4381.1090689950686908j)) + assert ae(fp.cospi(1+3j), (-6195.8239443081075259 + 0.0j)) + assert ae(fp.cospi(1.25+3j), (-4381.1091260582448033 + 4381.1090689950686908j)) + assert ae(fp.cospi(1.5+3j), (0.0 + 6195.8238636085899556j)) + assert ae(fp.cospi(1.75+3j), (4381.1091260582448033 + 4381.1090689950686908j)) + assert ae(fp.cospi(2+3j), (6195.8239443081075259 + 0.0j)) + assert ae(fp.cospi(2.25+3j), (4381.1091260582448033 - 4381.1090689950686908j)) + assert ae(fp.cospi(-0.75), -0.7071067811865475244) + assert ae(fp.sinpi(-0.7), -0.80901699437494750611) + assert ae(fp.cospi(-0.7), -0.5877852522924730163) + assert ae(fp.cospi(-3+2j), (-267.74676148374822225 + 0.0j)) + assert ae(fp.sinpi(-3+2j), (0.0 - 267.74489404101651426j)) + assert ae(fp.sinpi(-0.7+2j), (-216.6116802292079471 - 157.37650009392034693j)) + assert ae(fp.cospi(-0.7+2j), (-157.37759774921754565 + 216.61016943630197336j)) + +def test_fp_expj(): + assert ae(fp.expj(0), (1.0 + 0.0j)) + assert ae(fp.expj(1), (0.5403023058681397174 + 0.84147098480789650665j)) + assert ae(fp.expj(2), (-0.416146836547142387 + 0.9092974268256816954j)) + assert ae(fp.expj(0.75), (0.73168886887382088631 + 0.68163876002333416673j)) + assert ae(fp.expj(2+3j), (-0.020718731002242879378 + 0.045271253156092975488j)) + assert ae(fp.expjpi(0), (1.0 + 0.0j)) + assert ae(fp.expjpi(1), (-1.0 + 0.0j)) + assert ae(fp.expjpi(2), (1.0 + 0.0j)) + assert ae(fp.expjpi(0.75), (-0.7071067811865475244 + 0.7071067811865475244j)) + assert ae(fp.expjpi(2+3j), (0.000080699517570304599239 + 0.0j)) + +def test_fp_bernoulli(): + assert ae(fp.bernoulli(0), 1.0) + assert ae(fp.bernoulli(1), -0.5) + assert ae(fp.bernoulli(2), 0.16666666666666666667) + assert ae(fp.bernoulli(10), 0.075757575757575757576) + assert ae(fp.bernoulli(11), 0.0) + +def test_fp_gamma(): + assert ae(fp.gamma(1), 1.0) + assert ae(fp.gamma(1.5), 0.88622692545275801365) + assert ae(fp.gamma(10), 362880.0) + assert ae(fp.gamma(-0.5), -3.5449077018110320546) + assert ae(fp.gamma(-7.1), 0.0016478244570263333622) + assert ae(fp.gamma(12.3), 83385367.899970000963) + assert ae(fp.gamma(2+0j), (1.0 + 0.0j)) + assert ae(fp.gamma(-2.5+0j), (-0.94530872048294188123 + 0.0j)) + assert ae(fp.gamma(3+4j), (0.0052255384713692141947 - 0.17254707929430018772j)) + assert ae(fp.gamma(-3-4j), (0.00001460997305874775607 - 0.000020760733311509070396j)) + assert ae(fp.fac(0), 1.0) + assert ae(fp.fac(1), 1.0) + assert ae(fp.fac(20), 2432902008176640000.0) + assert ae(fp.fac(-3.5), -0.94530872048294188123) + assert ae(fp.fac(2+3j), (-0.44011340763700171113 - 0.06363724312631702183j)) + assert ae(fp.loggamma(1.0), 0.0) + assert ae(fp.loggamma(2.0), 0.0) + assert ae(fp.loggamma(3.0), 0.69314718055994530942) + assert ae(fp.loggamma(7.25), 7.0521854507385394449) + assert ae(fp.loggamma(1000.0), 5905.2204232091812118) + assert ae(fp.loggamma(1e50), 1.1412925464970229298e+52) + assert ae(fp.loggamma(1e25+1e25j), (5.6125802751733671621e+26 + 5.7696599078528568383e+26j)) + assert ae(fp.loggamma(3+4j), (-1.7566267846037841105 + 4.7426644380346579282j)) + assert ae(fp.loggamma(-0.5), (1.2655121234846453965 - 3.1415926535897932385j)) + assert ae(fp.loggamma(-1.25), (1.3664317612369762346 - 6.2831853071795864769j)) + assert ae(fp.loggamma(-2.75), (0.0044878975359557733115 - 9.4247779607693797154j)) + assert ae(fp.loggamma(-3.5), (-1.3090066849930420464 - 12.566370614359172954j)) + assert ae(fp.loggamma(-4.5), (-2.8130840817693161197 - 15.707963267948966192j)) + assert ae(fp.loggamma(-2+3j), (-6.776523813485657093 - 4.568791367260286402j)) + assert ae(fp.loggamma(-1000.3), (-5912.8440347785205041 - 3144.7342462433830317j)) + assert ae(fp.loggamma(-100-100j), (-632.35117666833135562 - 158.37641469650352462j)) + assert ae(fp.loggamma(1e-10), 23.025850929882735237) + assert ae(fp.loggamma(-1e-10), (23.02585092999817837 - 3.1415926535897932385j)) + assert ae(fp.loggamma(1e-10j), (23.025850929940456804 - 1.5707963268526181857j)) + assert ae(fp.loggamma(1e-10j-1e-10), (22.679277339718205716 - 2.3561944902500664954j)) + +def test_fp_psi(): + assert ae(fp.psi(0, 3.7), 1.1671535393615114409) + assert ae(fp.psi(0, 0.5), -1.9635100260214234794) + assert ae(fp.psi(0, 1), -0.57721566490153286061) + assert ae(fp.psi(0, -2.5), 1.1031566406452431872) + assert ae(fp.psi(0, 12.9), 2.5179671503279156347) + assert ae(fp.psi(0, 100), 4.6001618527380874002) + assert ae(fp.psi(0, 2500.3), 7.8239660143238547877) + assert ae(fp.psi(0, 1e40), 92.103403719761827391) + assert ae(fp.psi(0, 1e200), 460.51701859880913677) + assert ae(fp.psi(0, 3.7+0j), (1.1671535393615114409 + 0.0j)) + assert ae(fp.psi(1, 3), 0.39493406684822643647) + assert ae(fp.psi(3, 2+3j), (-0.05383196209159972116 + 0.0076890935247364805218j)) + assert ae(fp.psi(4, -0.5+1j), (1.2719531355492328195 - 18.211833410936276774j)) + assert ae(fp.harmonic(0), 0.0) + assert ae(fp.harmonic(1), 1.0) + assert ae(fp.harmonic(2), 1.5) + assert ae(fp.harmonic(100), 5.1873775176396202608) + assert ae(fp.harmonic(-2.5), 1.2803723055467760478) + assert ae(fp.harmonic(2+3j), (1.9390425294578375875 + 0.87336044981834544043j)) + assert ae(fp.harmonic(-5-4j), (2.3725754822349437733 - 2.4160904444801621j)) + +def test_fp_zeta(): + assert ae(fp.zeta(1e100), 1.0) + assert ae(fp.zeta(3), 1.2020569031595942854) + assert ae(fp.zeta(2+0j), (1.6449340668482264365 + 0.0j)) + assert ae(fp.zeta(0.93), -13.713619351638164784) + assert ae(fp.zeta(1.74), 1.9796863545771774095) + assert ae(fp.zeta(0.0), -0.5) + assert ae(fp.zeta(-1.0), -0.083333333333333333333) + assert ae(fp.zeta(-2.0), 0.0) + assert ae(fp.zeta(-3.0), 0.0083333333333333333333) + assert ae(fp.zeta(-500.0), 0.0) + assert ae(fp.zeta(-7.4), 0.0036537321227995882447) + assert ae(fp.zeta(2.1), 1.5602165335033620158) + assert ae(fp.zeta(26.9), 1.0000000079854809935) + assert ae(fp.zeta(26), 1.0000000149015548284) + assert ae(fp.zeta(27), 1.0000000074507117898) + assert ae(fp.zeta(28), 1.0000000037253340248) + assert ae(fp.zeta(27.1), 1.000000006951755045) + assert ae(fp.zeta(32.7), 1.0000000001433243232) + assert ae(fp.zeta(100), 1.0) + assert ae(fp.altzeta(3.5), 0.92755357777394803511) + assert ae(fp.altzeta(1), 0.69314718055994530942) + assert ae(fp.altzeta(2), 0.82246703342411321824) + assert ae(fp.altzeta(0), 0.5) + assert ae(fp.zeta(-2+3j, 1), (0.13297115587929864827 + 0.12305330040458776494j)) + assert ae(fp.zeta(-2+3j, 5), (18.384866151867576927 - 11.377015110597711009j)) + assert ae(fp.zeta(1.0000000001), 9999999173.1735741337) + assert ae(fp.zeta(0.9999999999), -9999999172.0191428039) + assert ae(fp.zeta(1+0.000000001j), (0.57721566490153286061 - 999999999.99999993765j)) + assert ae(fp.primezeta(2.5+4j), (-0.16922458243438033385 - 0.010847965298387727811j)) + assert ae(fp.primezeta(4), 0.076993139764246844943) + assert ae(fp.riemannr(3.7), 2.3034079839110855717) + assert ae(fp.riemannr(8), 3.9011860449341499474) + assert ae(fp.riemannr(3+4j), (2.2369653314259991796 + 1.6339943856990281694j)) + +def test_fp_hyp2f1(): + assert ae(fp.hyp2f1(1, (3,2), 3.25, 5.0), (-0.46600275923108143059 - 0.74393667908854842325j)) + assert ae(fp.hyp2f1(1+1j, (3,2), 3.25, 5.0), (-5.9208875603806515987 - 2.3813557707889590686j)) + assert ae(fp.hyp2f1(1+1j, (3,2), 3.25, 2+3j), (0.17174552030925080445 + 0.19589781970539389999j)) + +def test_fp_erf(): + assert fp.erf(2) == fp.erf(2.0) == fp.erf(2.0+0.0j) + assert fp.erf(fp.inf) == 1.0 + assert fp.erf(fp.ninf) == -1.0 + assert ae(fp.erf(0), 0.0) + assert ae(fp.erf(-0), -0.0) + assert ae(fp.erf(0.3), 0.32862675945912741619) + assert ae(fp.erf(-0.3), -0.32862675945912741619) + assert ae(fp.erf(0.9), 0.79690821242283213966) + assert ae(fp.erf(-0.9), -0.79690821242283213966) + assert ae(fp.erf(1.0), 0.84270079294971486934) + assert ae(fp.erf(-1.0), -0.84270079294971486934) + assert ae(fp.erf(1.1), 0.88020506957408172966) + assert ae(fp.erf(-1.1), -0.88020506957408172966) + assert ae(fp.erf(8.5), 1.0) + assert ae(fp.erf(-8.5), -1.0) + assert ae(fp.erf(9.1), 1.0) + assert ae(fp.erf(-9.1), -1.0) + assert ae(fp.erf(20.0), 1.0) + assert ae(fp.erf(-20.0), -1.0) + assert ae(fp.erf(10000.0), 1.0) + assert ae(fp.erf(-10000.0), -1.0) + assert ae(fp.erf(1e+50), 1.0) + assert ae(fp.erf(-1e+50), -1.0) + assert ae(fp.erf(1j), 1.650425758797542876j) + assert ae(fp.erf(-1j), -1.650425758797542876j) + assert ae(fp.erf((2+3j)), (-20.829461427614568389 + 8.6873182714701631444j)) + assert ae(fp.erf(-(2+3j)), -(-20.829461427614568389 + 8.6873182714701631444j)) + assert ae(fp.erf((8+9j)), (-1072004.2525062051158 + 364149.91954310255423j)) + assert ae(fp.erf(-(8+9j)), -(-1072004.2525062051158 + 364149.91954310255423j)) + assert fp.erfc(fp.inf) == 0.0 + assert fp.erfc(fp.ninf) == 2.0 + assert fp.erfc(0) == 1 + assert fp.erfc(-0.0) == 1 + assert fp.erfc(0+0j) == 1 + assert ae(fp.erfc(0.3), 0.67137324054087258381) + assert ae(fp.erfc(-0.3), 1.3286267594591274162) + assert ae(fp.erfc(0.9), 0.20309178757716786034) + assert ae(fp.erfc(-0.9), 1.7969082124228321397) + assert ae(fp.erfc(1.0), 0.15729920705028513066) + assert ae(fp.erfc(-1.0), 1.8427007929497148693) + assert ae(fp.erfc(1.1), 0.11979493042591827034) + assert ae(fp.erfc(-1.1), 1.8802050695740817297) + assert ae(fp.erfc(8.5), 2.7623240713337714461e-33) + assert ae(fp.erfc(-8.5), 2.0) + assert ae(fp.erfc(9.1), 6.6969004279886077452e-38) + assert ae(fp.erfc(-9.1), 2.0) + assert ae(fp.erfc(20.0), 5.3958656116079009289e-176) + assert ae(fp.erfc(-20.0), 2.0) + assert ae(fp.erfc(10000.0), 0.0) + assert ae(fp.erfc(-10000.0), 2.0) + assert ae(fp.erfc(1e+50), 0.0) + assert ae(fp.erfc(-1e+50), 2.0) + assert ae(fp.erfc(1j), (1.0 - 1.650425758797542876j)) + assert ae(fp.erfc(-1j), (1.0 + 1.650425758797542876j)) + assert ae(fp.erfc((2+3j)), (21.829461427614568389 - 8.6873182714701631444j), 1e-13) + assert ae(fp.erfc(-(2+3j)), (-19.829461427614568389 + 8.6873182714701631444j), 1e-13) + assert ae(fp.erfc((8+9j)), (1072005.2525062051158 - 364149.91954310255423j)) + assert ae(fp.erfc(-(8+9j)), (-1072003.2525062051158 + 364149.91954310255423j)) + assert ae(fp.erfc(20+0j), (5.3958656116079009289e-176 + 0.0j)) + +def test_fp_lambertw(): + assert ae(fp.lambertw(0.0), 0.0) + assert ae(fp.lambertw(1.0), 0.567143290409783873) + assert ae(fp.lambertw(7.5), 1.5662309537823875394) + assert ae(fp.lambertw(-0.25), -0.35740295618138890307) + assert ae(fp.lambertw(-10.0), (1.3699809685212708156 + 2.140194527074713196j)) + assert ae(fp.lambertw(0+0j), (0.0 + 0.0j)) + assert ae(fp.lambertw(4+0j), (1.2021678731970429392 + 0.0j)) + assert ae(fp.lambertw(1000.5), 5.2500227450408980127) + assert ae(fp.lambertw(1e100), 224.84310644511850156) + assert ae(fp.lambertw(-1000.0), (5.1501630246362515223 + 2.6641981432905204596j)) + assert ae(fp.lambertw(1e-10), 9.9999999990000003645e-11) + assert ae(fp.lambertw(1e-10j), (1.0000000000000000728e-20 + 1.0000000000000000364e-10j)) + assert ae(fp.lambertw(3+4j), (1.2815618061237758782 + 0.53309522202097107131j)) + assert ae(fp.lambertw(-3-4j), (1.0750730665692549276 - 1.3251023817343588823j)) + assert ae(fp.lambertw(10000+1000j), (7.2361526563371602186 + 0.087567810943839352034j)) + assert ae(fp.lambertw(0.0, -1), -fp.inf) + assert ae(fp.lambertw(1.0, -1), (-1.5339133197935745079 - 4.3751851530618983855j)) + assert ae(fp.lambertw(7.5, -1), (0.44125668415098614999 - 4.8039842008452390179j)) + assert ae(fp.lambertw(-0.25, -1), -2.1532923641103496492) + assert ae(fp.lambertw(-10.0, -1), (1.3699809685212708156 - 2.140194527074713196j)) + assert ae(fp.lambertw(0+0j, -1), -fp.inf) + assert ae(fp.lambertw(4+0j, -1), (-0.15730793189620765317 - 4.6787800704666656212j)) + assert ae(fp.lambertw(1000.5, -1), (4.9153765415404024736 - 5.4465682700815159569j)) + assert ae(fp.lambertw(1e100, -1), (224.84272130101601052 - 6.2553713838167244141j)) + assert ae(fp.lambertw(-1000.0, -1), (5.1501630246362515223 - 2.6641981432905204596j)) + assert ae(fp.lambertw(1e-10, -1), (-26.303186778379041521 - 3.2650939117038283975j)) + assert ae(fp.lambertw(1e-10j, -1), (-26.297238779529035028 - 1.6328071613455765135j)) + assert ae(fp.lambertw(3+4j, -1), (0.25856740686699741676 - 3.8521166861614355895j)) + assert ae(fp.lambertw(-3-4j, -1), (-0.32028750204310768396 - 6.8801677192091972343j)) + assert ae(fp.lambertw(10000+1000j, -1), (7.0255308742285435567 - 5.5177506835734067601j)) + assert ae(fp.lambertw(0.0, 2), -fp.inf) + assert ae(fp.lambertw(1.0, 2), (-2.4015851048680028842 + 10.776299516115070898j)) + assert ae(fp.lambertw(7.5, 2), (-0.38003357962843791529 + 10.960916473368746184j)) + assert ae(fp.lambertw(-0.25, 2), (-4.0558735269061511898 + 13.852334658567271386j)) + assert ae(fp.lambertw(-10.0, 2), (-0.34479123764318858696 + 14.112740596763592363j)) + assert ae(fp.lambertw(0+0j, 2), -fp.inf) + assert ae(fp.lambertw(4+0j, 2), (-1.0070343323804262788 + 10.903476551861683082j)) + assert ae(fp.lambertw(1000.5, 2), (4.4076185165459395295 + 11.365524591091402177j)) + assert ae(fp.lambertw(1e100, 2), (224.84156762724875878 + 12.510785262632255672j)) + assert ae(fp.lambertw(-1000.0, 2), (4.1984245610246530756 + 14.420478573754313845j)) + assert ae(fp.lambertw(1e-10, 2), (-26.362258095445866488 + 9.7800247407031482519j)) + assert ae(fp.lambertw(1e-10j, 2), (-26.384250801683084252 + 11.403535950607739763j)) + assert ae(fp.lambertw(3+4j, 2), (-0.86554679943333993562 + 11.849956798331992027j)) + assert ae(fp.lambertw(-3-4j, 2), (-0.55792273874679112639 + 8.7173627024159324811j)) + assert ae(fp.lambertw(10000+1000j, 2), (6.6223802254585662734 + 11.61348646825020766j)) + +def test_fp_stress_ei_e1(): + # Can be tightened on recent Pythons with more accurate math/cmath + ATOL = 1e-13 + PTOL = 1e-12 + v = fp.e1(1.1641532182693481445e-10) + assert ae(v, 22.296641293693077672, tol=ATOL) + assert type(v) is float + v = fp.e1(0.25) + assert ae(v, 1.0442826344437381945, tol=ATOL) + assert type(v) is float + v = fp.e1(1.0) + assert ae(v, 0.21938393439552027368, tol=ATOL) + assert type(v) is float + v = fp.e1(2.0) + assert ae(v, 0.048900510708061119567, tol=ATOL) + assert type(v) is float + v = fp.e1(5.0) + assert ae(v, 0.0011482955912753257973, tol=ATOL) + assert type(v) is float + v = fp.e1(20.0) + assert ae(v, 9.8355252906498816904e-11, tol=ATOL) + assert type(v) is float + v = fp.e1(30.0) + assert ae(v, 3.0215520106888125448e-15, tol=ATOL) + assert type(v) is float + v = fp.e1(40.0) + assert ae(v, 1.0367732614516569722e-19, tol=ATOL) + assert type(v) is float + v = fp.e1(50.0) + assert ae(v, 3.7832640295504590187e-24, tol=ATOL) + assert type(v) is float + v = fp.e1(80.0) + assert ae(v, 2.2285432586884729112e-37, tol=ATOL) + assert type(v) is float + v = fp.e1((1.1641532182693481445e-10 + 0.0j)) + assert ae(v, (22.296641293693077672 + 0.0j), tol=ATOL) + assert ae(v.real, 22.296641293693077672, tol=PTOL) + assert v.imag == 0 + v = fp.e1((0.25 + 0.0j)) + assert ae(v, (1.0442826344437381945 + 0.0j), tol=ATOL) + assert ae(v.real, 1.0442826344437381945, tol=PTOL) + assert v.imag == 0 + v = fp.e1((1.0 + 0.0j)) + assert ae(v, (0.21938393439552027368 + 0.0j), tol=ATOL) + assert ae(v.real, 0.21938393439552027368, tol=PTOL) + assert v.imag == 0 + v = fp.e1((2.0 + 0.0j)) + assert ae(v, (0.048900510708061119567 + 0.0j), tol=ATOL) + assert ae(v.real, 0.048900510708061119567, tol=PTOL) + assert v.imag == 0 + v = fp.e1((5.0 + 0.0j)) + assert ae(v, (0.0011482955912753257973 + 0.0j), tol=ATOL) + assert ae(v.real, 0.0011482955912753257973, tol=PTOL) + assert v.imag == 0 + v = fp.e1((20.0 + 0.0j)) + assert ae(v, (9.8355252906498816904e-11 + 0.0j), tol=ATOL) + assert ae(v.real, 9.8355252906498816904e-11, tol=PTOL) + assert v.imag == 0 + v = fp.e1((30.0 + 0.0j)) + assert ae(v, (3.0215520106888125448e-15 + 0.0j), tol=ATOL) + assert ae(v.real, 3.0215520106888125448e-15, tol=PTOL) + assert v.imag == 0 + v = fp.e1((40.0 + 0.0j)) + assert ae(v, (1.0367732614516569722e-19 + 0.0j), tol=ATOL) + assert ae(v.real, 1.0367732614516569722e-19, tol=PTOL) + assert v.imag == 0 + v = fp.e1((50.0 + 0.0j)) + assert ae(v, (3.7832640295504590187e-24 + 0.0j), tol=ATOL) + assert ae(v.real, 3.7832640295504590187e-24, tol=PTOL) + assert v.imag == 0 + v = fp.e1((80.0 + 0.0j)) + assert ae(v, (2.2285432586884729112e-37 + 0.0j), tol=ATOL) + assert ae(v.real, 2.2285432586884729112e-37, tol=PTOL) + assert v.imag == 0 + v = fp.e1((4.6566128730773925781e-10 + 1.1641532182693481445e-10j)) + assert ae(v, (20.880034622014215597 - 0.24497866301044883237j), tol=ATOL) + assert ae(v.real, 20.880034622014215597, tol=PTOL) + assert ae(v.imag, -0.24497866301044883237, tol=PTOL) + v = fp.e1((1.0 + 0.25j)) + assert ae(v, (0.19731063945004229095 - 0.087366045774299963672j), tol=ATOL) + assert ae(v.real, 0.19731063945004229095, tol=PTOL) + assert ae(v.imag, -0.087366045774299963672, tol=PTOL) + v = fp.e1((4.0 + 1.0j)) + assert ae(v, (0.0013106173980145506944 - 0.0034542480199350626699j), tol=ATOL) + assert ae(v.real, 0.0013106173980145506944, tol=PTOL) + assert ae(v.imag, -0.0034542480199350626699, tol=PTOL) + v = fp.e1((8.0 + 2.0j)) + assert ae(v, (-0.000022278049065270225945 - 0.000029191940456521555288j), tol=ATOL) + assert ae(v.real, -0.000022278049065270225945, tol=PTOL) + assert ae(v.imag, -0.000029191940456521555288, tol=PTOL) + v = fp.e1((20.0 + 5.0j)) + assert ae(v, (4.7711374515765346894e-11 + 8.2902652405126947359e-11j), tol=ATOL) + assert ae(v.real, 4.7711374515765346894e-11, tol=PTOL) + assert ae(v.imag, 8.2902652405126947359e-11, tol=PTOL) + v = fp.e1((80.0 + 20.0j)) + assert ae(v, (3.8353473865788235787e-38 - 2.129247592349605139e-37j), tol=ATOL) + assert ae(v.real, 3.8353473865788235787e-38, tol=PTOL) + assert ae(v.imag, -2.129247592349605139e-37, tol=PTOL) + v = fp.e1((120.0 + 30.0j)) + assert ae(v, (2.3836002337480334716e-55 + 5.6704043587126198306e-55j), tol=ATOL) + assert ae(v.real, 2.3836002337480334716e-55, tol=PTOL) + assert ae(v.imag, 5.6704043587126198306e-55, tol=PTOL) + v = fp.e1((160.0 + 40.0j)) + assert ae(v, (-1.6238022898654510661e-72 - 1.104172355572287367e-72j), tol=ATOL) + assert ae(v.real, -1.6238022898654510661e-72, tol=PTOL) + assert ae(v.imag, -1.104172355572287367e-72, tol=PTOL) + v = fp.e1((200.0 + 50.0j)) + assert ae(v, (6.6800061461666228487e-90 + 1.4473816083541016115e-91j), tol=ATOL) + assert ae(v.real, 6.6800061461666228487e-90, tol=PTOL) + assert ae(v.imag, 1.4473816083541016115e-91, tol=PTOL) + v = fp.e1((320.0 + 80.0j)) + assert ae(v, (4.2737871527778786157e-143 + 3.1789935525785660314e-142j), tol=ATOL) + assert ae(v.real, 4.2737871527778786157e-143, tol=PTOL) + assert ae(v.imag, 3.1789935525785660314e-142, tol=PTOL) + v = fp.e1((1.1641532182693481445e-10 + 1.1641532182693481445e-10j)) + assert ae(v, (21.950067703413105017 - 0.7853981632810329878j), tol=ATOL) + assert ae(v.real, 21.950067703413105017, tol=PTOL) + assert ae(v.imag, -0.7853981632810329878, tol=PTOL) + v = fp.e1((0.25 + 0.25j)) + assert ae(v, (0.71092525792923287894 - 0.56491812441304194711j), tol=ATOL) + assert ae(v.real, 0.71092525792923287894, tol=PTOL) + assert ae(v.imag, -0.56491812441304194711, tol=PTOL) + v = fp.e1((1.0 + 1.0j)) + assert ae(v, (0.00028162445198141832551 - 0.17932453503935894015j), tol=ATOL) + assert ae(v.real, 0.00028162445198141832551, tol=PTOL) + assert ae(v.imag, -0.17932453503935894015, tol=PTOL) + v = fp.e1((2.0 + 2.0j)) + assert ae(v, (-0.033767089606562004246 - 0.018599414169750541925j), tol=ATOL) + assert ae(v.real, -0.033767089606562004246, tol=PTOL) + assert ae(v.imag, -0.018599414169750541925, tol=PTOL) + v = fp.e1((5.0 + 5.0j)) + assert ae(v, (0.0007266506660356393891 + 0.00047102780163522245054j), tol=ATOL) + assert ae(v.real, 0.0007266506660356393891, tol=PTOL) + assert ae(v.imag, 0.00047102780163522245054, tol=PTOL) + v = fp.e1((20.0 + 20.0j)) + assert ae(v, (-2.3824537449367396579e-11 - 6.6969873156525615158e-11j), tol=ATOL) + assert ae(v.real, -2.3824537449367396579e-11, tol=PTOL) + assert ae(v.imag, -6.6969873156525615158e-11, tol=PTOL) + v = fp.e1((30.0 + 30.0j)) + assert ae(v, (1.7316045841744061617e-15 + 1.3065678019487308689e-15j), tol=ATOL) + assert ae(v.real, 1.7316045841744061617e-15, tol=PTOL) + assert ae(v.imag, 1.3065678019487308689e-15, tol=PTOL) + v = fp.e1((40.0 + 40.0j)) + assert ae(v, (-7.4001043002899232182e-20 - 4.991847855336816304e-21j), tol=ATOL) + assert ae(v.real, -7.4001043002899232182e-20, tol=PTOL) + assert ae(v.imag, -4.991847855336816304e-21, tol=PTOL) + v = fp.e1((50.0 + 50.0j)) + assert ae(v, (2.3566128324644641219e-24 - 1.3188326726201614778e-24j), tol=ATOL) + assert ae(v.real, 2.3566128324644641219e-24, tol=PTOL) + assert ae(v.imag, -1.3188326726201614778e-24, tol=PTOL) + v = fp.e1((80.0 + 80.0j)) + assert ae(v, (9.8279750572186526673e-38 + 1.243952841288868831e-37j), tol=ATOL) + assert ae(v.real, 9.8279750572186526673e-38, tol=PTOL) + assert ae(v.imag, 1.243952841288868831e-37, tol=PTOL) + v = fp.e1((1.1641532182693481445e-10 + 4.6566128730773925781e-10j)) + assert ae(v, (20.880034621664969632 - 1.3258176632023711778j), tol=ATOL) + assert ae(v.real, 20.880034621664969632, tol=PTOL) + assert ae(v.imag, -1.3258176632023711778, tol=PTOL) + v = fp.e1((0.25 + 1.0j)) + assert ae(v, (-0.16868306393667788761 - 0.4858011885947426971j), tol=ATOL) + assert ae(v.real, -0.16868306393667788761, tol=PTOL) + assert ae(v.imag, -0.4858011885947426971, tol=PTOL) + v = fp.e1((1.0 + 4.0j)) + assert ae(v, (0.03373591813926547318 + 0.073523452241083821877j), tol=ATOL) + assert ae(v.real, 0.03373591813926547318, tol=PTOL) + assert ae(v.imag, 0.073523452241083821877, tol=PTOL) + v = fp.e1((2.0 + 8.0j)) + assert ae(v, (-0.015392833434733785143 - 0.0031747121557605415914j), tol=ATOL) + assert ae(v.real, -0.015392833434733785143, tol=PTOL) + assert ae(v.imag, -0.0031747121557605415914, tol=PTOL) + v = fp.e1((5.0 + 20.0j)) + assert ae(v, (-0.00024419662286542966525 - 0.00021008322966152755674j), tol=ATOL) + assert ae(v.real, -0.00024419662286542966525, tol=PTOL) + assert ae(v.imag, -0.00021008322966152755674, tol=PTOL) + v = fp.e1((20.0 + 80.0j)) + assert ae(v, (2.3255552781051330088e-11 + 8.9463918891349438007e-12j), tol=ATOL) + assert ae(v.real, 2.3255552781051330088e-11, tol=PTOL) + assert ae(v.imag, 8.9463918891349438007e-12, tol=PTOL) + v = fp.e1((30.0 + 120.0j)) + assert ae(v, (-2.7068919097124652332e-16 - 7.0477762411705130239e-16j), tol=ATOL) + assert ae(v.real, -2.7068919097124652332e-16, tol=PTOL) + assert ae(v.imag, -7.0477762411705130239e-16, tol=PTOL) + v = fp.e1((40.0 + 160.0j)) + assert ae(v, (-1.1695597827678024687e-20 + 2.2907401455645736661e-20j), tol=ATOL) + assert ae(v.real, -1.1695597827678024687e-20, tol=PTOL) + assert ae(v.imag, 2.2907401455645736661e-20, tol=PTOL) + v = fp.e1((50.0 + 200.0j)) + assert ae(v, (9.0323746914410162531e-25 - 2.3950601790033530935e-25j), tol=ATOL) + assert ae(v.real, 9.0323746914410162531e-25, tol=PTOL) + assert ae(v.imag, -2.3950601790033530935e-25, tol=PTOL) + v = fp.e1((80.0 + 320.0j)) + assert ae(v, (3.4819106748728063576e-38 - 4.215653005615772724e-38j), tol=ATOL) + assert ae(v.real, 3.4819106748728063576e-38, tol=PTOL) + assert ae(v.imag, -4.215653005615772724e-38, tol=PTOL) + v = fp.e1((0.0 + 1.1641532182693481445e-10j)) + assert ae(v, (22.29664129357666235 - 1.5707963266784812974j), tol=ATOL) + assert ae(v.real, 22.29664129357666235, tol=PTOL) + assert ae(v.imag, -1.5707963266784812974, tol=PTOL) + v = fp.e1((0.0 + 0.25j)) + assert ae(v, (0.82466306258094565309 - 1.3216627564751394551j), tol=ATOL) + assert ae(v.real, 0.82466306258094565309, tol=PTOL) + assert ae(v.imag, -1.3216627564751394551, tol=PTOL) + v = fp.e1((0.0 + 1.0j)) + assert ae(v, (-0.33740392290096813466 - 0.62471325642771360429j), tol=ATOL) + assert ae(v.real, -0.33740392290096813466, tol=PTOL) + assert ae(v.imag, -0.62471325642771360429, tol=PTOL) + v = fp.e1((0.0 + 2.0j)) + assert ae(v, (-0.4229808287748649957 + 0.034616650007798229345j), tol=ATOL) + assert ae(v.real, -0.4229808287748649957, tol=PTOL) + assert ae(v.imag, 0.034616650007798229345, tol=PTOL) + v = fp.e1((0.0 + 5.0j)) + assert ae(v, (0.19002974965664387862 - 0.020865081850222481957j), tol=ATOL) + assert ae(v.real, 0.19002974965664387862, tol=PTOL) + assert ae(v.imag, -0.020865081850222481957, tol=PTOL) + v = fp.e1((0.0 + 20.0j)) + assert ae(v, (-0.04441982084535331654 - 0.022554625751456779068j), tol=ATOL) + assert ae(v.real, -0.04441982084535331654, tol=PTOL) + assert ae(v.imag, -0.022554625751456779068, tol=PTOL) + v = fp.e1((0.0 + 30.0j)) + assert ae(v, (0.033032417282071143779 - 0.0040397867645455082476j), tol=ATOL) + assert ae(v.real, 0.033032417282071143779, tol=PTOL) + assert ae(v.imag, -0.0040397867645455082476, tol=PTOL) + v = fp.e1((0.0 + 40.0j)) + assert ae(v, (-0.019020007896208766962 + 0.016188792559887887544j), tol=ATOL) + assert ae(v.real, -0.019020007896208766962, tol=PTOL) + assert ae(v.imag, 0.016188792559887887544, tol=PTOL) + v = fp.e1((0.0 + 50.0j)) + assert ae(v, (0.0056283863241163054402 - 0.019179254308960724503j), tol=ATOL) + assert ae(v.real, 0.0056283863241163054402, tol=PTOL) + assert ae(v.imag, -0.019179254308960724503, tol=PTOL) + v = fp.e1((0.0 + 80.0j)) + assert ae(v, (0.012402501155070958192 + 0.0015345601175906961199j), tol=ATOL) + assert ae(v.real, 0.012402501155070958192, tol=PTOL) + assert ae(v.imag, 0.0015345601175906961199, tol=PTOL) + v = fp.e1((-1.1641532182693481445e-10 + 4.6566128730773925781e-10j)) + assert ae(v, (20.880034621432138988 - 1.8157749894560994861j), tol=ATOL) + assert ae(v.real, 20.880034621432138988, tol=PTOL) + assert ae(v.imag, -1.8157749894560994861, tol=PTOL) + v = fp.e1((-0.25 + 1.0j)) + assert ae(v, (-0.59066621214766308594 - 0.74474454765205036972j), tol=ATOL) + assert ae(v.real, -0.59066621214766308594, tol=PTOL) + assert ae(v.imag, -0.74474454765205036972, tol=PTOL) + v = fp.e1((-1.0 + 4.0j)) + assert ae(v, (0.49739047283060471093 + 0.41543605404038863174j), tol=ATOL) + assert ae(v.real, 0.49739047283060471093, tol=PTOL) + assert ae(v.imag, 0.41543605404038863174, tol=PTOL) + v = fp.e1((-2.0 + 8.0j)) + assert ae(v, (-0.8705211147733730969 + 0.24099328498605539667j), tol=ATOL) + assert ae(v.real, -0.8705211147733730969, tol=PTOL) + assert ae(v.imag, 0.24099328498605539667, tol=PTOL) + v = fp.e1((-5.0 + 20.0j)) + assert ae(v, (-7.0789514293925893007 - 1.6102177171960790536j), tol=ATOL) + assert ae(v.real, -7.0789514293925893007, tol=PTOL) + assert ae(v.imag, -1.6102177171960790536, tol=PTOL) + v = fp.e1((-20.0 + 80.0j)) + assert ae(v, (5855431.4907298084434 - 720920.93315409165707j), tol=ATOL) + assert ae(v.real, 5855431.4907298084434, tol=PTOL) + assert ae(v.imag, -720920.93315409165707, tol=PTOL) + v = fp.e1((-30.0 + 120.0j)) + assert ae(v, (-65402491644.703470747 - 56697658399.657460294j), tol=ATOL) + assert ae(v.real, -65402491644.703470747, tol=PTOL) + assert ae(v.imag, -56697658399.657460294, tol=PTOL) + v = fp.e1((-40.0 + 160.0j)) + assert ae(v, (25504929379604.776769 + 1429035198630573.2463j), tol=ATOL) + assert ae(v.real, 25504929379604.776769, tol=PTOL) + assert ae(v.imag, 1429035198630573.2463, tol=PTOL) + v = fp.e1((-50.0 + 200.0j)) + assert ae(v, (18437746526988116954.0 - 17146362239046152345.0j), tol=ATOL) + assert ae(v.real, 18437746526988116954.0, tol=PTOL) + assert ae(v.imag, -17146362239046152345.0, tol=PTOL) + v = fp.e1((-80.0 + 320.0j)) + assert ae(v, (3.3464697299634526706e+31 - 1.6473152633843023919e+32j), tol=ATOL) + assert ae(v.real, 3.3464697299634526706e+31, tol=PTOL) + assert ae(v.imag, -1.6473152633843023919e+32, tol=PTOL) + v = fp.e1((-4.6566128730773925781e-10 + 1.1641532182693481445e-10j)) + assert ae(v, (20.880034621082893023 - 2.8966139903465137624j), tol=ATOL) + assert ae(v.real, 20.880034621082893023, tol=PTOL) + assert ae(v.imag, -2.8966139903465137624, tol=PTOL) + v = fp.e1((-1.0 + 0.25j)) + assert ae(v, (-1.8942716983721074932 - 2.4689102827070540799j), tol=ATOL) + assert ae(v.real, -1.8942716983721074932, tol=PTOL) + assert ae(v.imag, -2.4689102827070540799, tol=PTOL) + v = fp.e1((-4.0 + 1.0j)) + assert ae(v, (-14.806699492675420438 + 9.1384225230837893776j), tol=ATOL) + assert ae(v.real, -14.806699492675420438, tol=PTOL) + assert ae(v.imag, 9.1384225230837893776, tol=PTOL) + v = fp.e1((-8.0 + 2.0j)) + assert ae(v, (54.633252667426386294 + 413.20318163814670688j), tol=ATOL) + assert ae(v.real, 54.633252667426386294, tol=PTOL) + assert ae(v.imag, 413.20318163814670688, tol=PTOL) + v = fp.e1((-20.0 + 5.0j)) + assert ae(v, (-711836.97165402624643 - 24745250.939695900956j), tol=ATOL) + assert ae(v.real, -711836.97165402624643, tol=PTOL) + assert ae(v.imag, -24745250.939695900956, tol=PTOL) + v = fp.e1((-80.0 + 20.0j)) + assert ae(v, (-4.2139911108612653091e+32 + 5.3367124741918251637e+32j), tol=ATOL) + assert ae(v.real, -4.2139911108612653091e+32, tol=PTOL) + assert ae(v.imag, 5.3367124741918251637e+32, tol=PTOL) + v = fp.e1((-120.0 + 30.0j)) + assert ae(v, (9.7760616203707508892e+48 - 1.058257682317195792e+50j), tol=ATOL) + assert ae(v.real, 9.7760616203707508892e+48, tol=PTOL) + assert ae(v.imag, -1.058257682317195792e+50, tol=PTOL) + v = fp.e1((-160.0 + 40.0j)) + assert ae(v, (8.7065541466623638861e+66 + 1.6577106725141739889e+67j), tol=ATOL) + assert ae(v.real, 8.7065541466623638861e+66, tol=PTOL) + assert ae(v.imag, 1.6577106725141739889e+67, tol=PTOL) + v = fp.e1((-200.0 + 50.0j)) + assert ae(v, (-3.070744996327018106e+84 - 1.7243244846769415903e+84j), tol=ATOL) + assert ae(v.real, -3.070744996327018106e+84, tol=PTOL) + assert ae(v.imag, -1.7243244846769415903e+84, tol=PTOL) + v = fp.e1((-320.0 + 80.0j)) + assert ae(v, (9.9960598637998647276e+135 - 2.6855081527595608863e+136j), tol=ATOL) + assert ae(v.real, 9.9960598637998647276e+135, tol=PTOL) + assert ae(v.imag, -2.6855081527595608863e+136, tol=PTOL) + v = fp.e1(-1.1641532182693481445e-10) + assert ae(v, (22.296641293460247028 - 3.1415926535897932385j), tol=ATOL) + assert ae(v.real, 22.296641293460247028, tol=PTOL) + assert ae(v.imag, -3.1415926535897932385, tol=PTOL) + v = fp.e1(-0.25) + assert ae(v, (0.54254326466191372953 - 3.1415926535897932385j), tol=ATOL) + assert ae(v.real, 0.54254326466191372953, tol=PTOL) + assert ae(v.imag, -3.1415926535897932385, tol=PTOL) + v = fp.e1(-1.0) + assert ae(v, (-1.8951178163559367555 - 3.1415926535897932385j), tol=ATOL) + assert ae(v.real, -1.8951178163559367555, tol=PTOL) + assert ae(v.imag, -3.1415926535897932385, tol=PTOL) + v = fp.e1(-2.0) + assert ae(v, (-4.9542343560018901634 - 3.1415926535897932385j), tol=ATOL) + assert ae(v.real, -4.9542343560018901634, tol=PTOL) + assert ae(v.imag, -3.1415926535897932385, tol=PTOL) + v = fp.e1(-5.0) + assert ae(v, (-40.185275355803177455 - 3.1415926535897932385j), tol=ATOL) + assert ae(v.real, -40.185275355803177455, tol=PTOL) + assert ae(v.imag, -3.1415926535897932385, tol=PTOL) + v = fp.e1(-20.0) + assert ae(v, (-25615652.66405658882 - 3.1415926535897932385j), tol=ATOL) + assert ae(v.real, -25615652.66405658882, tol=PTOL) + assert ae(v.imag, -3.1415926535897932385, tol=PTOL) + v = fp.e1(-30.0) + assert ae(v, (-368973209407.27419706 - 3.1415926535897932385j), tol=ATOL) + assert ae(v.real, -368973209407.27419706, tol=PTOL) + assert ae(v.imag, -3.1415926535897932385, tol=PTOL) + v = fp.e1(-40.0) + assert ae(v, (-6039718263611241.5784 - 3.1415926535897932385j), tol=ATOL) + assert ae(v.real, -6039718263611241.5784, tol=PTOL) + assert ae(v.imag, -3.1415926535897932385, tol=PTOL) + v = fp.e1(-50.0) + assert ae(v, (-1.0585636897131690963e+20 - 3.1415926535897932385j), tol=ATOL) + assert ae(v.real, -1.0585636897131690963e+20, tol=PTOL) + assert ae(v.imag, -3.1415926535897932385, tol=PTOL) + v = fp.e1(-80.0) + assert ae(v, (-7.0146000049047999696e+32 - 3.1415926535897932385j), tol=ATOL) + assert ae(v.real, -7.0146000049047999696e+32, tol=PTOL) + assert ae(v.imag, -3.1415926535897932385, tol=PTOL) + v = fp.e1((-1.1641532182693481445e-10 + 0.0j)) + assert ae(v, (22.296641293460247028 - 3.1415926535897932385j), tol=ATOL) + assert ae(v.real, 22.296641293460247028, tol=PTOL) + assert ae(v.imag, -3.1415926535897932385, tol=PTOL) + v = fp.e1((-0.25 + 0.0j)) + assert ae(v, (0.54254326466191372953 - 3.1415926535897932385j), tol=ATOL) + assert ae(v.real, 0.54254326466191372953, tol=PTOL) + assert ae(v.imag, -3.1415926535897932385, tol=PTOL) + v = fp.e1((-1.0 + 0.0j)) + assert ae(v, (-1.8951178163559367555 - 3.1415926535897932385j), tol=ATOL) + assert ae(v.real, -1.8951178163559367555, tol=PTOL) + assert ae(v.imag, -3.1415926535897932385, tol=PTOL) + v = fp.e1((-2.0 + 0.0j)) + assert ae(v, (-4.9542343560018901634 - 3.1415926535897932385j), tol=ATOL) + assert ae(v.real, -4.9542343560018901634, tol=PTOL) + assert ae(v.imag, -3.1415926535897932385, tol=PTOL) + v = fp.e1((-5.0 + 0.0j)) + assert ae(v, (-40.185275355803177455 - 3.1415926535897932385j), tol=ATOL) + assert ae(v.real, -40.185275355803177455, tol=PTOL) + assert ae(v.imag, -3.1415926535897932385, tol=PTOL) + v = fp.e1((-20.0 + 0.0j)) + assert ae(v, (-25615652.66405658882 - 3.1415926535897932385j), tol=ATOL) + assert ae(v.real, -25615652.66405658882, tol=PTOL) + assert ae(v.imag, -3.1415926535897932385, tol=PTOL) + v = fp.e1((-30.0 + 0.0j)) + assert ae(v, (-368973209407.27419706 - 3.1415926535897932385j), tol=ATOL) + assert ae(v.real, -368973209407.27419706, tol=PTOL) + assert ae(v.imag, -3.1415926535897932385, tol=PTOL) + v = fp.e1((-40.0 + 0.0j)) + assert ae(v, (-6039718263611241.5784 - 3.1415926535897932385j), tol=ATOL) + assert ae(v.real, -6039718263611241.5784, tol=PTOL) + assert ae(v.imag, -3.1415926535897932385, tol=PTOL) + v = fp.e1((-50.0 + 0.0j)) + assert ae(v, (-1.0585636897131690963e+20 - 3.1415926535897932385j), tol=ATOL) + assert ae(v.real, -1.0585636897131690963e+20, tol=PTOL) + assert ae(v.imag, -3.1415926535897932385, tol=PTOL) + v = fp.e1((-80.0 + 0.0j)) + assert ae(v, (-7.0146000049047999696e+32 - 3.1415926535897932385j), tol=ATOL) + assert ae(v.real, -7.0146000049047999696e+32, tol=PTOL) + assert ae(v.imag, -3.1415926535897932385, tol=PTOL) + v = fp.e1((-4.6566128730773925781e-10 - 1.1641532182693481445e-10j)) + assert ae(v, (20.880034621082893023 + 2.8966139903465137624j), tol=ATOL) + assert ae(v.real, 20.880034621082893023, tol=PTOL) + assert ae(v.imag, 2.8966139903465137624, tol=PTOL) + v = fp.e1((-1.0 - 0.25j)) + assert ae(v, (-1.8942716983721074932 + 2.4689102827070540799j), tol=ATOL) + assert ae(v.real, -1.8942716983721074932, tol=PTOL) + assert ae(v.imag, 2.4689102827070540799, tol=PTOL) + v = fp.e1((-4.0 - 1.0j)) + assert ae(v, (-14.806699492675420438 - 9.1384225230837893776j), tol=ATOL) + assert ae(v.real, -14.806699492675420438, tol=PTOL) + assert ae(v.imag, -9.1384225230837893776, tol=PTOL) + v = fp.e1((-8.0 - 2.0j)) + assert ae(v, (54.633252667426386294 - 413.20318163814670688j), tol=ATOL) + assert ae(v.real, 54.633252667426386294, tol=PTOL) + assert ae(v.imag, -413.20318163814670688, tol=PTOL) + v = fp.e1((-20.0 - 5.0j)) + assert ae(v, (-711836.97165402624643 + 24745250.939695900956j), tol=ATOL) + assert ae(v.real, -711836.97165402624643, tol=PTOL) + assert ae(v.imag, 24745250.939695900956, tol=PTOL) + v = fp.e1((-80.0 - 20.0j)) + assert ae(v, (-4.2139911108612653091e+32 - 5.3367124741918251637e+32j), tol=ATOL) + assert ae(v.real, -4.2139911108612653091e+32, tol=PTOL) + assert ae(v.imag, -5.3367124741918251637e+32, tol=PTOL) + v = fp.e1((-120.0 - 30.0j)) + assert ae(v, (9.7760616203707508892e+48 + 1.058257682317195792e+50j), tol=ATOL) + assert ae(v.real, 9.7760616203707508892e+48, tol=PTOL) + assert ae(v.imag, 1.058257682317195792e+50, tol=PTOL) + v = fp.e1((-160.0 - 40.0j)) + assert ae(v, (8.7065541466623638861e+66 - 1.6577106725141739889e+67j), tol=ATOL) + assert ae(v.real, 8.7065541466623638861e+66, tol=PTOL) + assert ae(v.imag, -1.6577106725141739889e+67, tol=PTOL) + v = fp.e1((-200.0 - 50.0j)) + assert ae(v, (-3.070744996327018106e+84 + 1.7243244846769415903e+84j), tol=ATOL) + assert ae(v.real, -3.070744996327018106e+84, tol=PTOL) + assert ae(v.imag, 1.7243244846769415903e+84, tol=PTOL) + v = fp.e1((-320.0 - 80.0j)) + assert ae(v, (9.9960598637998647276e+135 + 2.6855081527595608863e+136j), tol=ATOL) + assert ae(v.real, 9.9960598637998647276e+135, tol=PTOL) + assert ae(v.imag, 2.6855081527595608863e+136, tol=PTOL) + v = fp.e1((-1.1641532182693481445e-10 - 1.1641532182693481445e-10j)) + assert ae(v, (21.950067703180274374 + 2.356194490075929607j), tol=ATOL) + assert ae(v.real, 21.950067703180274374, tol=PTOL) + assert ae(v.imag, 2.356194490075929607, tol=PTOL) + v = fp.e1((-0.25 - 0.25j)) + assert ae(v, (0.21441047326710323254 + 2.0732153554307936389j), tol=ATOL) + assert ae(v.real, 0.21441047326710323254, tol=PTOL) + assert ae(v.imag, 2.0732153554307936389, tol=PTOL) + v = fp.e1((-1.0 - 1.0j)) + assert ae(v, (-1.7646259855638540684 + 0.7538228020792708192j), tol=ATOL) + assert ae(v.real, -1.7646259855638540684, tol=PTOL) + assert ae(v.imag, 0.7538228020792708192, tol=PTOL) + v = fp.e1((-2.0 - 2.0j)) + assert ae(v, (-1.8920781621855474089 - 2.1753697842428647236j), tol=ATOL) + assert ae(v.real, -1.8920781621855474089, tol=PTOL) + assert ae(v.imag, -2.1753697842428647236, tol=PTOL) + v = fp.e1((-5.0 - 5.0j)) + assert ae(v, (13.470936071475245856 + 18.464085049321024206j), tol=ATOL) + assert ae(v.real, 13.470936071475245856, tol=PTOL) + assert ae(v.imag, 18.464085049321024206, tol=PTOL) + v = fp.e1((-20.0 - 20.0j)) + assert ae(v, (-16589317.398788971896 - 5831702.3296441771206j), tol=ATOL) + assert ae(v.real, -16589317.398788971896, tol=PTOL) + assert ae(v.imag, -5831702.3296441771206, tol=PTOL) + v = fp.e1((-30.0 - 30.0j)) + assert ae(v, (154596484273.69322527 + 204179357837.41389696j), tol=ATOL) + assert ae(v.real, 154596484273.69322527, tol=PTOL) + assert ae(v.imag, 204179357837.41389696, tol=PTOL) + v = fp.e1((-40.0 - 40.0j)) + assert ae(v, (-287512180321448.45408 - 4203502407932314.974j), tol=ATOL) + assert ae(v.real, -287512180321448.45408, tol=PTOL) + assert ae(v.imag, -4203502407932314.974, tol=PTOL) + v = fp.e1((-50.0 - 50.0j)) + assert ae(v, (-36128528616649268826.0 + 64648801861338741963.0j), tol=ATOL) + assert ae(v.real, -36128528616649268826.0, tol=PTOL) + assert ae(v.imag, 64648801861338741963.0, tol=PTOL) + v = fp.e1((-80.0 - 80.0j)) + assert ae(v, (3.8674816337930010217e+32 + 3.0540709639658071041e+32j), tol=ATOL) + assert ae(v.real, 3.8674816337930010217e+32, tol=PTOL) + assert ae(v.imag, 3.0540709639658071041e+32, tol=PTOL) + v = fp.e1((-1.1641532182693481445e-10 - 4.6566128730773925781e-10j)) + assert ae(v, (20.880034621432138988 + 1.8157749894560994861j), tol=ATOL) + assert ae(v.real, 20.880034621432138988, tol=PTOL) + assert ae(v.imag, 1.8157749894560994861, tol=PTOL) + v = fp.e1((-0.25 - 1.0j)) + assert ae(v, (-0.59066621214766308594 + 0.74474454765205036972j), tol=ATOL) + assert ae(v.real, -0.59066621214766308594, tol=PTOL) + assert ae(v.imag, 0.74474454765205036972, tol=PTOL) + v = fp.e1((-1.0 - 4.0j)) + assert ae(v, (0.49739047283060471093 - 0.41543605404038863174j), tol=ATOL) + assert ae(v.real, 0.49739047283060471093, tol=PTOL) + assert ae(v.imag, -0.41543605404038863174, tol=PTOL) + v = fp.e1((-2.0 - 8.0j)) + assert ae(v, (-0.8705211147733730969 - 0.24099328498605539667j), tol=ATOL) + assert ae(v.real, -0.8705211147733730969, tol=PTOL) + assert ae(v.imag, -0.24099328498605539667, tol=PTOL) + v = fp.e1((-5.0 - 20.0j)) + assert ae(v, (-7.0789514293925893007 + 1.6102177171960790536j), tol=ATOL) + assert ae(v.real, -7.0789514293925893007, tol=PTOL) + assert ae(v.imag, 1.6102177171960790536, tol=PTOL) + v = fp.e1((-20.0 - 80.0j)) + assert ae(v, (5855431.4907298084434 + 720920.93315409165707j), tol=ATOL) + assert ae(v.real, 5855431.4907298084434, tol=PTOL) + assert ae(v.imag, 720920.93315409165707, tol=PTOL) + v = fp.e1((-30.0 - 120.0j)) + assert ae(v, (-65402491644.703470747 + 56697658399.657460294j), tol=ATOL) + assert ae(v.real, -65402491644.703470747, tol=PTOL) + assert ae(v.imag, 56697658399.657460294, tol=PTOL) + v = fp.e1((-40.0 - 160.0j)) + assert ae(v, (25504929379604.776769 - 1429035198630573.2463j), tol=ATOL) + assert ae(v.real, 25504929379604.776769, tol=PTOL) + assert ae(v.imag, -1429035198630573.2463, tol=PTOL) + v = fp.e1((-50.0 - 200.0j)) + assert ae(v, (18437746526988116954.0 + 17146362239046152345.0j), tol=ATOL) + assert ae(v.real, 18437746526988116954.0, tol=PTOL) + assert ae(v.imag, 17146362239046152345.0, tol=PTOL) + v = fp.e1((-80.0 - 320.0j)) + assert ae(v, (3.3464697299634526706e+31 + 1.6473152633843023919e+32j), tol=ATOL) + assert ae(v.real, 3.3464697299634526706e+31, tol=PTOL) + assert ae(v.imag, 1.6473152633843023919e+32, tol=PTOL) + v = fp.e1((0.0 - 1.1641532182693481445e-10j)) + assert ae(v, (22.29664129357666235 + 1.5707963266784812974j), tol=ATOL) + assert ae(v.real, 22.29664129357666235, tol=PTOL) + assert ae(v.imag, 1.5707963266784812974, tol=PTOL) + v = fp.e1((0.0 - 0.25j)) + assert ae(v, (0.82466306258094565309 + 1.3216627564751394551j), tol=ATOL) + assert ae(v.real, 0.82466306258094565309, tol=PTOL) + assert ae(v.imag, 1.3216627564751394551, tol=PTOL) + v = fp.e1((0.0 - 1.0j)) + assert ae(v, (-0.33740392290096813466 + 0.62471325642771360429j), tol=ATOL) + assert ae(v.real, -0.33740392290096813466, tol=PTOL) + assert ae(v.imag, 0.62471325642771360429, tol=PTOL) + v = fp.e1((0.0 - 2.0j)) + assert ae(v, (-0.4229808287748649957 - 0.034616650007798229345j), tol=ATOL) + assert ae(v.real, -0.4229808287748649957, tol=PTOL) + assert ae(v.imag, -0.034616650007798229345, tol=PTOL) + v = fp.e1((0.0 - 5.0j)) + assert ae(v, (0.19002974965664387862 + 0.020865081850222481957j), tol=ATOL) + assert ae(v.real, 0.19002974965664387862, tol=PTOL) + assert ae(v.imag, 0.020865081850222481957, tol=PTOL) + v = fp.e1((0.0 - 20.0j)) + assert ae(v, (-0.04441982084535331654 + 0.022554625751456779068j), tol=ATOL) + assert ae(v.real, -0.04441982084535331654, tol=PTOL) + assert ae(v.imag, 0.022554625751456779068, tol=PTOL) + v = fp.e1((0.0 - 30.0j)) + assert ae(v, (0.033032417282071143779 + 0.0040397867645455082476j), tol=ATOL) + assert ae(v.real, 0.033032417282071143779, tol=PTOL) + assert ae(v.imag, 0.0040397867645455082476, tol=PTOL) + v = fp.e1((0.0 - 40.0j)) + assert ae(v, (-0.019020007896208766962 - 0.016188792559887887544j), tol=ATOL) + assert ae(v.real, -0.019020007896208766962, tol=PTOL) + assert ae(v.imag, -0.016188792559887887544, tol=PTOL) + v = fp.e1((0.0 - 50.0j)) + assert ae(v, (0.0056283863241163054402 + 0.019179254308960724503j), tol=ATOL) + assert ae(v.real, 0.0056283863241163054402, tol=PTOL) + assert ae(v.imag, 0.019179254308960724503, tol=PTOL) + v = fp.e1((0.0 - 80.0j)) + assert ae(v, (0.012402501155070958192 - 0.0015345601175906961199j), tol=ATOL) + assert ae(v.real, 0.012402501155070958192, tol=PTOL) + assert ae(v.imag, -0.0015345601175906961199, tol=PTOL) + v = fp.e1((1.1641532182693481445e-10 - 4.6566128730773925781e-10j)) + assert ae(v, (20.880034621664969632 + 1.3258176632023711778j), tol=ATOL) + assert ae(v.real, 20.880034621664969632, tol=PTOL) + assert ae(v.imag, 1.3258176632023711778, tol=PTOL) + v = fp.e1((0.25 - 1.0j)) + assert ae(v, (-0.16868306393667788761 + 0.4858011885947426971j), tol=ATOL) + assert ae(v.real, -0.16868306393667788761, tol=PTOL) + assert ae(v.imag, 0.4858011885947426971, tol=PTOL) + v = fp.e1((1.0 - 4.0j)) + assert ae(v, (0.03373591813926547318 - 0.073523452241083821877j), tol=ATOL) + assert ae(v.real, 0.03373591813926547318, tol=PTOL) + assert ae(v.imag, -0.073523452241083821877, tol=PTOL) + v = fp.e1((2.0 - 8.0j)) + assert ae(v, (-0.015392833434733785143 + 0.0031747121557605415914j), tol=ATOL) + assert ae(v.real, -0.015392833434733785143, tol=PTOL) + assert ae(v.imag, 0.0031747121557605415914, tol=PTOL) + v = fp.e1((5.0 - 20.0j)) + assert ae(v, (-0.00024419662286542966525 + 0.00021008322966152755674j), tol=ATOL) + assert ae(v.real, -0.00024419662286542966525, tol=PTOL) + assert ae(v.imag, 0.00021008322966152755674, tol=PTOL) + v = fp.e1((20.0 - 80.0j)) + assert ae(v, (2.3255552781051330088e-11 - 8.9463918891349438007e-12j), tol=ATOL) + assert ae(v.real, 2.3255552781051330088e-11, tol=PTOL) + assert ae(v.imag, -8.9463918891349438007e-12, tol=PTOL) + v = fp.e1((30.0 - 120.0j)) + assert ae(v, (-2.7068919097124652332e-16 + 7.0477762411705130239e-16j), tol=ATOL) + assert ae(v.real, -2.7068919097124652332e-16, tol=PTOL) + assert ae(v.imag, 7.0477762411705130239e-16, tol=PTOL) + v = fp.e1((40.0 - 160.0j)) + assert ae(v, (-1.1695597827678024687e-20 - 2.2907401455645736661e-20j), tol=ATOL) + assert ae(v.real, -1.1695597827678024687e-20, tol=PTOL) + assert ae(v.imag, -2.2907401455645736661e-20, tol=PTOL) + v = fp.e1((50.0 - 200.0j)) + assert ae(v, (9.0323746914410162531e-25 + 2.3950601790033530935e-25j), tol=ATOL) + assert ae(v.real, 9.0323746914410162531e-25, tol=PTOL) + assert ae(v.imag, 2.3950601790033530935e-25, tol=PTOL) + v = fp.e1((80.0 - 320.0j)) + assert ae(v, (3.4819106748728063576e-38 + 4.215653005615772724e-38j), tol=ATOL) + assert ae(v.real, 3.4819106748728063576e-38, tol=PTOL) + assert ae(v.imag, 4.215653005615772724e-38, tol=PTOL) + v = fp.e1((1.1641532182693481445e-10 - 1.1641532182693481445e-10j)) + assert ae(v, (21.950067703413105017 + 0.7853981632810329878j), tol=ATOL) + assert ae(v.real, 21.950067703413105017, tol=PTOL) + assert ae(v.imag, 0.7853981632810329878, tol=PTOL) + v = fp.e1((0.25 - 0.25j)) + assert ae(v, (0.71092525792923287894 + 0.56491812441304194711j), tol=ATOL) + assert ae(v.real, 0.71092525792923287894, tol=PTOL) + assert ae(v.imag, 0.56491812441304194711, tol=PTOL) + v = fp.e1((1.0 - 1.0j)) + assert ae(v, (0.00028162445198141832551 + 0.17932453503935894015j), tol=ATOL) + assert ae(v.real, 0.00028162445198141832551, tol=PTOL) + assert ae(v.imag, 0.17932453503935894015, tol=PTOL) + v = fp.e1((2.0 - 2.0j)) + assert ae(v, (-0.033767089606562004246 + 0.018599414169750541925j), tol=ATOL) + assert ae(v.real, -0.033767089606562004246, tol=PTOL) + assert ae(v.imag, 0.018599414169750541925, tol=PTOL) + v = fp.e1((5.0 - 5.0j)) + assert ae(v, (0.0007266506660356393891 - 0.00047102780163522245054j), tol=ATOL) + assert ae(v.real, 0.0007266506660356393891, tol=PTOL) + assert ae(v.imag, -0.00047102780163522245054, tol=PTOL) + v = fp.e1((20.0 - 20.0j)) + assert ae(v, (-2.3824537449367396579e-11 + 6.6969873156525615158e-11j), tol=ATOL) + assert ae(v.real, -2.3824537449367396579e-11, tol=PTOL) + assert ae(v.imag, 6.6969873156525615158e-11, tol=PTOL) + v = fp.e1((30.0 - 30.0j)) + assert ae(v, (1.7316045841744061617e-15 - 1.3065678019487308689e-15j), tol=ATOL) + assert ae(v.real, 1.7316045841744061617e-15, tol=PTOL) + assert ae(v.imag, -1.3065678019487308689e-15, tol=PTOL) + v = fp.e1((40.0 - 40.0j)) + assert ae(v, (-7.4001043002899232182e-20 + 4.991847855336816304e-21j), tol=ATOL) + assert ae(v.real, -7.4001043002899232182e-20, tol=PTOL) + assert ae(v.imag, 4.991847855336816304e-21, tol=PTOL) + v = fp.e1((50.0 - 50.0j)) + assert ae(v, (2.3566128324644641219e-24 + 1.3188326726201614778e-24j), tol=ATOL) + assert ae(v.real, 2.3566128324644641219e-24, tol=PTOL) + assert ae(v.imag, 1.3188326726201614778e-24, tol=PTOL) + v = fp.e1((80.0 - 80.0j)) + assert ae(v, (9.8279750572186526673e-38 - 1.243952841288868831e-37j), tol=ATOL) + assert ae(v.real, 9.8279750572186526673e-38, tol=PTOL) + assert ae(v.imag, -1.243952841288868831e-37, tol=PTOL) + v = fp.e1((4.6566128730773925781e-10 - 1.1641532182693481445e-10j)) + assert ae(v, (20.880034622014215597 + 0.24497866301044883237j), tol=ATOL) + assert ae(v.real, 20.880034622014215597, tol=PTOL) + assert ae(v.imag, 0.24497866301044883237, tol=PTOL) + v = fp.e1((1.0 - 0.25j)) + assert ae(v, (0.19731063945004229095 + 0.087366045774299963672j), tol=ATOL) + assert ae(v.real, 0.19731063945004229095, tol=PTOL) + assert ae(v.imag, 0.087366045774299963672, tol=PTOL) + v = fp.e1((4.0 - 1.0j)) + assert ae(v, (0.0013106173980145506944 + 0.0034542480199350626699j), tol=ATOL) + assert ae(v.real, 0.0013106173980145506944, tol=PTOL) + assert ae(v.imag, 0.0034542480199350626699, tol=PTOL) + v = fp.e1((8.0 - 2.0j)) + assert ae(v, (-0.000022278049065270225945 + 0.000029191940456521555288j), tol=ATOL) + assert ae(v.real, -0.000022278049065270225945, tol=PTOL) + assert ae(v.imag, 0.000029191940456521555288, tol=PTOL) + v = fp.e1((20.0 - 5.0j)) + assert ae(v, (4.7711374515765346894e-11 - 8.2902652405126947359e-11j), tol=ATOL) + assert ae(v.real, 4.7711374515765346894e-11, tol=PTOL) + assert ae(v.imag, -8.2902652405126947359e-11, tol=PTOL) + v = fp.e1((80.0 - 20.0j)) + assert ae(v, (3.8353473865788235787e-38 + 2.129247592349605139e-37j), tol=ATOL) + assert ae(v.real, 3.8353473865788235787e-38, tol=PTOL) + assert ae(v.imag, 2.129247592349605139e-37, tol=PTOL) + v = fp.e1((120.0 - 30.0j)) + assert ae(v, (2.3836002337480334716e-55 - 5.6704043587126198306e-55j), tol=ATOL) + assert ae(v.real, 2.3836002337480334716e-55, tol=PTOL) + assert ae(v.imag, -5.6704043587126198306e-55, tol=PTOL) + v = fp.e1((160.0 - 40.0j)) + assert ae(v, (-1.6238022898654510661e-72 + 1.104172355572287367e-72j), tol=ATOL) + assert ae(v.real, -1.6238022898654510661e-72, tol=PTOL) + assert ae(v.imag, 1.104172355572287367e-72, tol=PTOL) + v = fp.e1((200.0 - 50.0j)) + assert ae(v, (6.6800061461666228487e-90 - 1.4473816083541016115e-91j), tol=ATOL) + assert ae(v.real, 6.6800061461666228487e-90, tol=PTOL) + assert ae(v.imag, -1.4473816083541016115e-91, tol=PTOL) + v = fp.e1((320.0 - 80.0j)) + assert ae(v, (4.2737871527778786157e-143 - 3.1789935525785660314e-142j), tol=ATOL) + assert ae(v.real, 4.2737871527778786157e-143, tol=PTOL) + assert ae(v.imag, -3.1789935525785660314e-142, tol=PTOL) + v = fp.ei(1.1641532182693481445e-10) + assert ae(v, -22.296641293460247028, tol=ATOL) + assert type(v) is float + v = fp.ei(0.25) + assert ae(v, -0.54254326466191372953, tol=ATOL) + assert type(v) is float + v = fp.ei(1.0) + assert ae(v, 1.8951178163559367555, tol=ATOL) + assert type(v) is float + v = fp.ei(2.0) + assert ae(v, 4.9542343560018901634, tol=ATOL) + assert type(v) is float + v = fp.ei(5.0) + assert ae(v, 40.185275355803177455, tol=ATOL) + assert type(v) is float + v = fp.ei(20.0) + assert ae(v, 25615652.66405658882, tol=ATOL) + assert type(v) is float + v = fp.ei(30.0) + assert ae(v, 368973209407.27419706, tol=ATOL) + assert type(v) is float + v = fp.ei(40.0) + assert ae(v, 6039718263611241.5784, tol=ATOL) + assert type(v) is float + v = fp.ei(50.0) + assert ae(v, 1.0585636897131690963e+20, tol=ATOL) + assert type(v) is float + v = fp.ei(80.0) + assert ae(v, 7.0146000049047999696e+32, tol=ATOL) + assert type(v) is float + v = fp.ei((1.1641532182693481445e-10 + 0.0j)) + assert ae(v, (-22.296641293460247028 + 0.0j), tol=ATOL) + assert ae(v.real, -22.296641293460247028, tol=PTOL) + assert v.imag == 0 + v = fp.ei((0.25 + 0.0j)) + assert ae(v, (-0.54254326466191372953 + 0.0j), tol=ATOL) + assert ae(v.real, -0.54254326466191372953, tol=PTOL) + assert v.imag == 0 + v = fp.ei((1.0 + 0.0j)) + assert ae(v, (1.8951178163559367555 + 0.0j), tol=ATOL) + assert ae(v.real, 1.8951178163559367555, tol=PTOL) + assert v.imag == 0 + v = fp.ei((2.0 + 0.0j)) + assert ae(v, (4.9542343560018901634 + 0.0j), tol=ATOL) + assert ae(v.real, 4.9542343560018901634, tol=PTOL) + assert v.imag == 0 + v = fp.ei((5.0 + 0.0j)) + assert ae(v, (40.185275355803177455 + 0.0j), tol=ATOL) + assert ae(v.real, 40.185275355803177455, tol=PTOL) + assert v.imag == 0 + v = fp.ei((20.0 + 0.0j)) + assert ae(v, (25615652.66405658882 + 0.0j), tol=ATOL) + assert ae(v.real, 25615652.66405658882, tol=PTOL) + assert v.imag == 0 + v = fp.ei((30.0 + 0.0j)) + assert ae(v, (368973209407.27419706 + 0.0j), tol=ATOL) + assert ae(v.real, 368973209407.27419706, tol=PTOL) + assert v.imag == 0 + v = fp.ei((40.0 + 0.0j)) + assert ae(v, (6039718263611241.5784 + 0.0j), tol=ATOL) + assert ae(v.real, 6039718263611241.5784, tol=PTOL) + assert v.imag == 0 + v = fp.ei((50.0 + 0.0j)) + assert ae(v, (1.0585636897131690963e+20 + 0.0j), tol=ATOL) + assert ae(v.real, 1.0585636897131690963e+20, tol=PTOL) + assert v.imag == 0 + v = fp.ei((80.0 + 0.0j)) + assert ae(v, (7.0146000049047999696e+32 + 0.0j), tol=ATOL) + assert ae(v.real, 7.0146000049047999696e+32, tol=PTOL) + assert v.imag == 0 + v = fp.ei((4.6566128730773925781e-10 + 1.1641532182693481445e-10j)) + assert ae(v, (-20.880034621082893023 + 0.24497866324327947603j), tol=ATOL) + assert ae(v.real, -20.880034621082893023, tol=PTOL) + assert ae(v.imag, 0.24497866324327947603, tol=PTOL) + v = fp.ei((1.0 + 0.25j)) + assert ae(v, (1.8942716983721074932 + 0.67268237088273915854j), tol=ATOL) + assert ae(v.real, 1.8942716983721074932, tol=PTOL) + assert ae(v.imag, 0.67268237088273915854, tol=PTOL) + v = fp.ei((4.0 + 1.0j)) + assert ae(v, (14.806699492675420438 + 12.280015176673582616j), tol=ATOL) + assert ae(v.real, 14.806699492675420438, tol=PTOL) + assert ae(v.imag, 12.280015176673582616, tol=PTOL) + v = fp.ei((8.0 + 2.0j)) + assert ae(v, (-54.633252667426386294 + 416.34477429173650012j), tol=ATOL) + assert ae(v.real, -54.633252667426386294, tol=PTOL) + assert ae(v.imag, 416.34477429173650012, tol=PTOL) + v = fp.ei((20.0 + 5.0j)) + assert ae(v, (711836.97165402624643 - 24745247.798103247366j), tol=ATOL) + assert ae(v.real, 711836.97165402624643, tol=PTOL) + assert ae(v.imag, -24745247.798103247366, tol=PTOL) + v = fp.ei((80.0 + 20.0j)) + assert ae(v, (4.2139911108612653091e+32 + 5.3367124741918251637e+32j), tol=ATOL) + assert ae(v.real, 4.2139911108612653091e+32, tol=PTOL) + assert ae(v.imag, 5.3367124741918251637e+32, tol=PTOL) + v = fp.ei((120.0 + 30.0j)) + assert ae(v, (-9.7760616203707508892e+48 - 1.058257682317195792e+50j), tol=ATOL) + assert ae(v.real, -9.7760616203707508892e+48, tol=PTOL) + assert ae(v.imag, -1.058257682317195792e+50, tol=PTOL) + v = fp.ei((160.0 + 40.0j)) + assert ae(v, (-8.7065541466623638861e+66 + 1.6577106725141739889e+67j), tol=ATOL) + assert ae(v.real, -8.7065541466623638861e+66, tol=PTOL) + assert ae(v.imag, 1.6577106725141739889e+67, tol=PTOL) + v = fp.ei((200.0 + 50.0j)) + assert ae(v, (3.070744996327018106e+84 - 1.7243244846769415903e+84j), tol=ATOL) + assert ae(v.real, 3.070744996327018106e+84, tol=PTOL) + assert ae(v.imag, -1.7243244846769415903e+84, tol=PTOL) + v = fp.ei((320.0 + 80.0j)) + assert ae(v, (-9.9960598637998647276e+135 - 2.6855081527595608863e+136j), tol=ATOL) + assert ae(v.real, -9.9960598637998647276e+135, tol=PTOL) + assert ae(v.imag, -2.6855081527595608863e+136, tol=PTOL) + v = fp.ei((1.1641532182693481445e-10 + 1.1641532182693481445e-10j)) + assert ae(v, (-21.950067703180274374 + 0.78539816351386363145j), tol=ATOL) + assert ae(v.real, -21.950067703180274374, tol=PTOL) + assert ae(v.imag, 0.78539816351386363145, tol=PTOL) + v = fp.ei((0.25 + 0.25j)) + assert ae(v, (-0.21441047326710323254 + 1.0683772981589995996j), tol=ATOL) + assert ae(v.real, -0.21441047326710323254, tol=PTOL) + assert ae(v.imag, 1.0683772981589995996, tol=PTOL) + v = fp.ei((1.0 + 1.0j)) + assert ae(v, (1.7646259855638540684 + 2.3877698515105224193j), tol=ATOL) + assert ae(v.real, 1.7646259855638540684, tol=PTOL) + assert ae(v.imag, 2.3877698515105224193, tol=PTOL) + v = fp.ei((2.0 + 2.0j)) + assert ae(v, (1.8920781621855474089 + 5.3169624378326579621j), tol=ATOL) + assert ae(v.real, 1.8920781621855474089, tol=PTOL) + assert ae(v.imag, 5.3169624378326579621, tol=PTOL) + v = fp.ei((5.0 + 5.0j)) + assert ae(v, (-13.470936071475245856 - 15.322492395731230968j), tol=ATOL) + assert ae(v.real, -13.470936071475245856, tol=PTOL) + assert ae(v.imag, -15.322492395731230968, tol=PTOL) + v = fp.ei((20.0 + 20.0j)) + assert ae(v, (16589317.398788971896 + 5831705.4712368307104j), tol=ATOL) + assert ae(v.real, 16589317.398788971896, tol=PTOL) + assert ae(v.imag, 5831705.4712368307104, tol=PTOL) + v = fp.ei((30.0 + 30.0j)) + assert ae(v, (-154596484273.69322527 - 204179357834.2723043j), tol=ATOL) + assert ae(v.real, -154596484273.69322527, tol=PTOL) + assert ae(v.imag, -204179357834.2723043, tol=PTOL) + v = fp.ei((40.0 + 40.0j)) + assert ae(v, (287512180321448.45408 + 4203502407932318.1156j), tol=ATOL) + assert ae(v.real, 287512180321448.45408, tol=PTOL) + assert ae(v.imag, 4203502407932318.1156, tol=PTOL) + v = fp.ei((50.0 + 50.0j)) + assert ae(v, (36128528616649268826.0 - 64648801861338741960.0j), tol=ATOL) + assert ae(v.real, 36128528616649268826.0, tol=PTOL) + assert ae(v.imag, -64648801861338741960.0, tol=PTOL) + v = fp.ei((80.0 + 80.0j)) + assert ae(v, (-3.8674816337930010217e+32 - 3.0540709639658071041e+32j), tol=ATOL) + assert ae(v.real, -3.8674816337930010217e+32, tol=PTOL) + assert ae(v.imag, -3.0540709639658071041e+32, tol=PTOL) + v = fp.ei((1.1641532182693481445e-10 + 4.6566128730773925781e-10j)) + assert ae(v, (-20.880034621432138988 + 1.3258176641336937524j), tol=ATOL) + assert ae(v.real, -20.880034621432138988, tol=PTOL) + assert ae(v.imag, 1.3258176641336937524, tol=PTOL) + v = fp.ei((0.25 + 1.0j)) + assert ae(v, (0.59066621214766308594 + 2.3968481059377428687j), tol=ATOL) + assert ae(v.real, 0.59066621214766308594, tol=PTOL) + assert ae(v.imag, 2.3968481059377428687, tol=PTOL) + v = fp.ei((1.0 + 4.0j)) + assert ae(v, (-0.49739047283060471093 + 3.5570287076301818702j), tol=ATOL) + assert ae(v.real, -0.49739047283060471093, tol=PTOL) + assert ae(v.imag, 3.5570287076301818702, tol=PTOL) + v = fp.ei((2.0 + 8.0j)) + assert ae(v, (0.8705211147733730969 + 3.3825859385758486351j), tol=ATOL) + assert ae(v.real, 0.8705211147733730969, tol=PTOL) + assert ae(v.imag, 3.3825859385758486351, tol=PTOL) + v = fp.ei((5.0 + 20.0j)) + assert ae(v, (7.0789514293925893007 + 1.5313749363937141849j), tol=ATOL) + assert ae(v.real, 7.0789514293925893007, tol=PTOL) + assert ae(v.imag, 1.5313749363937141849, tol=PTOL) + v = fp.ei((20.0 + 80.0j)) + assert ae(v, (-5855431.4907298084434 - 720917.79156143806727j), tol=ATOL) + assert ae(v.real, -5855431.4907298084434, tol=PTOL) + assert ae(v.imag, -720917.79156143806727, tol=PTOL) + v = fp.ei((30.0 + 120.0j)) + assert ae(v, (65402491644.703470747 - 56697658396.51586764j), tol=ATOL) + assert ae(v.real, 65402491644.703470747, tol=PTOL) + assert ae(v.imag, -56697658396.51586764, tol=PTOL) + v = fp.ei((40.0 + 160.0j)) + assert ae(v, (-25504929379604.776769 + 1429035198630576.3879j), tol=ATOL) + assert ae(v.real, -25504929379604.776769, tol=PTOL) + assert ae(v.imag, 1429035198630576.3879, tol=PTOL) + v = fp.ei((50.0 + 200.0j)) + assert ae(v, (-18437746526988116954.0 - 17146362239046152342.0j), tol=ATOL) + assert ae(v.real, -18437746526988116954.0, tol=PTOL) + assert ae(v.imag, -17146362239046152342.0, tol=PTOL) + v = fp.ei((80.0 + 320.0j)) + assert ae(v, (-3.3464697299634526706e+31 - 1.6473152633843023919e+32j), tol=ATOL) + assert ae(v.real, -3.3464697299634526706e+31, tol=PTOL) + assert ae(v.imag, -1.6473152633843023919e+32, tol=PTOL) + v = fp.ei((0.0 + 1.1641532182693481445e-10j)) + assert ae(v, (-22.29664129357666235 + 1.5707963269113119411j), tol=ATOL) + assert ae(v.real, -22.29664129357666235, tol=PTOL) + assert ae(v.imag, 1.5707963269113119411, tol=PTOL) + v = fp.ei((0.0 + 0.25j)) + assert ae(v, (-0.82466306258094565309 + 1.8199298971146537833j), tol=ATOL) + assert ae(v.real, -0.82466306258094565309, tol=PTOL) + assert ae(v.imag, 1.8199298971146537833, tol=PTOL) + v = fp.ei((0.0 + 1.0j)) + assert ae(v, (0.33740392290096813466 + 2.5168793971620796342j), tol=ATOL) + assert ae(v.real, 0.33740392290096813466, tol=PTOL) + assert ae(v.imag, 2.5168793971620796342, tol=PTOL) + v = fp.ei((0.0 + 2.0j)) + assert ae(v, (0.4229808287748649957 + 3.1762093035975914678j), tol=ATOL) + assert ae(v.real, 0.4229808287748649957, tol=PTOL) + assert ae(v.imag, 3.1762093035975914678, tol=PTOL) + v = fp.ei((0.0 + 5.0j)) + assert ae(v, (-0.19002974965664387862 + 3.1207275717395707565j), tol=ATOL) + assert ae(v.real, -0.19002974965664387862, tol=PTOL) + assert ae(v.imag, 3.1207275717395707565, tol=PTOL) + v = fp.ei((0.0 + 20.0j)) + assert ae(v, (0.04441982084535331654 + 3.1190380278383364594j), tol=ATOL) + assert ae(v.real, 0.04441982084535331654, tol=PTOL) + assert ae(v.imag, 3.1190380278383364594, tol=PTOL) + v = fp.ei((0.0 + 30.0j)) + assert ae(v, (-0.033032417282071143779 + 3.1375528668252477302j), tol=ATOL) + assert ae(v.real, -0.033032417282071143779, tol=PTOL) + assert ae(v.imag, 3.1375528668252477302, tol=PTOL) + v = fp.ei((0.0 + 40.0j)) + assert ae(v, (0.019020007896208766962 + 3.157781446149681126j), tol=ATOL) + assert ae(v.real, 0.019020007896208766962, tol=PTOL) + assert ae(v.imag, 3.157781446149681126, tol=PTOL) + v = fp.ei((0.0 + 50.0j)) + assert ae(v, (-0.0056283863241163054402 + 3.122413399280832514j), tol=ATOL) + assert ae(v.real, -0.0056283863241163054402, tol=PTOL) + assert ae(v.imag, 3.122413399280832514, tol=PTOL) + v = fp.ei((0.0 + 80.0j)) + assert ae(v, (-0.012402501155070958192 + 3.1431272137073839346j), tol=ATOL) + assert ae(v.real, -0.012402501155070958192, tol=PTOL) + assert ae(v.imag, 3.1431272137073839346, tol=PTOL) + v = fp.ei((-1.1641532182693481445e-10 + 4.6566128730773925781e-10j)) + assert ae(v, (-20.880034621664969632 + 1.8157749903874220607j), tol=ATOL) + assert ae(v.real, -20.880034621664969632, tol=PTOL) + assert ae(v.imag, 1.8157749903874220607, tol=PTOL) + v = fp.ei((-0.25 + 1.0j)) + assert ae(v, (0.16868306393667788761 + 2.6557914649950505414j), tol=ATOL) + assert ae(v.real, 0.16868306393667788761, tol=PTOL) + assert ae(v.imag, 2.6557914649950505414, tol=PTOL) + v = fp.ei((-1.0 + 4.0j)) + assert ae(v, (-0.03373591813926547318 + 3.2151161058308770603j), tol=ATOL) + assert ae(v.real, -0.03373591813926547318, tol=PTOL) + assert ae(v.imag, 3.2151161058308770603, tol=PTOL) + v = fp.ei((-2.0 + 8.0j)) + assert ae(v, (0.015392833434733785143 + 3.1384179414340326969j), tol=ATOL) + assert ae(v.real, 0.015392833434733785143, tol=PTOL) + assert ae(v.imag, 3.1384179414340326969, tol=PTOL) + v = fp.ei((-5.0 + 20.0j)) + assert ae(v, (0.00024419662286542966525 + 3.1413825703601317109j), tol=ATOL) + assert ae(v.real, 0.00024419662286542966525, tol=PTOL) + assert ae(v.imag, 3.1413825703601317109, tol=PTOL) + v = fp.ei((-20.0 + 80.0j)) + assert ae(v, (-2.3255552781051330088e-11 + 3.1415926535987396304j), tol=ATOL) + assert ae(v.real, -2.3255552781051330088e-11, tol=PTOL) + assert ae(v.imag, 3.1415926535987396304, tol=PTOL) + v = fp.ei((-30.0 + 120.0j)) + assert ae(v, (2.7068919097124652332e-16 + 3.1415926535897925337j), tol=ATOL) + assert ae(v.real, 2.7068919097124652332e-16, tol=PTOL) + assert ae(v.imag, 3.1415926535897925337, tol=PTOL) + v = fp.ei((-40.0 + 160.0j)) + assert ae(v, (1.1695597827678024687e-20 + 3.1415926535897932385j), tol=ATOL) + assert ae(v.real, 1.1695597827678024687e-20, tol=PTOL) + assert ae(v.imag, 3.1415926535897932385, tol=PTOL) + v = fp.ei((-50.0 + 200.0j)) + assert ae(v, (-9.0323746914410162531e-25 + 3.1415926535897932385j), tol=ATOL) + assert ae(v.real, -9.0323746914410162531e-25, tol=PTOL) + assert ae(v.imag, 3.1415926535897932385, tol=PTOL) + v = fp.ei((-80.0 + 320.0j)) + assert ae(v, (-3.4819106748728063576e-38 + 3.1415926535897932385j), tol=ATOL) + assert ae(v.real, -3.4819106748728063576e-38, tol=PTOL) + assert ae(v.imag, 3.1415926535897932385, tol=PTOL) + v = fp.ei((-4.6566128730773925781e-10 + 1.1641532182693481445e-10j)) + assert ae(v, (-20.880034622014215597 + 2.8966139905793444061j), tol=ATOL) + assert ae(v.real, -20.880034622014215597, tol=PTOL) + assert ae(v.imag, 2.8966139905793444061, tol=PTOL) + v = fp.ei((-1.0 + 0.25j)) + assert ae(v, (-0.19731063945004229095 + 3.0542266078154932748j), tol=ATOL) + assert ae(v.real, -0.19731063945004229095, tol=PTOL) + assert ae(v.imag, 3.0542266078154932748, tol=PTOL) + v = fp.ei((-4.0 + 1.0j)) + assert ae(v, (-0.0013106173980145506944 + 3.1381384055698581758j), tol=ATOL) + assert ae(v.real, -0.0013106173980145506944, tol=PTOL) + assert ae(v.imag, 3.1381384055698581758, tol=PTOL) + v = fp.ei((-8.0 + 2.0j)) + assert ae(v, (0.000022278049065270225945 + 3.1415634616493367169j), tol=ATOL) + assert ae(v.real, 0.000022278049065270225945, tol=PTOL) + assert ae(v.imag, 3.1415634616493367169, tol=PTOL) + v = fp.ei((-20.0 + 5.0j)) + assert ae(v, (-4.7711374515765346894e-11 + 3.1415926536726958909j), tol=ATOL) + assert ae(v.real, -4.7711374515765346894e-11, tol=PTOL) + assert ae(v.imag, 3.1415926536726958909, tol=PTOL) + v = fp.ei((-80.0 + 20.0j)) + assert ae(v, (-3.8353473865788235787e-38 + 3.1415926535897932385j), tol=ATOL) + assert ae(v.real, -3.8353473865788235787e-38, tol=PTOL) + assert ae(v.imag, 3.1415926535897932385, tol=PTOL) + v = fp.ei((-120.0 + 30.0j)) + assert ae(v, (-2.3836002337480334716e-55 + 3.1415926535897932385j), tol=ATOL) + assert ae(v.real, -2.3836002337480334716e-55, tol=PTOL) + assert ae(v.imag, 3.1415926535897932385, tol=PTOL) + v = fp.ei((-160.0 + 40.0j)) + assert ae(v, (1.6238022898654510661e-72 + 3.1415926535897932385j), tol=ATOL) + assert ae(v.real, 1.6238022898654510661e-72, tol=PTOL) + assert ae(v.imag, 3.1415926535897932385, tol=PTOL) + v = fp.ei((-200.0 + 50.0j)) + assert ae(v, (-6.6800061461666228487e-90 + 3.1415926535897932385j), tol=ATOL) + assert ae(v.real, -6.6800061461666228487e-90, tol=PTOL) + assert ae(v.imag, 3.1415926535897932385, tol=PTOL) + v = fp.ei((-320.0 + 80.0j)) + assert ae(v, (-4.2737871527778786157e-143 + 3.1415926535897932385j), tol=ATOL) + assert ae(v.real, -4.2737871527778786157e-143, tol=PTOL) + assert ae(v.imag, 3.1415926535897932385, tol=PTOL) + v = fp.ei(-1.1641532182693481445e-10) + assert ae(v, -22.296641293693077672, tol=ATOL) + assert type(v) is float + v = fp.ei(-0.25) + assert ae(v, -1.0442826344437381945, tol=ATOL) + assert type(v) is float + v = fp.ei(-1.0) + assert ae(v, -0.21938393439552027368, tol=ATOL) + assert type(v) is float + v = fp.ei(-2.0) + assert ae(v, -0.048900510708061119567, tol=ATOL) + assert type(v) is float + v = fp.ei(-5.0) + assert ae(v, -0.0011482955912753257973, tol=ATOL) + assert type(v) is float + v = fp.ei(-20.0) + assert ae(v, -9.8355252906498816904e-11, tol=ATOL) + assert type(v) is float + v = fp.ei(-30.0) + assert ae(v, -3.0215520106888125448e-15, tol=ATOL) + assert type(v) is float + v = fp.ei(-40.0) + assert ae(v, -1.0367732614516569722e-19, tol=ATOL) + assert type(v) is float + v = fp.ei(-50.0) + assert ae(v, -3.7832640295504590187e-24, tol=ATOL) + assert type(v) is float + v = fp.ei(-80.0) + assert ae(v, -2.2285432586884729112e-37, tol=ATOL) + assert type(v) is float + v = fp.ei((-1.1641532182693481445e-10 + 0.0j)) + assert ae(v, (-22.296641293693077672 + 0.0j), tol=ATOL) + assert ae(v.real, -22.296641293693077672, tol=PTOL) + assert v.imag == 0 + v = fp.ei((-0.25 + 0.0j)) + assert ae(v, (-1.0442826344437381945 + 0.0j), tol=ATOL) + assert ae(v.real, -1.0442826344437381945, tol=PTOL) + assert v.imag == 0 + v = fp.ei((-1.0 + 0.0j)) + assert ae(v, (-0.21938393439552027368 + 0.0j), tol=ATOL) + assert ae(v.real, -0.21938393439552027368, tol=PTOL) + assert v.imag == 0 + v = fp.ei((-2.0 + 0.0j)) + assert ae(v, (-0.048900510708061119567 + 0.0j), tol=ATOL) + assert ae(v.real, -0.048900510708061119567, tol=PTOL) + assert v.imag == 0 + v = fp.ei((-5.0 + 0.0j)) + assert ae(v, (-0.0011482955912753257973 + 0.0j), tol=ATOL) + assert ae(v.real, -0.0011482955912753257973, tol=PTOL) + assert v.imag == 0 + v = fp.ei((-20.0 + 0.0j)) + assert ae(v, (-9.8355252906498816904e-11 + 0.0j), tol=ATOL) + assert ae(v.real, -9.8355252906498816904e-11, tol=PTOL) + assert v.imag == 0 + v = fp.ei((-30.0 + 0.0j)) + assert ae(v, (-3.0215520106888125448e-15 + 0.0j), tol=ATOL) + assert ae(v.real, -3.0215520106888125448e-15, tol=PTOL) + assert v.imag == 0 + v = fp.ei((-40.0 + 0.0j)) + assert ae(v, (-1.0367732614516569722e-19 + 0.0j), tol=ATOL) + assert ae(v.real, -1.0367732614516569722e-19, tol=PTOL) + assert v.imag == 0 + v = fp.ei((-50.0 + 0.0j)) + assert ae(v, (-3.7832640295504590187e-24 + 0.0j), tol=ATOL) + assert ae(v.real, -3.7832640295504590187e-24, tol=PTOL) + assert v.imag == 0 + v = fp.ei((-80.0 + 0.0j)) + assert ae(v, (-2.2285432586884729112e-37 + 0.0j), tol=ATOL) + assert ae(v.real, -2.2285432586884729112e-37, tol=PTOL) + assert v.imag == 0 + v = fp.ei((-4.6566128730773925781e-10 - 1.1641532182693481445e-10j)) + assert ae(v, (-20.880034622014215597 - 2.8966139905793444061j), tol=ATOL) + assert ae(v.real, -20.880034622014215597, tol=PTOL) + assert ae(v.imag, -2.8966139905793444061, tol=PTOL) + v = fp.ei((-1.0 - 0.25j)) + assert ae(v, (-0.19731063945004229095 - 3.0542266078154932748j), tol=ATOL) + assert ae(v.real, -0.19731063945004229095, tol=PTOL) + assert ae(v.imag, -3.0542266078154932748, tol=PTOL) + v = fp.ei((-4.0 - 1.0j)) + assert ae(v, (-0.0013106173980145506944 - 3.1381384055698581758j), tol=ATOL) + assert ae(v.real, -0.0013106173980145506944, tol=PTOL) + assert ae(v.imag, -3.1381384055698581758, tol=PTOL) + v = fp.ei((-8.0 - 2.0j)) + assert ae(v, (0.000022278049065270225945 - 3.1415634616493367169j), tol=ATOL) + assert ae(v.real, 0.000022278049065270225945, tol=PTOL) + assert ae(v.imag, -3.1415634616493367169, tol=PTOL) + v = fp.ei((-20.0 - 5.0j)) + assert ae(v, (-4.7711374515765346894e-11 - 3.1415926536726958909j), tol=ATOL) + assert ae(v.real, -4.7711374515765346894e-11, tol=PTOL) + assert ae(v.imag, -3.1415926536726958909, tol=PTOL) + v = fp.ei((-80.0 - 20.0j)) + assert ae(v, (-3.8353473865788235787e-38 - 3.1415926535897932385j), tol=ATOL) + assert ae(v.real, -3.8353473865788235787e-38, tol=PTOL) + assert ae(v.imag, -3.1415926535897932385, tol=PTOL) + v = fp.ei((-120.0 - 30.0j)) + assert ae(v, (-2.3836002337480334716e-55 - 3.1415926535897932385j), tol=ATOL) + assert ae(v.real, -2.3836002337480334716e-55, tol=PTOL) + assert ae(v.imag, -3.1415926535897932385, tol=PTOL) + v = fp.ei((-160.0 - 40.0j)) + assert ae(v, (1.6238022898654510661e-72 - 3.1415926535897932385j), tol=ATOL) + assert ae(v.real, 1.6238022898654510661e-72, tol=PTOL) + assert ae(v.imag, -3.1415926535897932385, tol=PTOL) + v = fp.ei((-200.0 - 50.0j)) + assert ae(v, (-6.6800061461666228487e-90 - 3.1415926535897932385j), tol=ATOL) + assert ae(v.real, -6.6800061461666228487e-90, tol=PTOL) + assert ae(v.imag, -3.1415926535897932385, tol=PTOL) + v = fp.ei((-320.0 - 80.0j)) + assert ae(v, (-4.2737871527778786157e-143 - 3.1415926535897932385j), tol=ATOL) + assert ae(v.real, -4.2737871527778786157e-143, tol=PTOL) + assert ae(v.imag, -3.1415926535897932385, tol=PTOL) + v = fp.ei((-1.1641532182693481445e-10 - 1.1641532182693481445e-10j)) + assert ae(v, (-21.950067703413105017 - 2.3561944903087602507j), tol=ATOL) + assert ae(v.real, -21.950067703413105017, tol=PTOL) + assert ae(v.imag, -2.3561944903087602507, tol=PTOL) + v = fp.ei((-0.25 - 0.25j)) + assert ae(v, (-0.71092525792923287894 - 2.5766745291767512913j), tol=ATOL) + assert ae(v.real, -0.71092525792923287894, tol=PTOL) + assert ae(v.imag, -2.5766745291767512913, tol=PTOL) + v = fp.ei((-1.0 - 1.0j)) + assert ae(v, (-0.00028162445198141832551 - 2.9622681185504342983j), tol=ATOL) + assert ae(v.real, -0.00028162445198141832551, tol=PTOL) + assert ae(v.imag, -2.9622681185504342983, tol=PTOL) + v = fp.ei((-2.0 - 2.0j)) + assert ae(v, (0.033767089606562004246 - 3.1229932394200426965j), tol=ATOL) + assert ae(v.real, 0.033767089606562004246, tol=PTOL) + assert ae(v.imag, -3.1229932394200426965, tol=PTOL) + v = fp.ei((-5.0 - 5.0j)) + assert ae(v, (-0.0007266506660356393891 - 3.1420636813914284609j), tol=ATOL) + assert ae(v.real, -0.0007266506660356393891, tol=PTOL) + assert ae(v.imag, -3.1420636813914284609, tol=PTOL) + v = fp.ei((-20.0 - 20.0j)) + assert ae(v, (2.3824537449367396579e-11 - 3.1415926535228233653j), tol=ATOL) + assert ae(v.real, 2.3824537449367396579e-11, tol=PTOL) + assert ae(v.imag, -3.1415926535228233653, tol=PTOL) + v = fp.ei((-30.0 - 30.0j)) + assert ae(v, (-1.7316045841744061617e-15 - 3.141592653589794545j), tol=ATOL) + assert ae(v.real, -1.7316045841744061617e-15, tol=PTOL) + assert ae(v.imag, -3.141592653589794545, tol=PTOL) + v = fp.ei((-40.0 - 40.0j)) + assert ae(v, (7.4001043002899232182e-20 - 3.1415926535897932385j), tol=ATOL) + assert ae(v.real, 7.4001043002899232182e-20, tol=PTOL) + assert ae(v.imag, -3.1415926535897932385, tol=PTOL) + v = fp.ei((-50.0 - 50.0j)) + assert ae(v, (-2.3566128324644641219e-24 - 3.1415926535897932385j), tol=ATOL) + assert ae(v.real, -2.3566128324644641219e-24, tol=PTOL) + assert ae(v.imag, -3.1415926535897932385, tol=PTOL) + v = fp.ei((-80.0 - 80.0j)) + assert ae(v, (-9.8279750572186526673e-38 - 3.1415926535897932385j), tol=ATOL) + assert ae(v.real, -9.8279750572186526673e-38, tol=PTOL) + assert ae(v.imag, -3.1415926535897932385, tol=PTOL) + v = fp.ei((-1.1641532182693481445e-10 - 4.6566128730773925781e-10j)) + assert ae(v, (-20.880034621664969632 - 1.8157749903874220607j), tol=ATOL) + assert ae(v.real, -20.880034621664969632, tol=PTOL) + assert ae(v.imag, -1.8157749903874220607, tol=PTOL) + v = fp.ei((-0.25 - 1.0j)) + assert ae(v, (0.16868306393667788761 - 2.6557914649950505414j), tol=ATOL) + assert ae(v.real, 0.16868306393667788761, tol=PTOL) + assert ae(v.imag, -2.6557914649950505414, tol=PTOL) + v = fp.ei((-1.0 - 4.0j)) + assert ae(v, (-0.03373591813926547318 - 3.2151161058308770603j), tol=ATOL) + assert ae(v.real, -0.03373591813926547318, tol=PTOL) + assert ae(v.imag, -3.2151161058308770603, tol=PTOL) + v = fp.ei((-2.0 - 8.0j)) + assert ae(v, (0.015392833434733785143 - 3.1384179414340326969j), tol=ATOL) + assert ae(v.real, 0.015392833434733785143, tol=PTOL) + assert ae(v.imag, -3.1384179414340326969, tol=PTOL) + v = fp.ei((-5.0 - 20.0j)) + assert ae(v, (0.00024419662286542966525 - 3.1413825703601317109j), tol=ATOL) + assert ae(v.real, 0.00024419662286542966525, tol=PTOL) + assert ae(v.imag, -3.1413825703601317109, tol=PTOL) + v = fp.ei((-20.0 - 80.0j)) + assert ae(v, (-2.3255552781051330088e-11 - 3.1415926535987396304j), tol=ATOL) + assert ae(v.real, -2.3255552781051330088e-11, tol=PTOL) + assert ae(v.imag, -3.1415926535987396304, tol=PTOL) + v = fp.ei((-30.0 - 120.0j)) + assert ae(v, (2.7068919097124652332e-16 - 3.1415926535897925337j), tol=ATOL) + assert ae(v.real, 2.7068919097124652332e-16, tol=PTOL) + assert ae(v.imag, -3.1415926535897925337, tol=PTOL) + v = fp.ei((-40.0 - 160.0j)) + assert ae(v, (1.1695597827678024687e-20 - 3.1415926535897932385j), tol=ATOL) + assert ae(v.real, 1.1695597827678024687e-20, tol=PTOL) + assert ae(v.imag, -3.1415926535897932385, tol=PTOL) + v = fp.ei((-50.0 - 200.0j)) + assert ae(v, (-9.0323746914410162531e-25 - 3.1415926535897932385j), tol=ATOL) + assert ae(v.real, -9.0323746914410162531e-25, tol=PTOL) + assert ae(v.imag, -3.1415926535897932385, tol=PTOL) + v = fp.ei((-80.0 - 320.0j)) + assert ae(v, (-3.4819106748728063576e-38 - 3.1415926535897932385j), tol=ATOL) + assert ae(v.real, -3.4819106748728063576e-38, tol=PTOL) + assert ae(v.imag, -3.1415926535897932385, tol=PTOL) + v = fp.ei((0.0 - 1.1641532182693481445e-10j)) + assert ae(v, (-22.29664129357666235 - 1.5707963269113119411j), tol=ATOL) + assert ae(v.real, -22.29664129357666235, tol=PTOL) + assert ae(v.imag, -1.5707963269113119411, tol=PTOL) + v = fp.ei((0.0 - 0.25j)) + assert ae(v, (-0.82466306258094565309 - 1.8199298971146537833j), tol=ATOL) + assert ae(v.real, -0.82466306258094565309, tol=PTOL) + assert ae(v.imag, -1.8199298971146537833, tol=PTOL) + v = fp.ei((0.0 - 1.0j)) + assert ae(v, (0.33740392290096813466 - 2.5168793971620796342j), tol=ATOL) + assert ae(v.real, 0.33740392290096813466, tol=PTOL) + assert ae(v.imag, -2.5168793971620796342, tol=PTOL) + v = fp.ei((0.0 - 2.0j)) + assert ae(v, (0.4229808287748649957 - 3.1762093035975914678j), tol=ATOL) + assert ae(v.real, 0.4229808287748649957, tol=PTOL) + assert ae(v.imag, -3.1762093035975914678, tol=PTOL) + v = fp.ei((0.0 - 5.0j)) + assert ae(v, (-0.19002974965664387862 - 3.1207275717395707565j), tol=ATOL) + assert ae(v.real, -0.19002974965664387862, tol=PTOL) + assert ae(v.imag, -3.1207275717395707565, tol=PTOL) + v = fp.ei((0.0 - 20.0j)) + assert ae(v, (0.04441982084535331654 - 3.1190380278383364594j), tol=ATOL) + assert ae(v.real, 0.04441982084535331654, tol=PTOL) + assert ae(v.imag, -3.1190380278383364594, tol=PTOL) + v = fp.ei((0.0 - 30.0j)) + assert ae(v, (-0.033032417282071143779 - 3.1375528668252477302j), tol=ATOL) + assert ae(v.real, -0.033032417282071143779, tol=PTOL) + assert ae(v.imag, -3.1375528668252477302, tol=PTOL) + v = fp.ei((0.0 - 40.0j)) + assert ae(v, (0.019020007896208766962 - 3.157781446149681126j), tol=ATOL) + assert ae(v.real, 0.019020007896208766962, tol=PTOL) + assert ae(v.imag, -3.157781446149681126, tol=PTOL) + v = fp.ei((0.0 - 50.0j)) + assert ae(v, (-0.0056283863241163054402 - 3.122413399280832514j), tol=ATOL) + assert ae(v.real, -0.0056283863241163054402, tol=PTOL) + assert ae(v.imag, -3.122413399280832514, tol=PTOL) + v = fp.ei((0.0 - 80.0j)) + assert ae(v, (-0.012402501155070958192 - 3.1431272137073839346j), tol=ATOL) + assert ae(v.real, -0.012402501155070958192, tol=PTOL) + assert ae(v.imag, -3.1431272137073839346, tol=PTOL) + v = fp.ei((1.1641532182693481445e-10 - 4.6566128730773925781e-10j)) + assert ae(v, (-20.880034621432138988 - 1.3258176641336937524j), tol=ATOL) + assert ae(v.real, -20.880034621432138988, tol=PTOL) + assert ae(v.imag, -1.3258176641336937524, tol=PTOL) + v = fp.ei((0.25 - 1.0j)) + assert ae(v, (0.59066621214766308594 - 2.3968481059377428687j), tol=ATOL) + assert ae(v.real, 0.59066621214766308594, tol=PTOL) + assert ae(v.imag, -2.3968481059377428687, tol=PTOL) + v = fp.ei((1.0 - 4.0j)) + assert ae(v, (-0.49739047283060471093 - 3.5570287076301818702j), tol=ATOL) + assert ae(v.real, -0.49739047283060471093, tol=PTOL) + assert ae(v.imag, -3.5570287076301818702, tol=PTOL) + v = fp.ei((2.0 - 8.0j)) + assert ae(v, (0.8705211147733730969 - 3.3825859385758486351j), tol=ATOL) + assert ae(v.real, 0.8705211147733730969, tol=PTOL) + assert ae(v.imag, -3.3825859385758486351, tol=PTOL) + v = fp.ei((5.0 - 20.0j)) + assert ae(v, (7.0789514293925893007 - 1.5313749363937141849j), tol=ATOL) + assert ae(v.real, 7.0789514293925893007, tol=PTOL) + assert ae(v.imag, -1.5313749363937141849, tol=PTOL) + v = fp.ei((20.0 - 80.0j)) + assert ae(v, (-5855431.4907298084434 + 720917.79156143806727j), tol=ATOL) + assert ae(v.real, -5855431.4907298084434, tol=PTOL) + assert ae(v.imag, 720917.79156143806727, tol=PTOL) + v = fp.ei((30.0 - 120.0j)) + assert ae(v, (65402491644.703470747 + 56697658396.51586764j), tol=ATOL) + assert ae(v.real, 65402491644.703470747, tol=PTOL) + assert ae(v.imag, 56697658396.51586764, tol=PTOL) + v = fp.ei((40.0 - 160.0j)) + assert ae(v, (-25504929379604.776769 - 1429035198630576.3879j), tol=ATOL) + assert ae(v.real, -25504929379604.776769, tol=PTOL) + assert ae(v.imag, -1429035198630576.3879, tol=PTOL) + v = fp.ei((50.0 - 200.0j)) + assert ae(v, (-18437746526988116954.0 + 17146362239046152342.0j), tol=ATOL) + assert ae(v.real, -18437746526988116954.0, tol=PTOL) + assert ae(v.imag, 17146362239046152342.0, tol=PTOL) + v = fp.ei((80.0 - 320.0j)) + assert ae(v, (-3.3464697299634526706e+31 + 1.6473152633843023919e+32j), tol=ATOL) + assert ae(v.real, -3.3464697299634526706e+31, tol=PTOL) + assert ae(v.imag, 1.6473152633843023919e+32, tol=PTOL) + v = fp.ei((1.1641532182693481445e-10 - 1.1641532182693481445e-10j)) + assert ae(v, (-21.950067703180274374 - 0.78539816351386363145j), tol=ATOL) + assert ae(v.real, -21.950067703180274374, tol=PTOL) + assert ae(v.imag, -0.78539816351386363145, tol=PTOL) + v = fp.ei((0.25 - 0.25j)) + assert ae(v, (-0.21441047326710323254 - 1.0683772981589995996j), tol=ATOL) + assert ae(v.real, -0.21441047326710323254, tol=PTOL) + assert ae(v.imag, -1.0683772981589995996, tol=PTOL) + v = fp.ei((1.0 - 1.0j)) + assert ae(v, (1.7646259855638540684 - 2.3877698515105224193j), tol=ATOL) + assert ae(v.real, 1.7646259855638540684, tol=PTOL) + assert ae(v.imag, -2.3877698515105224193, tol=PTOL) + v = fp.ei((2.0 - 2.0j)) + assert ae(v, (1.8920781621855474089 - 5.3169624378326579621j), tol=ATOL) + assert ae(v.real, 1.8920781621855474089, tol=PTOL) + assert ae(v.imag, -5.3169624378326579621, tol=PTOL) + v = fp.ei((5.0 - 5.0j)) + assert ae(v, (-13.470936071475245856 + 15.322492395731230968j), tol=ATOL) + assert ae(v.real, -13.470936071475245856, tol=PTOL) + assert ae(v.imag, 15.322492395731230968, tol=PTOL) + v = fp.ei((20.0 - 20.0j)) + assert ae(v, (16589317.398788971896 - 5831705.4712368307104j), tol=ATOL) + assert ae(v.real, 16589317.398788971896, tol=PTOL) + assert ae(v.imag, -5831705.4712368307104, tol=PTOL) + v = fp.ei((30.0 - 30.0j)) + assert ae(v, (-154596484273.69322527 + 204179357834.2723043j), tol=ATOL) + assert ae(v.real, -154596484273.69322527, tol=PTOL) + assert ae(v.imag, 204179357834.2723043, tol=PTOL) + v = fp.ei((40.0 - 40.0j)) + assert ae(v, (287512180321448.45408 - 4203502407932318.1156j), tol=ATOL) + assert ae(v.real, 287512180321448.45408, tol=PTOL) + assert ae(v.imag, -4203502407932318.1156, tol=PTOL) + v = fp.ei((50.0 - 50.0j)) + assert ae(v, (36128528616649268826.0 + 64648801861338741960.0j), tol=ATOL) + assert ae(v.real, 36128528616649268826.0, tol=PTOL) + assert ae(v.imag, 64648801861338741960.0, tol=PTOL) + v = fp.ei((80.0 - 80.0j)) + assert ae(v, (-3.8674816337930010217e+32 + 3.0540709639658071041e+32j), tol=ATOL) + assert ae(v.real, -3.8674816337930010217e+32, tol=PTOL) + assert ae(v.imag, 3.0540709639658071041e+32, tol=PTOL) + v = fp.ei((4.6566128730773925781e-10 - 1.1641532182693481445e-10j)) + assert ae(v, (-20.880034621082893023 - 0.24497866324327947603j), tol=ATOL) + assert ae(v.real, -20.880034621082893023, tol=PTOL) + assert ae(v.imag, -0.24497866324327947603, tol=PTOL) + v = fp.ei((1.0 - 0.25j)) + assert ae(v, (1.8942716983721074932 - 0.67268237088273915854j), tol=ATOL) + assert ae(v.real, 1.8942716983721074932, tol=PTOL) + assert ae(v.imag, -0.67268237088273915854, tol=PTOL) + v = fp.ei((4.0 - 1.0j)) + assert ae(v, (14.806699492675420438 - 12.280015176673582616j), tol=ATOL) + assert ae(v.real, 14.806699492675420438, tol=PTOL) + assert ae(v.imag, -12.280015176673582616, tol=PTOL) + v = fp.ei((8.0 - 2.0j)) + assert ae(v, (-54.633252667426386294 - 416.34477429173650012j), tol=ATOL) + assert ae(v.real, -54.633252667426386294, tol=PTOL) + assert ae(v.imag, -416.34477429173650012, tol=PTOL) + v = fp.ei((20.0 - 5.0j)) + assert ae(v, (711836.97165402624643 + 24745247.798103247366j), tol=ATOL) + assert ae(v.real, 711836.97165402624643, tol=PTOL) + assert ae(v.imag, 24745247.798103247366, tol=PTOL) + v = fp.ei((80.0 - 20.0j)) + assert ae(v, (4.2139911108612653091e+32 - 5.3367124741918251637e+32j), tol=ATOL) + assert ae(v.real, 4.2139911108612653091e+32, tol=PTOL) + assert ae(v.imag, -5.3367124741918251637e+32, tol=PTOL) + v = fp.ei((120.0 - 30.0j)) + assert ae(v, (-9.7760616203707508892e+48 + 1.058257682317195792e+50j), tol=ATOL) + assert ae(v.real, -9.7760616203707508892e+48, tol=PTOL) + assert ae(v.imag, 1.058257682317195792e+50, tol=PTOL) + v = fp.ei((160.0 - 40.0j)) + assert ae(v, (-8.7065541466623638861e+66 - 1.6577106725141739889e+67j), tol=ATOL) + assert ae(v.real, -8.7065541466623638861e+66, tol=PTOL) + assert ae(v.imag, -1.6577106725141739889e+67, tol=PTOL) + v = fp.ei((200.0 - 50.0j)) + assert ae(v, (3.070744996327018106e+84 + 1.7243244846769415903e+84j), tol=ATOL) + assert ae(v.real, 3.070744996327018106e+84, tol=PTOL) + assert ae(v.imag, 1.7243244846769415903e+84, tol=PTOL) + v = fp.ei((320.0 - 80.0j)) + assert ae(v, (-9.9960598637998647276e+135 + 2.6855081527595608863e+136j), tol=ATOL) + assert ae(v.real, -9.9960598637998647276e+135, tol=PTOL) + assert ae(v.imag, 2.6855081527595608863e+136, tol=PTOL) diff --git a/shared/package-files/00/009b99ced998299ff25084cb641eab8598c3cba44e042b5a8dc62a3dae74b237/blob b/shared/package-files/00/009b99ced998299ff25084cb641eab8598c3cba44e042b5a8dc62a3dae74b237/blob new file mode 100644 index 0000000000000000000000000000000000000000..5ae331f71b21c8a6ef35f499c5c5c89239349e9c --- /dev/null +++ b/shared/package-files/00/009b99ced998299ff25084cb641eab8598c3cba44e042b5a8dc62a3dae74b237/blob @@ -0,0 +1,66 @@ +""" +Replacement rules. +""" + +class Transform: + """ + Immutable mapping that can be used as a generic transformation rule. + + Parameters + ========== + + transform : callable + Computes the value corresponding to any key. + + filter : callable, optional + If supplied, specifies which objects are in the mapping. + + Examples + ======== + + >>> from sympy.core.rules import Transform + >>> from sympy.abc import x + + This Transform will return, as a value, one more than the key: + + >>> add1 = Transform(lambda x: x + 1) + >>> add1[1] + 2 + >>> add1[x] + x + 1 + + By default, all values are considered to be in the dictionary. If a filter + is supplied, only the objects for which it returns True are considered as + being in the dictionary: + + >>> add1_odd = Transform(lambda x: x + 1, lambda x: x%2 == 1) + >>> 2 in add1_odd + False + >>> add1_odd.get(2, 0) + 0 + >>> 3 in add1_odd + True + >>> add1_odd[3] + 4 + >>> add1_odd.get(3, 0) + 4 + """ + + def __init__(self, transform, filter=lambda x: True): + self._transform = transform + self._filter = filter + + def __contains__(self, item): + return self._filter(item) + + def __getitem__(self, key): + if self._filter(key): + return self._transform(key) + else: + raise KeyError(key) + + def get(self, item, default=None): + if item in self: + return self[item] + else: + return default diff --git a/shared/package-files/00/009bea66a10eac42951d06c02da7205a233ed54e38673a90f99b11f8d6d36e38/blob b/shared/package-files/00/009bea66a10eac42951d06c02da7205a233ed54e38673a90f99b11f8d6d36e38/blob new file mode 100644 index 0000000000000000000000000000000000000000..18f845bd8cd8d354743ff96fe2ea4e5d6a06563c --- /dev/null +++ b/shared/package-files/00/009bea66a10eac42951d06c02da7205a233ed54e38673a90f99b11f8d6d36e38/blob @@ -0,0 +1,24 @@ +# file generated by vcs-versioning +# don't change, don't track in version control +from __future__ import annotations + +__all__ = [ + "__version__", + "__version_tuple__", + "version", + "version_tuple", + "__commit_id__", + "commit_id", +] + +version: str +__version__: str +__version_tuple__: tuple[int | str, ...] +version_tuple: tuple[int | str, ...] +commit_id: str | None +__commit_id__: str | None + +__version__ = version = '2.0.1' +__version_tuple__ = version_tuple = (2, 0, 1) + +__commit_id__ = commit_id = None diff --git a/shared/package-files/00/009c278cffe437baef411104ca81f688e7114e8c34c4be95a79fcd0965e7b502/blob b/shared/package-files/00/009c278cffe437baef411104ca81f688e7114e8c34c4be95a79fcd0965e7b502/blob new file mode 100644 index 0000000000000000000000000000000000000000..ec0cb6c8fdfcb2a36139035340d75d96a7930dfc --- /dev/null +++ b/shared/package-files/00/009c278cffe437baef411104ca81f688e7114e8c34c4be95a79fcd0965e7b502/blob @@ -0,0 +1,72 @@ +#pragma once +#include +#include +#include + +namespace at { + +struct DimCounter { + DimCounter(IntArrayRef shape, Range range); + + void increment(const std::array& step); + bool is_done() const; + std::array max_2d_step() const; + + IntArrayRef shape; + Range range; + c10::SmallBuffer values; + int64_t offset; +}; + +namespace internal { + +inline void get_data_ptrs( + char** ptrs, + ArrayRef base, + IntArrayRef strides, + IntArrayRef counter) { + const auto ntensors = base.size(); + const auto ndim = counter.size(); + std::copy(base.begin(), base.end(), ptrs); + for (const auto dim : c10::irange(ndim)) { + int64_t value = counter[dim]; + for (const auto arg : c10::irange(ntensors)) { + ptrs[arg] += value * strides[dim * ntensors + arg]; + } + } +} + +inline void serial_for_each( + IntArrayRef shape, + IntArrayRef strides, + char** base_ptrs, + size_t ntensors, + typename TensorIteratorBase::loop2d_t loop, + Range range) { + const auto ndim = shape.size(); + TORCH_INTERNAL_ASSERT_DEBUG_ONLY( + strides.size() == ntensors * std::max(size_t{2}, ndim)); + + if (ndim <= 1) { + if (range.begin == 0) { + loop(base_ptrs, strides.data(), range.size(), 1); + } else { + c10::SmallBuffer ptrs(ntensors); + get_data_ptrs(ptrs.data(), {base_ptrs, ntensors}, strides, {range.begin}); + loop(ptrs.data(), strides.data(), range.size(), 1); + } + } else { + c10::SmallBuffer ptrs(ntensors); + auto counter = DimCounter(shape, range); + while (!counter.is_done()) { + get_data_ptrs( + ptrs.data(), {base_ptrs, ntensors}, strides, counter.values); + auto step = counter.max_2d_step(); + loop(ptrs.data(), strides.data(), step[0], step[1]); + counter.increment(step); + } + } +} + +} // namespace internal +} // namespace at diff --git a/shared/package-files/00/009e2e57b3d31db9ecc384dfc3c73613387454ca31de8007d2a861abbcbc85d3/blob b/shared/package-files/00/009e2e57b3d31db9ecc384dfc3c73613387454ca31de8007d2a861abbcbc85d3/blob new file mode 100644 index 0000000000000000000000000000000000000000..9d6d6ae425384b47613c146d567847c00660a5cc --- /dev/null +++ b/shared/package-files/00/009e2e57b3d31db9ecc384dfc3c73613387454ca31de8007d2a861abbcbc85d3/blob @@ -0,0 +1,13 @@ +from .otBase import BaseTTXConverter + + +# https://developer.apple.com/fonts/TrueType-Reference-Manual/RM06/Chap6gcid.html +class table__g_c_i_d(BaseTTXConverter): + """Glyph ID to CID table + + The AAT ``gcid`` table stores glyphID-to-CID mappings. + + See also https://developer.apple.com/fonts/TrueType-Reference-Manual/RM06/Chap6gcid.html + """ + + pass diff --git a/shared/package-files/00/00a0a78fd6b549faf3098ee5e229deaeb27b960317fe4587abdc9b5a8e82ab2e/blob b/shared/package-files/00/00a0a78fd6b549faf3098ee5e229deaeb27b960317fe4587abdc9b5a8e82ab2e/blob new file mode 100644 index 0000000000000000000000000000000000000000..1ed57193fbefcbd9eba9fd5b2995878e9e58877a --- /dev/null +++ b/shared/package-files/00/00a0a78fd6b549faf3098ee5e229deaeb27b960317fe4587abdc9b5a8e82ab2e/blob @@ -0,0 +1,318 @@ +""" +Created on Sun Nov 5 14:48:19 2017 + +Author: Josef Perktold +""" +import numpy as np +from numpy.testing import assert_allclose, assert_equal + +from statsmodels.stats import weightstats +import statsmodels.stats.multivariate as smmv # pytest cannot import test_xxx +from statsmodels.stats.multivariate import confint_mvmean_fromstats +from statsmodels.tools.testing import Holder + + +def test_mv_mean(): + # names = ['id', 'mpg1', 'mpg2', 'add'] + x = np.asarray([[1.0, 24.0, 23.5, 1.0], + [2.0, 25.0, 24.5, 1.0], + [3.0, 21.0, 20.5, 1.0], + [4.0, 22.0, 20.5, 1.0], + [5.0, 23.0, 22.5, 1.0], + [6.0, 18.0, 16.5, 1.0], + [7.0, 17.0, 16.5, 1.0], + [8.0, 28.0, 27.5, 1.0], + [9.0, 24.0, 23.5, 1.0], + [10.0, 27.0, 25.5, 1.0], + [11.0, 21.0, 20.5, 1.0], + [12.0, 23.0, 22.5, 1.0], + [1.0, 20.0, 19.0, 0.0], + [2.0, 23.0, 22.0, 0.0], + [3.0, 21.0, 20.0, 0.0], + [4.0, 25.0, 24.0, 0.0], + [5.0, 18.0, 17.0, 0.0], + [6.0, 17.0, 16.0, 0.0], + [7.0, 18.0, 17.0, 0.0], + [8.0, 24.0, 23.0, 0.0], + [9.0, 20.0, 19.0, 0.0], + [10.0, 24.0, 22.0, 0.0], + [11.0, 23.0, 22.0, 0.0], + [12.0, 19.0, 18.0, 0.0]]) + + res = smmv.test_mvmean(x[:, 1:3], [21, 21]) + + res_stata = Holder(p_F=1.25062334808e-09, + df_r=22, + df_m=2, + F=59.91609589041116, + T2=125.2791095890415) + + assert_allclose(res.statistic, res_stata.F, rtol=1e-10) + assert_allclose(res.pvalue, res_stata.p_F, rtol=1e-10) + assert_allclose(res.t2, res_stata.T2, rtol=1e-10) + assert_equal(res.df, [res_stata.df_m, res_stata.df_r]) + + # diff of paired sample + mask = x[:, -1] == 1 + x1 = x[mask, 1:3] + x0 = x[~mask, 1:3] + res_p = smmv.test_mvmean(x1 - x0, [0, 0]) + + # result Stata hotelling + res_stata = Holder(T2=9.698067632850247, + df=10, + k=2, + N=12, + F=4.4082126, # not in return List + p_F=0.0424) # not in return List + + res = res_p + assert_allclose(res.statistic, res_stata.F, atol=5e-7) + assert_allclose(res.pvalue, res_stata.p_F, atol=5e-4) + assert_allclose(res.t2, res_stata.T2, rtol=1e-10) + assert_equal(res.df, [res_stata.k, res_stata.df]) + + # mvtest means diff1 diff2, zero + res_stata = Holder(p_F=.0423949782937231, + df_r=10, + df_m=2, + F=4.408212560386478, + T2=9.69806763285025) + + assert_allclose(res.statistic, res_stata.F, rtol=1e-12) + assert_allclose(res.pvalue, res_stata.p_F, rtol=1e-12) + assert_allclose(res.t2, res_stata.T2, rtol=1e-12) + assert_equal(res.df, [res_stata.df_m, res_stata.df_r]) + + dw = weightstats.DescrStatsW(x) + ci0 = dw.tconfint_mean(alpha=0.05) + + nobs = len(x[:, 1:]) + ci1 = confint_mvmean_fromstats(dw.mean, np.diag(dw.var), nobs, + lin_transf=np.eye(4), alpha=0.05) + ci2 = confint_mvmean_fromstats(dw.mean, dw.cov, nobs, + lin_transf=np.eye(4), alpha=0.05) + + assert_allclose(ci1[:2], ci0, rtol=1e-13) + assert_allclose(ci2[:2], ci0, rtol=1e-13) + + # test from data + res = smmv.confint_mvmean(x, lin_transf=np.eye(4), alpha=0.05) + assert_allclose(res, ci2, rtol=1e-13) + + +def test_mvmean_2indep(): + x = np.asarray([[1.0, 24.0, 23.5, 1.0], + [2.0, 25.0, 24.5, 1.0], + [3.0, 21.0, 20.5, 1.0], + [4.0, 22.0, 20.5, 1.0], + [5.0, 23.0, 22.5, 1.0], + [6.0, 18.0, 16.5, 1.0], + [7.0, 17.0, 16.5, 1.0], + [8.0, 28.0, 27.5, 1.0], + [9.0, 24.0, 23.5, 1.0], + [10.0, 27.0, 25.5, 1.0], + [11.0, 21.0, 20.5, 1.0], + [12.0, 23.0, 22.5, 1.0], + [1.0, 20.0, 19.0, 0.0], + [2.0, 23.0, 22.0, 0.0], + [3.0, 21.0, 20.0, 0.0], + [4.0, 25.0, 24.0, 0.0], + [5.0, 18.0, 17.0, 0.0], + [6.0, 17.0, 16.0, 0.0], + [7.0, 18.0, 17.0, 0.0], + [8.0, 24.0, 23.0, 0.0], + [9.0, 20.0, 19.0, 0.0], + [10.0, 24.0, 22.0, 0.0], + [11.0, 23.0, 22.0, 0.0], + [12.0, 19.0, 18.0, 0.0]]) + + y = np.asarray([[1.1, 24.1, 23.4, 1.1], + [1.9, 25.2, 24.3, 1.2], + [3.2, 20.9, 20.2, 1.3], + [4.1, 21.8, 20.6, 0.9], + [5.2, 23.0, 22.7, 0.8], + [6.3, 18.1, 16.8, 0.7], + [7.1, 17.2, 16.5, 1.0], + [7.8, 28.3, 27.4, 1.1], + [9.5, 23.9, 23.3, 1.2], + [10.1, 26.8, 25.2, 1.3], + [10.5, 26.7, 20.6, 0.9], + [12.1, 23.0, 22.7, 0.8], + [1.1, 20.1, 19.0, 0.7], + [1.8, 23.2, 22.0, 0.1], + [3.2, 21.3, 20.3, 0.2], + [4.3, 24.9, 24.2, 0.3], + [5.5, 17.9, 17.1, 0.0], + [5.5, 17.8, 16.0, 0.6], + [7.1, 17.7, 16.7, 0.0], + [7.7, 24.0, 22.8, 0.5], + [9.1, 20.1, 18.9, 0.0], + [10.2, 24.2, 22.3, 0.3], + [11.3, 23.3, 22.2, 0.0], + [11.7, 18.8, 18.1, 0.1]]) + + res = smmv.test_mvmean_2indep(x, y) + + res_stata = Holder(p_F=0.6686659171701677, + df_r=43, + df_m=4, + F=0.594263378678938, + T2=2.5428944576028973) + + assert_allclose(res.statistic, res_stata.F, rtol=1e-10) + assert_allclose(res.pvalue, res_stata.p_F, rtol=1e-10) + assert_allclose(res.t2, res_stata.T2, rtol=1e-10) + assert_equal(res.df, [res_stata.df_m, res_stata.df_r]) + + +def test_confint_simult(): + # example from book for simultaneous confint + + m = [526.29, 54.69, 25.13] + cov = [[5808.06, 597.84, 222.03], + [597.84, 126.05, 23.39], + [222.03, 23.39, 23.11]] + nobs = 87 + res_ci = confint_mvmean_fromstats(m, cov, nobs, lin_transf=np.eye(3), + simult=True) + + cii = [confint_mvmean_fromstats( + m, cov, nobs, lin_transf=np.eye(3)[i], simult=True)[:2] + for i in range(3)] + cii = np.array(cii).squeeze() + # these might use rounded numbers in intermediate computation + res_ci_book = np.array([[503.06, 550.12], [51.22, 58.16], [23.65, 26.61]]) + + assert_allclose(res_ci[0], res_ci_book[:, 0], rtol=1e-3) # low + assert_allclose(res_ci[0], res_ci_book[:, 0], rtol=1e-3) # upp + + assert_allclose(res_ci[0], cii[:, 0], rtol=1e-13) + assert_allclose(res_ci[1], cii[:, 1], rtol=1e-13) + + res_constr = confint_mvmean_fromstats(m, cov, nobs, lin_transf=[0, 1, -1], + simult=True) + + assert_allclose(res_constr[0], 29.56 - 3.12, rtol=1e-3) + assert_allclose(res_constr[1], 29.56 + 3.12, rtol=1e-3) + + # TODO: this assumes separate constraints, + # but we want multiplicity correction + # test if several constraints or transformations work + # original, flipping sign, multiply by 2 + lt = [[0, 1, -1], [0, -1, 1], [0, 2, -2]] + res_constr2 = confint_mvmean_fromstats(m, cov, nobs, lin_transf=lt, + simult=True) + + lows = res_constr[0], - res_constr[1], 2 * res_constr[0] + upps = res_constr[1], - res_constr[0], 2 * res_constr[1] + # TODO: check return dimensions + lows = np.asarray(lows).squeeze() + upps = np.asarray(upps).squeeze() + assert_allclose(res_constr2[0], lows, rtol=1e-13) + assert_allclose(res_constr2[1], upps, rtol=1e-13) + + +class TestCovStructure: + + @classmethod + def setup_class(cls): + # computed from data with ``cov = np.cov(dta1, rowvar=0, ddof=1)`` + cls.cov = np.array( + [[28.965925000000002, 17.215358333333327, 2.6945666666666654], + [17.215358333333327, 21.452852666666672, 6.044527833333332], + [2.6945666666666654, 6.044527833333332, 13.599042333333331]]) + cls.nobs = 25 + + def test_spherical(self): + cov, nobs = self.cov, self.nobs + # from Stata 14 + p_chi2 = 0.0006422366870356 + # df = 5 + chi2 = 21.53275509455011 + + stat, pv = smmv.test_cov_spherical(cov, nobs) + assert_allclose(stat, chi2, rtol=1e-7) + assert_allclose(pv, p_chi2, rtol=1e-6) + + def test_diagonal(self): + cov, nobs = self.cov, self.nobs + # from Stata 14 + p_chi2 = 0.0004589987613319 + # df = 3 + chi2 = 17.91025335733012 + stat, pv = smmv.test_cov_diagonal(cov, nobs) + + assert_allclose(stat, chi2, rtol=1e-8) + assert_allclose(pv, p_chi2, rtol=1e-7) + + def test_blockdiagonal(self): + cov, nobs = self.cov, self.nobs + # from Stata 14 + p_chi2 = 0.1721758850671037 + # df = 2 + chi2 = 3.518477474111563 + + # cov_blocks = cov[:2, :2], cov[-1:, -1:] + # stat, pv = smmv.test_cov_blockdiagonal(cov, nobs, cov_blocks) + block_len = [2, 1] + stat, pv = smmv.test_cov_blockdiagonal(cov, nobs, block_len) + assert_allclose(stat, chi2, rtol=1e-7) + assert_allclose(pv, p_chi2, rtol=1e-6) + + def test_covmat(self): + cov, nobs = self.cov, self.nobs + # from Stata 14 + p_chi2 = 0.4837049015162541 + # df = 6 + chi2 = 5.481422374989864 + + cov_null = np.array([[30, 15, 0], [15, 20, 0], [0, 0, 10]]) + stat, pv = smmv.test_cov(cov, nobs, cov_null) + assert_allclose(stat, chi2, rtol=1e-7) + assert_allclose(pv, p_chi2, rtol=1e-6) + + stat_2, pv_2 = smmv.test_cov(cov.tolist(), nobs, cov_null.tolist()) + assert_allclose(stat, stat_2, rtol=1e-7) + assert_allclose(pv, pv_2, rtol=1e-6) + + +def test_cov_oneway(): + # from Stata 14 + p_chi2 = .1944866419800838 + chi2 = 13.55075120374669 + df = 10 + p_F_Box = .1949865290585139 + df_r_Box = 18377.68924302788 + df_m_Box = 10 + F_Box = 1.354282822767436 + + nobs = [32, 32] + cov_m = np.array( + [[5.192540322580645, 4.545362903225806, 6.522177419354839, 5.25], + [4.545362903225806, 13.184475806451612, 6.76008064516129, + 6.266129032258064], + [6.522177419354839, 6.76008064516129, 28.673387096774192, + 14.46774193548387], + [5.25, 6.266129032258064, 14.46774193548387, 16.64516129032258]]) + cov_f = np.array( + [[9.13608870967742, 7.549395161290322, 4.86391129032258, + 4.151209677419355], + [7.549395161290322, 18.60383064516129, 10.224798387096774, + 5.445564516129032], + [4.86391129032258, 10.224798387096774, 30.039314516129032, + 13.493951612903226], + [4.151209677419355, 5.445564516129032, 13.493951612903226, + 27.995967741935484]]) + + res = smmv.test_cov_oneway([cov_m, cov_f], nobs) + stat, pv = res + assert_allclose(stat, F_Box, rtol=1e-10) + assert_allclose(pv, p_F_Box, rtol=1e-6) + assert_allclose(res.statistic_f, F_Box, rtol=1e-10) + assert_allclose(res.pvalue_f, p_F_Box, rtol=1e-6) + assert_allclose(res.df_f, (df_m_Box, df_r_Box), rtol=1e-13) + + assert_allclose(res.statistic_chi2, chi2, rtol=1e-10) + assert_allclose(res.pvalue_chi2, p_chi2, rtol=1e-6) + assert_equal(res.df_chi2, df) diff --git a/shared/package-files/00/00a16df76cb2ba5d643c2536ffa3a63735da528cc101cbfd3f87ec553ae37efe/blob b/shared/package-files/00/00a16df76cb2ba5d643c2536ffa3a63735da528cc101cbfd3f87ec553ae37efe/blob new file mode 100644 index 0000000000000000000000000000000000000000..d7be5b8be4f8d0272e4321e3bb20995379300f61 --- /dev/null +++ b/shared/package-files/00/00a16df76cb2ba5d643c2536ffa3a63735da528cc101cbfd3f87ec553ae37efe/blob @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:00a16df76cb2ba5d643c2536ffa3a63735da528cc101cbfd3f87ec553ae37efe +size 300512 diff --git a/shared/package-files/00/00a69b6d715b3302f0f9240a7ad857343df8b89e72fc7500db40e03b3a92bec8/blob b/shared/package-files/00/00a69b6d715b3302f0f9240a7ad857343df8b89e72fc7500db40e03b3a92bec8/blob new file mode 100644 index 0000000000000000000000000000000000000000..51b77c491344963c648fef90cdeaa5adac5d9a6f --- /dev/null +++ b/shared/package-files/00/00a69b6d715b3302f0f9240a7ad857343df8b89e72fc7500db40e03b3a92bec8/blob @@ -0,0 +1,78 @@ +from scipy.constants import find, value, c, speed_of_light, precision +from numpy.testing import assert_equal, assert_, assert_almost_equal +import scipy.constants._codata as _cd +from scipy import constants + + +def test_find(): + keys = find('weak mixing', disp=False) + assert_equal(keys, ['weak mixing angle']) + + keys = find('qwertyuiop', disp=False) + assert_equal(keys, []) + + keys = find('natural unit', disp=False) + assert_equal(keys, sorted(['natural unit of velocity', + 'natural unit of action', + 'natural unit of action in eV s', + 'natural unit of mass', + 'natural unit of energy', + 'natural unit of energy in MeV', + 'natural unit of momentum', + 'natural unit of momentum in MeV/c', + 'natural unit of length', + 'natural unit of time'])) + + +def test_basic_table_parse(): + c_s = 'speed of light in vacuum' + assert_equal(value(c_s), c) + assert_equal(value(c_s), speed_of_light) + + +def test_basic_lookup(): + assert_equal('%d %s' % (_cd.value('speed of light in vacuum'), + _cd.unit('speed of light in vacuum')), + '299792458 m s^-1') + + +def test_find_all(): + assert_(len(find(disp=False)) > 300) + + +def test_find_single(): + assert_equal(find('Wien freq', disp=False)[0], + 'Wien frequency displacement law constant') + + +def test_2002_vs_2006(): + assert_almost_equal(value('magn. flux quantum'), + value('mag. flux quantum')) + + +def test_exact_values(): + # Check that updating stored values with exact ones worked. + exact = dict((k, v[0]) for k, v in _cd._physical_constants_2018.items()) + replace = _cd.exact2018(exact) + for key, val in replace.items(): + assert_equal(val, value(key)) + assert precision(key) == 0 + + +def test_gh11341(): + # gh-11341 noted that these three constants should exist (for backward + # compatibility) and should always have the same value: + a = constants.epsilon_0 + b = constants.physical_constants['electric constant'][0] + c = constants.physical_constants['vacuum electric permittivity'][0] + assert a == b == c + + +def test_gh14467(): + # gh-14467 noted that some physical constants in CODATA are rounded + # to only ten significant figures even though they are supposed to be + # exact. Check that (at least) the case mentioned in the issue is resolved. + res = constants.physical_constants['Boltzmann constant in eV/K'][0] + ref = (constants.physical_constants['Boltzmann constant'][0] + / constants.physical_constants['elementary charge'][0]) + assert res == ref diff --git a/shared/package-files/00/00a714b782fb7b802278692cb7d91372294746a5b801098444db3710e4bcbde3/blob b/shared/package-files/00/00a714b782fb7b802278692cb7d91372294746a5b801098444db3710e4bcbde3/blob new file mode 100644 index 0000000000000000000000000000000000000000..e1023bd1eb5c7b88895c6dc5b349d3b4a976f226 --- /dev/null +++ b/shared/package-files/00/00a714b782fb7b802278692cb7d91372294746a5b801098444db3710e4bcbde3/blob @@ -0,0 +1,147 @@ +#pragma once + +#include + +#include + +namespace torch { +namespace nn { +namespace utils { + +// Clips gradient norm of a vector of Tensors. +// See +// https://pytorch.org/docs/stable/nn.html?highlight=clip_grad_norm#torch.nn.utils.clip_grad_norm_ +// for more details about this module. +// +// Difference with the python version: unlike the python version, even when +// skipping the finiteness checks (error_if_nonfinite = false), this function +// will introduce a device <=> CPU synchronization (for devices where that makes +// sense!) in order to return a CPU-side `double`. This C++ version therefore +// cannot be run fully asynchronously w.r.t. the device of the gradients. +inline double clip_grad_norm_( + const std::vector& parameters, + double max_norm, + double norm_type = 2.0, + bool error_if_nonfinite = false) { + std::vector params_with_grad; + + for (const auto& param : parameters) { + auto& grad = param.grad(); + if (grad.defined()) { + params_with_grad.push_back(param); + } + } + + if (params_with_grad.empty()) { + return 0.0; + } + + Tensor total_norm_tensor; + if (norm_type == std::numeric_limits::infinity()) { + std::vector norms; + norms.reserve(params_with_grad.size()); + + for (const auto& param : params_with_grad) { + norms.emplace_back(param.grad().data().abs().max()); + } + total_norm_tensor = + (norms.size() == 1) ? norms[0] : torch::max(torch::stack(norms)); + } else if (norm_type == 0) { + total_norm_tensor = + torch::full({}, static_cast(params_with_grad.size())); + } else { + std::vector norms; + norms.reserve(params_with_grad.size()); + + for (const auto& param : params_with_grad) { + norms.emplace_back(param.grad().data().norm(norm_type)); + } + total_norm_tensor = + (norms.size() == 1) ? norms[0] : torch::stack(norms).norm(norm_type); + } + + // When possible (ie when skipping the finiteness check), we avoid + // synchronizing the CPU and the gradients' device until the very end to + // preserve async execution on the device. When checking for finite-ness, this + // optional ensures we only sync once. + c10::optional total_norm = c10::nullopt; + if (error_if_nonfinite) { + total_norm = total_norm_tensor.item().toDouble(); + TORCH_CHECK( + std::isfinite(*total_norm), + "The total norm of order ", + norm_type, + " for gradients from `parameters` ", + "is non-finite, so it cannot be clipped. To disable this error and scale ", + "the gradients with the non-finite norm anyway, set ", + "`error_if_nonfinite=false`"); + } + + auto clip_coef = max_norm / (total_norm_tensor + 1e-6); + auto clip_coef_clamped = + torch::clamp(clip_coef, c10::nullopt /* min */, 1.0 /* max */); + for (auto& param : params_with_grad) { + param.grad().data().mul_(clip_coef_clamped); + } + + if (!total_norm.has_value()) { + total_norm = total_norm_tensor.item().toDouble(); + } + return *total_norm; +} + +// A wrapper around clip_grad_norm_ that allows us to call the function with a +// braced-init-list of Tensors. +inline double clip_grad_norm_( + std::initializer_list parameters, + double max_norm, + double norm_type = 2.0, + bool error_if_nonfinite = false) { + return clip_grad_norm_( + std::vector(parameters), max_norm, norm_type, error_if_nonfinite); +} + +// A wrapper around clip_grad_norm_ that allows us to call the function with a +// single Tensor. +inline double clip_grad_norm_( + Tensor parameter, + double max_norm, + double norm_type = 2.0, + bool error_if_nonfinite = false) { + std::vector params = {std::move(parameter)}; + return clip_grad_norm_( + std::move(params), max_norm, norm_type, error_if_nonfinite); +} + +// Clips gradient of an iterable of parameters at specified value. +// Gradients are modified in-place. +// See https://pytorch.org/docs/stable/nn.html#clip-grad-value +// for more details about this module. +inline void clip_grad_value_( + const std::vector& parameters, + double clip_value) { + for (const auto& param : parameters) { + if (param.grad().defined()) { + param.grad().data().clamp_(-clip_value, clip_value); + } + } +} + +// A wrapper around clip_grad_value_ that allows us to call the function with a +// braced-init-list of Tensors. +inline void clip_grad_value_( + std::initializer_list parameters, + double clip_value) { + clip_grad_value_(std::vector(parameters), clip_value); +} + +// A wrapper around clip_grad_value_ that allows us to call the function with a +// single Tensor. +inline void clip_grad_value_(Tensor parameter, double clip_value) { + std::vector params = {std::move(parameter)}; + clip_grad_value_(std::move(params), clip_value); +} + +} // namespace utils +} // namespace nn +} // namespace torch diff --git a/shared/package-files/00/00ab15a4fb56b0b94446698572b00ff5fd87a603de4560a2cf71ee2c7c2ffd6a/blob b/shared/package-files/00/00ab15a4fb56b0b94446698572b00ff5fd87a603de4560a2cf71ee2c7c2ffd6a/blob new file mode 100644 index 0000000000000000000000000000000000000000..e968a99cf85ddd09f4d6cf1bc2ad76e69f1b552b --- /dev/null +++ b/shared/package-files/00/00ab15a4fb56b0b94446698572b00ff5fd87a603de4560a2cf71ee2c7c2ffd6a/blob @@ -0,0 +1,2350 @@ +import copy +import functools +import inspect +import itertools +import logging +import os +import sys +import warnings +import weakref +from collections import defaultdict, deque +from contextlib import contextmanager +from dataclasses import dataclass, fields, is_dataclass +from enum import auto, Enum +from typing import Any, Callable, List, Optional, Tuple, Type + +import torch +import torch.distributed as dist +from torch.autograd import Function, Variable +from torch.distributed.algorithms.join import Join, Joinable, JoinHook +from torch.utils._pytree import tree_flatten, tree_unflatten +from torch.utils.hooks import RemovableHandle + +RPC_AVAILABLE = False +if dist.is_available(): + from torch.distributed.distributed_c10d import ( + _get_default_group, + _rank_not_in_group, + ReduceOp, + ) + from torch.distributed.utils import ( + _alloc_storage, + _cast_forward_inputs, + _free_storage, + _sync_module_states, + _to_kwargs, + _verify_param_shape_across_processes, + ) +if torch.distributed.rpc.is_available(): + RPC_AVAILABLE = True + from torch.distributed.rpc import RRef + +from torch._utils import _get_device_index + +from ..modules import Module +from .scatter_gather import gather, scatter_kwargs # noqa: F401 + +__all__ = ["DistributedDataParallel"] + +logger = logging.getLogger(__name__) + + +@dataclass +class _MixedPrecision: + """ + This configures DDP-native mixed precision training. + + Attributes: + param_dtype (torch.dtype): This specifies the dtype for model + parameters, inputs (when ``cast_forward_inputs`` is set to + ``True``), and therefore the dtype for computation. + However, outside the forward and backward passes, parameters are in + full precision. Model checkpointing always happens in full + precision. + reduce_dtype (torch.dtype): This specifies the dtype for gradient + reduction, which is permitted to differ from ``param_dtype``. + buffer_dtype (torch.dtype): This specifies the dtype for buffers. + + .. note:: This API is experimental and subject to change. + + .. note:: Only floating point tensors are cast to their specified dtypes. + + .. note:: ``state_dict`` checkpoints parameters and buffers in full + precision. + + .. note:: Each low precision dtype must be specified explicitly. For + example, ``_MixedPrecision(reduce_dtype=torch.float16)`` only specifies + the reduction dtype to be low precision, and DDP will not cast + parameters or buffers. + + .. note:: If a ``reduce_dtype`` is not specified, then gradient reduction + happens in ``param_dtype`` if specified or the original parameter dtype + otherwise. For example, ``_MixedPrecision(param_dtype=torch.float16)`` + would result in communication occurring in fp16. + """ + + param_dtype: Optional[torch.dtype] = None + reduce_dtype: Optional[torch.dtype] = None + buffer_dtype: Optional[torch.dtype] = None + # TODO (rohan-varma): keep_low_precision_grads: bool = False + # TODO (rohan-varma): APIs to allow users to run batchnorm and layernorm + # in full precision. For DDP, this can be implemented by not performing the + # parameter cast for BN and LN units. + + +def _cast_buffers(mixed_precision_config, root_module): + """Casts buffers to the given ``buffer_dtype``.""" + for buf in root_module.buffers(): + if hasattr(buf, "_ddp_ignored") and buf._ddp_ignored: + continue + + buf.data = buf.to(dtype=mixed_precision_config.buffer_dtype) + + +def _setup_mixed_precision_params(mixed_precision_config, root_module): + """Create and free storage for the mixed precision parameters.""" + for param in root_module.parameters(): + # Do not setup mixed precision for DDP ignored parameters. + if hasattr(param, "_ddp_ignored") and param._ddp_ignored: + continue + + if not hasattr(param, "_mp_param"): + param._mp_param = torch.zeros_like( + param, + device=param.device, + dtype=mixed_precision_config.param_dtype, + requires_grad=param.requires_grad, + ) + _free_storage(param._mp_param) + # _fp_param will point to the full precision param so it can be switched + # back to at the end of forward / backward. + param._fp_param = param.data + + +def _tree_flatten_with_rref(output): + output_is_rref = RPC_AVAILABLE and isinstance(output, RRef) + if output_is_rref: + output_tensor_list, treespec = tree_flatten(output.local_value()) + else: + output_tensor_list, treespec = tree_flatten(output) + # Need to return flattened tensors, spec to re-pack them, as well + # as if the return type was actually an RRef to reconstruct. + return output_tensor_list, treespec, output_is_rref + + +def _tree_unflatten_with_rref(output, treespec, output_is_rref): + output = tree_unflatten(output, treespec) + if output_is_rref: + output = RRef(output) + return output + + +def _find_tensors(obj): + r"""Recursively find all tensors contained in the specified object.""" + if RPC_AVAILABLE and isinstance(obj, RRef): + # If the current node is the owner of the RRef, unwrap it and try to + # find Tensors. + # TODO: Expand to remote RRefs. + if obj.is_owner(): + return _find_tensors(obj.local_value()) + if isinstance(obj, torch.Tensor): + return [obj] + if isinstance(obj, (list, tuple)): + return itertools.chain.from_iterable(map(_find_tensors, obj)) + if isinstance(obj, dict): + return itertools.chain.from_iterable(map(_find_tensors, obj.values())) + if is_dataclass(obj): + return itertools.chain.from_iterable( + map(_find_tensors, (getattr(obj, f.name) for f in fields(obj))) + ) + + return [] + + +def _dump_DDP_relevant_env_vars(): + relevant_env_vars = [ + "RANK", + "LOCAL_RANK", + "WORLD_SIZE", + "MASTER_PORT", + "MASTER_ADDR", + "CUDA_VISIBLE_DEVICES", + "GLOO_SOCKET_IFNAME", + "GLOO_DEVICE_TRANSPORT", + "NCCL_SOCKET_IFNAME", + "TORCH_NCCL_BLOCKING_WAIT", + "NCCL_DEBUG", + "NCCL_DEBUG_SUBSYS", + "NCCL_IB_DISABLE", + # More NCCL env vars: + "NCCL_P2P_DISABLE", + "NCCL_P2P_LEVEL", + "NCCL_SHM_DISABLE", + "NCCL_SOCKET_NTHREADS", + "NCCL_NSOCKS_PERTHREAD", + "NCCL_BUFFSIZE", + "NCCL_NTHREADS", + "NCCL_RINGS", + "NCCL_MAX_NCHANNELS", + "NCCL_MIN_NCHANNELS", + "NCCL_CHECKS_DISABLE", + "NCCL_CHECK_POINTERS", + "NCCL_LAUNCH_MODE", + "NCCL_IB_HCA", + "NCCL_IB_TIMEOUT", + "NCCL_IB_RETRY_CNT", + "NCCL_IB_GID_INDEX", + "NCCL_IB_SL", + "NCCL_IB_TC", + "NCCL_IB_AR_THRESHOLD", + "NCCL_IB_CUDA_SUPPORT", + "NCCL_NET_GDR_LEVEL", + "NCCL_NET_GDR_READ", + "NCCL_SINGLE_RING_THRESHOLD", + "NCCL_LL_THRESHOLD", + "NCCL_TREE_THRESHOLD", + "NCCL_ALGO", + "NCCL_PROTO", + "NCCL_IGNORE_CPU_AFFINITY", + "NCCL_DEBUG_FILE", + "NCCL_COLLNET_ENABLE", + "NCCL_TOPO_FILE", + "NCCL_TOPO_DUMP_FILE", + "TORCH_NCCL_ASYNC_ERROR_HANDLING", + ] + formatted_output = "" + for var in relevant_env_vars: + value = os.environ[var] if var in os.environ else "N/A" + formatted_output += f"env:{var}={value}\n" + print(formatted_output) + + +class _BufferCommHookLocation(Enum): + PRE_FORWARD = auto() + POST_FORWARD = auto() + + +@dataclass +class _BufferCommHook: + buffer_comm_hook: Callable + buffer_comm_hook_state: Any + buffer_comm_hook_location: _BufferCommHookLocation + + +# Add a DDPSink to run various functions when backwards starts, such as +# queueing call back of out-most backward/graph task, +# this helps call back is fired after all gradients' calculation +# is completed. +class _DDPSink(Function): + @staticmethod + def forward(ctx, ddp_weakref, *inputs): + # set_materialize_grads(False) will ensure that None gradients stay as + # None and are not filled with zeros. + ctx.set_materialize_grads(False) + ctx.ddp_weakref = ddp_weakref + ret = tuple( + inp.clone() if isinstance(inp, torch.Tensor) else inp for inp in inputs + ) + return ret + + @staticmethod + def backward(ctx, *grad_outputs): + # Enqueue delay allreduce for static graph training on the first + # iteration. + ddp_weakref = ctx.ddp_weakref() + reducer = ddp_weakref.reducer + static_graph = ddp_weakref.static_graph + delay_ar_enqueued = ( + static_graph and ddp_weakref._static_graph_delay_allreduce_enqueued + ) + if static_graph and not delay_ar_enqueued: + Variable._execution_engine.queue_callback( # type: ignore[call-arg,misc] + reducer._delay_all_reduce + ) + ddp_weakref._static_graph_delay_allreduce_enqueued = True + + return (None, *grad_outputs) + + +class _DDPJoinHook(JoinHook): + def __init__(self, ddp, divide_by_initial_world_size): + """Set config variables for internal usage.""" + assert isinstance(ddp, DistributedDataParallel), ( + "DDP join hook requires passing in a DistributedDataParallel " + "instance as the state" + ) + assert ddp.logger is not None + ddp.logger._set_uneven_input_join() + self.ddp = ddp + self.ddp._divide_by_initial_world_size = divide_by_initial_world_size + super().__init__() + + def main_hook(self): + """Shadow the DDP collective communication operations in the forward and backward passes.""" + ddp = self.ddp + # Buckets are rebuilt only once during a training period + ddp.reducer._rebuild_buckets() + + # Schedule a broadcast if we are syncing module buffers in the + # forward pass + # TODO: make DDP uneven inputs context manager support buffer + # comm hook (https://github.com/pytorch/pytorch/issues/65436) + ddp._check_and_sync_module_buffers() + + # Check if need to sync in the backward pass + should_sync_backwards = ddp._check_global_requires_backward_grad_sync( + is_joined_rank=True + ) + # Forward parameter sync is disabled in the next iteration if we + # are skipping gradient sync this iteration, so set + # `require_forward_param_sync` accordingly + ddp.require_forward_param_sync = should_sync_backwards + if not should_sync_backwards: + return + + # Schedule one allreduce per gradient bucket to match the backward + # pass allreduce + ddp._match_all_reduce_for_bwd_pass() + + # Check if we need to allreduce locally unused parameters + if ddp.find_unused_parameters: + ddp._match_unused_params_allreduce() + + # Rebuilt parameters are pushed only once during a training period + ddp.reducer._push_all_rebuilt_params() + + def post_hook(self, is_last_joiner: bool): + """Sync the final model to ensure that the model is the same across all processes.""" + self.ddp._sync_final_model(is_last_joiner) + + +class DistributedDataParallel(Module, Joinable): + r"""Implement distributed data parallelism based on ``torch.distributed`` at module level. + + This container provides data parallelism by synchronizing gradients + across each model replica. The devices to synchronize across are + specified by the input ``process_group``, which is the entire world + by default. Note that ``DistributedDataParallel`` does not chunk or + otherwise shard the input across participating GPUs; the user is + responsible for defining how to do so, for example through the use + of a :class:`DistributedSampler`. + + See also: :ref:`distributed-basics` and :ref:`cuda-nn-ddp-instead`. + The same constraints on input as in :class:`torch.nn.DataParallel` apply. + + Creation of this class requires that ``torch.distributed`` to be already + initialized, by calling :func:`torch.distributed.init_process_group`. + + ``DistributedDataParallel`` is proven to be significantly faster than + :class:`torch.nn.DataParallel` for single-node multi-GPU data + parallel training. + + To use ``DistributedDataParallel`` on a host with N GPUs, you should spawn + up ``N`` processes, ensuring that each process exclusively works on a single + GPU from 0 to N-1. This can be done by either setting + ``CUDA_VISIBLE_DEVICES`` for every process or by calling: + + >>> # xdoctest: +SKIP("undefined variables") + >>> torch.cuda.set_device(i) + + where i is from 0 to N-1. In each process, you should refer the following + to construct this module: + + >>> # xdoctest: +SKIP("undefined variables") + >>> torch.distributed.init_process_group( + >>> backend='nccl', world_size=N, init_method='...' + >>> ) + >>> model = DistributedDataParallel(model, device_ids=[i], output_device=i) + + In order to spawn up multiple processes per node, you can use either + ``torch.distributed.launch`` or ``torch.multiprocessing.spawn``. + + .. note:: + Please refer to `PyTorch Distributed Overview `__ + for a brief introduction to all features related to distributed training. + + .. note:: + ``DistributedDataParallel`` can be used in conjunction with + :class:`torch.distributed.optim.ZeroRedundancyOptimizer` to reduce + per-rank optimizer states memory footprint. Please refer to + `ZeroRedundancyOptimizer recipe `__ + for more details. + + .. note:: ``nccl`` backend is currently the fastest and highly recommended + backend when using GPUs. This applies to both single-node and + multi-node distributed training. + + .. note:: This module also supports mixed-precision distributed training. + This means that your model can have different types of parameters such + as mixed types of ``fp16`` and ``fp32``, the gradient reduction on these + mixed types of parameters will just work fine. + + .. note:: If you use ``torch.save`` on one process to checkpoint the module, + and ``torch.load`` on some other processes to recover it, make sure that + ``map_location`` is configured properly for every process. Without + ``map_location``, ``torch.load`` would recover the module to devices + where the module was saved from. + + .. note:: When a model is trained on ``M`` nodes with ``batch=N``, the + gradient will be ``M`` times smaller when compared to the same model + trained on a single node with ``batch=M*N`` if the loss is summed (NOT + averaged as usual) across instances in a batch (because the gradients + between different nodes are averaged). You should take this into + consideration when you want to obtain a mathematically equivalent + training process compared to the local training counterpart. But in most + cases, you can just treat a DistributedDataParallel wrapped model, a + DataParallel wrapped model and an ordinary model on a single GPU as the + same (E.g. using the same learning rate for equivalent batch size). + + .. note:: + Parameters are never broadcast between processes. The module performs + an all-reduce step on gradients and assumes that they will be modified + by the optimizer in all processes in the same way. Buffers + (e.g. BatchNorm stats) are broadcast from the module in process of rank + 0, to all other replicas in the system in every iteration. + + .. note:: + If you are using DistributedDataParallel in conjunction with the + :ref:`distributed-rpc-framework`, you should always use + :meth:`torch.distributed.autograd.backward` to compute gradients and + :class:`torch.distributed.optim.DistributedOptimizer` for optimizing + parameters. + + Example:: + + >>> # xdoctest: +SKIP("undefined variables") + >>> import torch.distributed.autograd as dist_autograd + >>> from torch.nn.parallel import DistributedDataParallel as DDP + >>> import torch + >>> from torch import optim + >>> from torch.distributed.optim import DistributedOptimizer + >>> import torch.distributed.rpc as rpc + >>> from torch.distributed.rpc import RRef + >>> + >>> t1 = torch.rand((3, 3), requires_grad=True) + >>> t2 = torch.rand((3, 3), requires_grad=True) + >>> rref = rpc.remote("worker1", torch.add, args=(t1, t2)) + >>> ddp_model = DDP(my_model) + >>> + >>> # Setup optimizer + >>> optimizer_params = [rref] + >>> for param in ddp_model.parameters(): + >>> optimizer_params.append(RRef(param)) + >>> + >>> dist_optim = DistributedOptimizer( + >>> optim.SGD, + >>> optimizer_params, + >>> lr=0.05, + >>> ) + >>> + >>> with dist_autograd.context() as context_id: + >>> pred = ddp_model(rref.to_here()) + >>> loss = loss_func(pred, target) + >>> dist_autograd.backward(context_id, [loss]) + >>> dist_optim.step(context_id) + + .. note:: + DistributedDataParallel currently offers limited support for gradient + checkpointing with :meth:`torch.utils.checkpoint`. + If the checkpoint is done with use_reentrant=False (recommended), DDP + will work as expected without any limitations. + If, however, the checkpoint is done with use_reentrant=True (the default), + DDP will work as expected when there are no unused parameters in the model + and each layer is checkpointed at most once (make sure you are not passing + `find_unused_parameters=True` to DDP). We currently do not support the + case where a layer is checkpointed multiple times, or when there unused + parameters in the checkpointed model. + + .. note:: + To let a non-DDP model load a state dict from a DDP model, + :meth:`~torch.nn.modules.utils.consume_prefix_in_state_dict_if_present` + needs to be applied to strip the prefix "module." in the DDP state dict before loading. + + .. warning:: + Constructor, forward method, and differentiation of the output (or a + function of the output of this module) are distributed synchronization + points. Take that into account in case different processes might be + executing different code. + + .. warning:: + This module assumes all parameters are registered in the model by the + time it is created. No parameters should be added nor removed later. + Same applies to buffers. + + .. warning:: + This module assumes all parameters are registered in the model of each + distributed processes are in the same order. The module itself will + conduct gradient ``allreduce`` following the reverse order of the + registered parameters of the model. In other words, it is users' + responsibility to ensure that each distributed process has the exact + same model and thus the exact same parameter registration order. + + .. warning:: + This module allows parameters with non-rowmajor-contiguous strides. + For example, your model may contain some parameters whose + :class:`torch.memory_format` is ``torch.contiguous_format`` + and others whose format is ``torch.channels_last``. However, + corresponding parameters in different processes must have the + same strides. + + .. warning:: + This module doesn't work with :func:`torch.autograd.grad` (i.e. it will + only work if gradients are to be accumulated in ``.grad`` attributes of + parameters). + + .. warning:: + If you plan on using this module with a ``nccl`` backend or a ``gloo`` + backend (that uses Infiniband), together with a DataLoader that uses + multiple workers, please change the multiprocessing start method to + ``forkserver`` (Python 3 only) or ``spawn``. Unfortunately + Gloo (that uses Infiniband) and NCCL2 are not fork safe, and you will + likely experience deadlocks if you don't change this setting. + + .. warning:: + You should never try to change your model's parameters after wrapping + up your model with ``DistributedDataParallel``. Because, when + wrapping up your model with ``DistributedDataParallel``, the constructor + of ``DistributedDataParallel`` will register the additional gradient + reduction functions on all the parameters of the model itself at the + time of construction. If you change the model's parameters afterwards, + gradient reduction functions no longer match the correct set of + parameters. + + .. warning:: + Using ``DistributedDataParallel`` in conjunction with the + :ref:`distributed-rpc-framework` is experimental and subject to change. + + Args: + module (Module): module to be parallelized + device_ids (list of int or torch.device): CUDA devices. + 1) For single-device modules, ``device_ids`` can + contain exactly one device id, which represents the only + CUDA device where the input module corresponding to this process resides. + Alternatively, ``device_ids`` can also be ``None``. + 2) For multi-device modules and CPU modules, + ``device_ids`` must be ``None``. + + When ``device_ids`` is ``None`` for both cases, + both the input data for the forward pass and the actual module + must be placed on the correct device. + (default: ``None``) + output_device (int or torch.device): Device location of output for + single-device CUDA modules. For multi-device modules and + CPU modules, it must be ``None``, and the module itself + dictates the output location. (default: ``device_ids[0]`` + for single-device modules) + broadcast_buffers (bool): Flag that enables syncing (broadcasting) + buffers of the module at beginning of the ``forward`` + function. (default: ``True``) + process_group: The process group to be used for distributed data + all-reduction. If ``None``, the default process group, which + is created by :func:`torch.distributed.init_process_group`, + will be used. (default: ``None``) + bucket_cap_mb: ``DistributedDataParallel`` will bucket parameters into + multiple buckets so that gradient reduction of each + bucket can potentially overlap with backward computation. + :attr:`bucket_cap_mb` controls the bucket size in + MegaBytes (MB). (default: 25) + find_unused_parameters (bool): Traverse the autograd graph from all + tensors contained in the return value of the + wrapped module's ``forward`` function. Parameters + that don't receive gradients as part of this + graph are preemptively marked as being ready to + be reduced. In addition, parameters that may have + been used in the wrapped module's ``forward`` + function but were not part of loss computation and + thus would also not receive gradients are + preemptively marked as ready to be reduced. + (default: ``False``) + check_reduction: This argument is deprecated. + gradient_as_bucket_view (bool): When set to ``True``, gradients will be views + pointing to different offsets of ``allreduce`` communication + buckets. This can reduce peak memory usage, where the + saved memory size will be equal to the total gradients + size. Moreover, it avoids the overhead of copying between + gradients and ``allreduce`` communication buckets. When + gradients are views, ``detach_()`` cannot be called on the + gradients. If hitting such errors, please fix it by + referring to the :meth:`~torch.optim.Optimizer.zero_grad` + function in ``torch/optim/optimizer.py`` as a solution. + Note that gradients will be views after first iteration, so + the peak memory saving should be checked after first iteration. + static_graph (bool): When set to ``True``, DDP knows the trained graph is + static. Static graph means 1) The set of used and unused + parameters will not change during the whole training loop; in + this case, it does not matter whether users set + ``find_unused_parameters = True`` or not. 2) How the graph is trained + will not change during the whole training loop (meaning there is + no control flow depending on iterations). + When static_graph is set to be ``True``, DDP will support cases that + can not be supported in the past: + 1) Reentrant backwards. + 2) Activation checkpointing multiple times. + 3) Activation checkpointing when model has unused parameters. + 4) There are model parameters that are outside of forward function. + 5) Potentially improve performance when there are unused parameters, + as DDP will not search graph in each iteration to detect unused + parameters when static_graph is set to be ``True``. + To check whether you can set static_graph to be ``True``, one way is to + check ddp logging data at the end of your previous model training, + if ``ddp_logging_data.get("can_set_static_graph") == True``, mostly you + can set ``static_graph = True`` as well. + + Example:: + >>> # xdoctest: +SKIP("undefined variables") + >>> model_DDP = torch.nn.parallel.DistributedDataParallel(model) + >>> # Training loop + >>> ... + >>> ddp_logging_data = model_DDP._get_ddp_logging_data() + >>> static_graph = ddp_logging_data.get("can_set_static_graph") + delay_all_reduce_named_params (list of tuple of str and torch.nn.Parameter): a list + of named parameters whose all reduce will be delayed when the gradient of + the parameter specified in ``param_to_hook_all_reduce`` is ready. Other + arguments of DDP do not apply to named params specified in this argument + as these named params will be ignored by DDP reducer. + param_to_hook_all_reduce (torch.nn.Parameter): a parameter to hook delayed all reduce + of parameters specified in ``delay_all_reduce_named_params``. + + + Attributes: + module (Module): the module to be parallelized. + + Example:: + + >>> # xdoctest: +SKIP("undefined variables") + >>> torch.distributed.init_process_group(backend='nccl', world_size=4, init_method='...') + >>> net = torch.nn.parallel.DistributedDataParallel(model) + """ + + # used to track whether the given thread is inside ddp forward for torchdynamo purposes + _active_ddp_module: Optional["DistributedDataParallel"] = None + + def __init__( + self, + module, + device_ids=None, + output_device=None, + dim=0, + broadcast_buffers=True, + process_group=None, + bucket_cap_mb=25, + find_unused_parameters=False, + check_reduction=False, + gradient_as_bucket_view=False, + static_graph=False, + delay_all_reduce_named_params=None, + param_to_hook_all_reduce=None, + mixed_precision: Optional[_MixedPrecision] = None, + device_mesh=None, + ): + super().__init__() + Joinable.__init__(self) + self.logger = None + if bool(delay_all_reduce_named_params is not None) != bool( + param_to_hook_all_reduce is not None + ): + self._log_and_throw( + ValueError, + "delay_all_reduce_named_params and param_to_hook_all_reduce " + "need to be set at the same time.", + ) + + self._delay_all_reduce_params = [] + if hasattr(module, "_ddp_params_and_buffers_to_ignore"): + self.parameters_to_ignore = set(module._ddp_params_and_buffers_to_ignore) + else: + self.parameters_to_ignore = set() + if delay_all_reduce_named_params is not None: + for name, param in delay_all_reduce_named_params: + self.parameters_to_ignore.add(name) + self._delay_all_reduce_params.append(param) + + self._module_parameters = [ + p + for n, p in module.named_parameters() + if n not in self.parameters_to_ignore + ] + if not any(p.requires_grad for p in self._module_parameters): + if len(self._delay_all_reduce_params): + logger.info("Delay the AllReduce of all parameters.") + else: + self._log_and_throw( + RuntimeError, + "DistributedDataParallel is not needed when a module " + "doesn't have any parameter that requires a gradient.", + ) + + if device_ids is not None and len(device_ids) > 1: + self._log_and_throw( + ValueError, + "device_ids can only be None or contain a single element.", + ) + + self.is_multi_device_module = ( + len({p.device for p in self._module_parameters}) > 1 + ) + distinct_device_types = { + p.device.type for p in self._module_parameters if p.device is not None + } + if len(distinct_device_types) != 1: + self._log_and_throw( + ValueError, + "DistributedDataParallel's input module must be on " + f"the same type of devices, but input module parameters locate in {distinct_device_types}.", + ) + + self.device_type = next(iter(distinct_device_types)) + + if ( + device_ids is None + or len(device_ids) == 0 # For backward compatibility. + or self.device_type == "cpu" + or self.is_multi_device_module + ): + if device_ids or output_device: + self._log_and_throw( + ValueError, + "DistributedDataParallel device_ids and output_device arguments " + "only work with single-device/multiple-device GPU modules or CPU modules, " + "but got device_ids {}, output_device {}, and module parameters {}.".format( + device_ids, + output_device, + {p.device for p in self._module_parameters}, + ), + ) + + self.device_ids = None + self.output_device = None + else: + self.device_ids = [_get_device_index(x, True) for x in device_ids] + + if output_device is None: + output_device = device_ids[0] + + self.output_device = _get_device_index(output_device, True) + + if process_group and device_mesh is not None: + raise RuntimeError( + "Cannot specify both process_group and device_mesh arguments." + ) + elif process_group is None and device_mesh is None: + self.process_group = _get_default_group() + elif device_mesh is None: + self.process_group = process_group + else: + if device_mesh.ndim != 1: + raise RuntimeError( + f"Only 1D device mesh is supported, but got {device_mesh}." + ) + self.device_mesh = device_mesh + self.process_group = device_mesh.get_group(mesh_dim=0) + + self.static_graph = False + self.dim = dim + self.module = module + self.device = next(iter(self._module_parameters)).device + self.broadcast_buffers = broadcast_buffers + self.find_unused_parameters = find_unused_parameters + self.require_backward_grad_sync = True + self.require_forward_param_sync = True + self.gradient_as_bucket_view = gradient_as_bucket_view + self.mixed_precision = mixed_precision + if self.mixed_precision is not None: + logger.warning("Received mixed precision config %s", self.mixed_precision) + + if check_reduction: + # This argument is no longer used since the reducer + # will ensure reduction completes even if some parameters + # do not receive gradients. + warnings.warn( + "The `check_reduction` argument in `DistributedDataParallel` " + "module is deprecated. Please avoid using it." + ) + + # Check that a module does not have Uninitialized parameters + for param in self._module_parameters: + if isinstance(param, torch.nn.parameter.UninitializedParameter): + self._log_and_throw( + RuntimeError, + "Modules with uninitialized parameters can't be used with `DistributedDataParallel`. " + "Run a dummy forward pass to correctly initialize the modules", + ) + # used for intra-node param sync and inter-node sync as well + self.broadcast_bucket_size = int(250 * 1024 * 1024) + + # reduction bucket size + self.bucket_bytes_cap = int(bucket_cap_mb * 1024 * 1024) + # Whether to perform input tensor CPU to GPU copies on a side-stream + self.use_side_stream_for_tensor_copies = ( + os.environ.get("PYTORCH_DDP_USE_SIDE_STREAM", "1") == "1" + ) + + # Initialize gradient buffers and register all reduce hook + self._delay_grad_buffer = None + self._delay_grad_views: List[torch.Tensor] = [] + self._delay_all_reduce_all_params = False + if len(self._delay_all_reduce_params) != 0: + self._register_delay_all_reduce_hook( + bucket_cap_mb=bucket_cap_mb, + param_to_hook_all_reduce=param_to_hook_all_reduce, + device_ids=device_ids, + ) + if self._delay_all_reduce_all_params: + return + + # Build parameters for reducer. + parameters, expect_sparse_gradient = self._build_params_for_reducer() + # Verify model equivalence. + _verify_param_shape_across_processes(self.process_group, parameters) + # Sync params and buffers. Ensures all DDP models start off at the same value. + _sync_module_states( + module=self.module, + process_group=self.process_group, + broadcast_bucket_size=self.broadcast_bucket_size, + src=0, + params_and_buffers_to_ignore=self.parameters_to_ignore, + broadcast_buffers=self.broadcast_buffers, + ) + # In debug mode, build a mapping of parameter index -> parameter. + param_to_name_mapping = self._build_debug_param_to_name_mapping(parameters) + + # Builds reducer. + self._ddp_init_helper( + parameters, + expect_sparse_gradient, + param_to_name_mapping, + static_graph, + ) + self._comm_hooks: List[Tuple[Callable, object]] = [] + + if self.mixed_precision is not None: + _setup_mixed_precision_params(self.mixed_precision, self.module) + _cast_buffers(self.mixed_precision, self.module) + # Stream used for async low precision copies. + self._mp_stream = torch.cuda.Stream() + self._submodule_to_event = defaultdict(deque) # type: ignore[var-annotated] + # Add forward pre-hook to root module to kick off copies to lower + # precision. + self.module.register_forward_pre_hook( + self._root_copy_hook, prepend=False, with_kwargs=True + ) + # Add forward pre hook to all submodules to wait for copy events + # before running computation. + for module in self.module.modules(): + module.register_forward_pre_hook( + self._module_wait_for_copy_hook, + prepend=False, + with_kwargs=True, + ) + # Set up callbacks in backward to upcast and use full precision + # params. TODO (rohan-varma): Make this compose with general + # comm hooks and apply_optimizer_in_backward. Importing inline to + # avoid circular import issue. + from torch.distributed.algorithms.ddp_comm_hooks.mixed_precision_hooks import ( + _AllreduceUpcastHookState, + _reducer_allreduce_and_upcast_hook, + ) + + upcast_hook_state = _AllreduceUpcastHookState( + ddp_weakref=weakref.ref(self), + upcast_stream=torch.cuda.Stream(), + ) + self.register_comm_hook( + upcast_hook_state, + _reducer_allreduce_and_upcast_hook, + ) + # Inform reducer of reduced precision param dtype for correctness + # of type checks between gradient and bucket. + self.reducer._set_mixed_precision_param_dtype( # type: ignore[attr-defined] + self.mixed_precision.param_dtype + ) + + self._has_rebuilt_buckets = False + + if static_graph: + self._set_static_graph() + + self._lazy_init_ran = False + + # Register the AccumulateGrad post hooks if optimize_ddp is + # True. The hooks will be deregistered if compiled_autograd is not + # enabled. + self._accum_grad_hooks: List[RemovableHandle] = [] + optimize_ddp = torch._dynamo.config._get_optimize_ddp_mode() + self._use_python_reducer = optimize_ddp in ( + "python_reducer", + "python_reducer_without_compiled_forward", + ) + self._force_to_disable_cpp_reducer = ( + optimize_ddp == "python_reducer_without_compiled_forward" + ) + if self._use_python_reducer: + self._register_accum_grad_hook() + + def _register_accum_grad_hook(self): + import torch.distributed._functional_collectives as fcol + + def compiled_accum_grad_hook( + param, + *, + param_index: int, + ): + if not self.require_backward_grad_sync: + return + + if param.grad is None: + return + + if self._comm_hooks: + for hook, state in self._comm_hooks: + hook(state, (param.grad, param)) + else: + gradient = param.grad / self.process_group.size() + gradient = fcol.all_reduce(gradient, "sum", self.process_group) + param.grad.copy_(gradient) + + for index, param in enumerate(self._module_parameters): + self._accum_grad_hooks.append( + param.register_post_accumulate_grad_hook( + functools.partial( + compiled_accum_grad_hook, + param_index=index, + ) + ) + ) + + def _delayed_all_reduce_hook(self, grad): + world_size = dist.get_world_size(self.process_group) + + self._delay_grad_buffer.div_(world_size) # type: ignore[union-attr] + _ = dist.all_reduce( + self._delay_grad_buffer, group=self.process_group, async_op=True + ) + return grad + + def _register_delay_all_reduce_hook( + self, + bucket_cap_mb, + param_to_hook_all_reduce, + device_ids, + ): + # 1. Create gradient buffer + device = torch.device("cpu") if device_ids is None else device_ids[0] + self._delay_grad_buffer = torch.zeros( + sum([p.numel() for p in self._delay_all_reduce_params]), + device=device, + ) + + # 2. Broadcast the parameters + detached_params = [p.detach() for p in self._delay_all_reduce_params] + dist._broadcast_coalesced(self.process_group, detached_params, bucket_cap_mb, 0) + + # 3. Hook all reduce to the specified parameter + param_to_hook_all_reduce.register_hook(self._delayed_all_reduce_hook) + + # 4. Build tensor views for gradients + offset = 0 + for param in self._delay_all_reduce_params: + grad_view = self._delay_grad_buffer[offset : (offset + param.numel())].view( + param.shape + ) + self._delay_grad_views.append(grad_view) + offset = offset + param.numel() + + # 5. Check whether the all reduce of all params requiring grad is delayed. + for module_name, module in self.module.named_modules(): + for param_name, param in module.named_parameters(recurse=False): + if param.requires_grad: + full_name = f"{module_name}.{param_name}" + if full_name not in self.parameters_to_ignore: + # There is at least a param whose all reduce will not be delayed. + # In this case, we should not set self._delay_all_reduce_all_params + # to True. + return + self._delay_all_reduce_all_params = True + + def _setup_in_backward_optimizers(self): + # Check if user has used apply_optim_in_backward to overlap optimizer + # step + DDP backward. Current constraints: + # 1. Only allreduce is supported at the moment, no custom communication. + # 2. For DDP-managed parameters that have their optimizer run in + # backward, their gradients are set to ``None``. If your use case + # requires DDP parameters grad not to be set to ``None`` after their + # in-backward optimizer runs, please ping + # https://github.com/pytorch/pytorch/issues/90052. + # NOTE: we use self._module_parameters instead of .parameters() since + # the former excludes ignored (non-DDP managed) parameters. + if any(hasattr(p, "_in_backward_optimizers") for p in self._module_parameters): + torch._C._log_api_usage_once("ddp.optimizer_in_backward") + # Remove hooks that apply_optim_in_backward had registered because + # DDP customizes how optimizer is overlapped with backward due to + # the allreduce. + param_to_handle_map = ( + dist.optim.apply_optimizer_in_backward.param_to_optim_hook_handle_map + ) + for p in self._module_parameters: + for handle in param_to_handle_map.get(p, []): + handle.remove() + + # Need a weakref to DDP instance to run all_reduce (from reducer) + # and get managed DDP parameters. + ddp_weakref = weakref.ref(self) + # Note: importing in function, otherwise this will cause a circular + # import. + from torch.distributed.algorithms.ddp_comm_hooks.optimizer_overlap_hooks import ( + _apply_optim_in_backward_hook, + ) + + self.register_comm_hook( + ddp_weakref, + _apply_optim_in_backward_hook( + gradient_is_bucket_view=self.gradient_as_bucket_view + ), + ) + + self.reducer._set_optimizer_in_backward() # type: ignore[attr-defined] + + def _fire_reducer_autograd_hook(self, idx, *unused): + """ + Fire the reducer's autograd hook to allreduce params in a Reducer bucket. + + Note that this is only used during mixed precision training as the + Reducer's hooks installed during construction time would not be called + as we're working in the low precision parameter setting. + """ + self.reducer._autograd_hook(idx) # type: ignore[attr-defined] + + def _root_copy_hook(self, *args: Any, **kwargs: Any) -> None: + """ + For DDP mixed precision, put low precision copies on separate stream and create events to wait for them. + + When training with DDP mixed precision, this root pre-forward hook kicks + off low precision copies on a separate stream and creates respective + events to wait for them. + """ + # Clear out previous iteration submodule to event. This is because we + # may have populated some events for modules that didn't end up being + # used. + self._submodule_to_event = defaultdict(deque) # type: ignore[var-annotated] + with torch.cuda.stream(self._mp_stream): + for submodule in self.module.modules(): + for param in submodule.parameters(recurse=False): + # Do not cast DDP ignored parameters. + if hasattr(param, "_ddp_ignored") and param._ddp_ignored: + continue + _alloc_storage(param._mp_param, param.size()) + # copy() implicitly casts to low precision + with torch.no_grad(): + param._mp_param.copy_(param.data) + # TODO: when zero_grad(set_to_none=False) or in grad + # accumulation case, accumulated grads can be in fp32 + # which can cause errors when running DDP backwards due + # to mismatched incoming and accumulated gradient types. + # So we manually cast the accumulated grad down for now, + # in the future we may shift to FSDP style gradient + # accumulation management where the accumulated gradient + # is saved and .grad field is set to None, bypassing + # this issue. + if param.grad is not None: + param.grad.data = param.grad.to( + self.mixed_precision.param_dtype # type: ignore[union-attr] + ) + param.data = param._mp_param + copy_event = torch.cuda.Event() + copy_event.record() + self._submodule_to_event[submodule].append(copy_event) + + def _module_wait_for_copy_hook( + self, + module, + *args: Any, + **kwargs: Any, + ) -> None: + """Before carrying out computation, wait on the appropriate event to ensure low precision copies have finished.""" + try: + event = self._submodule_to_event[module].popleft() + except IndexError: + # copy event has already been waited on + return + + event.wait(stream=torch.cuda.current_stream()) + for p in module.parameters(recurse=False): + # Don't register hooks if param does not require grad + if not p.requires_grad or (hasattr(p, "_ddp_ignored") and p._ddp_ignored): + continue + # We need to register autograd hook here instead of DDP's ctor + # since we're working with the low precision param. Register them + # via obtaining the gradient accumulator. + tmp = p.expand_as(p) + grad_acc = tmp.grad_fn.next_functions[0][0] + + hook = grad_acc.register_hook( + functools.partial(self._fire_reducer_autograd_hook, p._idx) + ) + p._ddp_mp_hook_state = (grad_acc, hook) + + def _log_and_throw(self, err_type, err_msg): + if self.logger is not None: + self.logger.set_error_and_log(f"{str(err_type)}: {err_msg}") + raise err_type(err_msg) + + def _ddp_init_helper( + self, + parameters, + expect_sparse_gradient, + param_to_name_mapping, + static_graph, + ): + """ + DDP init helper function to manage parameters, grad hooks, logging, and SyncBatchNorm. + + Initialization helper function that does the following: + (1) bucketing the parameters for reductions + (2) resetting the bucketing states + (3) registering the grad hooks + (4) Logging construction-time DDP logging data + (5) passing a handle of DDP to SyncBatchNorm Layer + """ + # Notice, the parameters order is not in the order in which they are used, + # especially in models with control flow. + # + # Alongside parameters are not presented in the real execution order, + # if a certain model happens to also + # 1) have other collectives comm ops in its backward graph. + # 2) have unused parameter in subset ranks of the whole world. + # bucketing could insert ALL-REDUCE comm op too early on the rank with unused parameter, + # matching up with other collectives comm ops on other ranks unexpectedly. + # + # In order to handle this corner case, when the parameters are not in the real execution order, + # we don't do bucketing, thus only one ALL-REDUCE is inserted after all the gradients + # of the whole graph are computed. + # + # Notice, here we only disable bucketing for the first iteration. + # After the first iteration, it's OK to rebuild buckets, + # because "bucket rebuild" bucketizes parameters based on its real execution order in backward graph. + + # Can remove this branching once #73732 is landed. + if static_graph is True or self.find_unused_parameters is False: + bucket_size_limits = [sys.maxsize] + else: + bucket_size_limits = [ + dist._DEFAULT_FIRST_BUCKET_BYTES, + self.bucket_bytes_cap, + ] + ( + bucket_indices, + per_bucket_size_limits, + ) = dist._compute_bucket_assignment_by_size( + parameters, + bucket_size_limits, + expect_sparse_gradient, + ) + + # Remember index for parameters if we are in mixed precision, as we + # need to pass in index to Reducer's autograd hook via python. + if self.mixed_precision is not None: + for i, p in enumerate(parameters): + p._idx = i + + # Note: reverse list of buckets because we want to approximate the + # order in which their gradients are produced, and assume they + # are used in the forward pass in the order they are defined. + self.reducer = dist.Reducer( + parameters, + list(reversed(bucket_indices)), + list(reversed(per_bucket_size_limits)), + self.process_group, + expect_sparse_gradient, + # The bucket size limit is specified in the constructor. + # Additionally, we allow for a single small bucket for parameters + # that are defined first, such that their gradients don't spill into + # a much larger bucket, adding unnecessary latency after gradient + # computation finishes. Experiments showed 1MB is a reasonable value. + self.bucket_bytes_cap, + self.find_unused_parameters, + self.gradient_as_bucket_view, + param_to_name_mapping, + # User can set dist._DEFAULT_FIRST_BUCKET_BYTES to tune DDP first + # bucket. + dist._DEFAULT_FIRST_BUCKET_BYTES, + ) + + self.logger = dist.Logger(self.reducer) + # Set as a weak reference to avoid reference cycle between + # logger and reducer. + self.reducer.set_logger(self.logger) + + has_sync_bn = False + for submodule in self.module.modules(): + if isinstance(submodule, torch.nn.SyncBatchNorm): + has_sync_bn = True + break + + # Set logging data that can be got during construction time. + self.logger.set_construction_data_and_log( + self.module.__class__.__name__, + [] if self.device_ids is None else self.device_ids, + -1 if self.output_device is None else self.output_device, + self.broadcast_buffers, + has_sync_bn, + static_graph, + ) + + # passing a handle to torch.nn.SyncBatchNorm layer + self._passing_sync_batchnorm_handle(self.module) + + def __getstate__(self): + self._check_default_group() + attrs = copy.copy(self.__dict__) + del attrs["process_group"] + del attrs["reducer"] + del attrs["logger"] + return attrs + + def __setstate__(self, state): + # If serializable, then the process group should be the default one + self.process_group = _get_default_group() + super().__setstate__(state) + self.__dict__.setdefault("require_forward_param_sync", True) + self.__dict__.setdefault("require_backward_grad_sync", True) + parameters, expect_sparse_gradient = self._build_params_for_reducer() + # In debug mode, build a mapping of parameter index -> parameter. + param_to_name_mapping = self._build_debug_param_to_name_mapping(parameters) + # Builds reducer. + self._ddp_init_helper( + parameters, + expect_sparse_gradient, + param_to_name_mapping, + self.static_graph, + ) + if self.static_graph: + self.reducer._set_static_graph() + assert self.logger is not None + self.logger._set_static_graph() + + def _build_params_for_reducer(self): + # Build tuple of (module, parameter) for all parameters that require grads. + modules_and_parameters = [ + (module, parameter) + for module_name, module in self.module.named_modules() + for parameter in [ + param + # Note that we access module.named_parameters instead of + # parameters(module). parameters(module) is only needed in the + # single-process multi device case, where it accesses replicated + # parameters through _former_parameters. + for param_name, param in module.named_parameters(recurse=False) + if param.requires_grad + and f"{module_name}.{param_name}" not in self.parameters_to_ignore + ] + ] + + # Deduplicate any parameters that might be shared across child modules. + memo = set() + modules_and_parameters = [ + # "p not in memo" is the deduplication check. + # "not memo.add(p)" is always True, and it's only there to cause "add(p)" if needed. + (m, p) + for m, p in modules_and_parameters + if p not in memo and not memo.add(p) # type: ignore[func-returns-value] + ] + + # Build list of parameters. + parameters = [parameter for _, parameter in modules_and_parameters] + + # Checks if a module will produce a sparse gradient. + def produces_sparse_gradient(module): + if isinstance(module, (torch.nn.Embedding, torch.nn.EmbeddingBag)): + return module.sparse + return False + + # Build list of booleans indicating whether or not to expect sparse + # gradients for the corresponding parameters. + expect_sparse_gradient = [ + produces_sparse_gradient(module) for module, _ in modules_and_parameters + ] + + self._assign_modules_buffers() + + return parameters, expect_sparse_gradient + + def _assign_modules_buffers(self): + """ + Assign self.module.named_buffers to self.modules_buffers. + + Assigns module buffers to self.modules_buffers which are then used to + broadcast across ranks when broadcast_buffers=True. Note that this + must be called every time buffers need to be synced because buffers can + be reassigned by user module, + see https://github.com/pytorch/pytorch/issues/63916. + """ + # Collect buffers for modules, filtering out buffers that should be ignored. + named_module_buffers = [ + (buffer, buffer_name) + for buffer_name, buffer in self.module.named_buffers() + if buffer_name not in self.parameters_to_ignore + ] + self.modules_buffers = [ + buffer for (buffer, buffer_name) in named_module_buffers + ] + # Dict[str, tensor] representing module buffers not ignored by DDP. + self.named_module_buffers = { + buffer_name: buffer for (buffer, buffer_name) in named_module_buffers + } + + def _build_debug_param_to_name_mapping(self, parameters): + param_to_param_index = {parameters[i]: i for i in range(len(parameters))} + param_set = set(parameters) + param_index_to_param_fqn = {} + for module_name, module in self.module.named_modules(): + for param_name, param in module.named_parameters(recurse=False): + fqn = f"{module_name}.{param_name}" + # Bypass ignored parameters since those are not reduced by DDP + # to begin with. + if fqn not in self.parameters_to_ignore and param.requires_grad: + if param not in param_set: + self._log_and_throw( + ValueError, + f"Param with name {fqn} found in module parameters, but not DDP parameters." + " This indicates a bug in DDP, please report an issue to PyTorch.", + ) + param_index = param_to_param_index[param] + param_index_to_param_fqn[param_index] = fqn + + # Ensure we covered all parameters + if len(param_set) != len(param_index_to_param_fqn): + self._log_and_throw( + ValueError, + ( + "Expected param to name mapping to cover all parameters, but" + f" got conflicting lengths: {len(param_set)} vs " + f"{len(param_index_to_param_fqn)}. This indicates a bug in DDP" + ", please report an issue to PyTorch." + ), + ) + + return param_index_to_param_fqn + + def _get_parameters(self, m, recurse=True): + """Return a generator of module parameters.""" + + def model_parameters(m): + ps = ( + m._former_parameters.values() + if hasattr(m, "_former_parameters") + else m.parameters(recurse=False) + ) + yield from ps + + for mod in m.modules() if recurse else [m]: + yield from model_parameters(mod) + + def _check_default_group(self): + pickle_not_supported = False + try: + if self.process_group != _get_default_group(): + pickle_not_supported = True + except RuntimeError: + pickle_not_supported = True + + if pickle_not_supported: + self._log_and_throw( + RuntimeError, + "DDP Pickling/Unpickling are only supported " + "when using DDP with the default process " + "group. That is, when you have called " + "init_process_group and have not passed " + "process_group argument to DDP constructor", + ) + + @contextmanager + def no_sync(self): + r""" + Context manager to disable gradient synchronizations across DDP processes. + + Within this context, gradients will be accumulated on module + variables, which will later be synchronized in the first + forward-backward pass exiting the context. + + Example:: + + >>> # xdoctest: +SKIP("undefined variables") + >>> ddp = torch.nn.parallel.DistributedDataParallel(model, pg) + >>> with ddp.no_sync(): + >>> for input in inputs: + >>> ddp(input).backward() # no synchronization, accumulate grads + >>> ddp(another_input).backward() # synchronize grads + + .. warning:: + The forward pass should be included inside the context manager, or + else gradients will still be synchronized. + """ + old_require_backward_grad_sync = self.require_backward_grad_sync + self.require_backward_grad_sync = False + try: + yield + finally: + self.require_backward_grad_sync = old_require_backward_grad_sync + + @classmethod + def _get_active_ddp_module(cls): + """`TorchDynamo` requires DDP's status and module for cooperative optimization.""" + return cls._active_ddp_module + + # note, this ctxmgr function is marked 'skip' in torchdynamo, so dynamo only kicks in + # for the 'module_to_run' underneath + # see torch._dynamo/eval_frame.py TorchPatcher.patch for more details + @contextmanager + @torch._disable_dynamo(recursive=False) + def _inside_ddp_forward(self): + DistributedDataParallel._active_ddp_module = self + try: + yield + finally: + DistributedDataParallel._active_ddp_module = None + + def _run_ddp_forward(self, *inputs, **kwargs): + if self._use_python_reducer: + return self.module(*inputs, **kwargs) # type: ignore[index] + else: + with self._inside_ddp_forward(): + return self.module(*inputs, **kwargs) # type: ignore[index] + + def _clear_grad_buffer(self): + # Making param.grad points to the grad buffers before backward is based on the + # assumption that the grad accumulation is done in place in autograd engine, + # for some edge cases, if the grad accumulation in autograd engine is not in + # place, then the param.grad and grad buffers are detached. + if self._delay_grad_buffer is not None: + # We batch zero_grad for all params by resetting the whole grad + # buffer when the grad of all params is set to None. + all_param_grad_none = all( + param.grad is None for param in self._delay_all_reduce_params + ) + + for index, param in enumerate(self._delay_all_reduce_params): + if param.grad is None: + param.grad = self._delay_grad_views[index] + if not all_param_grad_none: + param.grad.zero_() + + if all_param_grad_none: + self._delay_grad_buffer.zero_() + + def _lazy_init(self): + # Initialization for DDP that occurs after construction, but lazily + # before the first forward pass. + self._setup_in_backward_optimizers() + self._lazy_init_ran = True + + def _should_disable_cpp_reducer(self) -> bool: + return self._use_python_reducer and ( + torch._utils.is_compiling() or self._force_to_disable_cpp_reducer + ) + + def _pre_forward(self, *inputs, **kwargs): + if self._should_disable_cpp_reducer(): + return inputs, kwargs + + # Disable the python reducer if compiled_autograd is not enabled. + if self._accum_grad_hooks: + for index, h in enumerate(self._accum_grad_hooks): + h.remove() + self._accum_grad_hooks.clear() + + if not self._lazy_init_ran and not torch._utils.is_compiling(): + self._lazy_init() + + if self._delay_all_reduce_all_params: + return inputs, kwargs + + if torch.is_grad_enabled() and self.require_backward_grad_sync: + assert self.logger is not None + self.logger.set_runtime_stats_and_log() + self.reducer.prepare_for_forward() + + # Notify the join context that this process has not joined, if + # needed + work = Join.notify_join_context(self) + if work: + self.reducer._set_forward_pass_work_handle( + work, self._divide_by_initial_world_size # type: ignore[arg-type] + ) + + # Calling _rebuild_buckets before forward computation, + # It may allocate new buckets before deallocating old buckets + # inside _rebuild_buckets. To save peak memory usage, + # call _rebuild_buckets before the peak memory usage increases + # during forward computation. + # This should be called only once during whole training period. + if torch.is_grad_enabled() and self.reducer._rebuild_buckets(): + logger.info("Reducer buckets have been rebuilt in this iteration.") + self._has_rebuilt_buckets = True + + # sync params according to location (before/after forward) user + # specified as part of hook, if hook was specified. + if self._check_sync_bufs_pre_fwd(): + self._sync_buffers() + + if self._join_config.enable: + # Notify joined ranks whether they should sync in backwards pass or not. + self._check_global_requires_backward_grad_sync(is_joined_rank=False) + + if self.device_ids: + moved_inputs, moved_kwargs = _to_kwargs( + inputs, + kwargs, + torch.device(self.device_type, self.device_ids[0]), + self.use_side_stream_for_tensor_copies, + ) + args, kwargs = moved_inputs[0], moved_kwargs[0] + # Cast inputs to reduced precision if needed. + if self.mixed_precision is not None: + args, kwargs = _cast_forward_inputs( + self.mixed_precision.param_dtype, + *args, + **kwargs, + ) + return args, kwargs + else: + # Cast inputs to reduced precision if needed. + # TODO (rohan-varma) test this codepath. + if self.mixed_precision is not None: + inputs, kwargs = _cast_forward_inputs( + self.mixed_precision.param_dtype, + *inputs, + **kwargs, + ) + return inputs, kwargs + + def _post_forward(self, output): + if self._should_disable_cpp_reducer(): + return output + + if self._delay_all_reduce_all_params: + self._clear_grad_buffer() + return output + + # sync params according to location (before/after forward) user + # specified as part of hook, if hook was specified. + if self._check_sync_bufs_post_fwd(): + self._sync_buffers() + + if torch.is_grad_enabled() and self.require_backward_grad_sync: + self.require_forward_param_sync = True + # We'll return the output object verbatim since it is a freeform + # object. We need to find any tensors in this object, though, + # because we need to figure out which parameters were used during + # this forward pass, to ensure we short circuit reduction for any + # unused parameters. Only if `find_unused_parameters` is set. + if self.find_unused_parameters and not self.static_graph: + # Do not need to populate this for static graph. + self.reducer.prepare_for_backward(list(_find_tensors(output))) + else: + self.reducer.prepare_for_backward([]) + else: + self.require_forward_param_sync = False + + # TODO: DDPSink is currently enabled for unused parameter detection and + # static graph training for first iteration. + if (self.find_unused_parameters and not self.static_graph) or ( + self.static_graph and not self._static_graph_delay_allreduce_enqueued + ): + ( + output_tensor_list, + treespec, + output_is_rref, + ) = _tree_flatten_with_rref(output) + output_placeholders = [None for _ in range(len(output_tensor_list))] + # Do not touch tensors that have no grad_fn, which can cause issues + # such as https://github.com/pytorch/pytorch/issues/60733 + for i, output in enumerate(output_tensor_list): + if torch.is_tensor(output) and output.grad_fn is None: + output_placeholders[i] = output + + # When find_unused_parameters=True, makes tensors which require grad + # run through the DDPSink backward pass. When not all outputs are + # used in loss, this makes those corresponding tensors receive + # undefined gradient which the reducer then handles to ensure + # param.grad field is not touched and we don't error out. + passthrough_tensor_list = _DDPSink.apply( + weakref.ref(self), + *output_tensor_list, + ) + for i in range(len(output_placeholders)): + if output_placeholders[i] is None: + output_placeholders[i] = passthrough_tensor_list[i] + + # Reconstruct output data structure. + output = _tree_unflatten_with_rref( + output_placeholders, treespec, output_is_rref + ) + + # At the end of the forward pass, reset the grad buffer and grad views + self._clear_grad_buffer() + return output + + def forward(self, *inputs, **kwargs): + with torch.autograd.profiler.record_function("DistributedDataParallel.forward"): + inputs, kwargs = self._pre_forward(*inputs, **kwargs) + output = ( + self.module.forward(*inputs, **kwargs) + if self._delay_all_reduce_all_params + else self._run_ddp_forward(*inputs, **kwargs) + ) + return self._post_forward(output) + + def scatter(self, inputs, kwargs, device_ids): + return scatter_kwargs(inputs, kwargs, device_ids, dim=self.dim) + + def to_kwargs(self, inputs, kwargs, device_id): + # Kept for BC + return _to_kwargs( + inputs, + kwargs, + torch.device(self.device_type, device_id), + self.use_side_stream_for_tensor_copies, + ) + + def gather(self, outputs, output_device): + return gather(outputs, output_device, dim=self.dim) + + def train(self, mode=True): + super().train(mode) + return self + + # When running in join mode, schedules an allreduce to notify joined ranks + # of whether backwards pass synchronization will run this iteration or not. + def _check_global_requires_backward_grad_sync(self, is_joined_rank): + if not is_joined_rank and self.require_backward_grad_sync: + requires_sync_tensor = torch.ones(1, device=self.device) + else: + requires_sync_tensor = torch.zeros(1, device=self.device) + + work = dist.all_reduce( + requires_sync_tensor, group=self.process_group, async_op=True + ) + + # (kwen2501) This if condition is a plain translation of previous + # behavior, i.e. in the `is_joined_rank=False` case, `work.wait()` + # is not called and it doesn't care about the result. I am guessing + # that it just wants to fire a matching all-reduce and does not want + # the main stream to wait. + if is_joined_rank: + work.wait() + should_sync_backwards = requires_sync_tensor.item() != 0 + return should_sync_backwards + else: + return None # Return value is not/should not be used. + + # When running in join mode, checks and performs sync of module buffers if + # the models have buffers that should be synchronized in the forward pass. + def _check_and_sync_module_buffers(self): + if self._check_sync_bufs_pre_fwd(): + authoritative_rank = self._find_common_rank(self._distributed_rank, False) + self._sync_module_buffers(authoritative_rank) + + # When running in join model, agrees upon a common rank and broadcast model + # parameters to all other ranks. + def _sync_final_model(self, is_last_joiner): + # Agree upon the process that will be the authoritative model copy. + # The current rank is a candidate for being the authoritative copy if + # is_last_joiner=True. We break ties via picking the larger rank. + self._authoritative_rank = self._find_common_rank( + self._distributed_rank, is_last_joiner + ) + _sync_module_states( + module=self.module, + process_group=self.process_group, + broadcast_bucket_size=self.broadcast_bucket_size, + src=self._authoritative_rank, + params_and_buffers_to_ignore=self.parameters_to_ignore, + broadcast_buffers=self.broadcast_buffers, + ) + + # Schedule comm ops to match those scheduled in the reducer's backward + # pass. + def _match_all_reduce_for_bwd_pass(self): + comm_work = [] + # Schedule comm in the same order as Reducer schedules them, i.e. + # the order of the buckets. Retrieving the bucket order from the reducer + # ensures that we keep the same order in join mode, such as when bucket + # order is rebuilt dynamically. + + # Returns grad_buckets in order, but real tensors are substituted with + # zero tensors of the same shape. + grad_buckets = self.reducer._get_zeros_like_grad_buckets() + for grad_bucket in grad_buckets: + # Joined processes contribute zero gradient. In the case that + # divide_by_initial_world_size=True, we divide grads by the static + # world size, if not, the dividing factor is reduced by the number + # of joined processes. + work = self.reducer._run_comm_hook(grad_bucket) + comm_work.append(work) + for work in comm_work: + work.wait() + + # Allreduces the used parameter mapping across ranks. + def _match_unused_params_allreduce(self): + locally_used_param_map = self.reducer._get_local_used_map() + self.process_group.allreduce(locally_used_param_map) + + def join( + self, + divide_by_initial_world_size: bool = True, + enable: bool = True, + throw_on_early_termination: bool = False, + ): + r""" + Context manager for training with uneven inputs across processes in DDP. + + This context manager will keep track of already-joined DDP processes, + and "shadow" the forward and backward passes by inserting collective + communication operations to match with the ones created by non-joined + DDP processes. This will ensure each collective call has a corresponding + call by already-joined DDP processes, preventing hangs or errors that + would otherwise happen when training with uneven inputs across + processes. Alternatively, if the flag ``throw_on_early_termination`` is + specified to be ``True``, all trainers will throw an error once one rank + runs out of inputs, allowing these errors to be caught and handled + according to application logic. + + Once all DDP processes have joined, the context manager will broadcast + the model corresponding to the last joined process to all processes to + ensure the model is the same across all processes + (which is guaranteed by DDP). + + To use this to enable training with uneven inputs across processes, + simply wrap this context manager around your training loop. No further + modifications to the model or data loading is required. + + .. warning:: + If the model or training loop this context manager is wrapped around + has additional distributed collective operations, such as + ``SyncBatchNorm`` in the model's forward pass, then the flag + ``throw_on_early_termination`` must be enabled. This is because this + context manager is not aware of non-DDP collective communication. + This flag will cause all ranks to throw when any one rank + exhausts inputs, allowing these errors to be caught and recovered + from across all ranks. + + Args: + divide_by_initial_world_size (bool): If ``True``, will divide + gradients by the initial ``world_size`` DDP training was launched + with. If ``False``, will compute the effective world size + (number of ranks that have not depleted their inputs yet) and + divide gradients by that during allreduce. Set + ``divide_by_initial_world_size=True`` to ensure every input + sample including the uneven inputs have equal weight in terms of + how much they contribute to the global gradient. This is + achieved by always dividing the gradient by the initial + ``world_size`` even when we encounter uneven inputs. If you set + this to ``False``, we divide the gradient by the remaining + number of nodes. This ensures parity with training on a smaller + ``world_size`` although it also means the uneven inputs would + contribute more towards the global gradient. Typically, you + would want to set this to ``True`` for cases where the last few + inputs of your training job are uneven. In extreme cases, where + there is a large discrepancy in the number of inputs, setting + this to ``False`` might provide better results. + enable (bool): Whether to enable uneven input detection or not. Pass + in ``enable=False`` to disable in cases where you know that + inputs are even across participating processes. Default is + ``True``. + throw_on_early_termination (bool): Whether to throw an error + or continue training when at least one rank has exhausted + inputs. If ``True``, will throw upon the first rank reaching end + of data. If ``False``, will continue training with a smaller + effective world size until all ranks are joined. Note that if + this flag is specified, then the flag + ``divide_by_initial_world_size`` would be ignored. Default + is ``False``. + + + Example:: + + >>> # xdoctest: +SKIP("Distributed") + >>> import torch + >>> import torch.distributed as dist + >>> import os + >>> import torch.multiprocessing as mp + >>> import torch.nn as nn + >>> # On each spawned worker + >>> def worker(rank): + >>> dist.init_process_group("nccl", rank=rank, world_size=2) + >>> torch.cuda.set_device(rank) + >>> model = nn.Linear(1, 1, bias=False).to(rank) + >>> model = torch.nn.parallel.DistributedDataParallel( + >>> model, device_ids=[rank], output_device=rank + >>> ) + >>> # Rank 1 gets one more input than rank 0. + >>> inputs = [torch.tensor([1]).float() for _ in range(10 + rank)] + >>> with model.join(): + >>> for _ in range(5): + >>> for inp in inputs: + >>> loss = model(inp).sum() + >>> loss.backward() + >>> # Without the join() API, the below synchronization will hang + >>> # blocking for rank 1's allreduce to complete. + >>> torch.cuda.synchronize(device=rank) + """ + return Join( + [self], + enable, + throw_on_early_termination, + divide_by_initial_world_size=divide_by_initial_world_size, + ) + + def join_hook( + self, + **kwargs, + ): + r""" + DDP join hook enables training on uneven inputs by mirroring communications in forward and backward passes. + + Arguments: + kwargs (dict): a :class:`dict` containing any keyword arguments + to modify the behavior of the join hook at run time; all + :class:`Joinable` instances sharing the same join context + manager are forwarded the same value for ``kwargs``. + + The hook supports the following keyword arguments: + divide_by_initial_world_size (bool, optional): + If ``True``, then gradients are divided by the initial world + size that DDP was launched with. + If ``False``, then gradients are divided by the effective world + size (i.e. the number of non-joined processes), meaning that + the uneven inputs contribute more toward the global gradient. + Typically, this should be set to ``True`` if the degree of + unevenness is small but can be set to ``False`` in extreme + cases for possibly better results. + Default is ``True``. + """ + divide_by_initial_world_size = kwargs.get("divide_by_initial_world_size", True) + return _DDPJoinHook( + self, divide_by_initial_world_size=divide_by_initial_world_size + ) + + @property + def join_device(self): + return self.device + + @property + def join_process_group(self): + return self.process_group + + def _register_buffer_comm_hook( + self, + state, + hook: Callable, + comm_hook_location=_BufferCommHookLocation.POST_FORWARD, + ): + r""" + Allow custom registration of hooks that define how buffer are synchronized across ranks. + + The hook takes in an optional state and is passed in a Dict[str, Tensor] + corresponding to buffer names and the buffers, and can run arbitrary reductions + on buffers as opposed to DDP's default broadcast from rank 0. This is useful for + example if a counter needs to be summed or averaged across ranks every iteration. + + Args: + state (Any): Optional state that is passed to the hook. + hook (Callable): Callable with the following signature: + ``hook(state: object, bucket: dist.GradBucket) -> torch.futures.Future[torch.Tensor]`` + comm_hook_location (_BufferCommHookLocation): Enum value indicating + where to run the hook. + _BufferCommHookLocation.PRE_FORWARD means that the + hook will run _before_ the forward pass, and + _BufferCommHookLocation.POST_FORWARD means that the + hook will run _after_ the forward pass. + + NOTE: To maximize performance, users can return a + List[torch.futures.Future] from their hook, and DDP will + install and await these hooks appropriately at the end of + the backward pass. This will ensure all buffers are + synchronized by the end of the backward pass. If this + setting is used, it is recommended to pass + comm_hook_location=_BufferCommHookLocation.POST_FORWARD, + which will trigger the hook after the forward pass. + If _BufferCommHookLocation.PRE_FORWARD is used, users must + ensure appropriate synchronization when manipulating GPU + buffers in the forward pass. + """ + assert callable(hook) + self.buffer_hook = _BufferCommHook( + buffer_comm_hook=hook, + buffer_comm_hook_state=state, + buffer_comm_hook_location=comm_hook_location, + ) + + def register_comm_hook(self, state: object, hook: Callable): + r""" + Register communication hook for user-defined DDP aggregation of gradients across multiple workers. + + This hook would be very useful for researchers to try out new ideas. For + example, this hook can be used to implement several algorithms like GossipGrad + and gradient compression which involve different communication strategies for + parameter syncs while running Distributed DataParallel training. + + Args: + state (object): Passed to the hook to maintain any state information during the training process. + Examples include error feedback in gradient compression, + peers to communicate with next in GossipGrad, etc. + + It is locally stored by each worker + and shared by all the gradient tensors on the worker. + hook (Callable): Callable with the following signature: + ``hook(state: object, bucket: dist.GradBucket) -> torch.futures.Future[torch.Tensor]``: + + This function is called once the bucket is ready. The + hook can perform whatever processing is needed and return + a Future indicating completion of any async work (ex: allreduce). + If the hook doesn't perform any communication, it still + must return a completed Future. The Future should hold the + new value of grad bucket's tensors. Once a bucket is ready, + c10d reducer would call this hook and use the tensors returned + by the Future and copy grads to individual parameters. + Note that the future's return type must be a single tensor. + + We also provide an API called ``get_future`` to retrieve a + Future associated with the completion of ``c10d.ProcessGroup.Work``. + ``get_future`` is currently supported for NCCL and also supported for most + operations on GLOO and MPI, except for peer to peer operations (send/recv). + + .. warning :: + Grad bucket's tensors will not be predivided by world_size. User is responsible + to divide by the world_size in case of operations like allreduce. + + .. warning :: + DDP communication hook can only be registered once and should be registered + before calling backward. + + .. warning :: + The Future object that hook returns should contain a single tensor + that has the same shape with the tensors inside grad bucket. + + .. warning :: + ``get_future`` API supports NCCL, and partially GLOO and MPI backends (no support + for peer-to-peer operations like send/recv) and will return a ``torch.futures.Future``. + + Example:: + Below is an example of a noop hook that returns the same tensor. + + >>> # xdoctest: +SKIP('undefined name') + >>> def noop(state: object, bucket: dist.GradBucket) -> torch.futures.Future[torch.Tensor]: + >>> fut = torch.futures.Future() + >>> fut.set_result(bucket.buffer()) + >>> return fut + >>> ddp.register_comm_hook(state=None, hook=noop) + + Example:: + Below is an example of a Parallel SGD algorithm where gradients are encoded before + allreduce, and then decoded after allreduce. + + >>> # xdoctest: +SKIP('undefined name') + >>> def encode_and_decode(state: object, bucket: dist.GradBucket) -> torch.futures.Future[torch.Tensor]: + >>> encoded_tensor = encode(bucket.buffer()) # encode gradients + >>> fut = torch.distributed.all_reduce(encoded_tensor).get_future() + >>> # Define the then callback to decode. + >>> def decode(fut): + >>> decoded_tensor = decode(fut.value()[0]) # decode gradients + >>> return decoded_tensor + >>> return fut.then(decode) + >>> ddp.register_comm_hook(state=None, hook=encode_and_decode) + """ + self._check_comm_hook(hook) + if hook.__name__ in ["bf16_compress_hook", "fp16_compress_hook"]: + # If we pass None, then the hook will try to get the world size + # by calling `dist.group.WORLD.size()`, which causes compilation + # errors. So we pre-decode the process group and pass it to the + # hook. + if state is None: + state = dist.group.WORLD + assert self.logger is not None + self.logger._set_comm_hook_name(hook.__qualname__) + self._comm_hooks.append((hook, state)) + dist._register_comm_hook(self.reducer, state, hook) + + def _register_builtin_comm_hook(self, comm_hook_type): + r""" + Register a built-in communication hook that specifies how DDP aggregates gradients across multiple workers. + + The built-in hooks aim to provide efficient C++ implementations for certain hooks, + which might not be as efficient if implemented in Python using a Python communication hook. + + Args: + comm_hook_type (dist.BuiltinCommHookType): type of communication hook, such as ALLREDUCE, FP16_COMPRESS, etc. + + .. warning :: + DDP communication hook can only be registered once and should be registered + before calling backward. + + Example:: + Below is an example of a FP16 compression where gradients are + compressed into 16-bit floating-point numbers before allreduce, and + then decompressed after allreduce. + + >>> # xdoctest: +SKIP('undefined name') + >>> ddp._register_builtin_comm_hook(dist.BuiltinCommHookType.FP16_COMPRESS) + + """ + assert self.logger is not None + self.logger._set_comm_hook_name(str(comm_hook_type)) + dist._register_builtin_comm_hook(self.reducer, comm_hook_type) + + def _register_fused_optim(self, optim: Type, *args, optim_params=None, **kwargs): + r""" + Register an optimizer in DDP to optimize parameter immediately after its gradient reduction. + + Registers an optimizer with DDP such that the optimization for a + parameter will run immediately when that parameter's gradient is + finished with reduction, instead of waiting for all parameters' + gradients to finish reduction. This can result in a training speedup + depending on your workload since the optimizer can run while gradient + reduction for other parameters are still ongoing. In addition, this has + the potential to reduce peak memory consumption during training, as it + only needs to load the per-parameter optimizer states of a single + parameter at a time, instead of loading all per-parameter optimizer + states at once. + + Args: + optim (Type): a ``torch.optim.Optimizer`` class to be registered + as a fused optimizer. + *args (Sequence[Any]): Arguments to forward to `optim`. + optim_params (Optional[Iterable[torch.Tensor]]): Set of parameters + to optimize, similar to `params` argument of traditional `torch.optim` + Optimizers. If this is omitted, all DDP model parameters will be + optimized. + **kwargs: (Dict[str, Any]): Keyword arguments to forward to `optim`. + + .. warning :: + _register_fused_optim should only be called once on a DDP instance, + and registering multiple fused optimizers for the same DDP model + is not currently supported. Please ping + https://github.com/pytorch/pytorch/issues/71595 if this is necessary + for your use case. + + .. warning :: + _register_fused_optim and register_comm_hook currently do not + compose together, meaning that custom DDP communication hooks are + not supported with overlapped optimizers. Please ping + https://github.com/pytorch/pytorch/issues/71595 if this is necessary + for your use case. + + .. warning :: + Gradient accumulation and DDP `no_sync` are currently not supported + with overlapped optimizer. Please ping + https://github.com/pytorch/pytorch/issues/71595 if this is necessary + for your use case. + + Example:: + + >>> # xdoctest: +SKIP("No rendezvous handler") + >>> torch.distributed.init_process_group(backend='nccl', world_size=4, init_method='...') + >>> net = torch.nn.parallel.DistributedDataParallel(model, pg) + >>> lr = 1e-2 + >>> betas = (0.9, 0.99) + >>> eps = 1e-6 + >>> net._register_fused_optim(torch.optim.Adam, lr, betas=betas, eps=eps) + >>> # Example with subset of parameters + >>> params_to_opt = [list(net.parameters())[0]] + >>> net._register_fused_optim( + ... torch.optim.Adam, lr, optim_params=params_to_opt, betas=betas, eps=eps + ... ) + """ + # Note: importing in function, otherwise this will cause a circular + # import as optimizer_overlap module needs to import DistributedDataParallel. + from torch.distributed.algorithms._optimizer_overlap import _as_overlapped_optim + + overlapped_optim = _as_overlapped_optim(optim, optim_params, *args, **kwargs) + try: + overlapped_optim.register_ddp(self) + except NotImplementedError as e: + raise RuntimeError( + f"{optim} does not support overlapped DDP. Please file an issue to PyTorch or the respective owner of {optim}." + ) from e + + def _distributed_broadcast_coalesced( + self, tensors, buffer_size, authoritative_rank=0 + ): + dist._broadcast_coalesced( + self.process_group, tensors, buffer_size, authoritative_rank + ) + + def _check_sync_bufs_post_fwd(self): + return ( + self.will_sync_module_buffers() + and hasattr(self, "buffer_hook") + and self.buffer_hook.buffer_comm_hook_location + == _BufferCommHookLocation.POST_FORWARD + ) + + def _check_sync_bufs_pre_fwd(self): + return self.will_sync_module_buffers() and ( + not hasattr(self, "buffer_hook") + or self.buffer_hook.buffer_comm_hook_location + == _BufferCommHookLocation.PRE_FORWARD + ) + + def will_sync_module_buffers(self): + return ( + self.require_forward_param_sync + and self.broadcast_buffers + and len(self.modules_buffers) > 0 + ) + + def _find_common_rank(self, input_rank, rank_cond): + # -1 indicates that this rank is not under consideration to be the + # common_rank + rank_to_use = torch.tensor( + [input_rank if rank_cond else -1], + device=self.device, + ) + dist.all_reduce(rank_to_use, op=ReduceOp.MAX, group=self.process_group) + if rank_to_use.item() == -1: + self._log_and_throw( + ValueError, + "BUG! Expected rank_cond to be true for at least one process." + " This indicates a bug in PyTorch, please report an issue.", + ) + return rank_to_use.item() + + def _sync_buffers(self): + with torch.no_grad(): + # module buffer sync + # Synchronize buffers across processes. + # If we are running DDP with the join manager, we have to agree + # upon a rank to sync module buffers from, since rank 0 may + # already have been joined and have stale module buffers. + if self._join_config.enable: + authoritative_rank = self._find_common_rank( + self._distributed_rank, True + ) + else: + # The process with rank 0 is considered the authoritative copy. + authoritative_rank = 0 + # Update self.modules_buffers incase any buffers were + # reassigned. + self._assign_modules_buffers() + self._sync_module_buffers(authoritative_rank) + + def _sync_module_buffers(self, authoritative_rank): + if not hasattr(self, "buffer_hook"): + self._default_broadcast_coalesced(authoritative_rank=authoritative_rank) + else: + hook = self.buffer_hook.buffer_comm_hook + state = self.buffer_hook.buffer_comm_hook_state + futs = hook(state, self.named_module_buffers) + if futs is not None: + self.reducer._install_post_backward_futures(futs) + + def _default_broadcast_coalesced( + self, bufs=None, bucket_size=None, authoritative_rank=0 + ): + """ + Broadcasts buffers from rank 0 to rest of workers. + + If bufs, bucket_size are None, default values self.modules_buffers + and self.broadcast_bucket_size are used instead. + """ + if bufs is None: + bufs = self.modules_buffers + if bucket_size is None: + bucket_size = self.broadcast_bucket_size + + self._distributed_broadcast_coalesced(bufs, bucket_size, authoritative_rank) + + def _passing_sync_batchnorm_handle(self, module): + for layer in module.modules(): + if isinstance(layer, torch.nn.modules.SyncBatchNorm): + if self.device_type == "cpu": + self._log_and_throw( + ValueError, + "SyncBatchNorm layers only work with GPU modules", + ) + + def _check_comm_hook(self, hook): + if not callable(hook): + self._log_and_throw(TypeError, "Communication hook must be callable.") + + sig = inspect.signature(hook) + if ( + sig.parameters["bucket"].annotation != inspect._empty + and sig.parameters["bucket"].annotation != dist.GradBucket + ): + self._log_and_throw( + ValueError, + "Communication hook: bucket annotation should be dist.GradBucket.", + ) + + if ( + sig.return_annotation != inspect._empty + and sig.return_annotation != torch.futures.Future[torch.Tensor] + ): + self._log_and_throw( + ValueError, + "Communication hook: return annotation should be torch.futures.Future[torch.Tensor].", + ) + + if hook.__name__ in [ + "bf16_compress_hook", + "bf16_compress_wrapper_hook", + ] and ( + (torch.version.cuda is None and torch.version.hip is None) + or ( + torch.version.cuda is not None + and int(torch.version.cuda.split(".")[0]) < 11 + ) + or not dist.is_available() + or not dist.is_nccl_available() + or torch.cuda.nccl.version() < (2, 10) + ): + self._log_and_throw( + TypeError, + "BF16 all reduce communication hook required CUDA 11+ and NCCL 2.10+.", + ) + + @property + def _distributed_rank(self): + return dist.get_rank(self.process_group) + + @staticmethod + def _get_data_parallel_params(module, named_params=False): + """Return a generator of parameters managed by a given DDP unit.""" + for param in ( + module.parameters() if not named_params else module.named_parameters() + ): + if not hasattr(param, "_ddp_ignored"): + yield param + + @staticmethod + def _set_params_and_buffers_to_ignore_for_model( + module, params_and_buffers_to_ignore + ): + """ + Set parameters and buffers to be ignored by DDP. + + Expected format for parameters is the fully qualified name: {module_name}.{param_name}, and + similarly, {module_name}.{buffer_name} for buffers. For example: + params_to_ignore = [] + # NB: model here is vanilla PyTorch module, not yet wrapped with DDP. + for module_name, module in model.named_modules(): + for param_name, param in module.named_parameters(recurse=False): + if should_ignore(param): + # Create expected format + fqn = f"{module_name}.{param_name}" + params_to_ignore.append(fqn) + torch.nn.parallel.DistributedDataParallel._set_params_and_buffers_to_ignore_for_model( + model, + params_to_ignore + ) + """ + # This is a workaround to set parameters and buffers DDP should ignore + # during synchronization. It will be removed when the API is finalized + # as part of addressing https://github.com/pytorch/pytorch/issues/43690. + module._ddp_params_and_buffers_to_ignore = params_and_buffers_to_ignore + for name, param in module.named_parameters(): + if name in params_and_buffers_to_ignore: + param._ddp_ignored = True + for name, buffer in module.named_buffers(): + if name in params_and_buffers_to_ignore: + buffer._ddp_ignored = True + + def _get_ddp_logging_data(self): + r""" + Return a dictionary of logging data for debugging and analysis. + + This interface can be called after DistributedDataParallel() is + constructed. It returns a dictionary of logging data. It could help + for debugging and analysis. The logging data includes DistributedDataParallel + constructor input parameters, some internal states of DistributedDataParallel + and performance metrics. Simply print the dictionary and see what + these metrics are. + This is a prototype interface and subject to change in the future. + """ + assert self.logger is not None + ddp_logging_data = self.logger._get_ddp_logging_data() + return {**ddp_logging_data.strs_map, **ddp_logging_data.ints_map} + + def _set_ddp_runtime_logging_sample_rate(self, sample_rate): + r""" + Set sample_rate of collecting runtime stats. + + This interface allows users to set sample_rate of collecting + runtime stats. The runtime stats will be recorded for the + first 10 iterations, after 10 iterations runtime stats will be + recorded once every "sample_rate" training iterations. In + default, runtime stats are recorded for the first 10 iterations, + after 10 iterations runtime stats are recorded once every + "kDDPRuntimeLoggingSampleRate=100" training iterations. + This is a prototype interface and subject to change in the future. + """ + if sample_rate < 1: + self._log_and_throw( + ValueError, + "DDP runtime logging sample rate should be equal or greater than 1", + ) + self.reducer._set_ddp_runtime_logging_sample_rate(sample_rate) + + def _set_static_graph(self): + """ + Set static graph for DDP. + + It is recommended to set static graph in the DDP constructor, which will + call this private API internally. + """ + # If self.static_graph has been set, no need to set it again + if self.static_graph: + warnings.warn( + "You've set static_graph to be True, no need to set it again." + ) + return + self.static_graph = True + self._static_graph_delay_allreduce_enqueued = False + self.reducer._set_static_graph() + assert self.logger is not None + self.logger._set_static_graph() + if self.find_unused_parameters: + warnings.warn( + "You passed find_unused_parameters=true to DistributedDataParallel, " + "`_set_static_graph` will detect unused parameters automatically, so " + "you do not need to set find_unused_parameters=true, just be sure these " + "unused parameters will not change during training loop while calling " + "`_set_static_graph`." + ) + + def _remove_autograd_hooks(self): + """Remove autograd hooks registered by the reducer on the model parameters.""" + self.reducer._remove_autograd_hooks() + + def _check_reducer_finalized(self): + """ + Check if the reducer has processed all buckets and finalized the backward appropriately. + + It is useful to call this method after calling .backward() in your training loop + in order to avoid subsequent hard to debug errors down the road due to the + reducer not finalizing backward. + """ + self.reducer._check_reducer_finalized() + + def _set_sparse_metadata(self, global_unique_ids): + self.reducer._set_sparse_metadata(global_unique_ids) + + def _update_process_group(self, new_process_group): + """ + Dynamically updates the process group for DDP so that we can shrink/expand DDP + world size without having to reinitialize DDP. + + NOTE: If you are using custom communications hooks via, register_comm_hook, + you need to update the process groups for those hooks separately. + """ + # Force a rebuild of buckets for a new process group. This ensures all ranks + # are synchronized in terms of when they will rebuild buckets and also + # re-evaluates previous assumptions of buckets given the world size might have + # changed. + self._has_rebuilt_buckets = False + self.reducer._reset_state() + + if not _rank_not_in_group(new_process_group): + self.process_group = new_process_group + self.reducer._update_process_group(new_process_group) diff --git a/shared/package-files/00/00ab61d75f635c60e1766c4d11000f19df89b27f39ccafcf9ba9cde119042c7e/blob b/shared/package-files/00/00ab61d75f635c60e1766c4d11000f19df89b27f39ccafcf9ba9cde119042c7e/blob new file mode 100644 index 0000000000000000000000000000000000000000..805558d8427bff383ef6f595d27e927f9c02bb6b --- /dev/null +++ b/shared/package-files/00/00ab61d75f635c60e1766c4d11000f19df89b27f39ccafcf9ba9cde119042c7e/blob @@ -0,0 +1,50 @@ +#pragma once + +// @generated by torchgen/gen.py from Operator.h + +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { +namespace _ops { + + +struct TORCH_API rad2deg { + 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::rad2deg") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "rad2deg(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 rad2deg_ { + using schema = at::Tensor & (at::Tensor &); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::rad2deg_") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "rad2deg_(Tensor(a!) self) -> Tensor(a!)") + static at::Tensor & call(at::Tensor & self); + static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, at::Tensor & self); +}; + +struct TORCH_API rad2deg_out { + using schema = at::Tensor & (const at::Tensor &, at::Tensor &); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::rad2deg") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "out") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "rad2deg.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!)") + static at::Tensor & call(const at::Tensor & self, at::Tensor & out); + static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, at::Tensor & out); +}; + +}} // namespace at::_ops diff --git a/shared/package-files/00/00ae2dcc6353694d429f5424e390303162db3ab93fd48f8ed68646406e63c5fc/blob b/shared/package-files/00/00ae2dcc6353694d429f5424e390303162db3ab93fd48f8ed68646406e63c5fc/blob new file mode 100644 index 0000000000000000000000000000000000000000..cf1e9a2042de51f038be78dd9ad9ef486dab2122 Binary files /dev/null and b/shared/package-files/00/00ae2dcc6353694d429f5424e390303162db3ab93fd48f8ed68646406e63c5fc/blob differ diff --git a/shared/package-files/00/00b0bdeca7f0396f6f76bf7904b8c23f1ccedd08dc12ad82bc90b4bf57d1b664/blob b/shared/package-files/00/00b0bdeca7f0396f6f76bf7904b8c23f1ccedd08dc12ad82bc90b4bf57d1b664/blob new file mode 100644 index 0000000000000000000000000000000000000000..d6949908707a89291a2ea9d76cb537dbde5b2d34 --- /dev/null +++ b/shared/package-files/00/00b0bdeca7f0396f6f76bf7904b8c23f1ccedd08dc12ad82bc90b4bf57d1b664/blob @@ -0,0 +1,39 @@ +#pragma once + +// @generated by torchgen/gen.py from Operator.h + +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { +namespace _ops { + + +struct TORCH_API frexp_Tensor { + using schema = ::std::tuple (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::frexp") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "Tensor") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "frexp.Tensor(Tensor self) -> (Tensor mantissa, Tensor exponent)") + static ::std::tuple call(const at::Tensor & self); + static ::std::tuple redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self); +}; + +struct TORCH_API frexp_Tensor_out { + using schema = ::std::tuple (const at::Tensor &, at::Tensor &, at::Tensor &); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::frexp") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "Tensor_out") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "frexp.Tensor_out(Tensor self, *, Tensor(a!) mantissa, Tensor(b!) exponent) -> (Tensor(a!) mantissa, Tensor(b!) exponent)") + static ::std::tuple call(const at::Tensor & self, at::Tensor & mantissa, at::Tensor & exponent); + static ::std::tuple redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, at::Tensor & mantissa, at::Tensor & exponent); +}; + +}} // namespace at::_ops diff --git a/shared/package-files/00/00b2b32c07023c8313af7242e91247b8e61deb3d1a155685e7e7b8f3589c61ef/blob b/shared/package-files/00/00b2b32c07023c8313af7242e91247b8e61deb3d1a155685e7e7b8f3589c61ef/blob new file mode 100644 index 0000000000000000000000000000000000000000..80a5dfda389e7595b666e11b97e608786f239df5 --- /dev/null +++ b/shared/package-files/00/00b2b32c07023c8313af7242e91247b8e61deb3d1a155685e7e7b8f3589c61ef/blob @@ -0,0 +1,250 @@ +from sympy.core.numbers import (I, Rational, nan, zoo) +from sympy.core.singleton import S +from sympy.core.symbol import Symbol +from sympy.ntheory.generate import (sieve, Sieve) +from sympy.series.limits import limit + +from sympy.ntheory import isprime, totient, mobius, randprime, nextprime, prevprime, \ + primerange, primepi, prime, primorial, composite, compositepi, reduced_totient +from sympy.ntheory.generate import cycle_length +from sympy.ntheory.primetest import mr +from sympy.testing.pytest import raises + +def test_prime(): + assert prime(1) == 2 + assert prime(2) == 3 + assert prime(5) == 11 + assert prime(11) == 31 + assert prime(57) == 269 + assert prime(296) == 1949 + assert prime(559) == 4051 + assert prime(3000) == 27449 + assert prime(4096) == 38873 + assert prime(9096) == 94321 + assert prime(25023) == 287341 + assert prime(10000000) == 179424673 # issue #20951 + assert prime(99999999) == 2038074739 + raises(ValueError, lambda: prime(0)) + sieve.extend(3000) + assert prime(401) == 2749 + raises(ValueError, lambda: prime(-1)) + + +def test_primepi(): + assert primepi(-1) == 0 + assert primepi(1) == 0 + assert primepi(2) == 1 + assert primepi(Rational(7, 2)) == 2 + assert primepi(3.5) == 2 + assert primepi(5) == 3 + assert primepi(11) == 5 + assert primepi(57) == 16 + assert primepi(296) == 62 + assert primepi(559) == 102 + assert primepi(3000) == 430 + assert primepi(4096) == 564 + assert primepi(9096) == 1128 + assert primepi(25023) == 2763 + assert primepi(10**8) == 5761455 + assert primepi(253425253) == 13856396 + assert primepi(8769575643) == 401464322 + sieve.extend(3000) + assert primepi(2000) == 303 + + n = Symbol('n') + assert primepi(n).subs(n, 2) == 1 + + r = Symbol('r', real=True) + assert primepi(r).subs(r, 2) == 1 + + assert primepi(S.Infinity) is S.Infinity + assert primepi(S.NegativeInfinity) == 0 + + assert limit(primepi(n), n, 100) == 25 + + raises(ValueError, lambda: primepi(I)) + raises(ValueError, lambda: primepi(1 + I)) + raises(ValueError, lambda: primepi(zoo)) + raises(ValueError, lambda: primepi(nan)) + + +def test_composite(): + from sympy.ntheory.generate import sieve + sieve._reset() + assert composite(1) == 4 + assert composite(2) == 6 + assert composite(5) == 10 + assert composite(11) == 20 + assert composite(41) == 58 + assert composite(57) == 80 + assert composite(296) == 370 + assert composite(559) == 684 + assert composite(3000) == 3488 + assert composite(4096) == 4736 + assert composite(9096) == 10368 + assert composite(25023) == 28088 + sieve.extend(3000) + assert composite(1957) == 2300 + assert composite(2568) == 2998 + raises(ValueError, lambda: composite(0)) + + +def test_compositepi(): + assert compositepi(1) == 0 + assert compositepi(2) == 0 + assert compositepi(5) == 1 + assert compositepi(11) == 5 + assert compositepi(57) == 40 + assert compositepi(296) == 233 + assert compositepi(559) == 456 + assert compositepi(3000) == 2569 + assert compositepi(4096) == 3531 + assert compositepi(9096) == 7967 + assert compositepi(25023) == 22259 + assert compositepi(10**8) == 94238544 + assert compositepi(253425253) == 239568856 + assert compositepi(8769575643) == 8368111320 + sieve.extend(3000) + assert compositepi(2321) == 1976 + + +def test_generate(): + from sympy.ntheory.generate import sieve + sieve._reset() + assert nextprime(-4) == 2 + assert nextprime(2) == 3 + assert nextprime(5) == 7 + assert nextprime(12) == 13 + assert prevprime(3) == 2 + assert prevprime(7) == 5 + assert prevprime(13) == 11 + assert prevprime(19) == 17 + assert prevprime(20) == 19 + + sieve.extend_to_no(9) + assert sieve._list[-1] == 23 + + assert sieve._list[-1] < 31 + assert 31 in sieve + + assert nextprime(90) == 97 + assert nextprime(10**40) == (10**40 + 121) + assert prevprime(97) == 89 + assert prevprime(10**40) == (10**40 - 17) + + assert list(sieve.primerange(10, 1)) == [] + assert list(sieve.primerange(5, 9)) == [5, 7] + sieve._reset(prime=True) + assert list(sieve.primerange(2, 13)) == [2, 3, 5, 7, 11] + assert list(sieve.primerange(13)) == [2, 3, 5, 7, 11] + assert list(sieve.primerange(8)) == [2, 3, 5, 7] + assert list(sieve.primerange(-2)) == [] + assert list(sieve.primerange(29)) == [2, 3, 5, 7, 11, 13, 17, 19, 23] + assert list(sieve.primerange(34)) == [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31] + + assert list(sieve.totientrange(5, 15)) == [4, 2, 6, 4, 6, 4, 10, 4, 12, 6] + sieve._reset(totient=True) + assert list(sieve.totientrange(3, 13)) == [2, 2, 4, 2, 6, 4, 6, 4, 10, 4] + assert list(sieve.totientrange(900, 1000)) == [totient(x) for x in range(900, 1000)] + assert list(sieve.totientrange(0, 1)) == [] + assert list(sieve.totientrange(1, 2)) == [1] + + assert list(sieve.mobiusrange(5, 15)) == [-1, 1, -1, 0, 0, 1, -1, 0, -1, 1] + sieve._reset(mobius=True) + assert list(sieve.mobiusrange(3, 13)) == [-1, 0, -1, 1, -1, 0, 0, 1, -1, 0] + assert list(sieve.mobiusrange(1050, 1100)) == [mobius(x) for x in range(1050, 1100)] + assert list(sieve.mobiusrange(0, 1)) == [] + assert list(sieve.mobiusrange(1, 2)) == [1] + + assert list(primerange(10, 1)) == [] + assert list(primerange(2, 7)) == [2, 3, 5] + assert list(primerange(2, 10)) == [2, 3, 5, 7] + assert list(primerange(1050, 1100)) == [1051, 1061, + 1063, 1069, 1087, 1091, 1093, 1097] + s = Sieve() + for i in range(30, 2350, 376): + for j in range(2, 5096, 1139): + A = list(s.primerange(i, i + j)) + B = list(primerange(i, i + j)) + assert A == B + s = Sieve() + assert s[10] == 29 + + assert nextprime(2, 2) == 5 + + raises(ValueError, lambda: totient(0)) + + raises(ValueError, lambda: reduced_totient(0)) + + raises(ValueError, lambda: primorial(0)) + + assert mr(1, [2]) is False + + func = lambda i: (i**2 + 1) % 51 + assert next(cycle_length(func, 4)) == (6, 2) + assert list(cycle_length(func, 4, values=True)) == \ + [17, 35, 2, 5, 26, 14, 44, 50, 2, 5, 26, 14] + assert next(cycle_length(func, 4, nmax=5)) == (5, None) + assert list(cycle_length(func, 4, nmax=5, values=True)) == \ + [17, 35, 2, 5, 26] + sieve.extend(3000) + assert nextprime(2968) == 2969 + assert prevprime(2930) == 2927 + raises(ValueError, lambda: prevprime(1)) + raises(ValueError, lambda: prevprime(-4)) + + +def test_randprime(): + assert randprime(10, 1) is None + assert randprime(3, -3) is None + assert randprime(2, 3) == 2 + assert randprime(1, 3) == 2 + assert randprime(3, 5) == 3 + raises(ValueError, lambda: randprime(-12, -2)) + raises(ValueError, lambda: randprime(-10, 0)) + raises(ValueError, lambda: randprime(20, 22)) + raises(ValueError, lambda: randprime(0, 2)) + raises(ValueError, lambda: randprime(1, 2)) + for a in [100, 300, 500, 250000]: + for b in [100, 300, 500, 250000]: + p = randprime(a, a + b) + assert a <= p < (a + b) and isprime(p) + + +def test_primorial(): + assert primorial(1) == 2 + assert primorial(1, nth=0) == 1 + assert primorial(2) == 6 + assert primorial(2, nth=0) == 2 + assert primorial(4, nth=0) == 6 + + +def test_search(): + assert 2 in sieve + assert 2.1 not in sieve + assert 1 not in sieve + assert 2**1000 not in sieve + raises(ValueError, lambda: sieve.search(1)) + + +def test_sieve_slice(): + assert sieve[5] == 11 + assert list(sieve[5:10]) == [sieve[x] for x in range(5, 10)] + assert list(sieve[5:10:2]) == [sieve[x] for x in range(5, 10, 2)] + assert list(sieve[1:5]) == [2, 3, 5, 7] + raises(IndexError, lambda: sieve[:5]) + raises(IndexError, lambda: sieve[0]) + raises(IndexError, lambda: sieve[0:5]) + +def test_sieve_iter(): + values = [] + for value in sieve: + if value > 7: + break + values.append(value) + assert values == list(sieve[1:5]) + + +def test_sieve_repr(): + assert "sieve" in repr(sieve) + assert "prime" in repr(sieve) diff --git a/shared/package-files/00/00b4d4763e03c347b2ad4dad4c7afca9a787a8d7cb7aa101ee5b1e7fe1e32811/blob b/shared/package-files/00/00b4d4763e03c347b2ad4dad4c7afca9a787a8d7cb7aa101ee5b1e7fe1e32811/blob new file mode 100644 index 0000000000000000000000000000000000000000..7ca1239286188cbc5f6041f9f6228a3ec938b23b --- /dev/null +++ b/shared/package-files/00/00b4d4763e03c347b2ad4dad4c7afca9a787a8d7cb7aa101ee5b1e7fe1e32811/blob @@ -0,0 +1,1722 @@ +from datetime import ( + datetime, + timedelta, +) +from decimal import Decimal + +import numpy as np +import pytest + +import pandas as pd +from pandas import ( + Categorical, + DataFrame, + DatetimeIndex, + Index, + NaT, + Period, + PeriodIndex, + RangeIndex, + Series, + Timedelta, + TimedeltaIndex, + Timestamp, + date_range, + isna, + period_range, + timedelta_range, + to_timedelta, +) +import pandas._testing as tm +from pandas.core import nanops +from pandas.core.arrays.string_arrow import ArrowStringArrayNumpySemantics + + +def get_objs(): + indexes = [ + Index([True, False] * 5, name="a"), + Index(np.arange(10), dtype=np.int64, name="a"), + Index(np.arange(10), dtype=np.float64, name="a"), + DatetimeIndex(date_range("2020-01-01", periods=10), name="a"), + DatetimeIndex(date_range("2020-01-01", periods=10), name="a").tz_localize( + tz="US/Eastern" + ), + PeriodIndex(period_range("2020-01-01", periods=10, freq="D"), name="a"), + Index([str(i) for i in range(10)], name="a"), + ] + + arr = np.random.default_rng(2).standard_normal(10) + series = [Series(arr, index=idx, name="a") for idx in indexes] + + objs = indexes + series + return objs + + +class TestReductions: + @pytest.mark.filterwarnings( + "ignore:Period with BDay freq is deprecated:FutureWarning" + ) + @pytest.mark.parametrize("opname", ["max", "min"]) + @pytest.mark.parametrize("obj", get_objs()) + def test_ops(self, opname, obj): + result = getattr(obj, opname)() + if not isinstance(obj, PeriodIndex): + if isinstance(obj.values, ArrowStringArrayNumpySemantics): + # max not on the interface + expected = getattr(np.array(obj.values), opname)() + else: + expected = getattr(obj.values, opname)() + else: + expected = Period(ordinal=getattr(obj.asi8, opname)(), freq=obj.freq) + + if getattr(obj, "tz", None) is not None: + # We need to de-localize before comparing to the numpy-produced result + expected = expected.astype("M8[ns]").astype("int64") + assert result._value == expected + else: + assert result == expected + + @pytest.mark.parametrize("opname", ["max", "min"]) + @pytest.mark.parametrize( + "dtype, val", + [ + ("object", 2.0), + ("float64", 2.0), + ("datetime64[ns]", datetime(2011, 11, 1)), + ("Int64", 2), + ("boolean", True), + ], + ) + def test_nanminmax(self, opname, dtype, val, index_or_series): + # GH#7261 + klass = index_or_series + + def check_missing(res): + if dtype == "datetime64[ns]": + return res is NaT + elif dtype in ["Int64", "boolean"]: + return res is pd.NA + else: + return isna(res) + + obj = klass([None], dtype=dtype) + assert check_missing(getattr(obj, opname)()) + assert check_missing(getattr(obj, opname)(skipna=False)) + + obj = klass([], dtype=dtype) + assert check_missing(getattr(obj, opname)()) + assert check_missing(getattr(obj, opname)(skipna=False)) + + if dtype == "object": + # generic test with object only works for empty / all NaN + return + + obj = klass([None, val], dtype=dtype) + assert getattr(obj, opname)() == val + assert check_missing(getattr(obj, opname)(skipna=False)) + + obj = klass([None, val, None], dtype=dtype) + assert getattr(obj, opname)() == val + assert check_missing(getattr(obj, opname)(skipna=False)) + + @pytest.mark.parametrize("opname", ["max", "min"]) + def test_nanargminmax(self, opname, index_or_series): + # GH#7261 + klass = index_or_series + arg_op = "arg" + opname if klass is Index else "idx" + opname + + obj = klass([NaT, datetime(2011, 11, 1)]) + assert getattr(obj, arg_op)() == 1 + + msg = ( + "The behavior of (DatetimeIndex|Series).argmax/argmin with " + "skipna=False and NAs" + ) + if klass is Series: + msg = "The behavior of Series.(idxmax|idxmin) with all-NA" + with tm.assert_produces_warning(FutureWarning, match=msg): + result = getattr(obj, arg_op)(skipna=False) + if klass is Series: + assert np.isnan(result) + else: + assert result == -1 + + obj = klass([NaT, datetime(2011, 11, 1), NaT]) + # check DatetimeIndex non-monotonic path + assert getattr(obj, arg_op)() == 1 + with tm.assert_produces_warning(FutureWarning, match=msg): + result = getattr(obj, arg_op)(skipna=False) + if klass is Series: + assert np.isnan(result) + else: + assert result == -1 + + @pytest.mark.parametrize("opname", ["max", "min"]) + @pytest.mark.parametrize("dtype", ["M8[ns]", "datetime64[ns, UTC]"]) + def test_nanops_empty_object(self, opname, index_or_series, dtype): + klass = index_or_series + arg_op = "arg" + opname if klass is Index else "idx" + opname + + obj = klass([], dtype=dtype) + + assert getattr(obj, opname)() is NaT + assert getattr(obj, opname)(skipna=False) is NaT + + with pytest.raises(ValueError, match="empty sequence"): + getattr(obj, arg_op)() + with pytest.raises(ValueError, match="empty sequence"): + getattr(obj, arg_op)(skipna=False) + + def test_argminmax(self): + obj = Index(np.arange(5, dtype="int64")) + assert obj.argmin() == 0 + assert obj.argmax() == 4 + + obj = Index([np.nan, 1, np.nan, 2]) + assert obj.argmin() == 1 + assert obj.argmax() == 3 + msg = "The behavior of Index.argmax/argmin with skipna=False and NAs" + with tm.assert_produces_warning(FutureWarning, match=msg): + assert obj.argmin(skipna=False) == -1 + with tm.assert_produces_warning(FutureWarning, match=msg): + assert obj.argmax(skipna=False) == -1 + + obj = Index([np.nan]) + with tm.assert_produces_warning(FutureWarning, match=msg): + assert obj.argmin() == -1 + with tm.assert_produces_warning(FutureWarning, match=msg): + assert obj.argmax() == -1 + with tm.assert_produces_warning(FutureWarning, match=msg): + assert obj.argmin(skipna=False) == -1 + with tm.assert_produces_warning(FutureWarning, match=msg): + assert obj.argmax(skipna=False) == -1 + + msg = "The behavior of DatetimeIndex.argmax/argmin with skipna=False and NAs" + obj = Index([NaT, datetime(2011, 11, 1), datetime(2011, 11, 2), NaT]) + assert obj.argmin() == 1 + assert obj.argmax() == 2 + with tm.assert_produces_warning(FutureWarning, match=msg): + assert obj.argmin(skipna=False) == -1 + with tm.assert_produces_warning(FutureWarning, match=msg): + assert obj.argmax(skipna=False) == -1 + + obj = Index([NaT]) + with tm.assert_produces_warning(FutureWarning, match=msg): + assert obj.argmin() == -1 + with tm.assert_produces_warning(FutureWarning, match=msg): + assert obj.argmax() == -1 + with tm.assert_produces_warning(FutureWarning, match=msg): + assert obj.argmin(skipna=False) == -1 + with tm.assert_produces_warning(FutureWarning, match=msg): + assert obj.argmax(skipna=False) == -1 + + @pytest.mark.parametrize("op, expected_col", [["max", "a"], ["min", "b"]]) + def test_same_tz_min_max_axis_1(self, op, expected_col): + # GH 10390 + df = DataFrame( + date_range("2016-01-01 00:00:00", periods=3, tz="UTC"), columns=["a"] + ) + df["b"] = df.a.subtract(Timedelta(seconds=3600)) + result = getattr(df, op)(axis=1) + expected = df[expected_col].rename(None) + tm.assert_series_equal(result, expected) + + @pytest.mark.parametrize("func", ["maximum", "minimum"]) + def test_numpy_reduction_with_tz_aware_dtype(self, tz_aware_fixture, func): + # GH 15552 + tz = tz_aware_fixture + arg = pd.to_datetime(["2019"]).tz_localize(tz) + expected = Series(arg) + result = getattr(np, func)(expected, expected) + tm.assert_series_equal(result, expected) + + def test_nan_int_timedelta_sum(self): + # GH 27185 + df = DataFrame( + { + "A": Series([1, 2, NaT], dtype="timedelta64[ns]"), + "B": Series([1, 2, np.nan], dtype="Int64"), + } + ) + expected = Series({"A": Timedelta(3), "B": 3}) + result = df.sum() + tm.assert_series_equal(result, expected) + + +class TestIndexReductions: + # Note: the name TestIndexReductions indicates these tests + # were moved from a Index-specific test file, _not_ that these tests are + # intended long-term to be Index-specific + + @pytest.mark.parametrize( + "start,stop,step", + [ + (0, 400, 3), + (500, 0, -6), + (-(10**6), 10**6, 4), + (10**6, -(10**6), -4), + (0, 10, 20), + ], + ) + def test_max_min_range(self, start, stop, step): + # GH#17607 + idx = RangeIndex(start, stop, step) + expected = idx._values.max() + result = idx.max() + assert result == expected + + # skipna should be irrelevant since RangeIndex should never have NAs + result2 = idx.max(skipna=False) + assert result2 == expected + + expected = idx._values.min() + result = idx.min() + assert result == expected + + # skipna should be irrelevant since RangeIndex should never have NAs + result2 = idx.min(skipna=False) + assert result2 == expected + + # empty + idx = RangeIndex(start, stop, -step) + assert isna(idx.max()) + assert isna(idx.min()) + + def test_minmax_timedelta64(self): + # monotonic + idx1 = TimedeltaIndex(["1 days", "2 days", "3 days"]) + assert idx1.is_monotonic_increasing + + # non-monotonic + idx2 = TimedeltaIndex(["1 days", np.nan, "3 days", "NaT"]) + assert not idx2.is_monotonic_increasing + + for idx in [idx1, idx2]: + assert idx.min() == Timedelta("1 days") + assert idx.max() == Timedelta("3 days") + assert idx.argmin() == 0 + assert idx.argmax() == 2 + + @pytest.mark.parametrize("op", ["min", "max"]) + def test_minmax_timedelta_empty_or_na(self, op): + # Return NaT + obj = TimedeltaIndex([]) + assert getattr(obj, op)() is NaT + + obj = TimedeltaIndex([NaT]) + assert getattr(obj, op)() is NaT + + obj = TimedeltaIndex([NaT, NaT, NaT]) + assert getattr(obj, op)() is NaT + + def test_numpy_minmax_timedelta64(self): + td = timedelta_range("16815 days", "16820 days", freq="D") + + assert np.min(td) == Timedelta("16815 days") + assert np.max(td) == Timedelta("16820 days") + + errmsg = "the 'out' parameter is not supported" + with pytest.raises(ValueError, match=errmsg): + np.min(td, out=0) + with pytest.raises(ValueError, match=errmsg): + np.max(td, out=0) + + assert np.argmin(td) == 0 + assert np.argmax(td) == 5 + + errmsg = "the 'out' parameter is not supported" + with pytest.raises(ValueError, match=errmsg): + np.argmin(td, out=0) + with pytest.raises(ValueError, match=errmsg): + np.argmax(td, out=0) + + def test_timedelta_ops(self): + # GH#4984 + # make sure ops return Timedelta + s = Series( + [Timestamp("20130101") + timedelta(seconds=i * i) for i in range(10)] + ) + td = s.diff() + + result = td.mean() + expected = to_timedelta(timedelta(seconds=9)) + assert result == expected + + result = td.to_frame().mean() + assert result[0] == expected + + result = td.quantile(0.1) + expected = Timedelta(np.timedelta64(2600, "ms")) + assert result == expected + + result = td.median() + expected = to_timedelta("00:00:09") + assert result == expected + + result = td.to_frame().median() + assert result[0] == expected + + # GH#6462 + # consistency in returned values for sum + result = td.sum() + expected = to_timedelta("00:01:21") + assert result == expected + + result = td.to_frame().sum() + assert result[0] == expected + + # std + result = td.std() + expected = to_timedelta(Series(td.dropna().values).std()) + assert result == expected + + result = td.to_frame().std() + assert result[0] == expected + + # GH#10040 + # make sure NaT is properly handled by median() + s = Series([Timestamp("2015-02-03"), Timestamp("2015-02-07")]) + assert s.diff().median() == timedelta(days=4) + + s = Series( + [Timestamp("2015-02-03"), Timestamp("2015-02-07"), Timestamp("2015-02-15")] + ) + assert s.diff().median() == timedelta(days=6) + + @pytest.mark.parametrize("opname", ["skew", "kurt", "sem", "prod", "var"]) + def test_invalid_td64_reductions(self, opname): + s = Series( + [Timestamp("20130101") + timedelta(seconds=i * i) for i in range(10)] + ) + td = s.diff() + + msg = "|".join( + [ + f"reduction operation '{opname}' not allowed for this dtype", + rf"cannot perform {opname} with type timedelta64\[ns\]", + f"does not support reduction '{opname}'", + ] + ) + + with pytest.raises(TypeError, match=msg): + getattr(td, opname)() + + with pytest.raises(TypeError, match=msg): + getattr(td.to_frame(), opname)(numeric_only=False) + + def test_minmax_tz(self, tz_naive_fixture): + tz = tz_naive_fixture + # monotonic + idx1 = DatetimeIndex(["2011-01-01", "2011-01-02", "2011-01-03"], tz=tz) + assert idx1.is_monotonic_increasing + + # non-monotonic + idx2 = DatetimeIndex( + ["2011-01-01", NaT, "2011-01-03", "2011-01-02", NaT], tz=tz + ) + assert not idx2.is_monotonic_increasing + + for idx in [idx1, idx2]: + assert idx.min() == Timestamp("2011-01-01", tz=tz) + assert idx.max() == Timestamp("2011-01-03", tz=tz) + assert idx.argmin() == 0 + assert idx.argmax() == 2 + + @pytest.mark.parametrize("op", ["min", "max"]) + def test_minmax_nat_datetime64(self, op): + # Return NaT + obj = DatetimeIndex([]) + assert isna(getattr(obj, op)()) + + obj = DatetimeIndex([NaT]) + assert isna(getattr(obj, op)()) + + obj = DatetimeIndex([NaT, NaT, NaT]) + assert isna(getattr(obj, op)()) + + def test_numpy_minmax_integer(self): + # GH#26125 + idx = Index([1, 2, 3]) + + expected = idx.values.max() + result = np.max(idx) + assert result == expected + + expected = idx.values.min() + result = np.min(idx) + assert result == expected + + errmsg = "the 'out' parameter is not supported" + with pytest.raises(ValueError, match=errmsg): + np.min(idx, out=0) + with pytest.raises(ValueError, match=errmsg): + np.max(idx, out=0) + + expected = idx.values.argmax() + result = np.argmax(idx) + assert result == expected + + expected = idx.values.argmin() + result = np.argmin(idx) + assert result == expected + + errmsg = "the 'out' parameter is not supported" + with pytest.raises(ValueError, match=errmsg): + np.argmin(idx, out=0) + with pytest.raises(ValueError, match=errmsg): + np.argmax(idx, out=0) + + def test_numpy_minmax_range(self): + # GH#26125 + idx = RangeIndex(0, 10, 3) + + result = np.max(idx) + assert result == 9 + + result = np.min(idx) + assert result == 0 + + errmsg = "the 'out' parameter is not supported" + with pytest.raises(ValueError, match=errmsg): + np.min(idx, out=0) + with pytest.raises(ValueError, match=errmsg): + np.max(idx, out=0) + + # No need to test again argmax/argmin compat since the implementation + # is the same as basic integer index + + def test_numpy_minmax_datetime64(self): + dr = date_range(start="2016-01-15", end="2016-01-20") + + assert np.min(dr) == Timestamp("2016-01-15 00:00:00") + assert np.max(dr) == Timestamp("2016-01-20 00:00:00") + + errmsg = "the 'out' parameter is not supported" + with pytest.raises(ValueError, match=errmsg): + np.min(dr, out=0) + + with pytest.raises(ValueError, match=errmsg): + np.max(dr, out=0) + + assert np.argmin(dr) == 0 + assert np.argmax(dr) == 5 + + errmsg = "the 'out' parameter is not supported" + with pytest.raises(ValueError, match=errmsg): + np.argmin(dr, out=0) + + with pytest.raises(ValueError, match=errmsg): + np.argmax(dr, out=0) + + def test_minmax_period(self): + # monotonic + idx1 = PeriodIndex([NaT, "2011-01-01", "2011-01-02", "2011-01-03"], freq="D") + assert not idx1.is_monotonic_increasing + assert idx1[1:].is_monotonic_increasing + + # non-monotonic + idx2 = PeriodIndex( + ["2011-01-01", NaT, "2011-01-03", "2011-01-02", NaT], freq="D" + ) + assert not idx2.is_monotonic_increasing + + for idx in [idx1, idx2]: + assert idx.min() == Period("2011-01-01", freq="D") + assert idx.max() == Period("2011-01-03", freq="D") + assert idx1.argmin() == 1 + assert idx2.argmin() == 0 + assert idx1.argmax() == 3 + assert idx2.argmax() == 2 + + @pytest.mark.parametrize("op", ["min", "max"]) + @pytest.mark.parametrize("data", [[], [NaT], [NaT, NaT, NaT]]) + def test_minmax_period_empty_nat(self, op, data): + # Return NaT + obj = PeriodIndex(data, freq="M") + result = getattr(obj, op)() + assert result is NaT + + def test_numpy_minmax_period(self): + pr = period_range(start="2016-01-15", end="2016-01-20") + + assert np.min(pr) == Period("2016-01-15", freq="D") + assert np.max(pr) == Period("2016-01-20", freq="D") + + errmsg = "the 'out' parameter is not supported" + with pytest.raises(ValueError, match=errmsg): + np.min(pr, out=0) + with pytest.raises(ValueError, match=errmsg): + np.max(pr, out=0) + + assert np.argmin(pr) == 0 + assert np.argmax(pr) == 5 + + errmsg = "the 'out' parameter is not supported" + with pytest.raises(ValueError, match=errmsg): + np.argmin(pr, out=0) + with pytest.raises(ValueError, match=errmsg): + np.argmax(pr, out=0) + + def test_min_max_categorical(self): + ci = pd.CategoricalIndex(list("aabbca"), categories=list("cab"), ordered=False) + msg = ( + r"Categorical is not ordered for operation min\n" + r"you can use .as_ordered\(\) to change the Categorical to an ordered one\n" + ) + with pytest.raises(TypeError, match=msg): + ci.min() + msg = ( + r"Categorical is not ordered for operation max\n" + r"you can use .as_ordered\(\) to change the Categorical to an ordered one\n" + ) + with pytest.raises(TypeError, match=msg): + ci.max() + + ci = pd.CategoricalIndex(list("aabbca"), categories=list("cab"), ordered=True) + assert ci.min() == "c" + assert ci.max() == "b" + + +class TestSeriesReductions: + # Note: the name TestSeriesReductions indicates these tests + # were moved from a series-specific test file, _not_ that these tests are + # intended long-term to be series-specific + + def test_sum_inf(self): + s = Series(np.random.default_rng(2).standard_normal(10)) + s2 = s.copy() + + s[5:8] = np.inf + s2[5:8] = np.nan + + assert np.isinf(s.sum()) + + arr = np.random.default_rng(2).standard_normal((100, 100)).astype("f4") + arr[:, 2] = np.inf + + msg = "use_inf_as_na option is deprecated" + with tm.assert_produces_warning(FutureWarning, match=msg): + with pd.option_context("mode.use_inf_as_na", True): + tm.assert_almost_equal(s.sum(), s2.sum()) + + res = nanops.nansum(arr, axis=1) + assert np.isinf(res).all() + + @pytest.mark.parametrize( + "dtype", ["float64", "Float32", "Int64", "boolean", "object"] + ) + @pytest.mark.parametrize("use_bottleneck", [True, False]) + @pytest.mark.parametrize("method, unit", [("sum", 0.0), ("prod", 1.0)]) + def test_empty(self, method, unit, use_bottleneck, dtype): + with pd.option_context("use_bottleneck", use_bottleneck): + # GH#9422 / GH#18921 + # Entirely empty + s = Series([], dtype=dtype) + # NA by default + result = getattr(s, method)() + assert result == unit + + # Explicit + result = getattr(s, method)(min_count=0) + assert result == unit + + result = getattr(s, method)(min_count=1) + assert isna(result) + + # Skipna, default + result = getattr(s, method)(skipna=True) + result == unit + + # Skipna, explicit + result = getattr(s, method)(skipna=True, min_count=0) + assert result == unit + + result = getattr(s, method)(skipna=True, min_count=1) + assert isna(result) + + result = getattr(s, method)(skipna=False, min_count=0) + assert result == unit + + result = getattr(s, method)(skipna=False, min_count=1) + assert isna(result) + + # All-NA + s = Series([np.nan], dtype=dtype) + # NA by default + result = getattr(s, method)() + assert result == unit + + # Explicit + result = getattr(s, method)(min_count=0) + assert result == unit + + result = getattr(s, method)(min_count=1) + assert isna(result) + + # Skipna, default + result = getattr(s, method)(skipna=True) + result == unit + + # skipna, explicit + result = getattr(s, method)(skipna=True, min_count=0) + assert result == unit + + result = getattr(s, method)(skipna=True, min_count=1) + assert isna(result) + + # Mix of valid, empty + s = Series([np.nan, 1], dtype=dtype) + # Default + result = getattr(s, method)() + assert result == 1.0 + + # Explicit + result = getattr(s, method)(min_count=0) + assert result == 1.0 + + result = getattr(s, method)(min_count=1) + assert result == 1.0 + + # Skipna + result = getattr(s, method)(skipna=True) + assert result == 1.0 + + result = getattr(s, method)(skipna=True, min_count=0) + assert result == 1.0 + + # GH#844 (changed in GH#9422) + df = DataFrame(np.empty((10, 0)), dtype=dtype) + assert (getattr(df, method)(1) == unit).all() + + s = Series([1], dtype=dtype) + result = getattr(s, method)(min_count=2) + assert isna(result) + + result = getattr(s, method)(skipna=False, min_count=2) + assert isna(result) + + s = Series([np.nan], dtype=dtype) + result = getattr(s, method)(min_count=2) + assert isna(result) + + s = Series([np.nan, 1], dtype=dtype) + result = getattr(s, method)(min_count=2) + assert isna(result) + + @pytest.mark.parametrize("method", ["mean", "var"]) + @pytest.mark.parametrize("dtype", ["Float64", "Int64", "boolean"]) + def test_ops_consistency_on_empty_nullable(self, method, dtype): + # GH#34814 + # consistency for nullable dtypes on empty or ALL-NA mean + + # empty series + eser = Series([], dtype=dtype) + result = getattr(eser, method)() + assert result is pd.NA + + # ALL-NA series + nser = Series([np.nan], dtype=dtype) + result = getattr(nser, method)() + assert result is pd.NA + + @pytest.mark.parametrize("method", ["mean", "median", "std", "var"]) + def test_ops_consistency_on_empty(self, method): + # GH#7869 + # consistency on empty + + # float + result = getattr(Series(dtype=float), method)() + assert isna(result) + + # timedelta64[ns] + tdser = Series([], dtype="m8[ns]") + if method == "var": + msg = "|".join( + [ + "operation 'var' not allowed", + r"cannot perform var with type timedelta64\[ns\]", + "does not support reduction 'var'", + ] + ) + with pytest.raises(TypeError, match=msg): + getattr(tdser, method)() + else: + result = getattr(tdser, method)() + assert result is NaT + + def test_nansum_buglet(self): + ser = Series([1.0, np.nan], index=[0, 1]) + result = np.nansum(ser) + tm.assert_almost_equal(result, 1) + + @pytest.mark.parametrize("use_bottleneck", [True, False]) + @pytest.mark.parametrize("dtype", ["int32", "int64"]) + def test_sum_overflow_int(self, use_bottleneck, dtype): + with pd.option_context("use_bottleneck", use_bottleneck): + # GH#6915 + # overflowing on the smaller int dtypes + v = np.arange(5000000, dtype=dtype) + s = Series(v) + + result = s.sum(skipna=False) + assert int(result) == v.sum(dtype="int64") + result = s.min(skipna=False) + assert int(result) == 0 + result = s.max(skipna=False) + assert int(result) == v[-1] + + @pytest.mark.parametrize("use_bottleneck", [True, False]) + @pytest.mark.parametrize("dtype", ["float32", "float64"]) + def test_sum_overflow_float(self, use_bottleneck, dtype): + with pd.option_context("use_bottleneck", use_bottleneck): + v = np.arange(5000000, dtype=dtype) + s = Series(v) + + result = s.sum(skipna=False) + assert result == v.sum(dtype=dtype) + result = s.min(skipna=False) + assert np.allclose(float(result), 0.0) + result = s.max(skipna=False) + assert np.allclose(float(result), v[-1]) + + def test_mean_masked_overflow(self): + # GH#48378 + val = 100_000_000_000_000_000 + n_elements = 100 + na = np.array([val] * n_elements) + ser = Series([val] * n_elements, dtype="Int64") + + result_numpy = np.mean(na) + result_masked = ser.mean() + assert result_masked - result_numpy == 0 + assert result_masked == 1e17 + + @pytest.mark.parametrize("ddof, exp", [(1, 2.5), (0, 2.0)]) + def test_var_masked_array(self, ddof, exp): + # GH#48379 + ser = Series([1, 2, 3, 4, 5], dtype="Int64") + ser_numpy_dtype = Series([1, 2, 3, 4, 5], dtype="int64") + result = ser.var(ddof=ddof) + result_numpy_dtype = ser_numpy_dtype.var(ddof=ddof) + assert result == result_numpy_dtype + assert result == exp + + @pytest.mark.parametrize("dtype", ("m8[ns]", "m8[ns]", "M8[ns]", "M8[ns, UTC]")) + @pytest.mark.parametrize("skipna", [True, False]) + def test_empty_timeseries_reductions_return_nat(self, dtype, skipna): + # covers GH#11245 + assert Series([], dtype=dtype).min(skipna=skipna) is NaT + assert Series([], dtype=dtype).max(skipna=skipna) is NaT + + def test_numpy_argmin(self): + # See GH#16830 + data = np.arange(1, 11) + + s = Series(data, index=data) + result = np.argmin(s) + + expected = np.argmin(data) + assert result == expected + + result = s.argmin() + + assert result == expected + + msg = "the 'out' parameter is not supported" + with pytest.raises(ValueError, match=msg): + np.argmin(s, out=data) + + def test_numpy_argmax(self): + # See GH#16830 + data = np.arange(1, 11) + + ser = Series(data, index=data) + result = np.argmax(ser) + expected = np.argmax(data) + assert result == expected + + result = ser.argmax() + + assert result == expected + + msg = "the 'out' parameter is not supported" + with pytest.raises(ValueError, match=msg): + np.argmax(ser, out=data) + + def test_idxmin_dt64index(self, unit): + # GH#43587 should have NaT instead of NaN + dti = DatetimeIndex(["NaT", "2015-02-08", "NaT"]).as_unit(unit) + ser = Series([1.0, 2.0, np.nan], index=dti) + msg = "The behavior of Series.idxmin with all-NA values" + with tm.assert_produces_warning(FutureWarning, match=msg): + res = ser.idxmin(skipna=False) + assert res is NaT + msg = "The behavior of Series.idxmax with all-NA values" + with tm.assert_produces_warning(FutureWarning, match=msg): + res = ser.idxmax(skipna=False) + assert res is NaT + + df = ser.to_frame() + msg = "The behavior of DataFrame.idxmin with all-NA values" + with tm.assert_produces_warning(FutureWarning, match=msg): + res = df.idxmin(skipna=False) + assert res.dtype == f"M8[{unit}]" + assert res.isna().all() + msg = "The behavior of DataFrame.idxmax with all-NA values" + with tm.assert_produces_warning(FutureWarning, match=msg): + res = df.idxmax(skipna=False) + assert res.dtype == f"M8[{unit}]" + assert res.isna().all() + + def test_idxmin(self): + # test idxmin + # _check_stat_op approach can not be used here because of isna check. + string_series = Series(range(20), dtype=np.float64, name="series") + + # add some NaNs + string_series[5:15] = np.nan + + # skipna or no + assert string_series[string_series.idxmin()] == string_series.min() + msg = "The behavior of Series.idxmin" + with tm.assert_produces_warning(FutureWarning, match=msg): + assert isna(string_series.idxmin(skipna=False)) + + # no NaNs + nona = string_series.dropna() + assert nona[nona.idxmin()] == nona.min() + assert nona.index.values.tolist().index(nona.idxmin()) == nona.values.argmin() + + # all NaNs + allna = string_series * np.nan + with tm.assert_produces_warning(FutureWarning, match=msg): + assert isna(allna.idxmin()) + + # datetime64[ns] + s = Series(date_range("20130102", periods=6)) + result = s.idxmin() + assert result == 0 + + s[0] = np.nan + result = s.idxmin() + assert result == 1 + + def test_idxmax(self): + # test idxmax + # _check_stat_op approach can not be used here because of isna check. + string_series = Series(range(20), dtype=np.float64, name="series") + + # add some NaNs + string_series[5:15] = np.nan + + # skipna or no + assert string_series[string_series.idxmax()] == string_series.max() + msg = "The behavior of Series.idxmax with all-NA values" + with tm.assert_produces_warning(FutureWarning, match=msg): + assert isna(string_series.idxmax(skipna=False)) + + # no NaNs + nona = string_series.dropna() + assert nona[nona.idxmax()] == nona.max() + assert nona.index.values.tolist().index(nona.idxmax()) == nona.values.argmax() + + # all NaNs + allna = string_series * np.nan + msg = "The behavior of Series.idxmax with all-NA values" + with tm.assert_produces_warning(FutureWarning, match=msg): + assert isna(allna.idxmax()) + + s = Series(date_range("20130102", periods=6)) + result = s.idxmax() + assert result == 5 + + s[5] = np.nan + result = s.idxmax() + assert result == 4 + + # Index with float64 dtype + # GH#5914 + s = Series([1, 2, 3], [1.1, 2.1, 3.1]) + result = s.idxmax() + assert result == 3.1 + result = s.idxmin() + assert result == 1.1 + + s = Series(s.index, s.index) + result = s.idxmax() + assert result == 3.1 + result = s.idxmin() + assert result == 1.1 + + def test_all_any(self): + ts = Series( + np.arange(10, dtype=np.float64), + index=date_range("2020-01-01", periods=10), + name="ts", + ) + bool_series = ts > 0 + assert not bool_series.all() + assert bool_series.any() + + # Alternative types, with implicit 'object' dtype. + s = Series(["abc", True]) + assert s.any() + + def test_numpy_all_any(self, index_or_series): + # GH#40180 + idx = index_or_series([0, 1, 2]) + assert not np.all(idx) + assert np.any(idx) + idx = Index([1, 2, 3]) + assert np.all(idx) + + def test_all_any_skipna(self): + # Check skipna, with implicit 'object' dtype. + s1 = Series([np.nan, True]) + s2 = Series([np.nan, False]) + assert s1.all(skipna=False) # nan && True => True + assert s1.all(skipna=True) + assert s2.any(skipna=False) + assert not s2.any(skipna=True) + + def test_all_any_bool_only(self): + s = Series([False, False, True, True, False, True], index=[0, 0, 1, 1, 2, 2]) + + # GH#47500 - test bool_only works + assert s.any(bool_only=True) + assert not s.all(bool_only=True) + + @pytest.mark.parametrize("bool_agg_func", ["any", "all"]) + @pytest.mark.parametrize("skipna", [True, False]) + def test_any_all_object_dtype(self, bool_agg_func, skipna): + # GH#12863 + ser = Series(["a", "b", "c", "d", "e"], dtype=object) + result = getattr(ser, bool_agg_func)(skipna=skipna) + expected = True + + assert result == expected + + @pytest.mark.parametrize("bool_agg_func", ["any", "all"]) + @pytest.mark.parametrize( + "data", [[False, None], [None, False], [False, np.nan], [np.nan, False]] + ) + def test_any_all_object_dtype_missing(self, data, bool_agg_func): + # GH#27709 + ser = Series(data) + result = getattr(ser, bool_agg_func)(skipna=False) + + # None is treated is False, but np.nan is treated as True + expected = bool_agg_func == "any" and None not in data + assert result == expected + + @pytest.mark.parametrize("dtype", ["boolean", "Int64", "UInt64", "Float64"]) + @pytest.mark.parametrize("bool_agg_func", ["any", "all"]) + @pytest.mark.parametrize("skipna", [True, False]) + @pytest.mark.parametrize( + # expected_data indexed as [[skipna=False/any, skipna=False/all], + # [skipna=True/any, skipna=True/all]] + "data,expected_data", + [ + ([0, 0, 0], [[False, False], [False, False]]), + ([1, 1, 1], [[True, True], [True, True]]), + ([pd.NA, pd.NA, pd.NA], [[pd.NA, pd.NA], [False, True]]), + ([0, pd.NA, 0], [[pd.NA, False], [False, False]]), + ([1, pd.NA, 1], [[True, pd.NA], [True, True]]), + ([1, pd.NA, 0], [[True, False], [True, False]]), + ], + ) + def test_any_all_nullable_kleene_logic( + self, bool_agg_func, skipna, data, dtype, expected_data + ): + # GH-37506, GH-41967 + ser = Series(data, dtype=dtype) + expected = expected_data[skipna][bool_agg_func == "all"] + + result = getattr(ser, bool_agg_func)(skipna=skipna) + assert (result is pd.NA and expected is pd.NA) or result == expected + + def test_any_axis1_bool_only(self): + # GH#32432 + df = DataFrame({"A": [True, False], "B": [1, 2]}) + result = df.any(axis=1, bool_only=True) + expected = Series([True, False]) + tm.assert_series_equal(result, expected) + + def test_any_all_datetimelike(self): + # GH#38723 these may not be the desired long-term behavior (GH#34479) + # but in the interim should be internally consistent + dta = date_range("1995-01-02", periods=3)._data + ser = Series(dta) + df = DataFrame(ser) + + msg = "'(any|all)' with datetime64 dtypes is deprecated" + with tm.assert_produces_warning(FutureWarning, match=msg): + # GH#34479 + assert dta.all() + assert dta.any() + + assert ser.all() + assert ser.any() + + assert df.any().all() + assert df.all().all() + + dta = dta.tz_localize("UTC") + ser = Series(dta) + df = DataFrame(ser) + + with tm.assert_produces_warning(FutureWarning, match=msg): + # GH#34479 + assert dta.all() + assert dta.any() + + assert ser.all() + assert ser.any() + + assert df.any().all() + assert df.all().all() + + tda = dta - dta[0] + ser = Series(tda) + df = DataFrame(ser) + + assert tda.any() + assert not tda.all() + + assert ser.any() + assert not ser.all() + + assert df.any().all() + assert not df.all().any() + + def test_any_all_string_dtype(self, any_string_dtype): + # GH#54591 + if ( + isinstance(any_string_dtype, pd.StringDtype) + and any_string_dtype.na_value is pd.NA + ): + # the nullable string dtype currently still raise an error + # https://github.com/pandas-dev/pandas/issues/51939 + ser = Series(["a", "b"], dtype=any_string_dtype) + with pytest.raises(TypeError): + ser.any() + with pytest.raises(TypeError): + ser.all() + return + + ser = Series(["", "a"], dtype=any_string_dtype) + assert ser.any() + assert not ser.all() + assert ser.any(skipna=False) + assert not ser.all(skipna=False) + + ser = Series([np.nan, "a"], dtype=any_string_dtype) + assert ser.any() + assert ser.all() + assert ser.any(skipna=False) + assert ser.all(skipna=False) # NaN is considered truthy + + ser = Series([np.nan, ""], dtype=any_string_dtype) + assert not ser.any() + assert not ser.all() + assert ser.any(skipna=False) # NaN is considered truthy + assert not ser.all(skipna=False) + + ser = Series(["a", "b"], dtype=any_string_dtype) + assert ser.any() + assert ser.all() + assert ser.any(skipna=False) + assert ser.all(skipna=False) + + ser = Series([], dtype=any_string_dtype) + assert not ser.any() + assert ser.all() + assert not ser.any(skipna=False) + assert ser.all(skipna=False) + + ser = Series([""], dtype=any_string_dtype) + assert not ser.any() + assert not ser.all() + assert not ser.any(skipna=False) + assert not ser.all(skipna=False) + + ser = Series([np.nan], dtype=any_string_dtype) + assert not ser.any() + assert ser.all() + assert ser.any(skipna=False) # NaN is considered truthy + assert ser.all(skipna=False) # NaN is considered truthy + + def test_timedelta64_analytics(self): + # index min/max + dti = date_range("2012-1-1", periods=3, freq="D") + td = Series(dti) - Timestamp("20120101") + + result = td.idxmin() + assert result == 0 + + result = td.idxmax() + assert result == 2 + + # GH#2982 + # with NaT + td[0] = np.nan + + result = td.idxmin() + assert result == 1 + + result = td.idxmax() + assert result == 2 + + # abs + s1 = Series(date_range("20120101", periods=3)) + s2 = Series(date_range("20120102", periods=3)) + expected = Series(s2 - s1) + + result = np.abs(s1 - s2) + tm.assert_series_equal(result, expected) + + result = (s1 - s2).abs() + tm.assert_series_equal(result, expected) + + # max/min + result = td.max() + expected = Timedelta("2 days") + assert result == expected + + result = td.min() + expected = Timedelta("1 days") + assert result == expected + + @pytest.mark.parametrize( + "test_input,error_type", + [ + (Series([], dtype="float64"), ValueError), + # For strings, or any Series with dtype 'O' + (Series(["foo", "bar", "baz"]), TypeError), + (Series([(1,), (2,)]), TypeError), + # For mixed data types + (Series(["foo", "foo", "bar", "bar", None, np.nan, "baz"]), TypeError), + ], + ) + def test_assert_idxminmax_empty_raises(self, test_input, error_type): + """ + Cases where ``Series.argmax`` and related should raise an exception + """ + test_input = Series([], dtype="float64") + msg = "attempt to get argmin of an empty sequence" + with pytest.raises(ValueError, match=msg): + test_input.idxmin() + with pytest.raises(ValueError, match=msg): + test_input.idxmin(skipna=False) + msg = "attempt to get argmax of an empty sequence" + with pytest.raises(ValueError, match=msg): + test_input.idxmax() + with pytest.raises(ValueError, match=msg): + test_input.idxmax(skipna=False) + + def test_idxminmax_object_dtype(self, using_infer_string): + # pre-2.1 object-dtype was disallowed for argmin/max + ser = Series(["foo", "bar", "baz"]) + assert ser.idxmax() == 0 + assert ser.idxmax(skipna=False) == 0 + assert ser.idxmin() == 1 + assert ser.idxmin(skipna=False) == 1 + + ser2 = Series([(1,), (2,)]) + assert ser2.idxmax() == 1 + assert ser2.idxmax(skipna=False) == 1 + assert ser2.idxmin() == 0 + assert ser2.idxmin(skipna=False) == 0 + + if not using_infer_string: + # attempting to compare np.nan with string raises + ser3 = Series(["foo", "foo", "bar", "bar", None, np.nan, "baz"]) + msg = "'>' not supported between instances of 'float' and 'str'" + with pytest.raises(TypeError, match=msg): + ser3.idxmax() + with pytest.raises(TypeError, match=msg): + ser3.idxmax(skipna=False) + msg = "'<' not supported between instances of 'float' and 'str'" + with pytest.raises(TypeError, match=msg): + ser3.idxmin() + with pytest.raises(TypeError, match=msg): + ser3.idxmin(skipna=False) + + def test_idxminmax_object_frame(self): + # GH#4279 + df = DataFrame([["zimm", 2.5], ["biff", 1.0], ["bid", 12.0]]) + res = df.idxmax() + exp = Series([0, 2]) + tm.assert_series_equal(res, exp) + + def test_idxminmax_object_tuples(self): + # GH#43697 + ser = Series([(1, 3), (2, 2), (3, 1)]) + assert ser.idxmax() == 2 + assert ser.idxmin() == 0 + assert ser.idxmax(skipna=False) == 2 + assert ser.idxmin(skipna=False) == 0 + + def test_idxminmax_object_decimals(self): + # GH#40685 + df = DataFrame( + { + "idx": [0, 1], + "x": [Decimal("8.68"), Decimal("42.23")], + "y": [Decimal("7.11"), Decimal("79.61")], + } + ) + res = df.idxmax() + exp = Series({"idx": 1, "x": 1, "y": 1}) + tm.assert_series_equal(res, exp) + + res2 = df.idxmin() + exp2 = exp - 1 + tm.assert_series_equal(res2, exp2) + + def test_argminmax_object_ints(self): + # GH#18021 + ser = Series([0, 1], dtype="object") + assert ser.argmax() == 1 + assert ser.argmin() == 0 + assert ser.argmax(skipna=False) == 1 + assert ser.argmin(skipna=False) == 0 + + def test_idxminmax_with_inf(self): + # For numeric data with NA and Inf (GH #13595) + s = Series([0, -np.inf, np.inf, np.nan]) + + assert s.idxmin() == 1 + msg = "The behavior of Series.idxmin with all-NA values" + with tm.assert_produces_warning(FutureWarning, match=msg): + assert np.isnan(s.idxmin(skipna=False)) + + assert s.idxmax() == 2 + msg = "The behavior of Series.idxmax with all-NA values" + with tm.assert_produces_warning(FutureWarning, match=msg): + assert np.isnan(s.idxmax(skipna=False)) + + msg = "use_inf_as_na option is deprecated" + with tm.assert_produces_warning(FutureWarning, match=msg): + # Using old-style behavior that treats floating point nan, -inf, and + # +inf as missing + with pd.option_context("mode.use_inf_as_na", True): + assert s.idxmin() == 0 + assert np.isnan(s.idxmin(skipna=False)) + assert s.idxmax() == 0 + np.isnan(s.idxmax(skipna=False)) + + def test_sum_uint64(self): + # GH 53401 + s = Series([10000000000000000000], dtype="uint64") + result = s.sum() + expected = np.uint64(10000000000000000000) + tm.assert_almost_equal(result, expected) + + +class TestDatetime64SeriesReductions: + # Note: the name TestDatetime64SeriesReductions indicates these tests + # were moved from a series-specific test file, _not_ that these tests are + # intended long-term to be series-specific + + @pytest.mark.parametrize( + "nat_ser", + [ + Series([NaT, NaT]), + Series([NaT, Timedelta("nat")]), + Series([Timedelta("nat"), Timedelta("nat")]), + ], + ) + def test_minmax_nat_series(self, nat_ser): + # GH#23282 + assert nat_ser.min() is NaT + assert nat_ser.max() is NaT + assert nat_ser.min(skipna=False) is NaT + assert nat_ser.max(skipna=False) is NaT + + @pytest.mark.parametrize( + "nat_df", + [ + DataFrame([NaT, NaT]), + DataFrame([NaT, Timedelta("nat")]), + DataFrame([Timedelta("nat"), Timedelta("nat")]), + ], + ) + def test_minmax_nat_dataframe(self, nat_df): + # GH#23282 + assert nat_df.min()[0] is NaT + assert nat_df.max()[0] is NaT + assert nat_df.min(skipna=False)[0] is NaT + assert nat_df.max(skipna=False)[0] is NaT + + def test_min_max(self): + rng = date_range("1/1/2000", "12/31/2000") + rng2 = rng.take(np.random.default_rng(2).permutation(len(rng))) + + the_min = rng2.min() + the_max = rng2.max() + assert isinstance(the_min, Timestamp) + assert isinstance(the_max, Timestamp) + assert the_min == rng[0] + assert the_max == rng[-1] + + assert rng.min() == rng[0] + assert rng.max() == rng[-1] + + def test_min_max_series(self): + rng = date_range("1/1/2000", periods=10, freq="4h") + lvls = ["A", "A", "A", "B", "B", "B", "C", "C", "C", "C"] + df = DataFrame( + { + "TS": rng, + "V": np.random.default_rng(2).standard_normal(len(rng)), + "L": lvls, + } + ) + + result = df.TS.max() + exp = Timestamp(df.TS.iat[-1]) + assert isinstance(result, Timestamp) + assert result == exp + + result = df.TS.min() + exp = Timestamp(df.TS.iat[0]) + assert isinstance(result, Timestamp) + assert result == exp + + +class TestCategoricalSeriesReductions: + # Note: the name TestCategoricalSeriesReductions indicates these tests + # were moved from a series-specific test file, _not_ that these tests are + # intended long-term to be series-specific + + @pytest.mark.parametrize("function", ["min", "max"]) + def test_min_max_unordered_raises(self, function): + # unordered cats have no min/max + cat = Series(Categorical(["a", "b", "c", "d"], ordered=False)) + msg = f"Categorical is not ordered for operation {function}" + with pytest.raises(TypeError, match=msg): + getattr(cat, function)() + + @pytest.mark.parametrize( + "values, categories", + [ + (list("abc"), list("abc")), + (list("abc"), list("cba")), + (list("abc") + [np.nan], list("cba")), + ([1, 2, 3], [3, 2, 1]), + ([1, 2, 3, np.nan], [3, 2, 1]), + ], + ) + @pytest.mark.parametrize("function", ["min", "max"]) + def test_min_max_ordered(self, values, categories, function): + # GH 25303 + cat = Series(Categorical(values, categories=categories, ordered=True)) + result = getattr(cat, function)(skipna=True) + expected = categories[0] if function == "min" else categories[2] + assert result == expected + + @pytest.mark.parametrize("function", ["min", "max"]) + @pytest.mark.parametrize("skipna", [True, False]) + def test_min_max_ordered_with_nan_only(self, function, skipna): + # https://github.com/pandas-dev/pandas/issues/33450 + cat = Series(Categorical([np.nan], categories=[1, 2], ordered=True)) + result = getattr(cat, function)(skipna=skipna) + assert result is np.nan + + @pytest.mark.parametrize("function", ["min", "max"]) + @pytest.mark.parametrize("skipna", [True, False]) + def test_min_max_skipna(self, function, skipna): + cat = Series( + Categorical(["a", "b", np.nan, "a"], categories=["b", "a"], ordered=True) + ) + result = getattr(cat, function)(skipna=skipna) + + if skipna is True: + expected = "b" if function == "min" else "a" + assert result == expected + else: + assert result is np.nan + + +class TestSeriesMode: + # Note: the name TestSeriesMode indicates these tests + # were moved from a series-specific test file, _not_ that these tests are + # intended long-term to be series-specific + + @pytest.mark.parametrize( + "dropna, expected", + [(True, Series([], dtype=np.float64)), (False, Series([], dtype=np.float64))], + ) + def test_mode_empty(self, dropna, expected): + s = Series([], dtype=np.float64) + result = s.mode(dropna) + tm.assert_series_equal(result, expected) + + @pytest.mark.parametrize( + "dropna, data, expected", + [ + (True, [1, 1, 1, 2], [1]), + (True, [1, 1, 1, 2, 3, 3, 3], [1, 3]), + (False, [1, 1, 1, 2], [1]), + (False, [1, 1, 1, 2, 3, 3, 3], [1, 3]), + ], + ) + @pytest.mark.parametrize( + "dt", list(np.typecodes["AllInteger"] + np.typecodes["Float"]) + ) + def test_mode_numerical(self, dropna, data, expected, dt): + s = Series(data, dtype=dt) + result = s.mode(dropna) + expected = Series(expected, dtype=dt) + tm.assert_series_equal(result, expected) + + @pytest.mark.parametrize("dropna, expected", [(True, [1.0]), (False, [1, np.nan])]) + def test_mode_numerical_nan(self, dropna, expected): + s = Series([1, 1, 2, np.nan, np.nan]) + result = s.mode(dropna) + expected = Series(expected) + tm.assert_series_equal(result, expected) + + @pytest.mark.parametrize( + "dropna, expected1, expected2", + [ + (True, ["b"], ["bar"]), + (False, ["b"], [np.nan]), + ], + ) + def test_mode_object(self, dropna, expected1, expected2): + # Test string and object types. + data = ["a"] * 2 + ["b"] * 3 + + s = Series(data, dtype="c") + result = s.mode(dropna) + expected1 = Series(expected1, dtype="c") + tm.assert_series_equal(result, expected1) + + data = ["foo", "bar", "bar", np.nan, np.nan, np.nan] + + s = Series(data, dtype=object) + result = s.mode(dropna) + expected2 = Series(expected2, dtype=object) + tm.assert_series_equal(result, expected2) + + @pytest.mark.parametrize( + "dropna, expected1, expected2", + [ + (True, ["b"], ["bar"]), + (False, ["b"], [np.nan]), + ], + ) + def test_mode_string(self, dropna, expected1, expected2, any_string_dtype): + # Test string and object types. + data = ["a"] * 2 + ["b"] * 3 + + s = Series(data, dtype=any_string_dtype) + result = s.mode(dropna) + expected1 = Series(expected1, dtype=any_string_dtype) + tm.assert_series_equal(result, expected1) + + data = ["foo", "bar", "bar", np.nan, np.nan, np.nan] + + s = Series(data, dtype=any_string_dtype) + result = s.mode(dropna) + expected2 = Series(expected2, dtype=any_string_dtype) + tm.assert_series_equal(result, expected2) + + @pytest.mark.parametrize( + "dropna, expected1, expected2", + [(True, ["foo"], ["foo"]), (False, ["foo"], [np.nan])], + ) + def test_mode_mixeddtype(self, dropna, expected1, expected2): + s = Series([1, "foo", "foo"]) + result = s.mode(dropna) + expected = Series(expected1, dtype=object) + tm.assert_series_equal(result, expected) + + s = Series([1, "foo", "foo", np.nan, np.nan, np.nan]) + result = s.mode(dropna) + expected = Series(expected2, dtype=object) + tm.assert_series_equal(result, expected) + + @pytest.mark.parametrize( + "dropna, expected1, expected2", + [ + ( + True, + ["1900-05-03", "2011-01-03", "2013-01-02"], + ["2011-01-03", "2013-01-02"], + ), + (False, [np.nan], [np.nan, "2011-01-03", "2013-01-02"]), + ], + ) + def test_mode_datetime(self, dropna, expected1, expected2): + s = Series( + ["2011-01-03", "2013-01-02", "1900-05-03", "nan", "nan"], dtype="M8[ns]" + ) + result = s.mode(dropna) + expected1 = Series(expected1, dtype="M8[ns]") + tm.assert_series_equal(result, expected1) + + s = Series( + [ + "2011-01-03", + "2013-01-02", + "1900-05-03", + "2011-01-03", + "2013-01-02", + "nan", + "nan", + ], + dtype="M8[ns]", + ) + result = s.mode(dropna) + expected2 = Series(expected2, dtype="M8[ns]") + tm.assert_series_equal(result, expected2) + + @pytest.mark.parametrize( + "dropna, expected1, expected2", + [ + (True, ["-1 days", "0 days", "1 days"], ["2 min", "1 day"]), + (False, [np.nan], [np.nan, "2 min", "1 day"]), + ], + ) + def test_mode_timedelta(self, dropna, expected1, expected2): + # gh-5986: Test timedelta types. + + s = Series( + ["1 days", "-1 days", "0 days", "nan", "nan"], dtype="timedelta64[ns]" + ) + result = s.mode(dropna) + expected1 = Series(expected1, dtype="timedelta64[ns]") + tm.assert_series_equal(result, expected1) + + s = Series( + [ + "1 day", + "1 day", + "-1 day", + "-1 day 2 min", + "2 min", + "2 min", + "nan", + "nan", + ], + dtype="timedelta64[ns]", + ) + result = s.mode(dropna) + expected2 = Series(expected2, dtype="timedelta64[ns]") + tm.assert_series_equal(result, expected2) + + @pytest.mark.parametrize( + "dropna, expected1, expected2, expected3", + [ + ( + True, + Categorical([1, 2], categories=[1, 2]), + Categorical(["a"], categories=[1, "a"]), + Categorical([3, 1], categories=[3, 2, 1], ordered=True), + ), + ( + False, + Categorical([np.nan], categories=[1, 2]), + Categorical([np.nan, "a"], categories=[1, "a"]), + Categorical([np.nan, 3, 1], categories=[3, 2, 1], ordered=True), + ), + ], + ) + def test_mode_category(self, dropna, expected1, expected2, expected3): + s = Series(Categorical([1, 2, np.nan, np.nan])) + result = s.mode(dropna) + expected1 = Series(expected1, dtype="category") + tm.assert_series_equal(result, expected1) + + s = Series(Categorical([1, "a", "a", np.nan, np.nan])) + result = s.mode(dropna) + expected2 = Series(expected2, dtype="category") + tm.assert_series_equal(result, expected2) + + s = Series( + Categorical( + [1, 1, 2, 3, 3, np.nan, np.nan], categories=[3, 2, 1], ordered=True + ) + ) + result = s.mode(dropna) + expected3 = Series(expected3, dtype="category") + tm.assert_series_equal(result, expected3) + + @pytest.mark.parametrize( + "dropna, expected1, expected2", + [(True, [2**63], [1, 2**63]), (False, [2**63], [1, 2**63])], + ) + def test_mode_intoverflow(self, dropna, expected1, expected2): + # Test for uint64 overflow. + s = Series([1, 2**63, 2**63], dtype=np.uint64) + result = s.mode(dropna) + expected1 = Series(expected1, dtype=np.uint64) + tm.assert_series_equal(result, expected1) + + s = Series([1, 2**63], dtype=np.uint64) + result = s.mode(dropna) + expected2 = Series(expected2, dtype=np.uint64) + tm.assert_series_equal(result, expected2) + + def test_mode_sort_with_na(self): + s = Series([1, "foo", "foo", np.nan, np.nan]) + expected = Series(["foo", np.nan], dtype=object) + result = s.mode(dropna=False) + tm.assert_series_equal(result, expected) + + def test_mode_boolean_with_na(self): + # GH#42107 + ser = Series([True, False, True, pd.NA], dtype="boolean") + result = ser.mode() + expected = Series({0: True}, dtype="boolean") + tm.assert_series_equal(result, expected) + + @pytest.mark.parametrize( + "array,expected,dtype", + [ + ( + [0, 1j, 1, 1, 1 + 1j, 1 + 2j], + Series([1], dtype=np.complex128), + np.complex128, + ), + ( + [0, 1j, 1, 1, 1 + 1j, 1 + 2j], + Series([1], dtype=np.complex64), + np.complex64, + ), + ( + [1 + 1j, 2j, 1 + 1j], + Series([1 + 1j], dtype=np.complex128), + np.complex128, + ), + ], + ) + def test_single_mode_value_complex(self, array, expected, dtype): + result = Series(array, dtype=dtype).mode() + tm.assert_series_equal(result, expected) + + @pytest.mark.parametrize( + "array,expected,dtype", + [ + ( + # no modes + [0, 1j, 1, 1 + 1j, 1 + 2j], + Series([0j, 1j, 1 + 0j, 1 + 1j, 1 + 2j], dtype=np.complex128), + np.complex128, + ), + ( + [1 + 1j, 2j, 1 + 1j, 2j, 3], + Series([2j, 1 + 1j], dtype=np.complex64), + np.complex64, + ), + ], + ) + def test_multimode_complex(self, array, expected, dtype): + # GH 17927 + # mode tries to sort multimodal series. + # Complex numbers are sorted by their magnitude + result = Series(array, dtype=dtype).mode() + tm.assert_series_equal(result, expected) diff --git a/shared/package-files/00/00b68b148ab038a1b2bf253192a054f29c8a82ea31f8cd0718c1043987300ecc/blob b/shared/package-files/00/00b68b148ab038a1b2bf253192a054f29c8a82ea31f8cd0718c1043987300ecc/blob new file mode 100644 index 0000000000000000000000000000000000000000..34e80bcb95f5e487c8fd7c9e8dcb01db56307bc5 --- /dev/null +++ b/shared/package-files/00/00b68b148ab038a1b2bf253192a054f29c8a82ea31f8cd0718c1043987300ecc/blob @@ -0,0 +1,689 @@ +# This base template ("datapipe.pyi.in") is generated from mypy stubgen with minimal editing for code injection +# The output file will be "datapipe.pyi". This is executed as part of torch/CMakeLists.txt +# Note that, for mypy, .pyi file takes precedent over .py file, such that we must define the interface for other +# classes/objects here, even though we are not injecting extra code into them at the moment. + +from typing import Any, Callable, Dict, Generic, Iterator, List, Literal, Optional, TypeVar, Union + +from torch.utils.data import Dataset, default_collate, IterableDataset +from torch.utils.data.datapipes._hook_iterator import _SnapshotState +from torch.utils.data.datapipes._typing import _DataPipeMeta, _IterDataPipeMeta + +T_co = TypeVar("T_co", covariant=True) +T = TypeVar("T") +UNTRACABLE_DATAFRAME_PIPES: Any + +class MapDataPipe(Dataset[T_co], metaclass=_DataPipeMeta): + functions: Dict[str, Callable] = ... + reduce_ex_hook: Optional[Callable] = ... + getstate_hook: Optional[Callable] = ... + str_hook: Optional[Callable] = ... + repr_hook: Optional[Callable] = ... + def __getattr__(self, attribute_name: Any): ... + @classmethod + def register_function(cls, function_name: Any, function: Any) -> None: ... + @classmethod + def register_datapipe_as_function( + cls, + function_name: Any, + cls_to_register: Any, + ): ... + def __getstate__(self): ... + def __reduce_ex__(self, *args: Any, **kwargs: Any): ... + @classmethod + def set_getstate_hook(cls, hook_fn: Any) -> None: ... + @classmethod + def set_reduce_ex_hook(cls, hook_fn: Any) -> None: ... + # Functional form of 'BatcherMapDataPipe' + def batch(self, batch_size: int, drop_last: bool = False, wrapper_class=DataChunk) -> MapDataPipe: + r""" + Create mini-batches of data (functional name: ``batch``). + + An outer dimension will be added as ``batch_size`` if ``drop_last`` is set to ``True``, + or ``length % batch_size`` for the last batch if ``drop_last`` is set to ``False``. + + Args: + datapipe: Iterable DataPipe being batched + batch_size: The size of each batch + drop_last: Option to drop the last batch if it's not full + + Example: + >>> # xdoctest: +SKIP + >>> from torchdata.datapipes.map import SequenceWrapper + >>> dp = SequenceWrapper(range(10)) + >>> batch_dp = dp.batch(batch_size=2) + >>> list(batch_dp) + [[0, 1], [2, 3], [4, 5], [6, 7], [8, 9]] + """ + + # Functional form of 'ConcaterMapDataPipe' + def concat(self, *datapipes: MapDataPipe) -> MapDataPipe: + r""" + Concatenate multiple Map DataPipes (functional name: ``concat``). + + The new index of is the cumulative sum of source DataPipes. + For example, if there are 2 source DataPipes both with length 5, + index 0 to 4 of the resulting `ConcatMapDataPipe` would refer to + elements of the first DataPipe, and 5 to 9 would refer to elements + of the second DataPipe. + + Args: + datapipes: Map DataPipes being concatenated + + Example: + >>> # xdoctest: +SKIP + >>> from torchdata.datapipes.map import SequenceWrapper + >>> dp1 = SequenceWrapper(range(3)) + >>> dp2 = SequenceWrapper(range(3)) + >>> concat_dp = dp1.concat(dp2) + >>> list(concat_dp) + [0, 1, 2, 0, 1, 2] + """ + + # Functional form of 'MapperMapDataPipe' + def map(self, fn: Callable= ...) -> MapDataPipe: + r""" + Apply the input function over each item from the source DataPipe (functional name: ``map``). + + The function can be any regular Python function or partial object. Lambda + function is not recommended as it is not supported by pickle. + + Args: + datapipe: Source MapDataPipe + fn: Function being applied to each item + + Example: + >>> # xdoctest: +SKIP + >>> from torchdata.datapipes.map import SequenceWrapper, Mapper + >>> def add_one(x): + ... return x + 1 + >>> dp = SequenceWrapper(range(10)) + >>> map_dp_1 = dp.map(add_one) + >>> list(map_dp_1) + [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] + >>> map_dp_2 = Mapper(dp, lambda x: x + 1) + >>> list(map_dp_2) + [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] + """ + + # Functional form of 'ShufflerIterDataPipe' + def shuffle(self, *, indices: Optional[List] = None) -> IterDataPipe: + r""" + Shuffle the input MapDataPipe via its indices (functional name: ``shuffle``). + + When it is used with :class:`~torch.utils.data.DataLoader`, the methods to + set up random seed are different based on :attr:`num_workers`. + + For single-process mode (:attr:`num_workers == 0`), the random seed is set before + the :class:`~torch.utils.data.DataLoader` in the main process. For multi-process + mode (:attr:`num_worker > 0`), ``worker_init_fn`` is used to set up a random seed + for each worker process. + + Args: + datapipe: MapDataPipe being shuffled + indices: a list of indices of the MapDataPipe. If not provided, we assume it uses 0-based indexing + + Example: + >>> # xdoctest: +SKIP + >>> from torchdata.datapipes.map import SequenceWrapper + >>> dp = SequenceWrapper(range(10)) + >>> shuffle_dp = dp.shuffle().set_seed(0) + >>> list(shuffle_dp) + [7, 8, 1, 5, 3, 4, 2, 0, 9, 6] + >>> list(shuffle_dp) + [6, 1, 9, 5, 2, 4, 7, 3, 8, 0] + >>> # Reset seed for Shuffler + >>> shuffle_dp = shuffle_dp.set_seed(0) + >>> list(shuffle_dp) + [7, 8, 1, 5, 3, 4, 2, 0, 9, 6] + + Note: + Even thought this ``shuffle`` operation takes a ``MapDataPipe`` as the input, it would return an + ``IterDataPipe`` rather than a ``MapDataPipe``, because ``MapDataPipe`` should be non-sensitive to + the order of data order for the sake of random reads, but ``IterDataPipe`` depends on the order + of data during data-processing. + """ + + # Functional form of 'ZipperMapDataPipe' + def zip(self, *datapipes: MapDataPipe[T_co]) -> MapDataPipe: + r""" + Aggregates elements into a tuple from each of the input DataPipes (functional name: ``zip``). + + This MataPipe is out of bound as soon as the shortest input DataPipe is exhausted. + + Args: + *datapipes: Map DataPipes being aggregated + + Example: + >>> # xdoctest: +SKIP + >>> from torchdata.datapipes.map import SequenceWrapper + >>> dp1 = SequenceWrapper(range(3)) + >>> dp2 = SequenceWrapper(range(10, 13)) + >>> zip_dp = dp1.zip(dp2) + >>> list(zip_dp) + [(0, 10), (1, 11), (2, 12)] + """ + + +class IterDataPipe(IterableDataset[T_co], metaclass=_IterDataPipeMeta): + functions: Dict[str, Callable] = ... + reduce_ex_hook: Optional[Callable] = ... + getstate_hook: Optional[Callable] = ... + str_hook: Optional[Callable] = ... + repr_hook: Optional[Callable] = ... + _number_of_samples_yielded: int = ... + _snapshot_state: _SnapshotState = _SnapshotState.Iterating + _fast_forward_iterator: Optional[Iterator] = ... + def __getattr__(self, attribute_name: Any): ... + @classmethod + def register_function(cls, function_name: Any, function: Any) -> None: ... + @classmethod + def register_datapipe_as_function( + cls, + function_name: Any, + cls_to_register: Any, + enable_df_api_tracing: bool = ..., + ): ... + def __getstate__(self): ... + def __reduce_ex__(self, *args: Any, **kwargs: Any): ... + @classmethod + def set_getstate_hook(cls, hook_fn: Any) -> None: ... + @classmethod + def set_reduce_ex_hook(cls, hook_fn: Any) -> None: ... + # Functional form of 'BatcherIterDataPipe' + def batch(self, batch_size: int, drop_last: bool = False, wrapper_class=DataChunk) -> IterDataPipe: + r""" + Creates mini-batches of data (functional name: ``batch``). + + An outer dimension will be added as ``batch_size`` if ``drop_last`` is set to ``True``, or ``length % batch_size`` for the + last batch if ``drop_last`` is set to ``False``. + + Args: + datapipe: Iterable DataPipe being batched + batch_size: The size of each batch + drop_last: Option to drop the last batch if it's not full + wrapper_class: wrapper to apply onto each batch (type ``List``) before yielding, + defaults to ``DataChunk`` + + Example: + >>> # xdoctest: +SKIP + >>> from torchdata.datapipes.iter import IterableWrapper + >>> dp = IterableWrapper(range(10)) + >>> dp = dp.batch(batch_size=3, drop_last=True) + >>> list(dp) + [[0, 1, 2], [3, 4, 5], [6, 7, 8]] + """ + + # Functional form of 'CollatorIterDataPipe' + def collate(self, conversion: Optional[Union[Callable[..., Any],Dict[Union[str, Any], Union[Callable, Any]],]] = default_collate, collate_fn: Optional[Callable] = None) -> IterDataPipe: + r""" + Collates samples from DataPipe to Tensor(s) by a custom collate function (functional name: ``collate``). + + By default, it uses :func:`torch.utils.data.default_collate`. + + .. note:: + While writing a custom collate function, you can import :func:`torch.utils.data.default_collate` for the + default behavior and `functools.partial` to specify any additional arguments. + + Args: + datapipe: Iterable DataPipe being collated + collate_fn: Customized collate function to collect and combine data or a batch of data. + Default function collates to Tensor(s) based on data type. + + Example: + >>> # xdoctest: +SKIP + >>> # Convert integer data to float Tensor + >>> class MyIterDataPipe(torch.utils.data.IterDataPipe): + ... def __init__(self, start, end): + ... super(MyIterDataPipe).__init__() + ... assert end > start, "this example code only works with end >= start" + ... self.start = start + ... self.end = end + ... + ... def __iter__(self): + ... return iter(range(self.start, self.end)) + ... + ... def __len__(self): + ... return self.end - self.start + ... + >>> ds = MyIterDataPipe(start=3, end=7) + >>> print(list(ds)) + [3, 4, 5, 6] + >>> def collate_fn(batch): + ... return torch.tensor(batch, dtype=torch.float) + ... + >>> collated_ds = CollateIterDataPipe(ds, collate_fn=collate_fn) + >>> print(list(collated_ds)) + [tensor(3.), tensor(4.), tensor(5.), tensor(6.)] + """ + + # Functional form of 'ConcaterIterDataPipe' + def concat(self, *datapipes: IterDataPipe) -> IterDataPipe: + r""" + Concatenates multiple Iterable DataPipes (functional name: ``concat``). + + The resulting DataPipe will yield all the elements from the first input DataPipe, before yielding from the subsequent ones. + + Args: + datapipes: Iterable DataPipes being concatenated + + Example: + >>> # xdoctest: +REQUIRES(module:torchdata) + >>> import random + >>> from torchdata.datapipes.iter import IterableWrapper + >>> dp1 = IterableWrapper(range(3)) + >>> dp2 = IterableWrapper(range(5)) + >>> list(dp1.concat(dp2)) + [0, 1, 2, 0, 1, 2, 3, 4] + """ + + # Functional form of 'DemultiplexerIterDataPipe' + def demux(self, num_instances: int, classifier_fn: Callable[[T_co], Optional[int]], drop_none: bool = False, buffer_size: int = 1000) -> List[IterDataPipe]: + r""" + Splits the input DataPipe into multiple child DataPipes, using the given classification function (functional name: ``demux``). + + A list of the child DataPipes is returned from this operation. + + Args: + datapipe: Iterable DataPipe being filtered + num_instances: number of instances of the DataPipe to create + classifier_fn: a function that maps values to an integer within the range ``[0, num_instances - 1]`` or ``None`` + drop_none: defaults to ``False``, if ``True``, the function will skip over elements classified as ``None`` + buffer_size: this defines the maximum number of inputs that the buffer can hold across all child + DataPipes while waiting for their values to be yielded. + Defaults to ``1000``. Use ``-1`` for the unlimited buffer. + + Examples: + >>> # xdoctest: +REQUIRES(module:torchdata) + >>> from torchdata.datapipes.iter import IterableWrapper + >>> def odd_or_even(n): + ... return n % 2 + >>> source_dp = IterableWrapper(range(5)) + >>> dp1, dp2 = source_dp.demux(num_instances=2, classifier_fn=odd_or_even) + >>> list(dp1) + [0, 2, 4] + >>> list(dp2) + [1, 3] + >>> # It can also filter out any element that gets `None` from the `classifier_fn` + >>> def odd_or_even_no_zero(n): + ... return n % 2 if n != 0 else None + >>> dp1, dp2 = source_dp.demux(num_instances=2, classifier_fn=odd_or_even_no_zero, drop_none=True) + >>> list(dp1) + [2, 4] + >>> list(dp2) + [1, 3] + """ + + # Functional form of 'FilterIterDataPipe' + def filter(self, filter_fn: Callable, input_col=None) -> IterDataPipe: + r""" + Filters out elements from the source datapipe according to input ``filter_fn`` (functional name: ``filter``). + + Args: + datapipe: Iterable DataPipe being filtered + filter_fn: Customized function mapping an element to a boolean. + input_col: Index or indices of data which ``filter_fn`` is applied, such as: + + - ``None`` as default to apply ``filter_fn`` to the data directly. + - Integer(s) is used for list/tuple. + - Key(s) is used for dict. + + Example: + >>> # xdoctest: +SKIP + >>> from torchdata.datapipes.iter import IterableWrapper + >>> def is_even(n): + ... return n % 2 == 0 + >>> dp = IterableWrapper(range(5)) + >>> filter_dp = dp.filter(filter_fn=is_even) + >>> list(filter_dp) + [0, 2, 4] + """ + + # Functional form of 'ForkerIterDataPipe' + def fork(self, num_instances: int, buffer_size: int = 1000, copy: Optional[Literal["shallow", "deep"]] = None) -> List[IterDataPipe]: + r""" + Creates multiple instances of the same Iterable DataPipe (functional name: ``fork``). + + Args: + datapipe: Iterable DataPipe being copied + num_instances: number of instances of the datapipe to create + buffer_size: this restricts how far ahead the leading child DataPipe + can read relative to the slowest child DataPipe. + Defaults to ``1000``. Use ``-1`` for the unlimited buffer. + copy: copy strategy to use for items yielded by each branch. Supported + options are ``None`` for no copying, ``"shallow"`` for shallow object + copies, and ``"deep"`` for deep object copies. Defaults to ``None``. + + Note: + All branches of the forked pipeline return the identical object unless + the copy parameter is supplied. If the object is mutable or contains + mutable objects, changing them in one branch will affect all others. + + Example: + >>> # xdoctest: +REQUIRES(module:torchdata) + >>> from torchdata.datapipes.iter import IterableWrapper + >>> source_dp = IterableWrapper(range(5)) + >>> dp1, dp2 = source_dp.fork(num_instances=2) + >>> list(dp1) + [0, 1, 2, 3, 4] + >>> list(dp2) + [0, 1, 2, 3, 4] + """ + + # Functional form of 'GrouperIterDataPipe' + def groupby(self, group_key_fn: Callable[[T_co], Any], *, keep_key: bool = False, buffer_size: int = 10000, group_size: Optional[int] = None, guaranteed_group_size: Optional[int] = None, drop_remaining: bool = False) -> IterDataPipe: + r""" + Groups data from IterDataPipe by keys from ``group_key_fn``, yielding a ``DataChunk`` with batch size up to ``group_size``. + + (functional name: ``groupby``). + + The samples are read sequentially from the source ``datapipe``, and a batch of samples belonging to the same group + will be yielded as soon as the size of the batch reaches ``group_size``. When the buffer is full, + the DataPipe will yield the largest batch with the same key, provided that its size is larger + than ``guaranteed_group_size``. If its size is smaller, it will be dropped if ``drop_remaining=True``. + + After iterating through the entirety of source ``datapipe``, everything not dropped due to the buffer capacity + will be yielded from the buffer, even if the group sizes are smaller than ``guaranteed_group_size``. + + Args: + datapipe: Iterable datapipe to be grouped + group_key_fn: Function used to generate group key from the data of the source datapipe + keep_key: Option to yield the matching key along with the items in a tuple, + resulting in `(key, [items])` otherwise returning [items] + buffer_size: The size of buffer for ungrouped data + group_size: The max size of each group, a batch is yielded as soon as it reaches this size + guaranteed_group_size: The guaranteed minimum group size to be yielded in case the buffer is full + drop_remaining: Specifies if the group smaller than ``guaranteed_group_size`` will be dropped from buffer + when the buffer is full + + Example: + >>> import os + >>> # xdoctest: +SKIP + >>> from torchdata.datapipes.iter import IterableWrapper + >>> def group_fn(file): + ... return os.path.basename(file).split(".")[0] + >>> source_dp = IterableWrapper(["a.png", "b.png", "a.json", "b.json", "a.jpg", "c.json"]) + >>> dp0 = source_dp.groupby(group_key_fn=group_fn) + >>> list(dp0) + [['a.png', 'a.json', 'a.jpg'], ['b.png', 'b.json'], ['c.json']] + >>> # A group is yielded as soon as its size equals to `group_size` + >>> dp1 = source_dp.groupby(group_key_fn=group_fn, group_size=2) + >>> list(dp1) + [['a.png', 'a.json'], ['b.png', 'b.json'], ['a.jpg'], ['c.json']] + >>> # Scenario where `buffer` is full, and group 'a' needs to be yielded since its size > `guaranteed_group_size` + >>> dp2 = source_dp.groupby(group_key_fn=group_fn, buffer_size=3, group_size=3, guaranteed_group_size=2) + >>> list(dp2) + [['a.png', 'a.json'], ['b.png', 'b.json'], ['a.jpg'], ['c.json']] + """ + + # Functional form of 'FileListerIterDataPipe' + def list_files(self, masks: Union[str, List[str]] = '', *, recursive: bool = False, abspath: bool = False, non_deterministic: bool = False, length: int = -1) -> IterDataPipe: + r""" + Given path(s) to the root directory, yields file pathname(s) (path + filename) of files within the root directory. + + Multiple root directories can be provided (functional name: ``list_files``). + + Args: + root: Root directory or a sequence of root directories + masks: Unix style filter string or string list for filtering file name(s) + recursive: Whether to return pathname from nested directories or not + abspath: Whether to return relative pathname or absolute pathname + non_deterministic: Whether to return pathname in sorted order or not. + If ``False``, the results yielded from each root directory will be sorted + length: Nominal length of the datapipe + + Example: + >>> # xdoctest: +SKIP + >>> from torchdata.datapipes.iter import FileLister + >>> dp = FileLister(root=".", recursive=True) + >>> list(dp) + ['example.py', './data/data.tar'] + """ + + # Functional form of 'MapperIterDataPipe' + def map(self, fn: Callable, input_col=None, output_col=None) -> IterDataPipe: + r""" + Applies a function over each item from the source DataPipe (functional name: ``map``). + + The function can be any regular Python function or partial object. Lambda + function is not recommended as it is not supported by pickle. + + Args: + datapipe: Source Iterable DataPipe + fn: Function being applied over each item + input_col: Index or indices of data which ``fn`` is applied, such as: + + - ``None`` as default to apply ``fn`` to the data directly. + - Integer(s) is used for list/tuple. + - Key(s) is used for dict. + + output_col: Index of data where result of ``fn`` is placed. ``output_col`` can be specified + only when ``input_col`` is not ``None`` + + - ``None`` as default to replace the index that ``input_col`` specified; For ``input_col`` with + multiple indices, the left-most one is used, and other indices will be removed. + - Integer is used for list/tuple. ``-1`` represents to append result at the end. + - Key is used for dict. New key is acceptable. + + Example: + >>> # xdoctest: +SKIP + >>> from torchdata.datapipes.iter import IterableWrapper, Mapper + >>> def add_one(x): + ... return x + 1 + >>> dp = IterableWrapper(range(10)) + >>> map_dp_1 = dp.map(add_one) # Invocation via functional form is preferred + >>> list(map_dp_1) + [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] + >>> # We discourage the usage of `lambda` functions as they are not serializable with `pickle` + >>> # Use `functools.partial` or explicitly define the function instead + >>> map_dp_2 = Mapper(dp, lambda x: x + 1) + >>> list(map_dp_2) + [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] + """ + + # Functional form of 'MultiplexerIterDataPipe' + def mux(self, *datapipes) -> IterDataPipe: + r""" + Yields one element at a time from each of the input Iterable DataPipes (functional name: ``mux``). + + As in, one element from the 1st input DataPipe, then one element from the 2nd DataPipe in the next iteration, + and so on. It ends when the shortest input DataPipe is exhausted. + + Args: + datapipes: Iterable DataPipes that will take turn to yield their elements, until the shortest DataPipe is exhausted + + Example: + >>> # xdoctest: +REQUIRES(module:torchdata) + >>> from torchdata.datapipes.iter import IterableWrapper + >>> dp1, dp2, dp3 = IterableWrapper(range(3)), IterableWrapper(range(10, 15)), IterableWrapper(range(20, 25)) + >>> list(dp1.mux(dp2, dp3)) + [0, 10, 20, 1, 11, 21, 2, 12, 22] + """ + + # Functional form of 'FileOpenerIterDataPipe' + def open_files(self, mode: str = 'r', encoding: Optional[str] = None, length: int = -1) -> IterDataPipe: + r""" + Given pathnames, opens files and yield pathname and file stream in a tuple (functional name: ``open_files``). + + Args: + datapipe: Iterable datapipe that provides pathnames + mode: An optional string that specifies the mode in which + the file is opened by ``open()``. It defaults to ``r``, other options are + ``b`` for reading in binary mode and ``t`` for text mode. + encoding: An optional string that specifies the encoding of the + underlying file. It defaults to ``None`` to match the default encoding of ``open``. + length: Nominal length of the datapipe + + Note: + The opened file handles will be closed by Python's GC periodically. Users can choose + to close them explicitly. + + Example: + >>> # xdoctest: +SKIP + >>> from torchdata.datapipes.iter import FileLister, FileOpener, StreamReader + >>> dp = FileLister(root=".").filter(lambda fname: fname.endswith('.txt')) + >>> dp = FileOpener(dp) + >>> dp = StreamReader(dp) + >>> list(dp) + [('./abc.txt', 'abc')] + """ + + # Functional form of 'StreamReaderIterDataPipe' + def read_from_stream(self, chunk=None) -> IterDataPipe: + r""" + Given IO streams and their label names, yield bytes with label name as tuple. + + (functional name: ``read_from_stream``). + + Args: + datapipe: Iterable DataPipe provides label/URL and byte stream + chunk: Number of bytes to be read from stream per iteration. + If ``None``, all bytes will be read until the EOF. + + Example: + >>> # xdoctest: +SKIP + >>> from torchdata.datapipes.iter import IterableWrapper, StreamReader + >>> from io import StringIO + >>> dp = IterableWrapper([("alphabet", StringIO("abcde"))]) + >>> list(StreamReader(dp, chunk=1)) + [('alphabet', 'a'), ('alphabet', 'b'), ('alphabet', 'c'), ('alphabet', 'd'), ('alphabet', 'e')] + """ + + # Functional form of 'RoutedDecoderIterDataPipe' + def routed_decode(self, *handlers: Callable, key_fn: Callable= ...) -> IterDataPipe: + r""" + Decodes binary streams from input DataPipe, yields pathname and decoded data in a tuple. + + (functional name: ``routed_decode``) + + Args: + datapipe: Iterable datapipe that provides pathname and binary stream in tuples + handlers: Optional user defined decoder handlers. If ``None``, basic and image decoder + handlers will be set as default. If multiple handles are provided, the priority + order follows the order of handlers (the first handler has the top priority) + key_fn: Function for decoder to extract key from pathname to dispatch handlers. + Default is set to extract file extension from pathname + + Note: + When ``key_fn`` is specified returning anything other than extension, the default + handler will not work and users need to specify custom handler. Custom handler + could use regex to determine the eligibility to handle data. + """ + + # Functional form of 'ShardingFilterIterDataPipe' + def sharding_filter(self, sharding_group_filter=None) -> IterDataPipe: + r""" + Wrapper that allows DataPipe to be sharded (functional name: ``sharding_filter``). + + After ``apply_sharding`` is called, each instance of the DataPipe (on different workers) will have every `n`-th element of the + original DataPipe, where `n` equals to the number of instances. + + Args: + source_datapipe: Iterable DataPipe that will be sharded + """ + + # Functional form of 'ShufflerIterDataPipe' + def shuffle(self, *, buffer_size: int = 10000, unbatch_level: int = 0) -> IterDataPipe: + r""" + Shuffle the input DataPipe with a buffer (functional name: ``shuffle``). + + The buffer with ``buffer_size`` is filled with elements from the datapipe first. Then, + each item will be yielded from the buffer by reservoir sampling via iterator. + + ``buffer_size`` is required to be larger than ``0``. For ``buffer_size == 1``, the + datapipe is not shuffled. In order to fully shuffle all elements from datapipe, + ``buffer_size`` is required to be greater than or equal to the size of datapipe. + + When it is used with :class:`torch.utils.data.DataLoader`, the methods to + set up random seed are different based on :attr:`num_workers`. + + For single-process mode (:attr:`num_workers == 0`), the random seed is set before + the :class:`~torch.utils.data.DataLoader` in the main process. For multi-process + mode (:attr:`num_worker > 0`), `worker_init_fn` is used to set up a random seed + for each worker process. + + Args: + datapipe: The IterDataPipe being shuffled + buffer_size: The buffer size for shuffling (default to ``10000``) + unbatch_level: Specifies if it is necessary to unbatch source data before + applying the shuffle + + Example: + >>> # xdoctest: +SKIP + >>> from torchdata.datapipes.iter import IterableWrapper + >>> dp = IterableWrapper(range(10)) + >>> shuffle_dp = dp.shuffle() + >>> list(shuffle_dp) + [0, 4, 1, 6, 3, 2, 9, 5, 7, 8] + """ + + # Functional form of 'UnBatcherIterDataPipe' + def unbatch(self, unbatch_level: int = 1) -> IterDataPipe: + r""" + Undos batching of data (functional name: ``unbatch``). + + In other words, it flattens the data up to the specified level within a batched DataPipe. + + Args: + datapipe: Iterable DataPipe being un-batched + unbatch_level: Defaults to ``1`` (only flattening the top level). If set to ``2``, + it will flatten the top two levels, and ``-1`` will flatten the entire DataPipe. + + Example: + >>> # xdoctest: +SKIP + >>> from torchdata.datapipes.iter import IterableWrapper + >>> source_dp = IterableWrapper([[[0, 1], [2]], [[3, 4], [5]], [[6]]]) + >>> dp1 = source_dp.unbatch() + >>> list(dp1) + [[0, 1], [2], [3, 4], [5], [6]] + >>> dp2 = source_dp.unbatch(unbatch_level=2) + >>> list(dp2) + [0, 1, 2, 3, 4, 5, 6] + """ + + # Functional form of 'ZipperIterDataPipe' + def zip(self, *datapipes: IterDataPipe) -> IterDataPipe: + r""" + Aggregates elements into a tuple from each of the input DataPipes (functional name: ``zip``). + + The output is stopped as soon as the shortest input DataPipe is exhausted. + + Args: + *datapipes: Iterable DataPipes being aggregated + + Example: + >>> # xdoctest: +REQUIRES(module:torchdata) + >>> from torchdata.datapipes.iter import IterableWrapper + >>> dp1, dp2, dp3 = IterableWrapper(range(5)), IterableWrapper(range(10, 15)), IterableWrapper(range(20, 25)) + >>> list(dp1.zip(dp2, dp3)) + [(0, 10, 20), (1, 11, 21), (2, 12, 22), (3, 13, 23), (4, 14, 24)] + """ + + +class DFIterDataPipe(IterDataPipe): + def _is_dfpipe(self): ... + def __iter__(self): ... + +class _DataPipeSerializationWrapper: + def __init__(self, datapipe): ... + def __getstate__(self): ... + def __setstate__(self, state): ... + def __len__(self): ... + +class _IterDataPipeSerializationWrapper(_DataPipeSerializationWrapper, IterDataPipe): + def __iter__(self): ... + +class _MapDataPipeSerializationWrapper(_DataPipeSerializationWrapper, MapDataPipe): + def __getitem__(self, idx): ... + +class DataChunk(list, Generic[T]): + def __init__(self, items): + super().__init__(items) + self.items = items + def as_str(self, indent: str = "") -> str: + res = indent + "[" + ", ".join(str(i) for i in iter(self)) + "]" + return res + def __iter__(self) -> Iterator[T]: + yield from super().__iter__() + def raw_iterator(self) -> T: # type: ignore[misc] + yield from self.items diff --git a/shared/package-files/00/00b8bfc90e316e90a5f33fc7313afe435c9299135759443ffece8e9796d46811/blob b/shared/package-files/00/00b8bfc90e316e90a5f33fc7313afe435c9299135759443ffece8e9796d46811/blob new file mode 100644 index 0000000000000000000000000000000000000000..445c5cabf8a8d377fac0b45c910a65dfe966a607 --- /dev/null +++ b/shared/package-files/00/00b8bfc90e316e90a5f33fc7313afe435c9299135759443ffece8e9796d46811/blob @@ -0,0 +1,24 @@ +#pragma once +// @generated by torchgen/gen.py from DispatchKeyFunction.h + +// NB: The implementing C++ file is RegisterDispatchKey.cpp + +// The only #includes we need are for custom classes that have defaults in the C++ API +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { + +namespace compositeimplicitautograd { + +TORCH_API at::Tensor argsort(const at::Tensor & self, int64_t dim=-1, bool descending=false); +TORCH_API at::Tensor argsort(const at::Tensor & self, at::Dimname dim, bool descending=false); + +} // namespace compositeimplicitautograd +} // namespace at diff --git a/shared/package-files/00/00bd32de69cbd0a8143a0c48833de605c7d710b04465a7e373a808c3a5988d55/blob b/shared/package-files/00/00bd32de69cbd0a8143a0c48833de605c7d710b04465a7e373a808c3a5988d55/blob new file mode 100644 index 0000000000000000000000000000000000000000..f443578dc3173485413cb72cc636302660e398cc Binary files /dev/null and b/shared/package-files/00/00bd32de69cbd0a8143a0c48833de605c7d710b04465a7e373a808c3a5988d55/blob differ diff --git a/shared/package-files/00/00bf278ce2f98438481aae6d8d1c5f173657c507531a5cf982cf60e114e86e56/blob b/shared/package-files/00/00bf278ce2f98438481aae6d8d1c5f173657c507531a5cf982cf60e114e86e56/blob new file mode 100644 index 0000000000000000000000000000000000000000..84df7e7d697616076d549dc4163b55cd34335a25 --- /dev/null +++ b/shared/package-files/00/00bf278ce2f98438481aae6d8d1c5f173657c507531a5cf982cf60e114e86e56/blob @@ -0,0 +1,8 @@ +# NOTE: +# The entire `torchaudio.backend` module is deprecated. +# New things should be added to `torchaudio._backend`. +# Only things related to backward compatibility should be placed here. + +from . import common, no_backend, soundfile_backend, sox_io_backend # noqa + +__all__ = [] diff --git a/shared/package-files/00/00bf38a14516407c2477c3823e12d1a363498d4e4c0dd99732a447bfea68b2ab/blob b/shared/package-files/00/00bf38a14516407c2477c3823e12d1a363498d4e4c0dd99732a447bfea68b2ab/blob new file mode 100644 index 0000000000000000000000000000000000000000..cd04599789742039ac2f3b2b5cd60ce7a6d81c71 --- /dev/null +++ b/shared/package-files/00/00bf38a14516407c2477c3823e12d1a363498d4e4c0dd99732a447bfea68b2ab/blob @@ -0,0 +1 @@ +{"is_release": false, "git_version": "8608a46"} \ No newline at end of file diff --git a/shared/package-files/00/00c1187ed26886613ce006b2a92027d025db01bd9a73f4002ff3926e33ac149c/blob b/shared/package-files/00/00c1187ed26886613ce006b2a92027d025db01bd9a73f4002ff3926e33ac149c/blob new file mode 100644 index 0000000000000000000000000000000000000000..14f45ba9675f5e6b188d3dfdd1c06bdf4136f0ca --- /dev/null +++ b/shared/package-files/00/00c1187ed26886613ce006b2a92027d025db01bd9a73f4002ff3926e33ac149c/blob @@ -0,0 +1,110 @@ +import numpy as np + + +from cython cimport floating +from libc.math cimport exp, fabs, log + +from ..utils._typedefs cimport float64_t, intp_t + + +def mean_change(const floating[:] arr_1, const floating[:] arr_2): + """Calculate the mean difference between two arrays. + + Equivalent to np.abs(arr_1 - arr2).mean(). + """ + + cdef float64_t total, diff + cdef intp_t i, size + + size = arr_1.shape[0] + total = 0.0 + for i in range(size): + diff = fabs(arr_1[i] - arr_2[i]) + total += diff + + return total / size + + +def _dirichlet_expectation_1d( + floating[:] doc_topic, + floating doc_topic_prior, + floating[:] out +): + """Dirichlet expectation for a single sample: + exp(E[log(theta)]) for theta ~ Dir(doc_topic) + after adding doc_topic_prior to doc_topic, in-place. + + Equivalent to + doc_topic += doc_topic_prior + out[:] = np.exp(psi(doc_topic) - psi(np.sum(doc_topic))) + """ + + cdef floating dt, psi_total, total + cdef intp_t i, size + + size = doc_topic.shape[0] + + total = 0.0 + for i in range(size): + dt = doc_topic[i] + doc_topic_prior + doc_topic[i] = dt + total += dt + psi_total = psi(total) + + for i in range(size): + out[i] = exp(psi(doc_topic[i]) - psi_total) + + +def _dirichlet_expectation_2d(const floating[:, :] arr): + """Dirichlet expectation for multiple samples: + E[log(theta)] for theta ~ Dir(arr). + + Equivalent to psi(arr) - psi(np.sum(arr, axis=1))[:, np.newaxis]. + + Note that unlike _dirichlet_expectation_1d, this function doesn't compute + the exp and doesn't add in the prior. + """ + cdef floating row_total, psi_row_total + cdef floating[:, :] d_exp + cdef intp_t i, j, n_rows, n_cols + + n_rows = arr.shape[0] + n_cols = arr.shape[1] + + d_exp = np.empty_like(arr) + for i in range(n_rows): + row_total = 0 + for j in range(n_cols): + row_total += arr[i, j] + psi_row_total = psi(row_total) + + for j in range(n_cols): + d_exp[i, j] = psi(arr[i, j]) - psi_row_total + + return d_exp.base + + +# Psi function for positive arguments. Optimized for speed, not accuracy. +# +# After: J. Bernardo (1976). Algorithm AS 103: Psi (Digamma) Function. +# https://www.uv.es/~bernardo/1976AppStatist.pdf +cdef floating psi(floating x) noexcept nogil: + cdef double EULER = 0.577215664901532860606512090082402431 + if x <= 1e-6: + # psi(x) = -EULER - 1/x + O(x) + return -EULER - 1. / x + + cdef floating r, result = 0 + + # psi(x + 1) = psi(x) + 1/x + while x < 6: + result -= 1. / x + x += 1 + + # psi(x) = log(x) - 1/(2x) - 1/(12x**2) + 1/(120x**4) - 1/(252x**6) + # + O(1/x**8) + r = 1. / x + result += log(x) - .5 * r + r = r * r + result -= r * ((1./12.) - r * ((1./120.) - r * (1./252.))) + return result diff --git a/shared/package-files/00/00c77a86ebe23e1ff0f9eae1a3aced70d225769d5948962e0ad72fde3b3e67b2/blob b/shared/package-files/00/00c77a86ebe23e1ff0f9eae1a3aced70d225769d5948962e0ad72fde3b3e67b2/blob new file mode 100644 index 0000000000000000000000000000000000000000..109d354ac1566e67be6ece483d7fe65fee9de58e --- /dev/null +++ b/shared/package-files/00/00c77a86ebe23e1ff0f9eae1a3aced70d225769d5948962e0ad72fde3b3e67b2/blob @@ -0,0 +1,39 @@ +#pragma once + +// @generated by torchgen/gen.py from Operator.h + +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { +namespace _ops { + + +struct TORCH_API soft_margin_loss_out { + using schema = at::Tensor & (const at::Tensor &, const at::Tensor &, int64_t, at::Tensor &); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::soft_margin_loss") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "out") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "soft_margin_loss.out(Tensor self, Tensor target, int reduction=Mean, *, Tensor(a!) out) -> Tensor(a!)") + static at::Tensor & call(const at::Tensor & self, const at::Tensor & target, int64_t reduction, at::Tensor & out); + static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, const at::Tensor & target, int64_t reduction, at::Tensor & out); +}; + +struct TORCH_API soft_margin_loss { + using schema = at::Tensor (const at::Tensor &, const at::Tensor &, int64_t); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::soft_margin_loss") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "soft_margin_loss(Tensor self, Tensor target, int reduction=Mean) -> Tensor") + static at::Tensor call(const at::Tensor & self, const at::Tensor & target, int64_t reduction); + static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, const at::Tensor & target, int64_t reduction); +}; + +}} // namespace at::_ops diff --git a/shared/package-files/00/00d24093a59d0d2188bcb96f9a99ef37e85a956264b3633814889cc4d15075d1/blob b/shared/package-files/00/00d24093a59d0d2188bcb96f9a99ef37e85a956264b3633814889cc4d15075d1/blob new file mode 100644 index 0000000000000000000000000000000000000000..724242bd5929ba52fe380f361cbdbe6cb32b9a6a --- /dev/null +++ b/shared/package-files/00/00d24093a59d0d2188bcb96f9a99ef37e85a956264b3633814889cc4d15075d1/blob @@ -0,0 +1,39 @@ +#pragma once + +// @generated by torchgen/gen.py from Operator.h + +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { +namespace _ops { + + +struct TORCH_API indices_copy { + using schema = at::Tensor (const at::Tensor &); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::indices_copy") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "indices_copy(Tensor self) -> Tensor") + static at::Tensor call(const at::Tensor & self); + static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self); +}; + +struct TORCH_API indices_copy_out { + using schema = at::Tensor & (const at::Tensor &, at::Tensor &); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::indices_copy") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "out") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "indices_copy.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!)") + static at::Tensor & call(const at::Tensor & self, at::Tensor & out); + static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, at::Tensor & out); +}; + +}} // namespace at::_ops diff --git a/shared/package-files/00/00d2a7d928ab651036007699a020c7081d408cb12e51381753699723a9f74efc/blob b/shared/package-files/00/00d2a7d928ab651036007699a020c7081d408cb12e51381753699723a9f74efc/blob new file mode 100644 index 0000000000000000000000000000000000000000..c670921decb78808fa54a35c45e3d2d15ab57a67 --- /dev/null +++ b/shared/package-files/00/00d2a7d928ab651036007699a020c7081d408cb12e51381753699723a9f74efc/blob @@ -0,0 +1,11 @@ +from pandas import Index +import pandas._testing as tm + + +def test_pickle_preserves_object_dtype(): + # GH#43188, GH#43155 don't infer numeric dtype + index = Index([1, 2, 3], dtype=object) + + result = tm.round_trip_pickle(index) + assert result.dtype == object + tm.assert_index_equal(index, result) diff --git a/shared/package-files/00/00d3d4de291b940752f8f7fc4d0dc0959237d2cf314ed3f0f8f4e55e671a5a16/blob b/shared/package-files/00/00d3d4de291b940752f8f7fc4d0dc0959237d2cf314ed3f0f8f4e55e671a5a16/blob new file mode 100644 index 0000000000000000000000000000000000000000..623d81a9c4b678943c071f52545cd263740a62d1 --- /dev/null +++ b/shared/package-files/00/00d3d4de291b940752f8f7fc4d0dc0959237d2cf314ed3f0f8f4e55e671a5a16/blob @@ -0,0 +1,91 @@ +#pragma once + +// @generated by torchgen/gen.py from Function.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + + +#include + +namespace at { + + +// aten::adaptive_avg_pool3d.out(Tensor self, SymInt[3] output_size, *, Tensor(a!) out) -> Tensor(a!) +inline at::Tensor & adaptive_avg_pool3d_out(at::Tensor & out, const at::Tensor & self, at::IntArrayRef output_size) { + return at::_ops::adaptive_avg_pool3d_out::call(self, c10::fromIntArrayRefSlow(output_size), out); +} +namespace symint { + template ::value>> + at::Tensor & adaptive_avg_pool3d_out(at::Tensor & out, const at::Tensor & self, at::IntArrayRef output_size) { + return at::_ops::adaptive_avg_pool3d_out::call(self, c10::fromIntArrayRefSlow(output_size), out); + } +} + +// aten::adaptive_avg_pool3d.out(Tensor self, SymInt[3] output_size, *, Tensor(a!) out) -> Tensor(a!) +inline at::Tensor & adaptive_avg_pool3d_outf(const at::Tensor & self, at::IntArrayRef output_size, at::Tensor & out) { + return at::_ops::adaptive_avg_pool3d_out::call(self, c10::fromIntArrayRefSlow(output_size), out); +} +namespace symint { + template ::value>> + at::Tensor & adaptive_avg_pool3d_outf(const at::Tensor & self, at::IntArrayRef output_size, at::Tensor & out) { + return at::_ops::adaptive_avg_pool3d_out::call(self, c10::fromIntArrayRefSlow(output_size), out); + } +} + +// aten::adaptive_avg_pool3d.out(Tensor self, SymInt[3] output_size, *, Tensor(a!) out) -> Tensor(a!) +inline at::Tensor & adaptive_avg_pool3d_symint_out(at::Tensor & out, const at::Tensor & self, c10::SymIntArrayRef output_size) { + return at::_ops::adaptive_avg_pool3d_out::call(self, output_size, out); +} +namespace symint { + template ::value>> + at::Tensor & adaptive_avg_pool3d_out(at::Tensor & out, const at::Tensor & self, c10::SymIntArrayRef output_size) { + return at::_ops::adaptive_avg_pool3d_out::call(self, output_size, out); + } +} + +// aten::adaptive_avg_pool3d.out(Tensor self, SymInt[3] output_size, *, Tensor(a!) out) -> Tensor(a!) +inline at::Tensor & adaptive_avg_pool3d_symint_outf(const at::Tensor & self, c10::SymIntArrayRef output_size, at::Tensor & out) { + return at::_ops::adaptive_avg_pool3d_out::call(self, output_size, out); +} +namespace symint { + template ::value>> + at::Tensor & adaptive_avg_pool3d_outf(const at::Tensor & self, c10::SymIntArrayRef output_size, at::Tensor & out) { + return at::_ops::adaptive_avg_pool3d_out::call(self, output_size, out); + } +} + +// aten::adaptive_avg_pool3d(Tensor self, SymInt[3] output_size) -> Tensor +inline at::Tensor adaptive_avg_pool3d(const at::Tensor & self, at::IntArrayRef output_size) { + return at::_ops::adaptive_avg_pool3d::call(self, c10::fromIntArrayRefSlow(output_size)); +} +namespace symint { + template ::value>> + at::Tensor adaptive_avg_pool3d(const at::Tensor & self, at::IntArrayRef output_size) { + return at::_ops::adaptive_avg_pool3d::call(self, c10::fromIntArrayRefSlow(output_size)); + } +} + +// aten::adaptive_avg_pool3d(Tensor self, SymInt[3] output_size) -> Tensor +inline at::Tensor adaptive_avg_pool3d_symint(const at::Tensor & self, c10::SymIntArrayRef output_size) { + return at::_ops::adaptive_avg_pool3d::call(self, output_size); +} +namespace symint { + template ::value>> + at::Tensor adaptive_avg_pool3d(const at::Tensor & self, c10::SymIntArrayRef output_size) { + return at::_ops::adaptive_avg_pool3d::call(self, output_size); + } +} + +} diff --git a/shared/package-files/00/00d89a4d7f6835608b53f5c58d6f9c763699bee692832b0659c0696e22c0f439/blob b/shared/package-files/00/00d89a4d7f6835608b53f5c58d6f9c763699bee692832b0659c0696e22c0f439/blob new file mode 100644 index 0000000000000000000000000000000000000000..d94e4723dba3828cff886148eacc5707def8ab5c --- /dev/null +++ b/shared/package-files/00/00d89a4d7f6835608b53f5c58d6f9c763699bee692832b0659c0696e22c0f439/blob @@ -0,0 +1,799 @@ +from __future__ import annotations + +import collections +import dataclasses +import itertools +import pprint +from typing import Any, Dict, Iterable, List, Optional, Protocol + +import sympy + +import torch +from .. import config, ir +from ..utils import cache_on_self, CachedMethod, IndentedBuffer +from ..virtualized import V + +from .wrapper import ( + AllocateLine, + FreeIfNotReusedLine, + MemoryPlanningLine, + NullLine, + ReuseLine, +) + + +ALIGN_BYTES = 64 +assert (ALIGN_BYTES & (ALIGN_BYTES - 1)) == 0 and ALIGN_BYTES >= 8, "must be power of 2" + + +def _align(nbytes): + """Round up to the nearest multiple of ALIGN_BYTES""" + return (nbytes + ALIGN_BYTES - 1) & -ALIGN_BYTES + + +def _is_aligned(v: sympy.Expr): + """v can be statically proven to be a multiple of ALIGN_BYTES""" + if isinstance(v, (sympy.Add, sympy.Max)): + return all(map(_is_aligned, v.args)) + return isinstance(v, align) or sympy.gcd(v, ALIGN_BYTES) == ALIGN_BYTES + + +class align(sympy.Function): + """Symbolically round up to the nearest multiple of ALIGN_BYTES""" + + nargs = (1,) + is_integer = True + + @classmethod + def eval(cls, value): + if isinstance(value, (int, sympy.Integer)): + return _align(int(value)) + if _is_aligned(value): + return value + + +@dataclasses.dataclass +class LiveRange: + """ + A range where a given tensor is live. Begin and end are both counters + representing points in the program of grouped memory operations. + Begin is inclusive, end is exclusive. + + Invariant: begin <= end + """ + + begin: float # int | ±inf + end: float # int | ±inf + + def contains(self, other: LiveRange): + """Is other entirely within self""" + return self.begin <= other.begin and other.end <= self.end + + def join(self, other: LiveRange): + """Combine two ranges using a union operation""" + return LiveRange(min(self.begin, other.begin), max(self.end, other.end)) + + def __len__(self): + return self.end - self.begin + + +class LiveRanges: + """ + A collection of LiveRange regions, allowing for non-contiguous + live regions. + + Invariant: LiveRanges.ranges is in sorted order and non-overlapping + """ + + def __init__(self, ranges: Iterable[LiveRange]): + ranges = [*sorted(ranges, key=lambda x: x.begin)] + self.ranges = ranges[:1] + for r in ranges[1:]: + assert self.ranges[-1].begin <= r.begin + if self.ranges[-1].end >= r.begin: + self.ranges[-1] = LiveRange.join(self.ranges[-1], r) + else: + self.ranges.append(r) + + def overlaps(self, other: LiveRanges): + """Check if any pair of ranges in self and other overlap""" + left = collections.deque(self.ranges) + right = collections.deque(other.ranges) + while left and right: + if left[0].begin > right[0].begin: + left, right = right, left + assert left[0].begin <= right[0].begin + if left[0].end > right[0].begin: + return True + left.popleft() + return False + + @property + def begin(self): + return self.ranges[0].begin + + @property + def end(self): + return self.ranges[-1].end + + def __repr__(self): + return f"{self.__class__.__name__}([{', '.join(map(repr, self.ranges))}])" + + +class AllocationTreeNode: + """ + Abstract base class for nodes in allocation pool. + """ + + def allocate(self, block: Allocation, is_last: bool) -> bool: + """ + Try to assign block to a memory location in this bool. Return True if + an assignment was made. + """ + return False + + def get_live_ranges(self) -> LiveRanges: + """Aggregate LiveRanges for all objects below this in tree""" + raise NotImplementedError() + + def get_size_hint(self) -> int: + """Number of bytes used for example inputs""" + raise NotImplementedError() + + def get_symbolic_size(self) -> sympy.Expr: + """Number of bytes needed at runtime""" + raise NotImplementedError() + + def finalize(self, pool, offset) -> AllocationTreeNode: + """Called after all allocations have been made""" + return self + + def is_empty(self): + return False + + +@dataclasses.dataclass +class Allocation(AllocationTreeNode): + """ + Represents memory allocated to a given node in the allocation pool. + """ + + node: ir.Buffer + live_range: LiveRange + size_hint: int + symbolic_size: sympy.Expr + allocated: bool = False + pool: Optional[AllocationPool] = None + offset: Optional[sympy.Expr] = None + + @property + def device(self): + return self.node.get_device() + + def get_live_ranges(self): + return LiveRanges([self.live_range]) + + def get_size_hint(self): + return self.size_hint + + def get_symbolic_size(self): + return self.symbolic_size + + def mark_allocated(self): + assert not self.allocated + self.allocated = True + + def finalize(self, pool, offset): + assert self.pool is None and self.offset is None + self.pool = pool + self.offset = offset + return self + + def codegen_alloc_from_pool(self, wrapper): + assert self.pool + node = self.node + shape = tuple(node.get_size()) + stride = tuple(node.get_stride()) + return wrapper.codegen_alloc_from_pool( + self.pool.name, self.offset, node.get_dtype(), shape, stride + ) + + def __repr__(self): + return ( + f"{self.__class__.__name__}(" + f"node={self.node.get_name()}, " + f"live_range={self.live_range}, " + f"size_hint={self.size_hint}, " + f"symbolic_size={self.symbolic_size}, " + f"pool={self.pool.name if self.pool else None}, " + f"offset={self.offset})" + ) + + +@dataclasses.dataclass +class Empty(AllocationTreeNode): + """ + Placeholder to represent empty space in the allocation pool. + Only exists to get the size_hint correct in parent nodes. + """ + + size_hint: int + + def get_live_ranges(self): + return LiveRanges([]) + + def get_size_hint(self): + return self.size_hint + + def get_symbolic_size(self): + return 0 + + def is_empty(self): + return True + + +class MemorySplitProtocol(Protocol): + get_live_ranges: CachedMethod[[], LiveRanges] + get_size_hint: CachedMethod[[], int] + get_symbolic_size: CachedMethod[[], sympy.Expr] + + def _allocate(self, block: Allocation, is_last: bool) -> bool: + ... + + +class ClearCacheOnAllocateMixin(MemorySplitProtocol): + """ + Helper to assist in caching get_live_ranges, get_size_hint, and + get_symbolic_size. + """ + + def allocate(self, block: Allocation, is_last: bool): + is_allocated = self._allocate(block, is_last) + if is_allocated: + self.clear_cache() + return is_allocated + + def clear_cache(self): + self.get_live_ranges.clear_cache(self) + self.get_size_hint.clear_cache(self) + self.get_symbolic_size.clear_cache(self) + + +@dataclasses.dataclass +class TemporalSplit(ClearCacheOnAllocateMixin, AllocationTreeNode): + """ + Contains a list of allocations not overlapping in LiveRanges. + + Invariant: no pair (a,b) in self.allocations will have: + a.get_live_ranges().overlaps(b.get_live_ranges()) + """ + + allocations: List[AllocationTreeNode] + + def _allocate(self, block: Allocation, is_last: bool): + slot_size = self.get_size_hint() + block_size = block.get_size_hint() + if not is_last and block_size > slot_size: + return False # doesn't fit + + block_live = block.get_live_ranges() + overlapping = [ + s for s in self.allocations if s.get_live_ranges().overlaps(block_live) + ] + if len(overlapping) > 1: + # TODO(jansel): we could try harder here by merging overlapping in space + return False + elif len(overlapping) == 1: + return overlapping[0].allocate(block, is_last) + else: + block.mark_allocated() + + if len(self.allocations) == 1 and isinstance(self.allocations[-1], Empty): + self.allocations.pop() + + if slot_size == block_size: + # perfect fit + self.allocations.append(block) + elif slot_size > block_size: + self.allocations.append( + SpatialSplit.create(block, slot_size - block_size) + ) + else: # grow this allocation + assert is_last + self.allocations = [ + *( + SpatialSplit.create(a, block_size - slot_size) + for a in self.allocations + ), + block, + ] + return True + + @cache_on_self + def get_live_ranges(self) -> LiveRanges: + return LiveRanges( + itertools.chain.from_iterable( + x.get_live_ranges().ranges for x in self.allocations + ) + ) + + @cache_on_self + def get_size_hint(self) -> int: + if not self.allocations: + return 0 + return max(x.get_size_hint() for x in self.allocations) + + @cache_on_self + def get_symbolic_size(self) -> sympy.Expr: + if not self.allocations: + return 0 # type: ignore[return-value] + return sympy.Max(*[x.get_symbolic_size() for x in self.allocations]) + + def is_empty(self): + return len(self.allocations) == 1 and self.allocations[0].is_empty() + + def finalize(self, pool, offset): + self.allocations = [block.finalize(pool, offset) for block in self.allocations] + self.clear_cache() + if len(self.allocations) == 1: + return self.allocations[0] + return self + + +@dataclasses.dataclass +class SpatialSplit(ClearCacheOnAllocateMixin, AllocationTreeNode): + """ + Contains two allocations, left and right, that do not overlap in space. + Right will be allocated immediately after left in memory. + """ + + left: TemporalSplit + right: TemporalSplit + + @staticmethod + def create(left, extra_space): + assert isinstance(left, AllocationTreeNode) + assert isinstance(extra_space, int) and extra_space >= 1 + return SpatialSplit(TemporalSplit([left]), TemporalSplit([Empty(extra_space)])) + + def _allocate(self, block: Allocation, is_last: bool): + return self.left.allocate(block, False) or self.right.allocate(block, is_last) + + @cache_on_self + def get_live_ranges(self): + return LiveRanges( + itertools.chain( + self.left.get_live_ranges().ranges, self.right.get_live_ranges().ranges + ) + ) + + @cache_on_self + def get_size_hint(self) -> int: + return _align(self.left.get_size_hint()) + self.right.get_size_hint() + + @cache_on_self + def get_symbolic_size(self) -> sympy.Expr: + return align(self.left.get_symbolic_size()) + self.right.get_symbolic_size() + + def finalize(self, pool, offset): + self.left = self.left.finalize(pool, offset) + self.right = self.right.finalize( + pool, offset + align(self.left.get_symbolic_size()) + ) + self.clear_cache() + if self.right.is_empty(): + return self.left + return self + + +@dataclasses.dataclass +class AllocationPool: + """ + Represents a pool of allocations that will be generated by a single + call to torch.empty. + """ + + device: torch.device + root: TemporalSplit + can_expand: bool = True + restrict_live_range: Optional[LiveRange] = None + name: Optional[str] = None + names_to_del: List[str] = dataclasses.field(default_factory=list) + creation_cache: Dict[str, str] = dataclasses.field(default_factory=dict) + + def allocate(self, block: Allocation, is_last: bool): + if self.restrict_live_range and not self.restrict_live_range.contains( + block.live_range + ): + return False + + is_last = self.can_expand and is_last + if self.root.allocate(block, is_last): + return True + + if is_last: + return self.allocate_at_end(block) + + return False + + def allocate_at_end(self, block): + block.mark_allocated() + self.root = TemporalSplit([SpatialSplit(self.root, TemporalSplit([block]))]) + return True + + def finalize(self, name): + assert not self.name + self.name = name + self.names_to_del.append(name) + self.root.finalize(self, 0) + + def codegen_create(self, wrapper, code: IndentedBuffer): + assert self.name + nbytes = self.root.get_symbolic_size() + for block in self.root.allocations: + if isinstance(block, Allocation) and nbytes == block.get_symbolic_size(): + # optimization: fuse first allocation and pool creation + node = block.node + code.writeline( + wrapper.make_allocation( + self.name, + device=self.device, + dtype=node.get_dtype(), + shape=tuple(node.get_size()), + stride=tuple(node.get_stride()), + ) + ) + self.creation_cache[block.codegen_alloc_from_pool(wrapper)] = self.name + return + else: + code.writeline( + wrapper.make_allocation( + self.name, + device=self.device, + dtype=torch.uint8, + shape=(nbytes,), + stride=(1,), + ) + ) + + def codegen_destroy(self, wrapper, code: IndentedBuffer): + code.writeline(wrapper.make_free_by_names(self.names_to_del)) + + def __eq__(self, other): + return self is other + + def __hash__(self): + return id(self) + + +@dataclasses.dataclass +class AllocationPools: + """ + Collection of many AllocationPool objects grouped by device. + """ + + device_to_pools: Dict[torch.device, List[AllocationPool]] = dataclasses.field( + default_factory=dict + ) + + def get_pools(self, block): + if block.device not in self.device_to_pools: + self.device_to_pools[block.device] = [] + return self.device_to_pools[block.device] + + def allocate(self, block: Allocation): + pools = self.get_pools(block) + + for pool in pools: + if pool.allocate(block, is_last=pool is pools[-1]): + return + + # everything is full, make a new pool + pools.append( + AllocationPool( + block.device, + TemporalSplit([block]), + can_expand=config.memory_pool != "none", + ) + ) + block.mark_allocated() + + def allocate_output(self, block: Allocation): + """Outputs get different pools so memory gets freed properly""" + pools = self.get_pools(block) + if pools and config.memory_pool in ("outputs", "combined"): + pools[-1].allocate_at_end(block) + else: + # create a new pool + block.mark_allocated() + pools.append( + AllocationPool( + block.device, + TemporalSplit([block]), + can_expand=config.memory_pool == "combined", + ) + ) + + def finalize(self): + """Called at the end of allocation process""" + for i, pool in enumerate( + itertools.chain.from_iterable(self.device_to_pools.values()) + ): + pool.finalize(f"pool{i}") + + def pprint(self): + for pool in itertools.chain.from_iterable(self.device_to_pools.values()): + print() + print(pool.name) + print(pool.root.get_live_ranges()) + pprint.pprint(pool.root) + + +class BufferGroup: + """ + Due to inplace reuse an allocated buffer can have many names. + This tracks these collections of buffers sharing underlying memory. + """ + + def __init__(self, node: ir.Buffer): + self.node = node + self.names = [node.get_name()] + self.is_output = False + self.allocation: Optional[Allocation] = None + self.live_range = LiveRange(float("inf"), -float("inf")) + + def update_usage(self, timestep: int): + """Expand self.live_range to include timestep""" + self.live_range = LiveRange( + min(timestep, self.live_range.begin), + max(timestep, self.live_range.end), + ) + + def sym_nbytes(self): + return self.node.get_layout().storage_size() * self.node.get_dtype().itemsize + + def make_allocation(self): + assert not self.allocation, "multiple allocations" + assert isinstance(self.live_range.begin, int), "live ranges not computed" + nbytes = self.sym_nbytes() + # For now, fallback value will be used if we encounter an unbacked SymInt. The longer-term plan is to have + # size_hint() use better heuristics for unbackeds, at which point the fallback value will be ignored. + size_hint = V.graph.sizevars.size_hint(nbytes, fallback=64) + self.allocation = Allocation( + self.node, + self.live_range, + size_hint=size_hint, + symbolic_size=nbytes, + ) + + def __repr__(self): + return ( + f"{self.__class__.__name__}({self.names!r}, is_output={self.is_output}, " + f"live_range={self.live_range}" + ) + + +@dataclasses.dataclass +class PoolMemoryPlanningLine(MemoryPlanningLine): + """Abstract base class for {Alloc,Dealloc}FromPoolLine""" + + group: BufferGroup + timestep: Optional[int] = None + + @property + def node(self): + return self.group.node + + +@dataclasses.dataclass +class AllocFromPoolLine(PoolMemoryPlanningLine): + """Similar to AllocationLine, but takes memory from a pool""" + + is_first_pool_usage: bool = False + + def codegen(self, code: IndentedBuffer): + allocation = self.group.allocation + assert allocation and allocation.pool + pool = allocation.pool + name = self.node.get_name() + + if self.is_first_pool_usage: + pool.codegen_create(self.wrapper, code) + + pool.names_to_del.extend(self.group.names) + alloc_from_pool = allocation.codegen_alloc_from_pool(self.wrapper) + if alloc_from_pool in pool.creation_cache: + code.writeline( + self.wrapper.make_tensor_alias( + name, pool.creation_cache[alloc_from_pool], "alloc" + ) + ) + else: + pool.creation_cache[alloc_from_pool] = name + code.writeline( + f"{self.wrapper.declare}{name} = {alloc_from_pool}{self.wrapper.ending}" + ) + + +@dataclasses.dataclass +class DeallocFromPoolLine(PoolMemoryPlanningLine): + """Similar to FreeIfNotReusedLine, but takes memory from a pool""" + + is_last_pool_usage: bool = False + + def codegen(self, code: IndentedBuffer): + if self.is_last_pool_usage: + assert self.group.allocation and self.group.allocation.pool + self.group.allocation.pool.codegen_destroy(self.wrapper, code) + + +@dataclasses.dataclass +class MemoryPlanner: + """ + Coordination object to run memory planning passes during wrapper + codegen. + """ + + wrapper: Any + pools: AllocationPools = dataclasses.field(default_factory=AllocationPools) + buffer_groups: Optional[List[BufferGroup]] = None + + def plan(self, lines: List[Any]) -> List[Any]: + """Call all the memory planning passes in sequence""" + lines = [*lines] + self.drop_removed_buffers(lines) + self.convert_to_pool_lines(lines) + self.compute_live_ranges(lines) + self.allocate_groups() + self.mark_first_last_usage(lines) + return lines + + def drop_removed_buffers(self, lines): + """ + Replace any memory planning lines in V.graph.removed_buffers with NullLine + """ + # drop any removed buffers + for i, line in enumerate(lines): + if isinstance(line, (AllocateLine, FreeIfNotReusedLine, ReuseLine)): + if line.node.get_name() in V.graph.removed_buffers: + lines[i] = NullLine(self.wrapper) + + def compute_buffer_groups(self, lines): + """ + Populates self.buffer_groups with BufferGroup objects that join + allocations with common storage (due to inplace reuse) into a + single object. + """ + name_to_group = {} + for line in lines: + if isinstance(line, AllocateLine): + name = line.node.get_name() + assert name not in name_to_group + name_to_group[name] = BufferGroup(line.node) + elif isinstance(line, ReuseLine): + old_name = line.node.get_name() + new_name = line.reused_as.get_name() + assert new_name not in name_to_group + # TODO(jansel): we should support reusing buffers created via ExternKernelAlloc + if old_name in name_to_group: + name_to_group[old_name].names.append(new_name) + name_to_group[new_name] = name_to_group[old_name] + + outputs = set(V.graph.get_output_names()) + unique_groups = [*{id(g): g for g in name_to_group.values()}.values()] + for group in unique_groups: + group.is_output = any(x in outputs for x in group.names) + + assert self.buffer_groups is None + self.buffer_groups = unique_groups + return name_to_group + + def convert_to_pool_lines(self, lines): + """ + Convert AllocateLine/FreeIfNotReusedLine/ReuseLine into their + pool-based counterparts. + """ + name_to_group = self.compute_buffer_groups(lines) + for i, line in enumerate(lines): + if isinstance(line, AllocateLine): + if line.node.get_name() in name_to_group: + lines[i] = AllocFromPoolLine( + self.wrapper, name_to_group[line.node.get_name()] + ) + elif isinstance(line, FreeIfNotReusedLine): + assert not line.is_reused + if line.node.get_name() in name_to_group: + lines[i] = DeallocFromPoolLine( + self.wrapper, name_to_group[line.node.get_name()] + ) + elif isinstance(line, ReuseLine): + if line.node.get_name() in name_to_group: + line.delete_old = False + + def compute_live_ranges(self, lines): + """Populate every BufferGroup.live_ranges field based on first/last usage""" + timestep = 0 + worklist = collections.deque(lines) + while worklist: + if isinstance(worklist[0], MemoryPlanningLine): + timestep += 1 + while worklist and isinstance(worklist[0], MemoryPlanningLine): + line = worklist.popleft() + if isinstance(line, PoolMemoryPlanningLine): + line.group.update_usage(timestep) + line.timestep = timestep + else: + worklist.popleft() + + timestep += 1 + assert self.buffer_groups is not None + for group in self.buffer_groups: + if group.is_output: + group.update_usage(timestep) + + def allocate_groups(self): + """ + Assign every allocation to a specific location in a specific AllocationPool. + """ + assert config.memory_pool in ("none", "intermediates", "outputs", "combined") + assert self.buffer_groups is not None + + for group in self.buffer_groups: + group.make_allocation() + + outputs: List[Allocation] = [] + intermediates: List[Allocation] = [] + for group in self.buffer_groups: + assert group.allocation + if group.is_output and config.memory_pool != "combined": + outputs.append(group.allocation) + else: + intermediates.append(group.allocation) + + for block in sorted( + outputs, + key=lambda x: ( + x.size_hint, + -len(x.live_range), + ), + ): + self.pools.allocate_output(block) + + for block in sorted( + intermediates, + key=lambda x: ( + -x.size_hint, + -len(x.live_range), + ), + ): + self.pools.allocate(block) + + self.pools.finalize() + + def mark_first_last_usage(self, lines): + """ + Populate the AllocFromPoolLine.is_first_pool_usage and + DeallocFromPoolLine.is_last_pool_usage fields so that pools + are created/destroyed. + """ + seen = set() + for line in lines: + if isinstance(line, AllocFromPoolLine): + assert line.group.allocation + pool = line.group.allocation.pool + assert pool is not None + if pool not in seen: + line.is_first_pool_usage = True + seen.add(pool) + + seen = set() + for line in reversed(lines): + if isinstance(line, DeallocFromPoolLine): + assert line.group.allocation + pool = line.group.allocation.pool + assert pool is not None + if pool not in seen: + line.is_last_pool_usage = ( + pool.root.get_live_ranges().end <= line.timestep + ) + seen.add(pool) diff --git a/shared/package-files/00/00da7f094f47725cbdf8d0719279bb83eb96c658ecb539ab8aadd2f1fe643ec3/blob b/shared/package-files/00/00da7f094f47725cbdf8d0719279bb83eb96c658ecb539ab8aadd2f1fe643ec3/blob new file mode 100644 index 0000000000000000000000000000000000000000..3e74402263cf9c119ec344c5da48dd8598970f69 --- /dev/null +++ b/shared/package-files/00/00da7f094f47725cbdf8d0719279bb83eb96c658ecb539ab8aadd2f1fe643ec3/blob @@ -0,0 +1,154 @@ +""" +Tests shared by MaskedArray subclasses. +""" +import numpy as np +import pytest + +import pandas as pd +import pandas._testing as tm +from pandas.tests.extension.base import BaseOpsUtil + + +class ComparisonOps(BaseOpsUtil): + def _compare_other(self, data, op, other): + # array + result = pd.Series(op(data, other)) + expected = pd.Series(op(data._data, other), dtype="boolean") + + # fill the nan locations + expected[data._mask] = pd.NA + + tm.assert_series_equal(result, expected) + + # series + ser = pd.Series(data) + result = op(ser, other) + + # Set nullable dtype here to avoid upcasting when setting to pd.NA below + expected = op(pd.Series(data._data), other).astype("boolean") + + # fill the nan locations + expected[data._mask] = pd.NA + + tm.assert_series_equal(result, expected) + + # subclass will override to parametrize 'other' + def test_scalar(self, other, comparison_op, dtype): + op = comparison_op + left = pd.array([1, 0, None], dtype=dtype) + + result = op(left, other) + + if other is pd.NA: + expected = pd.array([None, None, None], dtype="boolean") + else: + values = op(left._data, other) + expected = pd.arrays.BooleanArray(values, left._mask, copy=True) + tm.assert_extension_array_equal(result, expected) + + # ensure we haven't mutated anything inplace + result[0] = pd.NA + tm.assert_extension_array_equal(left, pd.array([1, 0, None], dtype=dtype)) + + +class NumericOps: + # Shared by IntegerArray and FloatingArray, not BooleanArray + + def test_searchsorted_nan(self, dtype): + # The base class casts to object dtype, for which searchsorted returns + # 0 from the left and 10 from the right. + arr = pd.array(range(10), dtype=dtype) + + assert arr.searchsorted(np.nan, side="left") == 10 + assert arr.searchsorted(np.nan, side="right") == 10 + + def test_no_shared_mask(self, data): + result = data + 1 + assert not tm.shares_memory(result, data) + + def test_array(self, comparison_op, dtype): + op = comparison_op + + left = pd.array([0, 1, 2, None, None, None], dtype=dtype) + right = pd.array([0, 1, None, 0, 1, None], dtype=dtype) + + result = op(left, right) + values = op(left._data, right._data) + mask = left._mask | right._mask + + expected = pd.arrays.BooleanArray(values, mask) + tm.assert_extension_array_equal(result, expected) + + # ensure we haven't mutated anything inplace + result[0] = pd.NA + tm.assert_extension_array_equal( + left, pd.array([0, 1, 2, None, None, None], dtype=dtype) + ) + tm.assert_extension_array_equal( + right, pd.array([0, 1, None, 0, 1, None], dtype=dtype) + ) + + def test_compare_with_booleanarray(self, comparison_op, dtype): + op = comparison_op + + left = pd.array([True, False, None] * 3, dtype="boolean") + right = pd.array([0] * 3 + [1] * 3 + [None] * 3, dtype=dtype) + other = pd.array([False] * 3 + [True] * 3 + [None] * 3, dtype="boolean") + + expected = op(left, other) + result = op(left, right) + tm.assert_extension_array_equal(result, expected) + + # reversed op + expected = op(other, left) + result = op(right, left) + tm.assert_extension_array_equal(result, expected) + + def test_compare_to_string(self, dtype): + # GH#28930 + ser = pd.Series([1, None], dtype=dtype) + result = ser == "a" + expected = pd.Series([False, pd.NA], dtype="boolean") + + tm.assert_series_equal(result, expected) + + def test_ufunc_with_out(self, dtype): + arr = pd.array([1, 2, 3], dtype=dtype) + arr2 = pd.array([1, 2, pd.NA], dtype=dtype) + + mask = arr == arr + mask2 = arr2 == arr2 + + result = np.zeros(3, dtype=bool) + result |= mask + # If MaskedArray.__array_ufunc__ handled "out" appropriately, + # `result` should still be an ndarray. + assert isinstance(result, np.ndarray) + assert result.all() + + # result |= mask worked because mask could be cast losslessly to + # boolean ndarray. mask2 can't, so this raises + result = np.zeros(3, dtype=bool) + msg = "Specify an appropriate 'na_value' for this dtype" + with pytest.raises(ValueError, match=msg): + result |= mask2 + + # addition + res = np.add(arr, arr2) + expected = pd.array([2, 4, pd.NA], dtype=dtype) + tm.assert_extension_array_equal(res, expected) + + # when passing out=arr, we will modify 'arr' inplace. + res = np.add(arr, arr2, out=arr) + assert res is arr + tm.assert_extension_array_equal(res, expected) + tm.assert_extension_array_equal(arr, expected) + + def test_mul_td64_array(self, dtype): + # GH#45622 + arr = pd.array([1, 2, pd.NA], dtype=dtype) + other = np.arange(3, dtype=np.int64).view("m8[ns]") + + result = arr * other + expected = pd.array([pd.Timedelta(0), pd.Timedelta(2), pd.NaT]) + tm.assert_extension_array_equal(result, expected) diff --git a/shared/package-files/00/00de069cd1d4ce5c595391ffa4bf72cbc3c6f7ebe4e9f209d081336abfb23cbd/blob b/shared/package-files/00/00de069cd1d4ce5c595391ffa4bf72cbc3c6f7ebe4e9f209d081336abfb23cbd/blob new file mode 100644 index 0000000000000000000000000000000000000000..7e4eceeb4f28c214b51a57643f60c50a145a9dac --- /dev/null +++ b/shared/package-files/00/00de069cd1d4ce5c595391ffa4bf72cbc3c6f7ebe4e9f209d081336abfb23cbd/blob @@ -0,0 +1,1122 @@ +# mypy: ignore-errors + +# Copyright (c) Facebook, Inc. and its affiliates. +# All rights reserved. +# +# This source code is licensed under the BSD-style license found in the +# LICENSE file in the root directory of this source tree. +import contextlib +import functools +from typing import Any, Callable, Dict, List, Optional, Tuple, Union +import torch +import torch.utils._pytree as pytree +from torch.fx import Tracer, GraphModule +from torch.fx.graph_module import _assign_attr +from weakref import WeakKeyDictionary +from collections import defaultdict +from torch._subclasses.fake_tensor import FakeTensor, FakeTensorMode, unset_fake_temporarily, is_fake +from torch._dispatch.python import enable_python_dispatcher, enable_pre_dispatch +import torch.fx as fx +from torch.fx.node import _side_effectful_need_to_be_preserved_pre_dispatch +from torch.fx.passes.shape_prop import _extract_tensor_metadata +from contextlib import contextmanager, nullcontext +import inspect +from dataclasses import dataclass +import weakref +import operator +from torch.utils._stats import count +import logging + +from torch.overrides import TorchFunctionMode + +from torch.utils._python_dispatch import ( + TorchDispatchMode, + _disable_infra_mode, + _push_mode, + _unset_infra_mode, +) + +from ._backward_state import BackwardState +from .sym_node import SymNode +from ._sym_dispatch_mode import SymDispatchMode +from torch.fx import Proxy +import torch.fx.traceback as fx_traceback +from torch import SymInt, SymFloat, SymBool +from torch.utils.weak import WeakTensorKeyDictionary, WeakIdKeyDictionary, _WeakHashRef + +__all__ = ["PythonKeyTracer", "dispatch_trace", "make_fx", "DecompositionInterpreter", "py_sym_types", "get_innermost_proxy_mode"] + +aten = torch.ops.aten +prim = torch.ops.prim + +log = logging.getLogger(__name__) +not_implemented_log = torch._logging.getArtifactLogger(__name__, "not_implemented") + +CURRENT_DECOMPOSITION_TABLE: Dict[torch._ops.OperatorBase, Callable] = {} + +CONSTANT_NUMEL_LIMIT = 1 + +# We currently convert all SymInt to proxies before we use them. +# This could plausibly be handled at the Dynamo level. +pytree.register_pytree_node( + torch.Size, + lambda xs: (list(xs), None), + lambda xs, _: tuple(xs), + flatten_with_keys_fn=lambda xs: ( + [(pytree.SequenceKey(i), x) for i, x in enumerate(xs)], + None, + ), +) +def fake_signature(fn, nargs): + """FX gets confused by varargs, de-confuse it""" + argnames = ",".join(f"arg{i}" for i in range(nargs)) + return eval(f"lambda {argnames}: fn({argnames})", {"fn": fn}) + +@contextmanager +def decompose(decomposition_table): + global CURRENT_DECOMPOSITION_TABLE + old_decomposition_table = CURRENT_DECOMPOSITION_TABLE + CURRENT_DECOMPOSITION_TABLE = decomposition_table + try: + yield CURRENT_DECOMPOSITION_TABLE + finally: + CURRENT_DECOMPOSITION_TABLE = old_decomposition_table + +# ensure we cannot collide with other properties +proxy_slot = object() +no_default = object() + +py_sym_types = (SymInt, SymFloat, SymBool) + +def is_sym_node(node): + assert hasattr(node, 'meta'), "All nodes traced with proxy_tensor should have meta" + return "val" in node.meta and isinstance(node.meta['val'], py_sym_types) + +def set_proxy_slot(obj, tracer, proxy): + if isinstance(obj, torch.Tensor): + # We DO want to clobber proxies whenever we run an inplace operation + # on a tensor, and it affects the metadata on the proxy. + tracer.tensor_tracker[obj] = proxy + elif isinstance(obj, torch.ScriptObject): + # We DO want to clobber proxies, with a similar rationale as for tensors. + tracer.script_object_tracker[obj] = proxy + else: + # NB: Never clobber pre-existing proxy. Although the proxies + # are in principle equivalent, when we do graph partitioning + # we need there not to be spurious dependencies on tangent inputs. + # This works because primals get their SymInts set first, and + # THEN later we allocate tangent inputs. Make sure if a SymInt + # is derivable from a primal that we use that. + assert isinstance(obj, py_sym_types), type(obj) + if obj not in tracer.symnode_tracker: + tracer.symnode_tracker[obj] = proxy + +def has_proxy_slot(obj, tracer): + assert isinstance(obj, (torch.Tensor, SymNode)), type(obj) + return get_proxy_slot(obj, tracer, False, lambda _: True) + +# the default argument is what to return if the slot is not set. +# the transform argument is handy if you need to extract a subfield from +# the successfully looked up result (but NOT the default.) +def get_proxy_slot(obj, tracer, default=no_default, transform=lambda x: x): + if isinstance(obj, torch.Tensor): + tracker = tracer.tensor_tracker + elif isinstance(obj, torch.ScriptObject): + tracker = tracer.script_object_tracker + else: + assert isinstance(obj, py_sym_types), type(obj) + tracker = tracer.symnode_tracker + + if obj not in tracker: + if default is no_default: + raise RuntimeError(f"{obj} is not tracked with proxy for {tracer}") + return default + return transform(tracker[obj]) + +def snapshot_fake(val): + return val.detach() + +def extract_val(val): + if is_fake(val): + return snapshot_fake(val) + elif isinstance(val, py_sym_types): + return val + elif isinstance(val, torch.ScriptObject): + return val + elif isinstance(val, BackwardState): + return val + elif isinstance(val, (list, tuple)): + return val.__class__([extract_val(x) for x in val]) + elif isinstance(val, torch.Tensor): + if not val.is_sparse: + # NB: Kinda hacky, but we should try to get val as the metadata + # everywhere + # TODO: This doesn't properly track storages. A more robust + # approach would be to maintain a per-trace FakeTensorMode and + # from_real_tensor to create fake values (don't forget to + # snapshot_fake) + fake_tensor_mode = FakeTensorMode(allow_fallback_kernels=True) + with fake_tensor_mode: + return torch.empty_strided(val.shape, val.stride(), device=val.device, dtype=val.dtype) + else: + return None + elif isinstance(val, (int, float, bool)): + return val + +# What invariants do we have for the 'val' set on the FX node? It has accurate +# metadata... but only for metadata that exists "below" all other subsystems +# (most notably autograd, but also vmap, functorch transforms, etc). This means +# you can get the dtype, shape, stride, storage, but you CANNOT get requires_grad, +# grad_fn, _base (_base actually may be set due to recursive call to +# ADInplaceOrView, but you shouldn't rely on it.) +def set_meta(proxy, val): + proxy.node.meta['val'] = extract_val(val) + # Best effort tensor_meta setting; prefer using val! + if is_fake(val): + proxy.node.meta['tensor_meta'] = _extract_tensor_metadata(val) + elif isinstance(val, torch.Tensor) and not val.is_sparse: + proxy.node.meta['tensor_meta'] = _extract_tensor_metadata(val) + return proxy + +def thunkify(f, *args, **kwargs): + """ + Delays computation of f until it's called again + Also caches the result + """ + return functools.lru_cache(1)(functools.partial(f, *args, **kwargs)) + +def track_tensor(tensor, proxy, *, constant, tracer): + def try_set_proxy_slot(outer_s, proxy_callable, *args): + assert callable(proxy_callable) + if isinstance(outer_s, SymInt): + set_proxy_slot(outer_s, tracer, thunkify(proxy_callable, outer_s, *args)) + # The basic idea is that we need to associate each tensor/SymInt + # with a Proxy. How do we setup this association? We just store + # the proxy on the proxy slot of the object, keyed on the tracer + # (so that if we have multiple tracers at the same time, they + # don't clobber each other.) + for i, s in enumerate(tensor.shape): + try_set_proxy_slot(s, lambda x, i: set_meta(torch.ops.aten.sym_size.int(proxy, i), x), i) + + for i, s in enumerate(tensor.stride()): + try_set_proxy_slot(s, lambda x, i: set_meta(torch.ops.aten.sym_stride.int(proxy, i), x), i) + + try_set_proxy_slot(tensor.numel(), lambda x: set_meta(torch.ops.aten.sym_numel.default(proxy), x)) + try_set_proxy_slot(tensor.storage_offset(), lambda x: set_meta(torch.ops.aten.sym_storage_offset.default(proxy), x)) + set_proxy_slot(tensor, tracer, _ProxyTensor(proxy, constant)) + +def track_tensor_tree(inner_res, proxy_res, *, constant, tracer): + def wrap_with_proxy(e, proxy, constant): + if isinstance(e, torch.Tensor): + track_tensor(e, proxy, tracer=tracer, constant=constant) + set_meta(proxy, e) + elif isinstance(e, py_sym_types): + # NB: eagerly set meta here, so that the numbering is in order + set_meta(proxy, e) + set_proxy_slot(e, tracer, lambda: proxy) + elif isinstance(e, torch.ScriptObject): + set_proxy_slot(e, tracer, proxy) + set_meta(proxy, e) + elif isinstance(e, (tuple, list)): + if isinstance(proxy, fx.Proxy): + set_meta(proxy, e) + + # example use case: allreduce_ returns ([tensor], work) + for idx, ee in enumerate(e): + wrap_with_proxy(ee, proxy[idx], get_constant(idx)) + elif isinstance(e, dict): + # In theory we could support const-prop when proxy-tensor-tracing + # operators that returns dicts of tensors, but we have no use case + # for it today (since the only op we currently trace that can + # return a dict is triton_kernel_wrapper_functional/mutation, + # which does not participate in const-prop) + assert constant is None + + if isinstance(proxy, fx.Proxy): + set_meta(proxy, e) + + # example use case: triton_kernel_wrapper takes arguments as kwargs + for key, val in e.items(): + wrap_with_proxy(val, proxy[key], None) + elif isinstance(e, BackwardState): + set_meta(proxy, e) + e.proxy = proxy + else: + # intentionally pass on primitives + pass + + + def get_constant(idx): + if constant is None: + return None + else: + return constant[idx] + + wrap_with_proxy(inner_res, proxy_res, constant) + + return inner_res + + +def maybe_disable_fake_tensor_mode(): + # TODO: figure out if this API generally makes sense and bake it into the + # library + return unset_fake_temporarily() + + +@dataclass +class _ProxyTensor: + proxy: Proxy + constant: Optional[torch.Tensor] + + +def fetch_sym_proxy(tracer): + def inner(e): + n = e.node + if n.constant is not None: + return n.constant + if e.node.expr.is_number: + if isinstance(e, SymBool): + return bool(e.node.expr) + elif isinstance(e, SymInt): + return int(e.node.expr) + return float(e.node.expr) + else: + # NB: we REQUIRE all symints to be tracked + return get_proxy_slot(e, tracer)() + return inner + + +def fetch_object_proxy(tracer): + return lambda t: get_proxy_slot(t, tracer, t) + +HANDLED_TYPES = (torch.Tensor, torch.nn.Parameter, FakeTensor) + +def proxy_call(proxy_mode, func, pre_dispatch, args, kwargs): + unrecognized_types = [] + + def can_handle_tensor(x): + r = type(x) in HANDLED_TYPES or has_proxy_slot(x, proxy_mode.tracer) + if proxy_mode._allow_fake_constant: + r = r or type(x) in (torch._subclasses.FakeTensor,) + if not r: + unrecognized_types.append(type(x)) + return r + + # If there are any tensor subclasses, we need to handle those tensor subclasses first + # TODO: we could use types to test this + if not pytree.tree_all_only(torch.Tensor, can_handle_tensor, (args, kwargs)): + not_implemented_log.debug("ProxyTensorMode tensors without proxy had unrecognized subclasses: %s", unrecognized_types) + return NotImplemented + + r = maybe_handle_decomp(proxy_mode, func, args, kwargs) + if r is not NotImplemented: + return r + + # For pre-autograd tracing, we do not want to run CompositeImplicit decomps. + if not pre_dispatch and func not in [ + torch.ops.aten.size.default, torch.ops.aten.stride.default, torch.ops.aten.storage_offset.default + ]: + with proxy_mode: + r = func.decompose(*args, **kwargs) + if r is not NotImplemented: + return r + + tracer = proxy_mode.tracer + f_args, f_kwargs = pytree.tree_map_only((torch.Tensor, torch.ScriptObject), fetch_object_proxy(tracer), (args, kwargs)) + + # If there are SymInts, we also should not consider this constant. + # However, fake tensor handling of SymInts is sufficiently broken that + # I couldn't write a test for this case + all_constant = ( + pytree.tree_all_only(_ProxyTensor, lambda t: t.constant is not None, (f_args, f_kwargs)) + # TODO: maybe constant SymInts should also be allowed? Not sure if + # this can happen + and pytree.tree_all_only((SymInt, SymFloat, SymBool), lambda _: False, (args, kwargs)) + ) + + if torch.Tag.data_dependent_output in func.tags: + # Check if all of the Tensor inputs are constants + if all_constant: + const_args, const_kwargs = pytree.tree_map_only( + _ProxyTensor, lambda t: t.constant, (f_args, f_kwargs) + ) + with maybe_disable_fake_tensor_mode(): + return func(*const_args, **const_kwargs) + # If any of the Tensor inputs are "real" (not FakeTensor), we may + # incorrectly burn in constants by allowing this access. Raise + # an error in this case + if proxy_mode._error_on_data_dependent_ops and pytree.tree_all_only(torch.Tensor, lambda t: not is_fake(t), (args, kwargs)): + raise RuntimeError( + f"It appears that you're trying to get value out of a tracing tensor with {func} - erroring out! " + "It's likely that this is caused by data-dependent control flow or similar. " + "It may be possible to trace this with dynamic shapes; try setting tracing_mode='symbolic' " + "in your make_fx call." + ) + proxy_args, proxy_kwargs = pytree.tree_map_only( + (SymInt, SymFloat, SymBool), + fetch_sym_proxy(proxy_mode.tracer), + pytree.tree_map_only(_ProxyTensor, lambda e: e.proxy, (f_args, f_kwargs)) + ) + + # When we trace through a torch.tensor invocation, you never actually + # see a torch.ops.aten.tensor call. Instead, the way this function is + # implemented internally is that we allocate a plain tensor (this is + # *guaranteed* to be a plain tensor, we disable all modes when doing + # so), and then call at::lift_fresh on it (to give modes a chance to do + # their stuff). Furthermore, the tensor argument to lift_fresh is guaranteed + # to be freshly allocated, so we want lift_fresh to be a no-op (directly + # returning the input argument). + # + # Here is the basic problem: when we trace this sequence of executions + # into an FX graph, what happens to this call sequence? Traditionally, + # tensor constants get interned as buffers on the FX GraphModule. But + # this is dangerous. Consider: + # + # x = torch.tensor(1) + # x.add_(2) + # + # Naively, this traces into: + # + # t = self._tensor_constant0 # initialized to torch.tensor(1) + # x = torch.ops.aten.lift_fresh(t) + # x.add_(2) + # + # If lift_fresh returns t directly, the subsequent add_ call will + # modify the tensor constant. Really, the problem is we've violated + # the invariant the argument to lift is fresh. So what we should + # preserve the invariant by replacing lift_fresh with lift_fresh_copy: + # + # t = self._tensor_constant0 # initialized to torch.tensor(1) + # x = torch.ops.aten.lift_fresh_copy(t) + # x.add_(2) + # + # This is what the overload modification does. + if func is torch.ops.aten.lift_fresh.default: + func = torch.ops.aten.lift_fresh_copy.default + + + proxy_out = proxy_mode.tracer.create_proxy('call_function', func, proxy_args, proxy_kwargs, + name=proxy_mode.tracer.graph._target_to_str(func.overloadpacket.__name__)) + + # This makes DCE marginally less likely to DCE inplace operations. + # It is not strictly necessary + # Kind of a hacky way to test if an op is in-place or not + if func.overloadpacket.__name__[-1] == "_" and func.overloadpacket.__name__[0] != "_": + if isinstance(args[0], List): + # e.g., c10d::allreduce_ returns a list of tensors as the first element + # in the output. + for i, a in enumerate(args[0]): + a.proxy = proxy_out[0][i] + else: + args[0].proxy = proxy_out + + out = func(*args, **kwargs) + + # In some circumstances, we will be tracing in a situation where a tensor + # is *statically* known to be a constant (currently, this only happens if + # you run torch.tensor; deterministic factory functions like torch.arange + # don't get this treatment). When the tensor in question is small, it's + # helpful to due constant propagation in case we call item() (in which + # case we can return the constant value that is known, rather than give + # an error.) The logic here tests if constant propagation is possible + # (because all of the inputs are constant). If so, we disable fake tensor + # mode (if it is on) and do true compute on the constant. + # + # It's worth highlighting that we're making a policy decision here. + # There is a potential that the tensor is actually quite large, and we + # don't actually want to run the compute. The tensor being quite large + # is one of the reasons why factory functions don't get this treatment + # (since they can be quite large; if a parameter is initialized to a + # constant value it will be!) Similarly, there is also a potential + # to run an operator that blows up the size of a small tensor; we don't + # protect against this case, but we could force, e.g., only single + # element constant computation by testing the numel of the result before + # propagating const-ness. Similarly, we don't require the constant to + # live on CPU, but we could. + any_constant = pytree.tree_any_only(_ProxyTensor, lambda t: t.constant is not None, (f_args, f_kwargs)) + + constant = None + + # If this is a lift, the input tensor is guaranteed to be a + # constant, so we keep a copy of the original argument along so + # we can query it if we're asked to item() it at some later point + if func is torch.ops.aten.lift_fresh_copy.default and out.numel() <= CONSTANT_NUMEL_LIMIT: + with maybe_disable_fake_tensor_mode(): + constant = args[0].clone() + elif ( + torch.Tag.nondeterministic_seeded not in func.tags + and all_constant + and any_constant + and pytree.tree_all_only(torch.Tensor, lambda t: t.numel() <= CONSTANT_NUMEL_LIMIT, out) + ): + # NB: do NOT include factories as constants + with maybe_disable_fake_tensor_mode(): + const_args, const_kwargs = pytree.tree_map_only( + _ProxyTensor, lambda t: t.constant, (f_args, f_kwargs) + ) + constant = func(*const_args, **const_kwargs) + else: + constant = None + + track_tensor_tree(out, proxy_out, constant=constant, tracer=tracer) + return out + +class _SymNodeDict: + """ + Wrapper around a dictionary that will hash SymInts with their nodes + """ + def __init__(self): + self.sym_node_dict = {} + + def __setitem__(self, key: py_sym_types, value: Any): + self.sym_node_dict[key.node] = value + + def __getitem__(self, key: py_sym_types): + return self.sym_node_dict[key.node] + + def __contains__(self, key: py_sym_types): + return key.node in self.sym_node_dict + + def get(self, key: py_sym_types, default: Any = None): + return self.sym_node_dict.get(key.node, default) + +class PythonKeyTracer(Tracer): + def __init__(self): + super().__init__(autowrap_modules=()) + self.tensor_tracker = WeakTensorKeyDictionary() + self.symnode_tracker = _SymNodeDict() # type: ignore[var-annotated] + self.script_object_tracker = WeakIdKeyDictionary(dict=None, ref_type=_WeakHashRef) + + # In general, we don't want to make modules leaves. In principle, users of + # this tracer might want to override this in order to turn a couple specific + # modules into leaves in the traced graph. + def call_module( + self, m: torch.nn.Module, forward: Callable[..., Any], args: Tuple[Any, ...], kwargs: Dict[str, Any] + ) -> Any: + return forward(*args, **kwargs) + + # We don't want to turn getattr calls into proxies. So we just return the actual value. + def getattr(self, attr, attr_val, parameter_proxy_cache): + return attr_val + + def create_arg(self, a: Any): + if isinstance(a, torch.nn.Parameter): + for n, p in self.root.named_parameters(): + if a is p: + return self.create_node('get_attr', n, (), {}) + qualname: Optional[str] = None + + if not qualname: + i = 0 + while True: + qualname = f'_param_constant{i}' + if not hasattr(self.root, qualname): + break + i += 1 + setattr(self.root, qualname, a) + + return self.create_node('get_attr', qualname, (), {}) + elif isinstance(a, (SymInt, SymFloat, SymBool)): + assert a.node.constant is not None + return a.node.constant + return super().create_arg(a) + + def unwrap_proxy(self, e): + if isinstance(e, torch.Tensor): + return get_proxy_slot(e, self, e, lambda e: e.proxy) + elif isinstance(e, (torch.SymInt, torch.SymFloat, torch.SymBool)): + return get_proxy_slot(e, self, e, lambda e: e()) + elif isinstance(e, torch.ScriptObject): + return get_proxy_slot(e, self, e) + else: + return e + + +@torch._disable_dynamo +def dispatch_trace( + root: Union[torch.nn.Module, Callable], + tracer: Tracer, + concrete_args: Optional[Tuple[Any, ...]] = None, +) -> GraphModule: + graph = tracer.trace(root, concrete_args) + from torch._inductor.fx_passes.dedupe_symint_uses import dedupe_symints + dedupe_symints(graph) + name = root.__class__.__name__ if isinstance(root, torch.nn.Module) else root.__name__ + return fx._lazy_graph_module._make_graph_module(tracer.root, graph, name) + + +def wrap_key(f, tensors, tracer, pre_dispatch: bool): + flat_tensors, tensors_spec = pytree.tree_flatten(tensors) + + @functools.wraps(f) + def wrapped(*proxies): + flat_proxies, proxies_spec = pytree.tree_flatten(proxies) + assert len(flat_proxies) == len(flat_tensors) + with disable_proxy_modes_tracing() as m: + assert isinstance(m, ProxyTorchDispatchMode) + track_tensor_tree(flat_tensors, flat_proxies, constant=None, tracer=tracer) + + out = f(*tensors) + out = pytree.tree_map_only( + torch.Tensor, + lambda t: get_proxy_slot(t, tracer, t, lambda x: x.proxy), + out + ) + out = pytree.tree_map_only( + (SymInt, SymFloat, SymBool), + lambda t: get_proxy_slot(t, tracer)(), + out + ) + return out + + return wrapped + +ORIGINAL_ATEN = None +@contextmanager +def set_original_aten_op(func): + global ORIGINAL_ATEN + if ORIGINAL_ATEN is None and fx_traceback.has_preserved_node_meta(): + ORIGINAL_ATEN = func + fx_traceback.current_meta['original_aten'] = func + try: + yield + finally: + ORIGINAL_ATEN = None + fx_traceback.current_meta['original_aten'] = None + else: + yield + + + +# This mode is **only** used for pre_dispatch tracing. +# In particular, we need to make sure that autograd/autocast API's +# that do not desugar into dispatcher operators stay in the graph. +class PreDispatchTorchFunctionMode(TorchFunctionMode): + + def __init__(self, tracer): + self.tracer = tracer + + def __torch_function__(self, func, types, args=(), kwargs=None): + kwargs = kwargs or {} + if func in _side_effectful_need_to_be_preserved_pre_dispatch: + # It's for passing the export verifier which needs to verify the meta['val'] + # TODO(tmanlaibaatar): we should systematically couple it with expoert verifier, + # instead of hardcoding it here. + node = self.tracer.create_node("call_function", func, args, {}) + if func is torch._C._set_grad_enabled: + node.meta['val'] = None + return node + # Don't actually run the function! We just want to trace the calls + # into a graph. We don't actualy want to change global autograd state. + return func(*args, **kwargs) + + +class ProxyTorchDispatchMode(TorchDispatchMode): + def __init__(self, tracer, tracing_mode, pre_dispatch=False, _allow_fake_constant=False, _error_on_data_dependent_ops=True): + dk = torch._C.DispatchKey.PreDispatch if pre_dispatch else None + super().__init__(dk) + self.tracer = tracer + self.tracing_mode = tracing_mode + self.enable_tracing = True + self.pre_dispatch = pre_dispatch + self._allow_fake_constant = _allow_fake_constant + self._error_on_data_dependent_ops = _error_on_data_dependent_ops + self.sym_mode = ProxySymDispatchMode(tracer) + self.trace_state = {} + self._managers = [] + # Indicates to our torch_dispatch dispatching infra that + # this is an "infra" mode with lower dispatching precedence. + self._mode_key = torch._C._TorchDispatchModeKey.PROXY + # Every time we enter a mode, we maintain a stack telling us what the previous + # ProxyTorchDispatchMode state was (if there was any). + # This lets us properly reset the state on exit. + self.enter_stack: List[Optional[ProxyTorchDispatchMode]] = [] + + @count + def __torch_dispatch__(self, func, types, args=(), kwargs=None): + with self.sym_mode.enable(False), set_original_aten_op(func): + return self.inner_torch_dispatch(func, types, args, kwargs) + + def __enter__(self): + # sym mode first, then us... + m = self.sym_mode.enable(True) + self._managers.append(m) + m.__enter__() + # Stash and store the previous proxy mode (there may or may not be one) + maybe_prev_proxy_mode = _unset_infra_mode(torch._C._TorchDispatchModeKey.PROXY) + self.enter_stack.append(maybe_prev_proxy_mode) + return super().__enter__() + + def __exit__(self, exc_type, exc_value, traceback): + m = self._managers.pop() + # ...exit us first, then sym mode + b = super().__exit__(exc_type, exc_value, traceback) + + # Re-enable the previous proxy mode, if there was one. + mb_previous_proxy_mode = self.enter_stack.pop() + if mb_previous_proxy_mode is not None: + _push_mode(mb_previous_proxy_mode) + + if not b: + return m.__exit__(exc_type, exc_value, traceback) + else: + return m.__exit__(None, None, None) + + + def inner_torch_dispatch(self, func, types, args=(), kwargs=None): + if not self.enable_tracing: + return func(*args, **kwargs) + + if func in [prim.device.default]: + return func(*args, **kwargs) + + return proxy_call(self, func, self.pre_dispatch, args, kwargs) + + +class ProxySymDispatchMode(SymDispatchMode): + def __init__(self, tracer): + super().__init__() + self.tracer = tracer + # When false, we don't trace operations. If you do this, you MUST + # call track_tensor/track_tensor_tree on all results of the operation + # to ensure we can adequately track the results + self.enable_tracing = True + + @contextmanager + def enable(self, b): + old = self.enable_tracing + self.enable_tracing = b + try: + yield + finally: + self.enable_tracing = old + + def _compute_proxy(self, func, args, out: Union[SymInt, SymFloat, SymBool]): + n_args = tuple( + get_proxy_slot(a, self.tracer)().node if isinstance(a, py_sym_types) else a + for a in args + ) + + # func doesn't have a __torch_function__ that Proxy can interpose, so + # we gotta do it manually + n_out = self.tracer.create_node("call_function", func, n_args, {}) + p_out = fx.Proxy(n_out, self.tracer) + set_meta(p_out, out) + return p_out + + def __sym_dispatch__(self, func, types, args, kwargs): + if not self.enable_tracing: + return func(*args, **kwargs) + + # Peephole optimize multiply by one + # NB: be careful not to trigger guards here! + if func == operator.mul: + if isinstance(args[1], int) and args[1] == 1: + return args[0] + elif isinstance(args[0], int) and args[0] == 1: + return args[1] + + # For speed, we assume there are no nested data structures + # (otherwise we could use tree_map) + # We also assume there are no keyword arguments. + assert not kwargs + out = func(*args, **kwargs) + + # If func returned a constant, we don't need to trace; we have + # determined that the result is constant (no matter if the inputs + # were symbolic) and it is no longer necessary to trace the + # computation. This could occur if func triggered some guards. + if isinstance(out, py_sym_types): + # Delays tracing out the proxies on this op until we actually need it + p_out_thunk = thunkify(self._compute_proxy, func=func, args=args, out=out) + set_proxy_slot(out, self.tracer, p_out_thunk) + + return out + + +# TODO: I'm not sure what the point of this class is; you can just +# make_fx through a regular Interpreter +class DecompositionInterpreter(torch.fx.Interpreter): + def __init__(self, module: torch.fx.GraphModule, new_graph: torch.fx.Graph, decomposition_table=None, **kwargs): + super().__init__(module, **kwargs) + self.new_graph = new_graph + self.tracer = torch.fx.proxy.GraphAppendingTracer(self.new_graph) + # Blegh + self.tracer.tensor_tracker = WeakTensorKeyDictionary() # type: ignore[attr-defined] + self.tracer.symnode_tracker = weakref.WeakKeyDictionary() # type: ignore[attr-defined] + self.decomposition_table = decomposition_table + if self.decomposition_table is None: + self.decomposition_table = {} + self.mode = ProxyTorchDispatchMode(self.tracer, tracing_mode="real") + + def placeholder(self, target, args, kwargs): + out = super().placeholder(target, args, kwargs) + proxy = torch.fx.Proxy(self.new_graph.placeholder(target), self.tracer) + track_tensor_tree(out, proxy, constant=None, tracer=self.tracer) + # TODO handle case where the first character of target is '*' + return out + + def get_attr(self, target, args, kwargs): + out = super().get_attr(target, args, kwargs) + proxy = torch.fx.Proxy(self.new_graph.get_attr(target), self.tracer) + track_tensor_tree(out, proxy, constant=None, tracer=self.tracer) + return out + + # call_function, call_method, call_module get traced automatically by the outer mode. + + def output(self, target, args, kwargs): + out = super().output(target, args, kwargs) + + def unwrap(e): + return get_proxy_slot(e, self.tracer, e, lambda x: x.proxy.node) + self.new_graph.output(pytree.tree_map(unwrap, out)) + return out + + def run(self, *args, **kwargs): + # Should enter the mode at least once for being able to restore it later + # See: https://github.com/pytorch/pytorch/pull/82549#discussion_r934782025 + with decompose(self.decomposition_table), self.mode: + return super().run(*args, **kwargs) + + +def wrapper_and_args_for_make_fx(func, args, kwargs): + # make_fx doesn't support kwargs, so we need to do this flattening + # and then unflatten the args before calling func + flat_args, spec = pytree.tree_flatten((args, kwargs)) + + def wrapped(flat_args): + fn_args, fn_kwargs = pytree.tree_unflatten(flat_args, spec) + return func(*fn_args, **fn_kwargs) + return wrapped, flat_args + +@contextmanager +def disable_autocast_cache(): + old_value = torch.is_autocast_cache_enabled() + torch.set_autocast_cache_enabled(False) + try: + yield + finally: + torch.set_autocast_cache_enabled(old_value) + + +class _ModuleStackTracer(PythonKeyTracer): + r"""Customized version of PythonKeyTracer that retains module stack + information in node.meta["nn_module_stack"]. + + FX symbolic trace actually does this already, but it relies on `self.root` + being the actual module being traced. Since make_fx traces a lambda of our + creation, things don't work properly. + + So for this version we hold onto a reference to the original module + (scope_root) and use that to match the path. Also when we see, + A + / \ + B C + \ / + D + we want to record the path as A.B.D by recording only one path. + See Note [Preserving the nn module stack metadata during export non-strict mode] # noqa: W605 + """ + + def __init__(self, scope_root): + super().__init__() + self.scope_root = scope_root + self.proxy_paths = WeakKeyDictionary() + self.proxy_modules = WeakKeyDictionary() + self.counter = 0 + + self.module_id_cache = defaultdict(list) + for name, mod in self.scope_root.named_modules(remove_duplicate=False): + self.module_id_cache[id(mod)].append(name) + + self_ = self + + class AttrProxy: + def __init__(self, base, path): + self.__class__ = type( + base.__class__.__name__, + (self.__class__, base.__class__), + {}, + ) + self.__dict__ = base.__dict__ + self.__class__.__module__ = base.__class__.__module__ + self.__class__.__qualname__ = base.__class__.__qualname__ + self_.proxy_paths[self] = path + self_.proxy_modules[self] = base + + def __getattr__(self, name): + assert isinstance(self, torch.nn.Module) + attr_val = super().__getattr__(name) + if isinstance(attr_val, AttrProxy): + attr_val = self_.proxy_modules[attr_val] + elif not isinstance(attr_val, torch.nn.Module): + return attr_val + return AttrProxy(attr_val, self_.proxy_paths[self] + "." + name) + + @property + def _modules(self): + assert "_modules" in self.__dict__ + submodules = self.__dict__["_modules"] + assert isinstance(submodules, dict) + return { + key: AttrProxy(value, self_.proxy_paths[self] + "." + str(key)) + for key, value in submodules.items() + } + + self.proxy_type = AttrProxy + + def path_of_module(self, mod: torch.nn.Module) -> str: + """ + Use tracked access path during tracing instead of the default BFS behavior. + Still use all the possible module paths to verify the result. + """ + if mod is self.scope_root: + return "" + + if isinstance(mod, self.proxy_type): + return self.proxy_paths[mod] + + return Tracer.path_of_module(self, mod) + + def getattr(self, attr, attr_val, parameter_proxy_cache): + if not isinstance(attr_val, torch.nn.Module) or isinstance(attr_val, torch.fx.GraphModule): + return super().getattr(attr, attr_val, parameter_proxy_cache) + if isinstance(attr_val, self.proxy_type): + return attr_val + return self.proxy_type(attr_val, attr) + + def trace(self, root, concrete_args): + res = super().trace(root, concrete_args) + # Since we are making AttrProxy mimic the original + # submodule, when someone registers a module directly + # to the tracer while tracing, the proxy object gets registered + # first. So we need to replace the proxy modules with the real ones + # This can happen during HOO tracing + proxy_module_names_to_be_replaced = [] + for name, module in self.root.named_modules(): + if module in self.proxy_modules: + proxy_module_names_to_be_replaced.append((name, module)) + + def _delete_proxy_attr(obj, target): + # Copied from fx/graph_module.py + # Customized it for proxy type + atoms = target.split(".") + path, target_submod = atoms[:-1], atoms[-1] + assert isinstance(obj, torch.nn.Module) + mod = obj + + # Get the parent module + for item in path: + + if not hasattr(mod, item): + return False + + mod = getattr(mod, item) + + if not isinstance(mod, (self.proxy_type, torch.nn.Module)): + return False + + if not hasattr(mod, target_submod): + return False + + # At least the leaf module should be proxy type. + if not isinstance(getattr(mod, target_submod), self.proxy_type): + return False + + delattr(mod, target_submod) + return True + + for (proxy_module_name, proxy_module) in proxy_module_names_to_be_replaced: + _delete_proxy_attr(self.root, proxy_module_name) + actual_module = self.proxy_modules[proxy_module] + _assign_attr(actual_module, self.root, proxy_module_name) + + return res + + + def call_module(self, m, forward, args, kwargs): + """PythonKeyTracer overrides call_module to avoid the scope handling, + but we actually want it. + """ + from torch._dynamo import OptimizedModule + # FIXME (tmanlaibaatar) + # When we call torch.compile inside HOO, we will end up + # invoking a module that is not registered on the root. For + # now, we just inline them. But once we start supporting + # mark_strict in export, we do need to properly handle this. + # Right now, it doesn't matter because current non-strict + # use cases don't need to work with HOO. + if isinstance(m, (OptimizedModule, GraphModule)): + return forward(*args, **kwargs) + return Tracer.call_module(self, m, forward, args, kwargs) + + + def is_leaf_module(self, m, module_qualified_name): + return False + + +def make_fx(f, + decomposition_table=None, + tracing_mode="real", + _allow_non_fake_inputs=False, + *, + pre_dispatch=False, + record_module_stack=False, + _allow_fake_constant=False, + _error_on_data_dependent_ops=True): + assert tracing_mode in ["real", "fake", "symbolic"] + + if decomposition_table is None: + decomposition_table = {} + + if torch.ops.aten.sym_numel.default not in decomposition_table: + decomposition_table = { + **decomposition_table, + torch.ops.aten.sym_numel.default: torch._decomp.decompositions.sym_numel + } + + @functools.wraps(f) + def wrapped(*args): + # Avoid importing sympy at a module level + from .symbolic_shapes import ShapeEnv + + phs = pytree.tree_map(lambda _: fx.PH, args) # type: ignore[attr-defined] + + if hasattr(f, "_orig_mod") and record_module_stack: + scope_root = f._orig_mod + fx_tracer = _ModuleStackTracer(scope_root) + else: + fx_tracer = PythonKeyTracer() + fake_tensor_mode: Any = nullcontext() + if tracing_mode == "real": + fake_tensor_mode = nullcontext() + elif tracing_mode == "fake": + import torch._dynamo + fake_tensor_mode = torch._dynamo.utils.detect_fake_mode(args) + if fake_tensor_mode is None: + fake_tensor_mode = FakeTensorMode( + allow_fallback_kernels=True, + allow_non_fake_inputs=_allow_non_fake_inputs, + shape_env=ShapeEnv(), + static_shapes=True, + ) + elif tracing_mode == "symbolic": + import torch._dynamo + fake_tensor_mode = torch._dynamo.utils.detect_fake_mode(args) + if fake_tensor_mode is None: + shape_env = ShapeEnv() + fake_tensor_mode = FakeTensorMode( + allow_fallback_kernels=False, + allow_non_fake_inputs=_allow_non_fake_inputs, + shape_env=shape_env) + else: + shape_env = fake_tensor_mode.shape_env + assert shape_env is not None, "shape_env should be set if tracing with 'symbolic'" + + else: + raise AssertionError(f"Unexpected tracing type: {tracing_mode}") + + python_dispatcher_mode: Any = nullcontext() + pre_dispatch_mode: Any = nullcontext() + # pre-autograd tracing uses per-dispatch-key modes, + # which requires the python dispatcher + if tracing_mode == "symbolic" or pre_dispatch: + python_dispatcher_mode = enable_python_dispatcher() + if pre_dispatch: + pre_dispatch_mode = enable_pre_dispatch() + + proxy_function_mode: Any = nullcontext() + if pre_dispatch: + proxy_function_mode = PreDispatchTorchFunctionMode(fx_tracer) + + proxy_mode = ProxyTorchDispatchMode(fx_tracer, + tracing_mode, + pre_dispatch=pre_dispatch, + _allow_fake_constant=_allow_fake_constant, + _error_on_data_dependent_ops=_error_on_data_dependent_ops) + + arg_count = 0 + + def wrap_fake(x): + nonlocal arg_count + # TODO: it would be nice to line these up with the names + # FX will choose for the placeholders, but we don't + # actually know what the names will be at this point yet + # NB: the Source here is actually meaningless + from torch._dynamo.source import ConstantSource + source = ConstantSource(f"input{arg_count}") + if isinstance(x, torch.Tensor): + arg_count += 1 + return fake_tensor_mode.from_tensor(x, source=source) # type: ignore[attr-defined] + # NB: don't match on bools + elif type(x) is int and tracing_mode == "symbolic": + return shape_env.create_symintnode(shape_env.create_symbol(x, source, positive=None), hint=x, source=source) + + return x + + sym_mode = proxy_mode.sym_mode + + wrap_fn_map = { + "real": lambda x: x, + "fake": wrap_fake, + "symbolic": wrap_fake, + } + args = pytree.tree_map(wrap_fn_map[tracing_mode], args) + + if not hasattr(inspect.unwrap(f), '__code__') or inspect.unwrap(f).__code__.co_flags & inspect.CO_VARARGS: + # FX doesn't support varargs, so we gotta fake up a wrapper + # TODO: Would be nice to fix this at the source... + func = fake_signature(f, len(phs)) + else: + func = f + + # We disable the autocast cache as the autocast cache causes type conversions on parameters to + # check a cache, which introduces untracked tensors into the graph + # + # We also disable tracing by any other tensor proxy-based tracers except the current. The + # purpose of `make_fx` is to produce graphmodules as a side effect; its internal execution is + # thus irrelevant to any external functional trace. + with decompose(decomposition_table), fake_tensor_mode, python_dispatcher_mode, pre_dispatch_mode, proxy_function_mode, \ + sym_mode, proxy_mode, disable_autocast_cache(): + t = dispatch_trace(wrap_key(func, args, fx_tracer, pre_dispatch), tracer=fx_tracer, concrete_args=tuple(phs)) + + # TODO: kind of a bad way to do it, should maybe figure out a better way + if tracing_mode == "symbolic": + t.shape_env = shape_env # type: ignore[assignment] + return t + + return wrapped + + +def get_torch_dispatch_modes(): + return torch.utils._python_dispatch._get_current_dispatch_mode_stack() + + +def get_innermost_proxy_mode(): + return torch._C._get_dispatch_mode(torch._C._TorchDispatchModeKey.PROXY) + + +@contextlib.contextmanager +def disable_proxy_modes_tracing(): + return _disable_infra_mode(torch._C._TorchDispatchModeKey.PROXY) + + +def maybe_handle_decomp(proxy_mode, op, args, kwargs): + if op in CURRENT_DECOMPOSITION_TABLE: + with proxy_mode: + return CURRENT_DECOMPOSITION_TABLE[op](*args, **kwargs) + return NotImplemented + + +def get_isolated_graphmodule(func, args, kwargs, tracing_mode="real"): + """A helper function used to get the GraphModule for the given func. + + It's expected to be used in the ProxyTensor tracing context. + It detaches the args and kwargs from the current tracer so that the trace of + the current graph module can be created without any side-effects. + """ + wrapped, all_args = wrapper_and_args_for_make_fx(func, args, kwargs) + + with disable_proxy_modes_tracing(): + gm = make_fx(wrapped, tracing_mode=tracing_mode)(all_args) + return gm diff --git a/shared/package-files/00/00e05d5392ade2059e856d3a302c83faf9947022c8be4e8c855bbdf79d82610c/blob b/shared/package-files/00/00e05d5392ade2059e856d3a302c83faf9947022c8be4e8c855bbdf79d82610c/blob new file mode 100644 index 0000000000000000000000000000000000000000..6065622b0f1419b0ab221c4171b93e0bc1023ec3 --- /dev/null +++ b/shared/package-files/00/00e05d5392ade2059e856d3a302c83faf9947022c8be4e8c855bbdf79d82610c/blob @@ -0,0 +1,28 @@ +#pragma once +// @generated by torchgen/gen.py from DispatchKeyFunction.h + +// NB: The implementing C++ file is RegisterDispatchKey.cpp + +// The only #includes we need are for custom classes that have defaults in the C++ API +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { + +namespace compositeexplicitautograd { + +TORCH_API at::Tensor diagonal_backward(const at::Tensor & grad_output, at::IntArrayRef input_sizes, int64_t offset, int64_t dim1, int64_t dim2); +TORCH_API at::Tensor diagonal_backward_symint(const at::Tensor & grad_output, c10::SymIntArrayRef input_sizes, int64_t offset, int64_t dim1, int64_t dim2); +TORCH_API at::Tensor & diagonal_backward_out(at::Tensor & out, const at::Tensor & grad_output, at::IntArrayRef input_sizes, int64_t offset, int64_t dim1, int64_t dim2); +TORCH_API at::Tensor & diagonal_backward_outf(const at::Tensor & grad_output, at::IntArrayRef input_sizes, int64_t offset, int64_t dim1, int64_t dim2, at::Tensor & out); +TORCH_API at::Tensor & diagonal_backward_symint_out(at::Tensor & out, const at::Tensor & grad_output, c10::SymIntArrayRef input_sizes, int64_t offset, int64_t dim1, int64_t dim2); +TORCH_API at::Tensor & diagonal_backward_symint_outf(const at::Tensor & grad_output, c10::SymIntArrayRef input_sizes, int64_t offset, int64_t dim1, int64_t dim2, at::Tensor & out); + +} // namespace compositeexplicitautograd +} // namespace at diff --git a/shared/package-files/00/00e18bb82020f479d75e45d0b1519ada543a4c0c6a935f06d11a72b6c0f4481a/blob b/shared/package-files/00/00e18bb82020f479d75e45d0b1519ada543a4c0c6a935f06d11a72b6c0f4481a/blob new file mode 100644 index 0000000000000000000000000000000000000000..75354cedcc972590eac9cacd1bdf153b62b8fed2 --- /dev/null +++ b/shared/package-files/00/00e18bb82020f479d75e45d0b1519ada543a4c0c6a935f06d11a72b6c0f4481a/blob @@ -0,0 +1,8 @@ +from typing import Any + +def wsgi_errors_stream(): ... +def has_level_handler(logger: Any): ... + +default_handler: Any + +def create_logger(app: Any): ... diff --git a/shared/package-files/00/00e480b57333389137ad7c0015b0674683edfe29c544981ce12fd7bd306a3964/blob b/shared/package-files/00/00e480b57333389137ad7c0015b0674683edfe29c544981ce12fd7bd306a3964/blob new file mode 100644 index 0000000000000000000000000000000000000000..2b48303c7a513de89ca97c84fe477104a16503bf --- /dev/null +++ b/shared/package-files/00/00e480b57333389137ad7c0015b0674683edfe29c544981ce12fd7bd306a3964/blob @@ -0,0 +1,10 @@ +libdir=/opt/conda/lib +includedir=/opt/conda/include + +Name: gtest_main +Description: GoogleTest (with main() function) +Version: 1.11.0 +URL: https://github.com/google/googletest +Requires: gtest = 1.11.0 +Libs: -L${libdir} -lgtest_main -lpthread +Cflags: -I${includedir} -DGTEST_HAS_PTHREAD=1 diff --git a/shared/package-files/00/00e743ca2baee2dda2b691e115c05dbd8f93833ce2d47c10367bb695adf2697c/blob b/shared/package-files/00/00e743ca2baee2dda2b691e115c05dbd8f93833ce2d47c10367bb695adf2697c/blob new file mode 100644 index 0000000000000000000000000000000000000000..49e5ac4ea9b3a7080f99c2bbccf0aafb552c743b --- /dev/null +++ b/shared/package-files/00/00e743ca2baee2dda2b691e115c05dbd8f93833ce2d47c10367bb695adf2697c/blob @@ -0,0 +1,46 @@ +from __future__ import annotations + +from .dialogs import ( + button_dialog, + checkboxlist_dialog, + input_dialog, + message_dialog, + progress_dialog, + radiolist_dialog, + yes_no_dialog, +) +from .progress_bar import ProgressBar, ProgressBarCounter +from .prompt import ( + CompleteStyle, + PromptSession, + confirm, + create_confirm_session, + prompt, +) +from .utils import clear, clear_title, print_container, print_formatted_text, set_title + +__all__ = [ + # Dialogs. + "input_dialog", + "message_dialog", + "progress_dialog", + "checkboxlist_dialog", + "radiolist_dialog", + "yes_no_dialog", + "button_dialog", + # Prompts. + "PromptSession", + "prompt", + "confirm", + "create_confirm_session", + "CompleteStyle", + # Progress bars. + "ProgressBar", + "ProgressBarCounter", + # Utils. + "clear", + "clear_title", + "print_container", + "print_formatted_text", + "set_title", +] diff --git a/shared/package-files/00/00e7764971f660f09a40be6303a21e8187af74c164027183ed27a1f430b68121/blob b/shared/package-files/00/00e7764971f660f09a40be6303a21e8187af74c164027183ed27a1f430b68121/blob new file mode 100644 index 0000000000000000000000000000000000000000..a040efc4bba984d27b132e961f8245c1ec11721d --- /dev/null +++ b/shared/package-files/00/00e7764971f660f09a40be6303a21e8187af74c164027183ed27a1f430b68121/blob @@ -0,0 +1,1096 @@ +import asyncio +import asyncio.events +import functools +import inspect +import io +import numbers +import os +import re +import threading +from contextlib import contextmanager +from glob import has_magic +from typing import TYPE_CHECKING, Iterable + +from .callbacks import DEFAULT_CALLBACK +from .exceptions import FSTimeoutError +from .implementations.local import LocalFileSystem, make_path_posix, trailing_sep +from .spec import AbstractBufferedFile, AbstractFileSystem +from .utils import glob_translate, is_exception, other_paths + +private = re.compile("_[^_]") +iothread = [None] # dedicated fsspec IO thread +loop = [None] # global event loop for any non-async instance +_lock = None # global lock placeholder +get_running_loop = asyncio.get_running_loop + + +def get_lock(): + """Allocate or return a threading lock. + + The lock is allocated on first use to allow setting one lock per forked process. + """ + global _lock + if not _lock: + _lock = threading.Lock() + return _lock + + +def reset_lock(): + """Reset the global lock. + + This should be called only on the init of a forked process to reset the lock to + None, enabling the new forked process to get a new lock. + """ + global _lock + + iothread[0] = None + loop[0] = None + _lock = None + + +async def _runner(event, coro, result, timeout=None): + timeout = timeout if timeout else None # convert 0 or 0.0 to None + if timeout is not None: + coro = asyncio.wait_for(coro, timeout=timeout) + try: + result[0] = await coro + except Exception as ex: + result[0] = ex + finally: + event.set() + + +def sync(loop, func, *args, timeout=None, **kwargs): + """ + Make loop run coroutine until it returns. Runs in other thread + + Examples + -------- + >>> fsspec.asyn.sync(fsspec.asyn.get_loop(), func, *args, + timeout=timeout, **kwargs) + """ + timeout = timeout if timeout else None # convert 0 or 0.0 to None + # NB: if the loop is not running *yet*, it is OK to submit work + # and we will wait for it + if loop is None or loop.is_closed(): + raise RuntimeError("Loop is not running") + try: + loop0 = asyncio.events.get_running_loop() + if loop0 is loop: + raise NotImplementedError("Calling sync() from within a running loop") + except NotImplementedError: + raise + except RuntimeError: + pass + coro = func(*args, **kwargs) + result = [None] + event = threading.Event() + asyncio.run_coroutine_threadsafe(_runner(event, coro, result, timeout), loop) + while True: + # this loops allows thread to get interrupted + if event.wait(1): + break + if timeout is not None: + timeout -= 1 + if timeout < 0: + raise FSTimeoutError + + return_result = result[0] + if isinstance(return_result, asyncio.TimeoutError): + # suppress asyncio.TimeoutError, raise FSTimeoutError + raise FSTimeoutError from return_result + elif isinstance(return_result, BaseException): + raise return_result + else: + return return_result + + +def sync_wrapper(func, obj=None): + """Given a function, make so can be called in blocking contexts + + Leave obj=None if defining within a class. Pass the instance if attaching + as an attribute of the instance. + """ + + @functools.wraps(func) + def wrapper(*args, **kwargs): + self = obj or args[0] + return sync(self.loop, func, *args, **kwargs) + + return wrapper + + +@contextmanager +def _selector_policy(): + original_policy = asyncio.get_event_loop_policy() + try: + if os.name == "nt" and hasattr(asyncio, "WindowsSelectorEventLoopPolicy"): + asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy()) + + yield + finally: + asyncio.set_event_loop_policy(original_policy) + + +def get_loop(): + """Create or return the default fsspec IO loop + + The loop will be running on a separate thread. + """ + if loop[0] is None: + with get_lock(): + # repeat the check just in case the loop got filled between the + # previous two calls from another thread + if loop[0] is None: + with _selector_policy(): + loop[0] = asyncio.new_event_loop() + th = threading.Thread(target=loop[0].run_forever, name="fsspecIO") + th.daemon = True + th.start() + iothread[0] = th + return loop[0] + + +if TYPE_CHECKING: + import resource + + ResourceError = resource.error +else: + try: + import resource + except ImportError: + resource = None + ResourceError = OSError + else: + ResourceError = getattr(resource, "error", OSError) + +_DEFAULT_BATCH_SIZE = 128 +_NOFILES_DEFAULT_BATCH_SIZE = 1280 + + +def _get_batch_size(nofiles=False): + from fsspec.config import conf + + if nofiles: + if "nofiles_gather_batch_size" in conf: + return conf["nofiles_gather_batch_size"] + else: + if "gather_batch_size" in conf: + return conf["gather_batch_size"] + if nofiles: + return _NOFILES_DEFAULT_BATCH_SIZE + if resource is None: + return _DEFAULT_BATCH_SIZE + + try: + soft_limit, _ = resource.getrlimit(resource.RLIMIT_NOFILE) + except (ImportError, ValueError, ResourceError): + return _DEFAULT_BATCH_SIZE + + if soft_limit == resource.RLIM_INFINITY: + return -1 + else: + return soft_limit // 8 + + +def running_async() -> bool: + """Being executed by an event loop?""" + try: + asyncio.get_running_loop() + return True + except RuntimeError: + return False + + +async def _run_coros_in_chunks( + coros, + batch_size=None, + callback=DEFAULT_CALLBACK, + timeout=None, + return_exceptions=False, + nofiles=False, +): + """Run the given coroutines in chunks. + + Parameters + ---------- + coros: list of coroutines to run + batch_size: int or None + Number of coroutines to submit/wait on simultaneously. + If -1, then it will not be any throttling. If + None, it will be inferred from _get_batch_size() + callback: fsspec.callbacks.Callback instance + Gets a relative_update when each coroutine completes + timeout: number or None + If given, each coroutine times out after this time. Note that, since + there are multiple batches, the total run time of this function will in + general be longer + return_exceptions: bool + Same meaning as in asyncio.gather + nofiles: bool + If inferring the batch_size, does this operation involve local files? + If yes, you normally expect smaller batches. + """ + + if batch_size is None: + batch_size = _get_batch_size(nofiles=nofiles) + + if batch_size == -1: + batch_size = len(coros) + + assert batch_size > 0 + + async def _run_coro(coro, i): + try: + return await asyncio.wait_for(coro, timeout=timeout), i + except Exception as e: + if not return_exceptions: + raise + return e, i + finally: + callback.relative_update(1) + + i = 0 + n = len(coros) + results = [None] * n + pending = set() + + while pending or i < n: + while len(pending) < batch_size and i < n: + pending.add(asyncio.ensure_future(_run_coro(coros[i], i))) + i += 1 + + if not pending: + break + + done, pending = await asyncio.wait(pending, return_when=asyncio.FIRST_COMPLETED) + while done: + result, k = await done.pop() + results[k] = result + + return results + + +# these methods should be implemented as async by any async-able backend +async_methods = [ + "_ls", + "_cat_file", + "_get_file", + "_put_file", + "_rm_file", + "_cp_file", + "_pipe_file", + "_expand_path", + "_info", + "_isfile", + "_isdir", + "_exists", + "_walk", + "_glob", + "_find", + "_du", + "_size", + "_mkdir", + "_makedirs", +] + + +class AsyncFileSystem(AbstractFileSystem): + """Async file operations, default implementations + + Passes bulk operations to asyncio.gather for concurrent operation. + + Implementations that have concurrent batch operations and/or async methods + should inherit from this class instead of AbstractFileSystem. Docstrings are + copied from the un-underscored method in AbstractFileSystem, if not given. + """ + + # note that methods do not have docstring here; they will be copied + # for _* methods and inferred for overridden methods. + + async_impl = True + mirror_sync_methods = True + disable_throttling = False + + def __init__(self, *args, asynchronous=False, loop=None, batch_size=None, **kwargs): + self.asynchronous = asynchronous + self._pid = os.getpid() + if not asynchronous: + self._loop = loop or get_loop() + else: + self._loop = None + self.batch_size = batch_size + super().__init__(*args, **kwargs) + + @property + def loop(self): + if self._pid != os.getpid(): + raise RuntimeError("This class is not fork-safe") + return self._loop + + async def _rm_file(self, path, **kwargs): + raise NotImplementedError + + async def _rm(self, path, recursive=False, batch_size=None, **kwargs): + # TODO: implement on_error + batch_size = batch_size or self.batch_size + path = await self._expand_path(path, recursive=recursive) + return await _run_coros_in_chunks( + [self._rm_file(p, **kwargs) for p in reversed(path)], + batch_size=batch_size, + nofiles=True, + ) + + async def _cp_file(self, path1, path2, **kwargs): + raise NotImplementedError + + async def _copy( + self, + path1, + path2, + recursive=False, + on_error=None, + maxdepth=None, + batch_size=None, + **kwargs, + ): + if on_error is None and recursive: + on_error = "ignore" + elif on_error is None: + on_error = "raise" + + if isinstance(path1, list) and isinstance(path2, list): + # No need to expand paths when both source and destination + # are provided as lists + paths1 = path1 + paths2 = path2 + else: + source_is_str = isinstance(path1, str) + paths1 = await self._expand_path( + path1, maxdepth=maxdepth, recursive=recursive + ) + if source_is_str and (not recursive or maxdepth is not None): + # Non-recursive glob does not copy directories + paths1 = [ + p for p in paths1 if not (trailing_sep(p) or await self._isdir(p)) + ] + if not paths1: + return + + source_is_file = len(paths1) == 1 + dest_is_dir = isinstance(path2, str) and ( + trailing_sep(path2) or await self._isdir(path2) + ) + + exists = source_is_str and ( + (has_magic(path1) and source_is_file) + or (not has_magic(path1) and dest_is_dir and not trailing_sep(path1)) + ) + paths2 = other_paths( + paths1, + path2, + exists=exists, + flatten=not source_is_str, + ) + + batch_size = batch_size or self.batch_size + coros = [self._cp_file(p1, p2, **kwargs) for p1, p2 in zip(paths1, paths2)] + result = await _run_coros_in_chunks( + coros, batch_size=batch_size, return_exceptions=True, nofiles=True + ) + + for ex in filter(is_exception, result): + if on_error == "ignore" and isinstance(ex, FileNotFoundError): + continue + raise ex + + async def _pipe_file(self, path, value, **kwargs): + raise NotImplementedError + + async def _pipe(self, path, value=None, batch_size=None, **kwargs): + if isinstance(path, str): + path = {path: value} + batch_size = batch_size or self.batch_size + return await _run_coros_in_chunks( + [self._pipe_file(k, v, **kwargs) for k, v in path.items()], + batch_size=batch_size, + nofiles=True, + ) + + async def _process_limits(self, url, start, end): + """Helper for "Range"-based _cat_file""" + size = None + suff = False + if start is not None and start < 0: + # if start is negative and end None, end is the "suffix length" + if end is None: + end = -start + start = "" + suff = True + else: + size = size or (await self._info(url))["size"] + start = size + start + elif start is None: + start = 0 + if not suff: + if end is not None and end < 0: + if start is not None: + size = size or (await self._info(url))["size"] + end = size + end + elif end is None: + end = "" + if isinstance(end, numbers.Integral): + end -= 1 # bytes range is inclusive + return f"bytes={start}-{end}" + + async def _cat_file(self, path, start=None, end=None, **kwargs): + raise NotImplementedError + + async def _cat( + self, path, recursive=False, on_error="raise", batch_size=None, **kwargs + ): + paths = await self._expand_path(path, recursive=recursive) + coros = [self._cat_file(path, **kwargs) for path in paths] + batch_size = batch_size or self.batch_size + out = await _run_coros_in_chunks( + coros, batch_size=batch_size, nofiles=True, return_exceptions=True + ) + if on_error == "raise": + ex = next(filter(is_exception, out), False) + if ex: + raise ex + if ( + len(paths) > 1 + or isinstance(path, list) + or paths[0] != self._strip_protocol(path) + ): + return { + k: v + for k, v in zip(paths, out) + if on_error != "omit" or not is_exception(v) + } + else: + return out[0] + + async def _cat_ranges( + self, + paths, + starts, + ends, + max_gap=None, + batch_size=None, + on_error="return", + **kwargs, + ): + """Get the contents of byte ranges from one or more files + + Parameters + ---------- + paths: list + A list of of filepaths on this filesystems + starts, ends: int or list + Bytes limits of the read. If using a single int, the same value will be + used to read all the specified files. + """ + # TODO: on_error + if max_gap is not None: + # use utils.merge_offset_ranges + raise NotImplementedError + if not isinstance(paths, list): + raise TypeError + if not isinstance(starts, Iterable): + starts = [starts] * len(paths) + if not isinstance(ends, Iterable): + ends = [ends] * len(paths) + if len(starts) != len(paths) or len(ends) != len(paths): + raise ValueError + coros = [ + self._cat_file(p, start=s, end=e, **kwargs) + for p, s, e in zip(paths, starts, ends) + ] + batch_size = batch_size or self.batch_size + return await _run_coros_in_chunks( + coros, batch_size=batch_size, nofiles=True, return_exceptions=True + ) + + async def _put_file(self, lpath, rpath, **kwargs): + raise NotImplementedError + + async def _put( + self, + lpath, + rpath, + recursive=False, + callback=DEFAULT_CALLBACK, + batch_size=None, + maxdepth=None, + **kwargs, + ): + """Copy file(s) from local. + + Copies a specific file or tree of files (if recursive=True). If rpath + ends with a "/", it will be assumed to be a directory, and target files + will go within. + + The put_file method will be called concurrently on a batch of files. The + batch_size option can configure the amount of futures that can be executed + at the same time. If it is -1, then all the files will be uploaded concurrently. + The default can be set for this instance by passing "batch_size" in the + constructor, or for all instances by setting the "gather_batch_size" key + in ``fsspec.config.conf``, falling back to 1/8th of the system limit . + """ + if isinstance(lpath, list) and isinstance(rpath, list): + # No need to expand paths when both source and destination + # are provided as lists + rpaths = rpath + lpaths = lpath + else: + source_is_str = isinstance(lpath, str) + if source_is_str: + lpath = make_path_posix(lpath) + fs = LocalFileSystem() + lpaths = fs.expand_path(lpath, recursive=recursive, maxdepth=maxdepth) + if source_is_str and (not recursive or maxdepth is not None): + # Non-recursive glob does not copy directories + lpaths = [p for p in lpaths if not (trailing_sep(p) or fs.isdir(p))] + if not lpaths: + return + + source_is_file = len(lpaths) == 1 + dest_is_dir = isinstance(rpath, str) and ( + trailing_sep(rpath) or await self._isdir(rpath) + ) + + rpath = self._strip_protocol(rpath) + exists = source_is_str and ( + (has_magic(lpath) and source_is_file) + or (not has_magic(lpath) and dest_is_dir and not trailing_sep(lpath)) + ) + rpaths = other_paths( + lpaths, + rpath, + exists=exists, + flatten=not source_is_str, + ) + + is_dir = {l: os.path.isdir(l) for l in lpaths} + rdirs = [r for l, r in zip(lpaths, rpaths) if is_dir[l]] + file_pairs = [(l, r) for l, r in zip(lpaths, rpaths) if not is_dir[l]] + + await asyncio.gather(*[self._makedirs(d, exist_ok=True) for d in rdirs]) + batch_size = batch_size or self.batch_size + + coros = [] + callback.set_size(len(file_pairs)) + for lfile, rfile in file_pairs: + put_file = callback.branch_coro(self._put_file) + coros.append(put_file(lfile, rfile, **kwargs)) + + return await _run_coros_in_chunks( + coros, batch_size=batch_size, callback=callback + ) + + async def _get_file(self, rpath, lpath, **kwargs): + raise NotImplementedError + + async def _get( + self, + rpath, + lpath, + recursive=False, + callback=DEFAULT_CALLBACK, + maxdepth=None, + **kwargs, + ): + """Copy file(s) to local. + + Copies a specific file or tree of files (if recursive=True). If lpath + ends with a "/", it will be assumed to be a directory, and target files + will go within. Can submit a list of paths, which may be glob-patterns + and will be expanded. + + The get_file method will be called concurrently on a batch of files. The + batch_size option can configure the amount of futures that can be executed + at the same time. If it is -1, then all the files will be uploaded concurrently. + The default can be set for this instance by passing "batch_size" in the + constructor, or for all instances by setting the "gather_batch_size" key + in ``fsspec.config.conf``, falling back to 1/8th of the system limit . + """ + if isinstance(lpath, list) and isinstance(rpath, list): + # No need to expand paths when both source and destination + # are provided as lists + rpaths = rpath + lpaths = lpath + else: + source_is_str = isinstance(rpath, str) + # First check for rpath trailing slash as _strip_protocol removes it. + source_not_trailing_sep = source_is_str and not trailing_sep(rpath) + rpath = self._strip_protocol(rpath) + rpaths = await self._expand_path( + rpath, recursive=recursive, maxdepth=maxdepth + ) + if source_is_str and (not recursive or maxdepth is not None): + # Non-recursive glob does not copy directories + rpaths = [ + p for p in rpaths if not (trailing_sep(p) or await self._isdir(p)) + ] + if not rpaths: + return + + lpath = make_path_posix(lpath) + source_is_file = len(rpaths) == 1 + dest_is_dir = isinstance(lpath, str) and ( + trailing_sep(lpath) or LocalFileSystem().isdir(lpath) + ) + + exists = source_is_str and ( + (has_magic(rpath) and source_is_file) + or (not has_magic(rpath) and dest_is_dir and source_not_trailing_sep) + ) + lpaths = other_paths( + rpaths, + lpath, + exists=exists, + flatten=not source_is_str, + ) + + [os.makedirs(os.path.dirname(lp), exist_ok=True) for lp in lpaths] + batch_size = kwargs.pop("batch_size", self.batch_size) + + coros = [] + callback.set_size(len(lpaths)) + for lpath, rpath in zip(lpaths, rpaths): + get_file = callback.branch_coro(self._get_file) + coros.append(get_file(rpath, lpath, **kwargs)) + return await _run_coros_in_chunks( + coros, batch_size=batch_size, callback=callback + ) + + async def _isfile(self, path): + try: + return (await self._info(path))["type"] == "file" + except: # noqa: E722 + return False + + async def _isdir(self, path): + try: + return (await self._info(path))["type"] == "directory" + except OSError: + return False + + async def _size(self, path): + return (await self._info(path)).get("size", None) + + async def _sizes(self, paths, batch_size=None): + batch_size = batch_size or self.batch_size + return await _run_coros_in_chunks( + [self._size(p) for p in paths], batch_size=batch_size + ) + + async def _exists(self, path, **kwargs): + try: + await self._info(path, **kwargs) + return True + except FileNotFoundError: + return False + + async def _info(self, path, **kwargs): + raise NotImplementedError + + async def _ls(self, path, detail=True, **kwargs): + raise NotImplementedError + + async def _walk(self, path, maxdepth=None, on_error="omit", **kwargs): + if maxdepth is not None and maxdepth < 1: + raise ValueError("maxdepth must be at least 1") + + path = self._strip_protocol(path) + full_dirs = {} + dirs = {} + files = {} + + detail = kwargs.pop("detail", False) + try: + listing = await self._ls(path, detail=True, **kwargs) + except (FileNotFoundError, OSError) as e: + if on_error == "raise": + raise + elif callable(on_error): + on_error(e) + if detail: + yield path, {}, {} + else: + yield path, [], [] + return + + for info in listing: + # each info name must be at least [path]/part , but here + # we check also for names like [path]/part/ + pathname = info["name"].rstrip("/") + name = pathname.rsplit("/", 1)[-1] + if info["type"] == "directory" and pathname != path: + # do not include "self" path + full_dirs[name] = pathname + dirs[name] = info + elif pathname == path: + # file-like with same name as give path + files[""] = info + else: + files[name] = info + + if detail: + yield path, dirs, files + else: + yield path, list(dirs), list(files) + + if maxdepth is not None: + maxdepth -= 1 + if maxdepth < 1: + return + + for d in dirs: + async for _ in self._walk( + full_dirs[d], maxdepth=maxdepth, detail=detail, **kwargs + ): + yield _ + + async def _glob(self, path, maxdepth=None, **kwargs): + if maxdepth is not None and maxdepth < 1: + raise ValueError("maxdepth must be at least 1") + + import re + + seps = (os.path.sep, os.path.altsep) if os.path.altsep else (os.path.sep,) + ends_with_sep = path.endswith(seps) # _strip_protocol strips trailing slash + path = self._strip_protocol(path) + append_slash_to_dirname = ends_with_sep or path.endswith( + tuple(sep + "**" for sep in seps) + ) + idx_star = path.find("*") if path.find("*") >= 0 else len(path) + idx_qmark = path.find("?") if path.find("?") >= 0 else len(path) + idx_brace = path.find("[") if path.find("[") >= 0 else len(path) + + min_idx = min(idx_star, idx_qmark, idx_brace) + + detail = kwargs.pop("detail", False) + + if not has_magic(path): + if await self._exists(path, **kwargs): + if not detail: + return [path] + else: + return {path: await self._info(path, **kwargs)} + else: + if not detail: + return [] # glob of non-existent returns empty + else: + return {} + elif "/" in path[:min_idx]: + min_idx = path[:min_idx].rindex("/") + root = path[: min_idx + 1] + depth = path[min_idx + 1 :].count("/") + 1 + else: + root = "" + depth = path[min_idx + 1 :].count("/") + 1 + + if "**" in path: + if maxdepth is not None: + idx_double_stars = path.find("**") + depth_double_stars = path[idx_double_stars:].count("/") + 1 + depth = depth - depth_double_stars + maxdepth + else: + depth = None + + allpaths = await self._find( + root, maxdepth=depth, withdirs=True, detail=True, **kwargs + ) + + pattern = glob_translate(path + ("/" if ends_with_sep else "")) + pattern = re.compile(pattern) + + out = { + p: info + for p, info in sorted(allpaths.items()) + if pattern.match( + ( + p + "/" + if append_slash_to_dirname and info["type"] == "directory" + else p + ) + ) + } + + if detail: + return out + else: + return list(out) + + async def _du(self, path, total=True, maxdepth=None, **kwargs): + sizes = {} + # async for? + for f in await self._find(path, maxdepth=maxdepth, **kwargs): + info = await self._info(f) + sizes[info["name"]] = info["size"] + if total: + return sum(sizes.values()) + else: + return sizes + + async def _find(self, path, maxdepth=None, withdirs=False, **kwargs): + path = self._strip_protocol(path) + out = {} + detail = kwargs.pop("detail", False) + + # Add the root directory if withdirs is requested + # This is needed for posix glob compliance + if withdirs and path != "" and await self._isdir(path): + out[path] = await self._info(path) + + # async for? + async for _, dirs, files in self._walk(path, maxdepth, detail=True, **kwargs): + if withdirs: + files.update(dirs) + out.update({info["name"]: info for name, info in files.items()}) + if not out and (await self._isfile(path)): + # walk works on directories, but find should also return [path] + # when path happens to be a file + out[path] = {} + names = sorted(out) + if not detail: + return names + else: + return {name: out[name] for name in names} + + async def _expand_path(self, path, recursive=False, maxdepth=None): + if maxdepth is not None and maxdepth < 1: + raise ValueError("maxdepth must be at least 1") + + if isinstance(path, str): + out = await self._expand_path([path], recursive, maxdepth) + else: + out = set() + path = [self._strip_protocol(p) for p in path] + for p in path: # can gather here + if has_magic(p): + bit = set(await self._glob(p, maxdepth=maxdepth)) + out |= bit + if recursive: + # glob call above expanded one depth so if maxdepth is defined + # then decrement it in expand_path call below. If it is zero + # after decrementing then avoid expand_path call. + if maxdepth is not None and maxdepth <= 1: + continue + out |= set( + await self._expand_path( + list(bit), + recursive=recursive, + maxdepth=maxdepth - 1 if maxdepth is not None else None, + ) + ) + continue + elif recursive: + rec = set(await self._find(p, maxdepth=maxdepth, withdirs=True)) + out |= rec + if p not in out and (recursive is False or (await self._exists(p))): + # should only check once, for the root + out.add(p) + if not out: + raise FileNotFoundError(path) + return sorted(out) + + async def _mkdir(self, path, create_parents=True, **kwargs): + pass # not necessary to implement, may not have directories + + async def _makedirs(self, path, exist_ok=False): + pass # not necessary to implement, may not have directories + + async def open_async(self, path, mode="rb", **kwargs): + if "b" not in mode or kwargs.get("compression"): + raise ValueError + raise NotImplementedError + + +def mirror_sync_methods(obj): + """Populate sync and async methods for obj + + For each method will create a sync version if the name refers to an async method + (coroutine) and there is no override in the child class; will create an async + method for the corresponding sync method if there is no implementation. + + Uses the methods specified in + - async_methods: the set that an implementation is expected to provide + - default_async_methods: that can be derived from their sync version in + AbstractFileSystem + - AsyncFileSystem: async-specific default coroutines + """ + from fsspec import AbstractFileSystem + + for method in async_methods + dir(AsyncFileSystem): + if not method.startswith("_"): + continue + smethod = method[1:] + if private.match(method): + isco = inspect.iscoroutinefunction(getattr(obj, method, None)) + unsync = getattr(getattr(obj, smethod, False), "__func__", None) + is_default = unsync is getattr(AbstractFileSystem, smethod, "") + if isco and is_default: + mth = sync_wrapper(getattr(obj, method), obj=obj) + setattr(obj, smethod, mth) + if not mth.__doc__: + mth.__doc__ = getattr( + getattr(AbstractFileSystem, smethod, None), "__doc__", "" + ) + + +class FSSpecCoroutineCancel(Exception): + pass + + +def _dump_running_tasks( + printout=True, cancel=True, exc=FSSpecCoroutineCancel, with_task=False +): + import traceback + + tasks = [t for t in asyncio.tasks.all_tasks(loop[0]) if not t.done()] + if printout: + [task.print_stack() for task in tasks] + out = [ + { + "locals": task._coro.cr_frame.f_locals, + "file": task._coro.cr_frame.f_code.co_filename, + "firstline": task._coro.cr_frame.f_code.co_firstlineno, + "linelo": task._coro.cr_frame.f_lineno, + "stack": traceback.format_stack(task._coro.cr_frame), + "task": task if with_task else None, + } + for task in tasks + ] + if cancel: + for t in tasks: + cbs = t._callbacks + t.cancel() + asyncio.futures.Future.set_exception(t, exc) + asyncio.futures.Future.cancel(t) + [cb[0](t) for cb in cbs] # cancels any dependent concurrent.futures + try: + t._coro.throw(exc) # exits coro, unless explicitly handled + except exc: + pass + return out + + +class AbstractAsyncStreamedFile(AbstractBufferedFile): + # no read buffering, and always auto-commit + # TODO: readahead might still be useful here, but needs async version + + async def read(self, length=-1): + """ + Return data from cache, or fetch pieces as necessary + + Parameters + ---------- + length: int (-1) + Number of bytes to read; if <0, all remaining bytes. + """ + length = -1 if length is None else int(length) + if self.mode != "rb": + raise ValueError("File not in read mode") + if length < 0: + length = self.size - self.loc + if self.closed: + raise ValueError("I/O operation on closed file.") + if length == 0: + # don't even bother calling fetch + return b"" + out = await self._fetch_range(self.loc, self.loc + length) + self.loc += len(out) + return out + + async def write(self, data): + """ + Write data to buffer. + + Buffer only sent on flush() or if buffer is greater than + or equal to blocksize. + + Parameters + ---------- + data: bytes + Set of bytes to be written. + """ + if self.mode not in {"wb", "ab"}: + raise ValueError("File not in write mode") + if self.closed: + raise ValueError("I/O operation on closed file.") + if self.forced: + raise ValueError("This file has been force-flushed, can only close") + out = self.buffer.write(data) + self.loc += out + if self.buffer.tell() >= self.blocksize: + await self.flush() + return out + + async def close(self): + """Close file + + Finalizes writes, discards cache + """ + if getattr(self, "_unclosable", False): + return + if self.closed: + return + if self.mode == "rb": + self.cache = None + else: + if not self.forced: + await self.flush(force=True) + + if self.fs is not None: + self.fs.invalidate_cache(self.path) + self.fs.invalidate_cache(self.fs._parent(self.path)) + + self.closed = True + + async def flush(self, force=False): + if self.closed: + raise ValueError("Flush on closed file") + if force and self.forced: + raise ValueError("Force flush cannot be called more than once") + if force: + self.forced = True + + if self.mode not in {"wb", "ab"}: + # no-op to flush on read-mode + return + + if not force and self.buffer.tell() < self.blocksize: + # Defer write on small block + return + + if self.offset is None: + # Initialize a multipart upload + self.offset = 0 + try: + await self._initiate_upload() + except: # noqa: E722 + self.closed = True + raise + + if await self._upload_chunk(final=force) is not False: + self.offset += self.buffer.seek(0, 2) + self.buffer = io.BytesIO() + + async def __aenter__(self): + return self + + async def __aexit__(self, exc_type, exc_val, exc_tb): + await self.close() + + async def _fetch_range(self, start, end): + raise NotImplementedError + + async def _initiate_upload(self): + pass + + async def _upload_chunk(self, final=False): + raise NotImplementedError diff --git a/shared/package-files/00/00e825125e7316ce462f28315dd656201bcb63c13e7ae194b4e2abebbd1d6119/blob b/shared/package-files/00/00e825125e7316ce462f28315dd656201bcb63c13e7ae194b4e2abebbd1d6119/blob new file mode 100644 index 0000000000000000000000000000000000000000..75f36313b3a1510dec9ec8107b1e5d1c2a781c49 --- /dev/null +++ b/shared/package-files/00/00e825125e7316ce462f28315dd656201bcb63c13e7ae194b4e2abebbd1d6119/blob @@ -0,0 +1,12 @@ +#pragma once + +#include + +namespace torch { +namespace jit { + +// updates the types of tuples according to the type of their current inputs. +TORCH_API void RefineTupleTypes(std::shared_ptr& graph); + +} // namespace jit +} // namespace torch diff --git a/shared/package-files/00/00e8a3bb66c2cead68e7624756a011eafe8cf402b0f7d8879787787e075d3ec0/blob b/shared/package-files/00/00e8a3bb66c2cead68e7624756a011eafe8cf402b0f7d8879787787e075d3ec0/blob new file mode 100644 index 0000000000000000000000000000000000000000..b6b6b000f10c8c73296f2428e9d69b2c42aaef39 --- /dev/null +++ b/shared/package-files/00/00e8a3bb66c2cead68e7624756a011eafe8cf402b0f7d8879787787e075d3ec0/blob @@ -0,0 +1,1367 @@ +""" +Compiler-side implementation of the dictionary. +""" +import ctypes +import operator +from enum import IntEnum + +from llvmlite import ir + +from numba import _helperlib + +from numba.core.extending import ( + overload, + overload_method, + overload_attribute, + intrinsic, + register_model, + models, + lower_builtin, + lower_cast, + make_attribute_wrapper, +) +from numba.core.imputils import iternext_impl, impl_ret_untracked +from numba.core import types, cgutils +from numba.core.types import ( + DictType, + DictItemsIterableType, + DictKeysIterableType, + DictValuesIterableType, + DictIteratorType, + Type, +) +from numba.core.imputils import impl_ret_borrowed, RefType +from numba.core.errors import TypingError, LoweringError, NumbaTypeError +from numba.core import typing +from numba.typed.typedobjectutils import (_as_bytes, _cast, _nonoptional, + _sentry_safe_cast_default, + _get_incref_decref, + _get_equal, _container_get_data,) + +ll_dict_type = cgutils.voidptr_t +ll_dictiter_type = cgutils.voidptr_t +ll_voidptr_type = cgutils.voidptr_t +ll_status = cgutils.int32_t +ll_ssize_t = cgutils.intp_t +ll_hash = ll_ssize_t +ll_bytes = cgutils.voidptr_t + + +_meminfo_dictptr = types.MemInfoPointer(types.voidptr) + + +# The following enums must match _dictobject.c + +class DKIX(IntEnum): + """Special return value of dict lookup. + """ + EMPTY = -1 + + +class Status(IntEnum): + """Status code for other dict operations. + """ + OK = 0 + OK_REPLACED = 1 + ERR_NO_MEMORY = -1 + ERR_DICT_MUTATED = -2 + ERR_ITER_EXHAUSTED = -3 + ERR_DICT_EMPTY = -4 + ERR_CMP_FAILED = -5 + + +def new_dict(key, value, n_keys=0): + """Construct a new dict with enough space for *n_keys* without a resize. + + Parameters + ---------- + key, value : TypeRef + Key type and value type of the new dict. + n_keys : int, default 0 + The number of keys to insert without needing a resize. + A value of 0 creates a dict with minimum size. + """ + # With JIT disabled, ignore all arguments and return a Python dict. + return dict() + + +@register_model(DictType) +class DictModel(models.StructModel): + def __init__(self, dmm, fe_type): + members = [ + ('meminfo', _meminfo_dictptr), + ('data', types.voidptr), # ptr to the C dict + ] + super(DictModel, self).__init__(dmm, fe_type, members) + + +@register_model(DictItemsIterableType) +@register_model(DictKeysIterableType) +@register_model(DictValuesIterableType) +@register_model(DictIteratorType) +class DictIterModel(models.StructModel): + def __init__(self, dmm, fe_type): + members = [ + ('parent', fe_type.parent), # reference to the dict + ('state', types.voidptr), # iterator state in C code + ] + super(DictIterModel, self).__init__(dmm, fe_type, members) + + +# Make _parent available to make len simple +make_attribute_wrapper(DictItemsIterableType, "parent", "_parent") +make_attribute_wrapper(DictKeysIterableType, "parent", "_parent") +make_attribute_wrapper(DictValuesIterableType, "parent", "_parent") + + +def _raise_if_error(context, builder, status, msg): + """Raise an internal error depending on the value of *status* + """ + ok_status = status.type(int(Status.OK)) + with builder.if_then(builder.icmp_signed('!=', status, ok_status)): + context.call_conv.return_user_exc(builder, RuntimeError, (msg,)) + + +@intrinsic +def _as_meminfo(typingctx, dctobj): + """Returns the MemInfoPointer of a dictionary. + """ + if not isinstance(dctobj, types.DictType): + raise TypingError('expected *dctobj* to be a DictType') + + def codegen(context, builder, sig, args): + [td] = sig.args + [d] = args + # Incref + context.nrt.incref(builder, td, d) + ctor = cgutils.create_struct_proxy(td) + dstruct = ctor(context, builder, value=d) + # Returns the plain MemInfo + return dstruct.meminfo + + sig = _meminfo_dictptr(dctobj) + return sig, codegen + + +@intrinsic +def _from_meminfo(typingctx, mi, dicttyperef): + """Recreate a dictionary from a MemInfoPointer + """ + if mi != _meminfo_dictptr: + raise TypingError('expected a MemInfoPointer for dict.') + dicttype = dicttyperef.instance_type + if not isinstance(dicttype, DictType): + raise TypingError('expected a {}'.format(DictType)) + + def codegen(context, builder, sig, args): + [tmi, tdref] = sig.args + td = tdref.instance_type + [mi, _] = args + + ctor = cgutils.create_struct_proxy(td) + dstruct = ctor(context, builder) + + data_pointer = context.nrt.meminfo_data(builder, mi) + data_pointer = builder.bitcast(data_pointer, ll_dict_type.as_pointer()) + + dstruct.data = builder.load(data_pointer) + dstruct.meminfo = mi + + return impl_ret_borrowed( + context, + builder, + dicttype, + dstruct._getvalue(), + ) + + sig = dicttype(mi, dicttyperef) + return sig, codegen + + +def _call_dict_free(context, builder, ptr): + """Call numba_dict_free(ptr) + """ + fnty = ir.FunctionType( + ir.VoidType(), + [ll_dict_type], + ) + free = cgutils.get_or_insert_function(builder.module, fnty, + 'numba_dict_free') + builder.call(free, [ptr]) + + +def _imp_dtor(context, module): + """Define the dtor for dictionary + """ + llvoidptr = context.get_value_type(types.voidptr) + llsize = context.get_value_type(types.uintp) + fnty = ir.FunctionType( + ir.VoidType(), + [llvoidptr, llsize, llvoidptr], + ) + fname = '_numba_dict_dtor' + fn = cgutils.get_or_insert_function(module, fnty, fname) + + if fn.is_declaration: + # Set linkage + fn.linkage = 'linkonce_odr' + # Define + builder = ir.IRBuilder(fn.append_basic_block()) + dp = builder.bitcast(fn.args[0], ll_dict_type.as_pointer()) + d = builder.load(dp) + _call_dict_free(context, builder, d) + builder.ret_void() + + return fn + + +@intrinsic +def _dict_new_sized(typingctx, n_keys, keyty, valty): + """Wrap numba_dict_new_sized. + + Allocate a new dictionary object with enough space to hold + *n_keys* keys without needing a resize. + + Parameters + ---------- + keyty, valty: Type + Type of the key and value, respectively. + n_keys: int + The number of keys to insert without needing a resize. + A value of 0 creates a dict with minimum size. + """ + resty = types.voidptr + sig = resty(n_keys, keyty, valty) + + def codegen(context, builder, sig, args): + n_keys = builder.bitcast(args[0], ll_ssize_t) + + # Determine sizeof key and value types + ll_key = context.get_data_type(keyty.instance_type) + ll_val = context.get_data_type(valty.instance_type) + sz_key = context.get_abi_sizeof(ll_key) + sz_val = context.get_abi_sizeof(ll_val) + + refdp = cgutils.alloca_once(builder, ll_dict_type, zfill=True) + + argtys = [ll_dict_type.as_pointer(), ll_ssize_t, ll_ssize_t, ll_ssize_t] + fnty = ir.FunctionType(ll_status, argtys) + fn = ir.Function(builder.module, fnty, 'numba_dict_new_sized') + + args = [refdp, n_keys, ll_ssize_t(sz_key), ll_ssize_t(sz_val)] + status = builder.call(fn, args) + + allocated_failed_msg = "Failed to allocate dictionary" + _raise_if_error(context, builder, status, msg=allocated_failed_msg) + + dp = builder.load(refdp) + return dp + + return sig, codegen + + +@intrinsic +def _dict_set_method_table(typingctx, dp, keyty, valty): + """Wrap numba_dict_set_method_table + """ + resty = types.void + sig = resty(dp, keyty, valty) + + def codegen(context, builder, sig, args): + vtablety = ir.LiteralStructType([ + ll_voidptr_type, # equal + ll_voidptr_type, # key incref + ll_voidptr_type, # key decref + ll_voidptr_type, # val incref + ll_voidptr_type, # val decref + ]) + setmethod_fnty = ir.FunctionType( + ir.VoidType(), + [ll_dict_type, vtablety.as_pointer()] + ) + setmethod_fn = ir.Function( + builder.module, + setmethod_fnty, + name='numba_dict_set_method_table', + ) + dp = args[0] + vtable = cgutils.alloca_once(builder, vtablety, zfill=True) + + # install key incref/decref + key_equal_ptr = cgutils.gep_inbounds(builder, vtable, 0, 0) + key_incref_ptr = cgutils.gep_inbounds(builder, vtable, 0, 1) + key_decref_ptr = cgutils.gep_inbounds(builder, vtable, 0, 2) + val_incref_ptr = cgutils.gep_inbounds(builder, vtable, 0, 3) + val_decref_ptr = cgutils.gep_inbounds(builder, vtable, 0, 4) + + dm_key = context.data_model_manager[keyty.instance_type] + if dm_key.contains_nrt_meminfo(): + equal = _get_equal(context, builder.module, dm_key, 'dict_key') + key_incref, key_decref = _get_incref_decref( + context, builder.module, dm_key, 'dict_key' + ) + builder.store( + builder.bitcast(equal, key_equal_ptr.type.pointee), + key_equal_ptr, + ) + builder.store( + builder.bitcast(key_incref, key_incref_ptr.type.pointee), + key_incref_ptr, + ) + builder.store( + builder.bitcast(key_decref, key_decref_ptr.type.pointee), + key_decref_ptr, + ) + + dm_val = context.data_model_manager[valty.instance_type] + if dm_val.contains_nrt_meminfo(): + val_incref, val_decref = _get_incref_decref( + context, builder.module, dm_val, 'dict_value' + ) + builder.store( + builder.bitcast(val_incref, val_incref_ptr.type.pointee), + val_incref_ptr, + ) + builder.store( + builder.bitcast(val_decref, val_decref_ptr.type.pointee), + val_decref_ptr, + ) + + builder.call(setmethod_fn, [dp, vtable]) + + return sig, codegen + + +@intrinsic +def _dict_insert(typingctx, d, key, hashval, val): + """Wrap numba_dict_insert + """ + resty = types.int32 + sig = resty(d, d.key_type, types.intp, d.value_type) + + def codegen(context, builder, sig, args): + fnty = ir.FunctionType( + ll_status, + [ll_dict_type, ll_bytes, ll_hash, ll_bytes, ll_bytes], + ) + [d, key, hashval, val] = args + [td, tkey, thashval, tval] = sig.args + fn = cgutils.get_or_insert_function(builder.module, fnty, + 'numba_dict_insert') + + dm_key = context.data_model_manager[tkey] + dm_val = context.data_model_manager[tval] + + data_key = dm_key.as_data(builder, key) + data_val = dm_val.as_data(builder, val) + + ptr_key = cgutils.alloca_once_value(builder, data_key) + cgutils.memset_padding(builder, ptr_key) + + ptr_val = cgutils.alloca_once_value(builder, data_val) + # TODO: the ptr_oldval is not used. needed for refct + ptr_oldval = cgutils.alloca_once(builder, data_val.type) + + dp = _container_get_data(context, builder, td, d) + status = builder.call( + fn, + [ + dp, + _as_bytes(builder, ptr_key), + hashval, + _as_bytes(builder, ptr_val), + _as_bytes(builder, ptr_oldval), + ], + ) + return status + + return sig, codegen + + +@intrinsic +def _dict_length(typingctx, d): + """Wrap numba_dict_length + + Returns the length of the dictionary. + """ + resty = types.intp + sig = resty(d) + + def codegen(context, builder, sig, args): + fnty = ir.FunctionType( + ll_ssize_t, + [ll_dict_type], + ) + fn = cgutils.get_or_insert_function(builder.module, fnty, + 'numba_dict_length') + [d] = args + [td] = sig.args + dp = _container_get_data(context, builder, td, d) + n = builder.call(fn, [dp]) + return n + + return sig, codegen + + +@intrinsic +def _dict_dump(typingctx, d): + """Dump the dictionary keys and values. + Wraps numba_dict_dump for debugging. + """ + resty = types.void + sig = resty(d) + + def codegen(context, builder, sig, args): + fnty = ir.FunctionType( + ir.VoidType(), + [ll_dict_type], + ) + [td] = sig.args + [d] = args + dp = _container_get_data(context, builder, td, d) + fn = cgutils.get_or_insert_function(builder.module, fnty, + 'numba_dict_dump') + + builder.call(fn, [dp]) + + return sig, codegen + + +@intrinsic +def _dict_lookup(typingctx, d, key, hashval): + """Wrap numba_dict_lookup + + Returns 2-tuple of (intp, ?value_type) + """ + resty = types.Tuple([types.intp, types.Optional(d.value_type)]) + sig = resty(d, key, hashval) + + def codegen(context, builder, sig, args): + fnty = ir.FunctionType( + ll_ssize_t, + [ll_dict_type, ll_bytes, ll_hash, ll_bytes], + ) + [td, tkey, thashval] = sig.args + [d, key, hashval] = args + fn = cgutils.get_or_insert_function(builder.module, fnty, + 'numba_dict_lookup') + + dm_key = context.data_model_manager[tkey] + dm_val = context.data_model_manager[td.value_type] + + data_key = dm_key.as_data(builder, key) + ptr_key = cgutils.alloca_once_value(builder, data_key) + cgutils.memset_padding(builder, ptr_key) + + ll_val = context.get_data_type(td.value_type) + ptr_val = cgutils.alloca_once(builder, ll_val) + + dp = _container_get_data(context, builder, td, d) + ix = builder.call( + fn, + [ + dp, + _as_bytes(builder, ptr_key), + hashval, + _as_bytes(builder, ptr_val), + ], + ) + # Load value if output is available + found = builder.icmp_signed('>', ix, ix.type(int(DKIX.EMPTY))) + + out = context.make_optional_none(builder, td.value_type) + pout = cgutils.alloca_once_value(builder, out) + + with builder.if_then(found): + val = dm_val.load_from_data_pointer(builder, ptr_val) + context.nrt.incref(builder, td.value_type, val) + loaded = context.make_optional_value(builder, td.value_type, val) + builder.store(loaded, pout) + + out = builder.load(pout) + return context.make_tuple(builder, resty, [ix, out]) + + return sig, codegen + + +@intrinsic +def _dict_popitem(typingctx, d): + """Wrap numba_dict_popitem + """ + + keyvalty = types.Tuple([d.key_type, d.value_type]) + resty = types.Tuple([types.int32, types.Optional(keyvalty)]) + sig = resty(d) + + def codegen(context, builder, sig, args): + fnty = ir.FunctionType( + ll_status, + [ll_dict_type, ll_bytes, ll_bytes], + ) + [d] = args + [td] = sig.args + fn = cgutils.get_or_insert_function(builder.module, fnty, + 'numba_dict_popitem') + + dm_key = context.data_model_manager[td.key_type] + dm_val = context.data_model_manager[td.value_type] + + ptr_key = cgutils.alloca_once(builder, dm_key.get_data_type()) + ptr_val = cgutils.alloca_once(builder, dm_val.get_data_type()) + + dp = _container_get_data(context, builder, td, d) + status = builder.call( + fn, + [ + dp, + _as_bytes(builder, ptr_key), + _as_bytes(builder, ptr_val), + ], + ) + out = context.make_optional_none(builder, keyvalty) + pout = cgutils.alloca_once_value(builder, out) + + cond = builder.icmp_signed('==', status, status.type(int(Status.OK))) + with builder.if_then(cond): + key = dm_key.load_from_data_pointer(builder, ptr_key) + val = dm_val.load_from_data_pointer(builder, ptr_val) + keyval = context.make_tuple(builder, keyvalty, [key, val]) + optkeyval = context.make_optional_value(builder, keyvalty, keyval) + builder.store(optkeyval, pout) + + out = builder.load(pout) + return cgutils.pack_struct(builder, [status, out]) + + return sig, codegen + + +@intrinsic +def _dict_delitem(typingctx, d, hk, ix): + """Wrap numba_dict_delitem + """ + resty = types.int32 + sig = resty(d, hk, types.intp) + + def codegen(context, builder, sig, args): + fnty = ir.FunctionType( + ll_status, + [ll_dict_type, ll_hash, ll_ssize_t], + ) + [d, hk, ix] = args + [td, thk, tix] = sig.args + + fn = cgutils.get_or_insert_function(builder.module, fnty, + 'numba_dict_delitem') + + dp = _container_get_data(context, builder, td, d) + status = builder.call(fn, [dp, hk, ix]) + return status + + return sig, codegen + + +def _iterator_codegen(resty): + """The common codegen for iterator intrinsics. + + Populates the iterator struct and increfs. + """ + + def codegen(context, builder, sig, args): + [d] = args + [td] = sig.args + iterhelper = context.make_helper(builder, resty) + iterhelper.parent = d + iterhelper.state = iterhelper.state.type(None) + return impl_ret_borrowed( + context, + builder, + resty, + iterhelper._getvalue(), + ) + + return codegen + + +@intrinsic +def _dict_items(typingctx, d): + """Get dictionary iterator for .items()""" + resty = types.DictItemsIterableType(d) + sig = resty(d) + codegen = _iterator_codegen(resty) + return sig, codegen + + +@intrinsic +def _dict_keys(typingctx, d): + """Get dictionary iterator for .keys()""" + resty = types.DictKeysIterableType(d) + sig = resty(d) + codegen = _iterator_codegen(resty) + return sig, codegen + + +@intrinsic +def _dict_values(typingctx, d): + """Get dictionary iterator for .values()""" + resty = types.DictValuesIterableType(d) + sig = resty(d) + codegen = _iterator_codegen(resty) + return sig, codegen + + +@intrinsic +def _make_dict(typingctx, keyty, valty, ptr): + """Make a dictionary struct with the given *ptr* + + Parameters + ---------- + keyty, valty: Type + Type of the key and value, respectively. + ptr : llvm pointer value + Points to the dictionary object. + """ + dict_ty = types.DictType(keyty.instance_type, valty.instance_type) + + def codegen(context, builder, signature, args): + [_, _, ptr] = args + ctor = cgutils.create_struct_proxy(dict_ty) + dstruct = ctor(context, builder) + dstruct.data = ptr + + alloc_size = context.get_abi_sizeof( + context.get_value_type(types.voidptr), + ) + dtor = _imp_dtor(context, builder.module) + meminfo = context.nrt.meminfo_alloc_dtor( + builder, + context.get_constant(types.uintp, alloc_size), + dtor, + ) + + data_pointer = context.nrt.meminfo_data(builder, meminfo) + data_pointer = builder.bitcast(data_pointer, ll_dict_type.as_pointer()) + builder.store(ptr, data_pointer) + + dstruct.meminfo = meminfo + + return dstruct._getvalue() + + sig = dict_ty(keyty, valty, ptr) + return sig, codegen + + +@overload(new_dict) +def impl_new_dict(key, value, n_keys=0): + """Creates a new dictionary with *key* and *value* as the type + of the dictionary key and value, respectively. *n_keys* is the + number of keys to insert without requiring a resize, where a + value of 0 creates a dictionary with minimum size. + """ + if any([ + not isinstance(key, Type), + not isinstance(value, Type), + ]): + raise NumbaTypeError("expecting *key* and *value* to be a Numba Type") + + keyty, valty = key, value + + def imp(key, value, n_keys=0): + if n_keys < 0: + raise RuntimeError("expecting *n_keys* to be >= 0") + dp = _dict_new_sized(n_keys, keyty, valty) + _dict_set_method_table(dp, keyty, valty) + d = _make_dict(keyty, valty, dp) + return d + + return imp + + +@overload(len) +def impl_len(d): + """len(dict) + """ + if not isinstance(d, types.DictType): + return + + def impl(d): + return _dict_length(d) + + return impl + + +@overload(len) +def impl_len_iters(d): + """len(dict.keys()), len(dict.values()), len(dict.items()) + """ + if not isinstance(d, (DictKeysIterableType, + DictValuesIterableType, DictItemsIterableType)): + return + + def impl(d): + return _dict_length(d._parent) + + return impl + + +@overload_method(types.DictType, '__setitem__') +@overload(operator.setitem) +def impl_setitem(d, key, value): + if not isinstance(d, types.DictType): + return + + keyty, valty = d.key_type, d.value_type + + def impl(d, key, value): + castedkey = _cast(key, keyty) + castedval = _cast(value, valty) + status = _dict_insert(d, castedkey, hash(castedkey), castedval) + if status == Status.OK: + return + elif status == Status.OK_REPLACED: + # replaced + # XXX handle refcount + return + elif status == Status.ERR_CMP_FAILED: + raise ValueError('key comparison failed') + else: + raise RuntimeError('dict.__setitem__ failed unexpectedly') + + if d.is_precise(): + # Handle the precise case. + return impl + else: + # Handle the imprecise case. + d = d.refine(key, value) + # Re-bind the key type and value type to match the arguments. + keyty, valty = d.key_type, d.value_type + # Create the signature that we wanted this impl to have. + sig = typing.signature(types.void, d, keyty, valty) + return sig, impl + + +@overload_method(types.DictType, 'get') +def impl_get(dct, key, default=None): + if not isinstance(dct, types.DictType): + return + keyty = dct.key_type + valty = dct.value_type + _sentry_safe_cast_default(default, valty) + + def impl(dct, key, default=None): + castedkey = _cast(key, keyty) + ix, val = _dict_lookup(dct, castedkey, hash(castedkey)) + if ix > DKIX.EMPTY: + return val + return default + + return impl + + +@overload_attribute(types.DictType, '__hash__') +def impl_hash(dct): + if not isinstance(dct, types.DictType): + return + return lambda dct: None + + +@overload(operator.getitem) +def impl_getitem(d, key): + if not isinstance(d, types.DictType): + return + + keyty = d.key_type + + def impl(d, key): + castedkey = _cast(key, keyty) + ix, val = _dict_lookup(d, castedkey, hash(castedkey)) + if ix == DKIX.EMPTY: + raise KeyError(key) + elif ix < DKIX.EMPTY: + raise AssertionError("internal dict error during lookup") + else: + return _nonoptional(val) + + return impl + + +@overload_method(types.DictType, 'popitem') +def impl_popitem(d): + if not isinstance(d, types.DictType): + return + + def impl(d): + status, keyval = _dict_popitem(d) + if status == Status.OK: + return _nonoptional(keyval) + elif status == Status.ERR_DICT_EMPTY: + raise KeyError() + else: + raise AssertionError('internal dict error during popitem') + + return impl + + +@overload_method(types.DictType, 'pop') +def impl_pop(dct, key, default=None): + if not isinstance(dct, types.DictType): + return + + keyty = dct.key_type + valty = dct.value_type + should_raise = isinstance(default, types.Omitted) + _sentry_safe_cast_default(default, valty) + + def impl(dct, key, default=None): + castedkey = _cast(key, keyty) + hashed = hash(castedkey) + ix, val = _dict_lookup(dct, castedkey, hashed) + if ix == DKIX.EMPTY: + if should_raise: + raise KeyError() + else: + return default + elif ix < DKIX.EMPTY: + raise AssertionError("internal dict error during lookup") + else: + status = _dict_delitem(dct, hashed, ix) + if status != Status.OK: + raise AssertionError("internal dict error during delitem") + return val + + return impl + + +@overload(operator.delitem) +def impl_delitem(d, k): + if not isinstance(d, types.DictType): + return + + def impl(d, k): + d.pop(k) + return impl + + +@overload(operator.contains) +def impl_contains(d, k): + if not isinstance(d, types.DictType): + return + + keyty = d.key_type + + def impl(d, k): + k = _cast(k, keyty) + ix, val = _dict_lookup(d, k, hash(k)) + return ix > DKIX.EMPTY + return impl + + +@overload_method(types.DictType, 'clear') +def impl_clear(d): + if not isinstance(d, types.DictType): + return + + def impl(d): + while len(d): + d.popitem() + + return impl + + +@overload_method(types.DictType, 'copy') +def impl_copy(d): + if not isinstance(d, types.DictType): + return + + key_type, val_type = d.key_type, d.value_type + + def impl(d): + newd = new_dict(key_type, val_type, n_keys=len(d)) + for k, v in d.items(): + newd[k] = v + return newd + + return impl + + +@overload_method(types.DictType, 'setdefault') +def impl_setdefault(dct, key, default=None): + if not isinstance(dct, types.DictType): + return + + def impl(dct, key, default=None): + if key not in dct: + dct[key] = default + return dct[key] + + return impl + + +@overload_method(types.DictType, 'items') +def impl_items(d): + if not isinstance(d, types.DictType): + return + + def impl(d): + it = _dict_items(d) + return it + + return impl + + +@overload_method(types.DictType, 'keys') +def impl_keys(d): + if not isinstance(d, types.DictType): + return + + def impl(d): + return _dict_keys(d) + + return impl + + +@overload_method(types.DictType, 'values') +def impl_values(d): + if not isinstance(d, types.DictType): + return + + def impl(d): + return _dict_values(d) + + return impl + + +@overload_method(types.DictType, 'update') +def ol_dict_update(d, other): + if not isinstance(d, types.DictType): + return + if not isinstance(other, types.DictType): + return + + def impl(d, other): + for k, v in other.items(): + d[k] = v + return impl + + +@overload(operator.eq) +def impl_equal(da, db): + if not isinstance(da, types.DictType): + return + if not isinstance(db, types.DictType): + # If RHS is not a dictionary, always returns False + def impl_type_mismatch(da, db): + return False + return impl_type_mismatch + + otherkeyty = db.key_type + + def impl_type_matched(da, db): + if len(da) != len(db): + return False + for ka, va in da.items(): + # Cast key from LHS to the key-type of RHS + kb = _cast(ka, otherkeyty) + ix, vb = _dict_lookup(db, kb, hash(kb)) + if ix <= DKIX.EMPTY: + # Quit early if the key is not found + return False + if va != vb: + # Quit early if the values do not match + return False + return True + + return impl_type_matched + + +@overload(operator.ne) +def impl_not_equal(da, db): + if not isinstance(da, types.DictType): + return + + def impl(da, db): + return not (da == db) + + return impl + + +@lower_builtin('getiter', types.DictItemsIterableType) +@lower_builtin('getiter', types.DictKeysIterableType) +@lower_builtin('getiter', types.DictValuesIterableType) +def impl_iterable_getiter(context, builder, sig, args): + """Implement iter() for .keys(), .values(), .items() + """ + iterablety = sig.args[0] + it = context.make_helper(builder, iterablety.iterator_type, args[0]) + + fnty = ir.FunctionType( + ir.VoidType(), + [ll_dictiter_type, ll_dict_type], + ) + + fn = cgutils.get_or_insert_function(builder.module, fnty, + 'numba_dict_iter') + + proto = ctypes.CFUNCTYPE(ctypes.c_size_t) + dictiter_sizeof = proto(_helperlib.c_helpers['dict_iter_sizeof']) + state_type = ir.ArrayType(ir.IntType(8), dictiter_sizeof()) + + pstate = cgutils.alloca_once(builder, state_type, zfill=True) + it.state = _as_bytes(builder, pstate) + + dp = _container_get_data(context, builder, iterablety.parent, it.parent) + builder.call(fn, [it.state, dp]) + return impl_ret_borrowed( + context, + builder, + sig.return_type, + it._getvalue(), + ) + + +@lower_builtin('getiter', types.DictType) +def impl_dict_getiter(context, builder, sig, args): + """Implement iter(Dict). Semantically equivalent to dict.keys() + """ + [td] = sig.args + [d] = args + iterablety = types.DictKeysIterableType(td) + it = context.make_helper(builder, iterablety.iterator_type) + + fnty = ir.FunctionType( + ir.VoidType(), + [ll_dictiter_type, ll_dict_type], + ) + + fn = cgutils.get_or_insert_function(builder.module, fnty, 'numba_dict_iter') + + proto = ctypes.CFUNCTYPE(ctypes.c_size_t) + dictiter_sizeof = proto(_helperlib.c_helpers['dict_iter_sizeof']) + state_type = ir.ArrayType(ir.IntType(8), dictiter_sizeof()) + + pstate = cgutils.alloca_once(builder, state_type, zfill=True) + it.state = _as_bytes(builder, pstate) + it.parent = d + + dp = _container_get_data(context, builder, iterablety.parent, args[0]) + builder.call(fn, [it.state, dp]) + return impl_ret_borrowed( + context, + builder, + sig.return_type, + it._getvalue(), + ) + + +@lower_builtin('iternext', types.DictIteratorType) +@iternext_impl(RefType.BORROWED) +def impl_iterator_iternext(context, builder, sig, args, result): + iter_type = sig.args[0] + it = context.make_helper(builder, iter_type, args[0]) + + p2p_bytes = ll_bytes.as_pointer() + + iternext_fnty = ir.FunctionType( + ll_status, + [ll_bytes, p2p_bytes, p2p_bytes] + ) + iternext = cgutils.get_or_insert_function( + builder.module, iternext_fnty, 'numba_dict_iter_next', + ) + key_raw_ptr = cgutils.alloca_once(builder, ll_bytes) + val_raw_ptr = cgutils.alloca_once(builder, ll_bytes) + + status = builder.call(iternext, (it.state, key_raw_ptr, val_raw_ptr)) + # TODO: no handling of error state i.e. mutated dictionary + # all errors are treated as exhausted iterator + is_valid = builder.icmp_unsigned('==', status, status.type(0)) + result.set_valid(is_valid) + + with builder.if_then(is_valid): + yield_type = iter_type.yield_type + key_ty, val_ty = iter_type.parent.keyvalue_type + + dm_key = context.data_model_manager[key_ty] + dm_val = context.data_model_manager[val_ty] + + key_ptr = builder.bitcast( + builder.load(key_raw_ptr), + dm_key.get_data_type().as_pointer(), + ) + val_ptr = builder.bitcast( + builder.load(val_raw_ptr), + dm_val.get_data_type().as_pointer(), + ) + + key = dm_key.load_from_data_pointer(builder, key_ptr) + val = dm_val.load_from_data_pointer(builder, val_ptr) + + # All dict iterators use this common implementation. + # Their differences are resolved here. + if isinstance(iter_type.iterable, DictItemsIterableType): + # .items() + tup = context.make_tuple(builder, yield_type, [key, val]) + result.yield_(tup) + elif isinstance(iter_type.iterable, DictKeysIterableType): + # .keys() + result.yield_(key) + elif isinstance(iter_type.iterable, DictValuesIterableType): + # .values() + result.yield_(val) + else: + # unreachable + raise AssertionError('unknown type: {}'.format(iter_type.iterable)) + + +def build_map(context, builder, dict_type, item_types, items): + + if isinstance(dict_type, types.LiteralStrKeyDict): + unliteral_tys = [x for x in + dict_type.literal_value.values()] + nbty = types.NamedTuple(unliteral_tys, + dict_type.tuple_ty) + values = [x[1] for x in items] + # replace with make_tuple call? + tup = context.get_constant_undef(nbty) + literal_tys = [x for x in dict_type.literal_value.values()] + + # this is to deal with repeated keys + value_index = dict_type.value_index + if value_index is None: + # 1:1 map keys:values + value_indexer = range(len(values)) + else: + # 1:>1 map keys:values, e.g. {'a':1, 'a': 'foo'} + value_indexer = value_index.values() + + for i, ix in enumerate(value_indexer): + val = values[ix] + casted = context.cast(builder, val, literal_tys[i], + unliteral_tys[i]) + tup = builder.insert_value(tup, casted, i) + d = tup + context.nrt.incref(builder, nbty, d) + + else: + from numba.typed import Dict + + dt = types.DictType(dict_type.key_type, dict_type.value_type) + kt, vt = dict_type.key_type, dict_type.value_type + sig = typing.signature(dt) + + def make_dict(): + return Dict.empty(kt, vt) + + d = context.compile_internal(builder, make_dict, sig, ()) + + if items: + for (kt, vt), (k, v) in zip(item_types, items): + sig = typing.signature(types.void, dt, kt, vt) + args = d, k, v + + def put(d, k, v): + d[k] = v + + context.compile_internal(builder, put, sig, args) + + return d + + +# ------------------------------------------------------------------------------ +# Literal dictionaries +# ------------------------------------------------------------------------------ + +@intrinsic +def _mixed_values_to_tuple(tyctx, d): + keys = [x for x in d.literal_value.keys()] + literal_tys = [x for x in d.literal_value.values()] + + def impl(cgctx, builder, sig, args): + lld, = args + impl = cgctx.get_function('static_getitem', + types.none(d, types.literal('dummy'))) + items = [] + for k in range(len(keys)): + item = impl(builder, (lld, k),) + casted = cgctx.cast(builder, item, literal_tys[k], d.types[k]) + items.append(casted) + cgctx.nrt.incref(builder, d.types[k], item) + ret = cgctx.make_tuple(builder, sig.return_type, items) + return ret + sig = types.Tuple(d.types)(d) + return sig, impl + + +@overload_method(types.LiteralStrKeyDict, 'values') +def literalstrkeydict_impl_values(d): + # This requires faking a values() iterator simply as a tuple, creating a + # type specialising iterator would be possible but horrendous and end up + # down the "versioned" loop body route. + if not isinstance(d, types.LiteralStrKeyDict): + return + + def impl(d): + return _mixed_values_to_tuple(d) + return impl + + +@overload_method(types.LiteralStrKeyDict, 'keys') +def literalstrkeydict_impl_keys(d): + if not isinstance(d, types.LiteralStrKeyDict): + return + # create a key iterator by specialising a DictType instance with the + # literal keys and returning that + t = tuple([x.literal_value for x in d.literal_value.keys()]) + + def impl(d): + d = dict() + for x in t: + d[x] = 0 + return d.keys() + return impl + + +# have to lower_builtin as this inherits from tuple and literal, both of which +# provide a match, hence ambiguous before proper resolution gets a chance +@lower_builtin(operator.eq, types.LiteralStrKeyDict, types.LiteralStrKeyDict) +def literalstrkeydict_impl_equals(context, builder, sig, args): + tu, tv = sig.args + u, v = args + pred = tu.literal_value == tv.literal_value + res = context.get_constant(types.boolean, pred) + return impl_ret_untracked(context, builder, sig.return_type, res) + + +@overload(operator.getitem) +@overload_method(types.LiteralStrKeyDict, 'get') +def literalstrkeydict_impl_get(dct, *args): + if not isinstance(dct, types.LiteralStrKeyDict): + return + msg = ("Cannot get{item}() on a literal dictionary, return type cannot be " + "statically determined") + raise TypingError(msg) + + +@overload_method(types.LiteralStrKeyDict, 'copy') +def literalstrkeydict_impl_copy(d): + if not isinstance(d, types.LiteralStrKeyDict): + return + + def impl(d): + return d + return impl + + +@intrinsic +def _str_items_mixed_values_to_tuple(tyctx, d): + keys = [x for x in d.literal_value.keys()] + literal_tys = [x for x in d.literal_value.values()] + + def impl(cgctx, builder, sig, args): + + lld, = args + impl = cgctx.get_function('static_getitem', + types.none(d, types.literal('dummy'))) + items = [] + from numba.cpython.unicode import make_string_from_constant + for k in range(len(keys)): + item = impl(builder, (lld, k),) + casted = cgctx.cast(builder, item, literal_tys[k], d.types[k]) + cgctx.nrt.incref(builder, d.types[k], item) + keydata = make_string_from_constant(cgctx, builder, + types.unicode_type, + keys[k].literal_value) + pair = cgctx.make_tuple(builder, + types.Tuple([types.unicode_type, + d.types[k]]), (keydata, casted)) + items.append(pair) + ret = cgctx.make_tuple(builder, sig.return_type, items) + return ret + kvs = [types.Tuple((types.unicode_type, x)) for x in d.types] + sig = types.Tuple(kvs)(d) + return sig, impl + + +@overload_method(types.LiteralStrKeyDict, 'items') +def literalstrkeydict_impl_items(d): + if not isinstance(d, types.LiteralStrKeyDict): + return + + def impl(d): + return _str_items_mixed_values_to_tuple(d) + return impl + + +@overload(operator.contains) +def literalstrkeydict_impl_contains(d, k): + if not isinstance(d, types.LiteralStrKeyDict): + return + + def impl(d, k): + for key in d.keys(): + if k == key: + return True + return False + return impl + + +@overload(len) +def literalstrkeydict_impl_len(d): + if not isinstance(d, types.LiteralStrKeyDict): + return + l = d.count + return lambda d: l + + +@overload(operator.setitem) +def literalstrkeydict_banned_impl_setitem(d, key, value): + if not isinstance(d, types.LiteralStrKeyDict): + return + raise TypingError("Cannot mutate a literal dictionary") + + +@overload(operator.delitem) +def literalstrkeydict_banned_impl_delitem(d, k): + if not isinstance(d, types.LiteralStrKeyDict): + return + raise TypingError("Cannot mutate a literal dictionary") + + +@overload_method(types.LiteralStrKeyDict, 'popitem') +@overload_method(types.LiteralStrKeyDict, 'pop') +@overload_method(types.LiteralStrKeyDict, 'clear') +@overload_method(types.LiteralStrKeyDict, 'setdefault') +@overload_method(types.LiteralStrKeyDict, 'update') +def literalstrkeydict_banned_impl_mutators(d, *args): + if not isinstance(d, types.LiteralStrKeyDict): + return + raise TypingError("Cannot mutate a literal dictionary") + + +@lower_cast(types.LiteralStrKeyDict, types.LiteralStrKeyDict) +def cast_LiteralStrKeyDict_LiteralStrKeyDict(context, builder, fromty, toty, + val): + # should have been picked up by typing + for (k1, v1), (k2, v2) in zip(fromty.literal_value.items(), + toty.literal_value.items()): + # these checks are just guards, typing should have picked up any + # problems + if k1 != k2: # keys must be same + msg = "LiteralDictionary keys are not the same {} != {}" + raise LoweringError(msg.format(k1, k2)) + # values must be same ty + if context.typing_context.unify_pairs(v1, v2) is None: + msg = "LiteralDictionary values cannot by unified, have {} and {}" + raise LoweringError(msg.format(v1, v2)) + else: + fromty = types.Tuple(fromty.types) + toty = types.Tuple(toty.types) + olditems = cgutils.unpack_tuple(builder, val, len(fromty)) + items = [context.cast(builder, v, f, t) + for v, f, t in zip(olditems, fromty, toty)] + return context.make_tuple(builder, toty, items) + + +@lower_cast(types.DictType, types.DictType) +def cast_DictType_DictType(context, builder, fromty, toty, val): + # should have been picked up by typing + return val diff --git a/shared/package-files/00/00f0eb214d9b8b016c4959a1ad78de9667389dd7266f424bf87d7cf59a7af3d8/blob b/shared/package-files/00/00f0eb214d9b8b016c4959a1ad78de9667389dd7266f424bf87d7cf59a7af3d8/blob new file mode 100644 index 0000000000000000000000000000000000000000..74255684c8fa75789e88fc224bcdac12aa1b29cf --- /dev/null +++ b/shared/package-files/00/00f0eb214d9b8b016c4959a1ad78de9667389dd7266f424bf87d7cf59a7af3d8/blob @@ -0,0 +1,347 @@ +import io +from typing import Iterator, List, Optional + +import torch +from torch import Tensor + +from torio.io._streaming_media_decoder import _get_afilter_desc, StreamingMediaDecoder as StreamReader +from torio.io._streaming_media_encoder import CodecConfig, StreamingMediaEncoder as StreamWriter + + +class _StreamingIOBuffer: + """Streaming Bytes IO buffer. Data are dropped when read.""" + + def __init__(self): + self._buffer: List(bytes) = [] + + def write(self, b: bytes): + if b: + self._buffer.append(b) + return len(b) + + def pop(self, n): + """Pop the oldest byte string. It does not necessary return the requested amount""" + if not self._buffer: + return b"" + if len(self._buffer[0]) <= n: + return self._buffer.pop(0) + ret = self._buffer[0][:n] + self._buffer[0] = self._buffer[0][n:] + return ret + + +def _get_sample_fmt(dtype: torch.dtype): + types = { + torch.uint8: "u8", + torch.int16: "s16", + torch.int32: "s32", + torch.float32: "flt", + torch.float64: "dbl", + } + if dtype not in types: + raise ValueError(f"Unsupported dtype is provided {dtype}. Supported dtypes are: {types.keys()}") + return types[dtype] + + +class _AudioStreamingEncoder: + """Given a waveform, encode on-demand and return bytes""" + + def __init__( + self, + src: Tensor, + sample_rate: int, + effect: str, + muxer: str, + encoder: Optional[str], + codec_config: Optional[CodecConfig], + frames_per_chunk: int, + ): + self.src = src + self.buffer = _StreamingIOBuffer() + self.writer = StreamWriter(self.buffer, format=muxer) + self.writer.add_audio_stream( + num_channels=src.size(1), + sample_rate=sample_rate, + format=_get_sample_fmt(src.dtype), + encoder=encoder, + filter_desc=effect, + codec_config=codec_config, + ) + self.writer.open() + self.fpc = frames_per_chunk + + # index on the input tensor (along time-axis) + # we use -1 to indicate that we finished iterating the tensor and + # the writer is closed. + self.i_iter = 0 + + def read(self, n): + while not self.buffer._buffer and self.i_iter >= 0: + self.writer.write_audio_chunk(0, self.src[self.i_iter : self.i_iter + self.fpc]) + self.i_iter += self.fpc + if self.i_iter >= self.src.size(0): + self.writer.flush() + self.writer.close() + self.i_iter = -1 + return self.buffer.pop(n) + + +def _encode( + src: Tensor, + sample_rate: int, + effect: str, + muxer: str, + encoder: Optional[str], + codec_config: Optional[CodecConfig], +): + buffer = io.BytesIO() + writer = StreamWriter(buffer, format=muxer) + writer.add_audio_stream( + num_channels=src.size(1), + sample_rate=sample_rate, + format=_get_sample_fmt(src.dtype), + encoder=encoder, + filter_desc=effect, + codec_config=codec_config, + ) + with writer.open(): + writer.write_audio_chunk(0, src) + buffer.seek(0) + return buffer + + +def _get_muxer(dtype: torch.dtype): + # TODO: check if this works in Windows. + types = { + torch.uint8: "u8", + torch.int16: "s16le", + torch.int32: "s32le", + torch.float32: "f32le", + torch.float64: "f64le", + } + if dtype not in types: + raise ValueError(f"Unsupported dtype is provided {dtype}. Supported dtypes are: {types.keys()}") + return types[dtype] + + +class AudioEffector: + """Apply various filters and/or codecs to waveforms. + + .. versionadded:: 2.1 + + Args: + effect (str or None, optional): Filter expressions or ``None`` to apply no filter. + See https://ffmpeg.org/ffmpeg-filters.html#Audio-Filters for the + details of filter syntax. + + format (str or None, optional): When provided, encode the audio into the + corresponding format. Default: ``None``. + + encoder (str or None, optional): When provided, override the encoder used + by the ``format``. Default: ``None``. + + codec_config (CodecConfig or None, optional): When provided, configure the encoding codec. + Should be provided in conjunction with ``format`` option. + + pad_end (bool, optional): When enabled, and if the waveform becomes shorter after applying + effects/codec, then pad the end with silence. + + Example - Basic usage + To use ``AudioEffector``, first instantiate it with a set of + ``effect`` and ``format``. + + >>> # instantiate the effector + >>> effector = AudioEffector(effect=..., format=...) + + Then, use :py:meth:`~AudioEffector.apply` or :py:meth:`~AudioEffector.stream` + method to apply them. + + >>> # Apply the effect to the whole waveform + >>> applied = effector.apply(waveform, sample_rate) + + >>> # Apply the effect chunk-by-chunk + >>> for chunk in effector.stream(waveform, sample_rate): + >>> ... + + Example - Applying effects + Please refer to + https://ffmpeg.org/ffmpeg-filters.html#Filtergraph-description + for the overview of filter description, and + https://ffmpeg.org/ffmpeg-filters.html#toc-Audio-Filters + for the list of available filters. + + Tempo - https://ffmpeg.org/ffmpeg-filters.html#atempo + + >>> AudioEffector(effect="atempo=1.5") + + Echo - https://ffmpeg.org/ffmpeg-filters.html#aecho + + >>> AudioEffector(effect="aecho=0.8:0.88:60:0.4") + + Flanger - https://ffmpeg.org/ffmpeg-filters.html#flanger + + >>> AudioEffector(effect="aflanger") + + Vibrato - https://ffmpeg.org/ffmpeg-filters.html#vibrato + + >>> AudioEffector(effect="vibrato") + + Tremolo - https://ffmpeg.org/ffmpeg-filters.html#tremolo + + >>> AudioEffector(effect="vibrato") + + You can also apply multiple effects at once. + + >>> AudioEffector(effect="") + + Example - Applying codec + One can apply codec using ``format`` argument. ``format`` can be + audio format or container format. If the container format supports + multiple encoders, you can specify it with ``encoder`` argument. + + Wav format + (no compression is applied but samples are converted to + 16-bit signed integer) + + >>> AudioEffector(format="wav") + + Ogg format with default encoder + + >>> AudioEffector(format="ogg") + + Ogg format with vorbis + + >>> AudioEffector(format="ogg", encoder="vorbis") + + Ogg format with opus + + >>> AudioEffector(format="ogg", encoder="opus") + + Webm format with opus + + >>> AudioEffector(format="webm", encoder="opus") + + Example - Applying codec with configuration + Reference: https://trac.ffmpeg.org/wiki/Encode/MP3 + + MP3 with default config + + >>> AudioEffector(format="mp3") + + MP3 with variable bitrate + + >>> AudioEffector(format="mp3", codec_config=CodecConfig(qscale=5)) + + MP3 with constant bitrate + + >>> AudioEffector(format="mp3", codec_config=CodecConfig(bit_rate=32_000)) + """ + + def __init__( + self, + effect: Optional[str] = None, + format: Optional[str] = None, + *, + encoder: Optional[str] = None, + codec_config: Optional[CodecConfig] = None, + pad_end: bool = True, + ): + if format is None: + if encoder is not None or codec_config is not None: + raise ValueError("`encoder` and/or `condec_config` opions are provided without `format` option.") + self.effect = effect + self.format = format + self.encoder = encoder + self.codec_config = codec_config + self.pad_end = pad_end + + def _get_reader(self, waveform, sample_rate, output_sample_rate, frames_per_chunk=None): + num_frames, num_channels = waveform.shape + + if self.format is not None: + muxer = self.format + encoder = self.encoder + option = {} + # Some formats are headerless, so need to provide these infomation. + if self.format == "mulaw": + option = {"sample_rate": f"{sample_rate}", "channels": f"{num_channels}"} + + else: # PCM + muxer = _get_muxer(waveform.dtype) + encoder = None + option = {"sample_rate": f"{sample_rate}", "channels": f"{num_channels}"} + + if frames_per_chunk is None: + src = _encode(waveform, sample_rate, self.effect, muxer, encoder, self.codec_config) + else: + src = _AudioStreamingEncoder( + waveform, sample_rate, self.effect, muxer, encoder, self.codec_config, frames_per_chunk + ) + + output_sr = sample_rate if output_sample_rate is None else output_sample_rate + filter_desc = _get_afilter_desc(output_sr, _get_sample_fmt(waveform.dtype), num_channels) + if self.pad_end: + filter_desc = f"{filter_desc},apad=whole_len={num_frames}" + + reader = StreamReader(src, format=muxer, option=option) + reader.add_audio_stream(frames_per_chunk or -1, -1, filter_desc=filter_desc) + return reader + + def apply(self, waveform: Tensor, sample_rate: int, output_sample_rate: Optional[int] = None) -> Tensor: + """Apply the effect and/or codecs to the whole tensor. + + Args: + waveform (Tensor): The input waveform. Shape: ``(time, channel)`` + sample_rate (int): Sample rate of the input waveform. + output_sample_rate (int or None, optional): Output sample rate. + If provided, override the output sample rate. + Otherwise, the resulting tensor is resampled to have + the same sample rate as the input. + Default: ``None``. + + Returns: + Tensor: + Resulting Tensor. Shape: ``(time, channel)``. The number of frames + could be different from that of the input. + """ + if waveform.ndim != 2: + raise ValueError(f"Expected the input waveform to be 2D. Found: {waveform.ndim}") + + if waveform.numel() == 0: + return waveform + + reader = self._get_reader(waveform, sample_rate, output_sample_rate) + reader.process_all_packets() + (applied,) = reader.pop_chunks() + return Tensor(applied) + + def stream( + self, waveform: Tensor, sample_rate: int, frames_per_chunk: int, output_sample_rate: Optional[int] = None + ) -> Iterator[Tensor]: + """Apply the effect and/or codecs to the given tensor chunk by chunk. + + Args: + waveform (Tensor): The input waveform. Shape: ``(time, channel)`` + sample_rate (int): Sample rate of the waveform. + frames_per_chunk (int): The number of frames to return at a time. + output_sample_rate (int or None, optional): Output sample rate. + If provided, override the output sample rate. + Otherwise, the resulting tensor is resampled to have + the same sample rate as the input. + Default: ``None``. + + Returns: + Iterator[Tensor]: + Series of processed chunks. Shape: ``(time, channel)``, where the + the number of frames matches ``frames_per_chunk`` except the + last chunk, which could be shorter. + """ + if waveform.ndim != 2: + raise ValueError(f"Expected the input waveform to be 2D. Found: {waveform.ndim}") + + if waveform.numel() == 0: + return waveform + + reader = self._get_reader(waveform, sample_rate, output_sample_rate, frames_per_chunk) + for (applied,) in reader.stream(): + yield Tensor(applied) diff --git a/shared/package-files/00/00f119701c9f3eba273701a6a731adafd7b8902f6bccf34e61308984456e193a/blob b/shared/package-files/00/00f119701c9f3eba273701a6a731adafd7b8902f6bccf34e61308984456e193a/blob new file mode 100644 index 0000000000000000000000000000000000000000..6ee0fc7f40c711e254f713ab86a3c8be654b5f49 --- /dev/null +++ b/shared/package-files/00/00f119701c9f3eba273701a6a731adafd7b8902f6bccf34e61308984456e193a/blob @@ -0,0 +1,52 @@ +# created by tools/loadICU.tcl -- do not edit +namespace eval ::tcl::clock { + ::msgcat::mcset sh DAYS_OF_WEEK_ABBREV [list \ + "Ned"\ + "Pon"\ + "Uto"\ + "Sre"\ + "\u010cet"\ + "Pet"\ + "Sub"] + ::msgcat::mcset sh DAYS_OF_WEEK_FULL [list \ + "Nedelja"\ + "Ponedeljak"\ + "Utorak"\ + "Sreda"\ + "\u010cetvrtak"\ + "Petak"\ + "Subota"] + ::msgcat::mcset sh MONTHS_ABBREV [list \ + "Jan"\ + "Feb"\ + "Mar"\ + "Apr"\ + "Maj"\ + "Jun"\ + "Jul"\ + "Avg"\ + "Sep"\ + "Okt"\ + "Nov"\ + "Dec"\ + ""] + ::msgcat::mcset sh MONTHS_FULL [list \ + "Januar"\ + "Februar"\ + "Mart"\ + "April"\ + "Maj"\ + "Juni"\ + "Juli"\ + "Avgust"\ + "Septembar"\ + "Oktobar"\ + "Novembar"\ + "Decembar"\ + ""] + ::msgcat::mcset sh BCE "p. n. e." + ::msgcat::mcset sh CE "n. e." + ::msgcat::mcset sh DATE_FORMAT "%d.%m.%Y." + ::msgcat::mcset sh TIME_FORMAT "%k.%M.%S" + ::msgcat::mcset sh DATE_TIME_FORMAT "%d.%m.%Y. %k.%M.%S %z" +} diff --git a/shared/package-files/00/00f29370ba18139ce888b59558de76ca163e58b3d7f56fa883b60577d23aba82/blob b/shared/package-files/00/00f29370ba18139ce888b59558de76ca163e58b3d7f56fa883b60577d23aba82/blob new file mode 100644 index 0000000000000000000000000000000000000000..9a549c76b8fe6676799a6a27c1bf78e9a2d3cdbf --- /dev/null +++ b/shared/package-files/00/00f29370ba18139ce888b59558de76ca163e58b3d7f56fa883b60577d23aba82/blob @@ -0,0 +1,34 @@ +from builtins import range as prange +from typing import TypeVar + +from _typeshed import Incomplete +from numpy import ndindex as pndindex + +from numba.core.typing.asnumbatype import as_numba_type +from numba.core.typing.typeof import typeof + +__all__ = [ + "typeof", + "as_numba_type", + "prange", + "pndindex", + "gdb", + "gdb_breakpoint", + "gdb_init", + "literally", + "literal_unroll", +] + +### + +_T = TypeVar("_T") + +### + +def gdb(*args: Incomplete) -> None: ... +def gdb_breakpoint() -> None: ... +def gdb_init(*args: Incomplete) -> None: ... + +# +def literally(obj: _T) -> _T: ... +def literal_unroll(container: _T) -> _T: ... diff --git a/shared/package-files/00/00f3702457ba7f1c52e54052472ce53f16b49a2c8534303edb55da36ae3b12b1/blob b/shared/package-files/00/00f3702457ba7f1c52e54052472ce53f16b49a2c8534303edb55da36ae3b12b1/blob new file mode 100644 index 0000000000000000000000000000000000000000..2784eeb214d5c59e1e3aa3ac21c7059f032f16de --- /dev/null +++ b/shared/package-files/00/00f3702457ba7f1c52e54052472ce53f16b49a2c8534303edb55da36ae3b12b1/blob @@ -0,0 +1,262 @@ +import math + +import torch +from torch.distributions import constraints +from torch.distributions.distribution import Distribution +from torch.distributions.utils import _standard_normal, lazy_property + +__all__ = ["MultivariateNormal"] + + +def _batch_mv(bmat, bvec): + r""" + Performs a batched matrix-vector product, with compatible but different batch shapes. + + This function takes as input `bmat`, containing :math:`n \times n` matrices, and + `bvec`, containing length :math:`n` vectors. + + Both `bmat` and `bvec` may have any number of leading dimensions, which correspond + to a batch shape. They are not necessarily assumed to have the same batch shape, + just ones which can be broadcasted. + """ + return torch.matmul(bmat, bvec.unsqueeze(-1)).squeeze(-1) + + +def _batch_mahalanobis(bL, bx): + r""" + Computes the squared Mahalanobis distance :math:`\mathbf{x}^\top\mathbf{M}^{-1}\mathbf{x}` + for a factored :math:`\mathbf{M} = \mathbf{L}\mathbf{L}^\top`. + + Accepts batches for both bL and bx. They are not necessarily assumed to have the same batch + shape, but `bL` one should be able to broadcasted to `bx` one. + """ + n = bx.size(-1) + bx_batch_shape = bx.shape[:-1] + + # Assume that bL.shape = (i, 1, n, n), bx.shape = (..., i, j, n), + # we are going to make bx have shape (..., 1, j, i, 1, n) to apply batched tri.solve + bx_batch_dims = len(bx_batch_shape) + bL_batch_dims = bL.dim() - 2 + outer_batch_dims = bx_batch_dims - bL_batch_dims + old_batch_dims = outer_batch_dims + bL_batch_dims + new_batch_dims = outer_batch_dims + 2 * bL_batch_dims + # Reshape bx with the shape (..., 1, i, j, 1, n) + bx_new_shape = bx.shape[:outer_batch_dims] + for sL, sx in zip(bL.shape[:-2], bx.shape[outer_batch_dims:-1]): + bx_new_shape += (sx // sL, sL) + bx_new_shape += (n,) + bx = bx.reshape(bx_new_shape) + # Permute bx to make it have shape (..., 1, j, i, 1, n) + permute_dims = ( + list(range(outer_batch_dims)) + + list(range(outer_batch_dims, new_batch_dims, 2)) + + list(range(outer_batch_dims + 1, new_batch_dims, 2)) + + [new_batch_dims] + ) + bx = bx.permute(permute_dims) + + flat_L = bL.reshape(-1, n, n) # shape = b x n x n + flat_x = bx.reshape(-1, flat_L.size(0), n) # shape = c x b x n + flat_x_swap = flat_x.permute(1, 2, 0) # shape = b x n x c + M_swap = ( + torch.linalg.solve_triangular(flat_L, flat_x_swap, upper=False).pow(2).sum(-2) + ) # shape = b x c + M = M_swap.t() # shape = c x b + + # Now we revert the above reshape and permute operators. + permuted_M = M.reshape(bx.shape[:-1]) # shape = (..., 1, j, i, 1) + permute_inv_dims = list(range(outer_batch_dims)) + for i in range(bL_batch_dims): + permute_inv_dims += [outer_batch_dims + i, old_batch_dims + i] + reshaped_M = permuted_M.permute(permute_inv_dims) # shape = (..., 1, i, j, 1) + return reshaped_M.reshape(bx_batch_shape) + + +def _precision_to_scale_tril(P): + # Ref: https://nbviewer.jupyter.org/gist/fehiepsi/5ef8e09e61604f10607380467eb82006#Precision-to-scale_tril + Lf = torch.linalg.cholesky(torch.flip(P, (-2, -1))) + L_inv = torch.transpose(torch.flip(Lf, (-2, -1)), -2, -1) + Id = torch.eye(P.shape[-1], dtype=P.dtype, device=P.device) + L = torch.linalg.solve_triangular(L_inv, Id, upper=False) + return L + + +class MultivariateNormal(Distribution): + r""" + Creates a multivariate normal (also called Gaussian) distribution + parameterized by a mean vector and a covariance matrix. + + The multivariate normal distribution can be parameterized either + in terms of a positive definite covariance matrix :math:`\mathbf{\Sigma}` + or a positive definite precision matrix :math:`\mathbf{\Sigma}^{-1}` + or a lower-triangular matrix :math:`\mathbf{L}` with positive-valued + diagonal entries, such that + :math:`\mathbf{\Sigma} = \mathbf{L}\mathbf{L}^\top`. This triangular matrix + can be obtained via e.g. Cholesky decomposition of the covariance. + + Example: + + >>> # xdoctest: +REQUIRES(env:TORCH_DOCTEST_LAPACK) + >>> # xdoctest: +IGNORE_WANT("non-deterministic") + >>> m = MultivariateNormal(torch.zeros(2), torch.eye(2)) + >>> m.sample() # normally distributed with mean=`[0,0]` and covariance_matrix=`I` + tensor([-0.2102, -0.5429]) + + Args: + loc (Tensor): mean of the distribution + covariance_matrix (Tensor): positive-definite covariance matrix + precision_matrix (Tensor): positive-definite precision matrix + scale_tril (Tensor): lower-triangular factor of covariance, with positive-valued diagonal + + Note: + Only one of :attr:`covariance_matrix` or :attr:`precision_matrix` or + :attr:`scale_tril` can be specified. + + Using :attr:`scale_tril` will be more efficient: all computations internally + are based on :attr:`scale_tril`. If :attr:`covariance_matrix` or + :attr:`precision_matrix` is passed instead, it is only used to compute + the corresponding lower triangular matrices using a Cholesky decomposition. + """ + arg_constraints = { + "loc": constraints.real_vector, + "covariance_matrix": constraints.positive_definite, + "precision_matrix": constraints.positive_definite, + "scale_tril": constraints.lower_cholesky, + } + support = constraints.real_vector + has_rsample = True + + def __init__( + self, + loc, + covariance_matrix=None, + precision_matrix=None, + scale_tril=None, + validate_args=None, + ): + if loc.dim() < 1: + raise ValueError("loc must be at least one-dimensional.") + if (covariance_matrix is not None) + (scale_tril is not None) + ( + precision_matrix is not None + ) != 1: + raise ValueError( + "Exactly one of covariance_matrix or precision_matrix or scale_tril may be specified." + ) + + if scale_tril is not None: + if scale_tril.dim() < 2: + raise ValueError( + "scale_tril matrix must be at least two-dimensional, " + "with optional leading batch dimensions" + ) + batch_shape = torch.broadcast_shapes(scale_tril.shape[:-2], loc.shape[:-1]) + self.scale_tril = scale_tril.expand(batch_shape + (-1, -1)) + elif covariance_matrix is not None: + if covariance_matrix.dim() < 2: + raise ValueError( + "covariance_matrix must be at least two-dimensional, " + "with optional leading batch dimensions" + ) + batch_shape = torch.broadcast_shapes( + covariance_matrix.shape[:-2], loc.shape[:-1] + ) + self.covariance_matrix = covariance_matrix.expand(batch_shape + (-1, -1)) + else: + if precision_matrix.dim() < 2: + raise ValueError( + "precision_matrix must be at least two-dimensional, " + "with optional leading batch dimensions" + ) + batch_shape = torch.broadcast_shapes( + precision_matrix.shape[:-2], loc.shape[:-1] + ) + self.precision_matrix = precision_matrix.expand(batch_shape + (-1, -1)) + self.loc = loc.expand(batch_shape + (-1,)) + + event_shape = self.loc.shape[-1:] + super().__init__(batch_shape, event_shape, validate_args=validate_args) + + if scale_tril is not None: + self._unbroadcasted_scale_tril = scale_tril + elif covariance_matrix is not None: + self._unbroadcasted_scale_tril = torch.linalg.cholesky(covariance_matrix) + else: # precision_matrix is not None + self._unbroadcasted_scale_tril = _precision_to_scale_tril(precision_matrix) + + def expand(self, batch_shape, _instance=None): + new = self._get_checked_instance(MultivariateNormal, _instance) + batch_shape = torch.Size(batch_shape) + loc_shape = batch_shape + self.event_shape + cov_shape = batch_shape + self.event_shape + self.event_shape + new.loc = self.loc.expand(loc_shape) + new._unbroadcasted_scale_tril = self._unbroadcasted_scale_tril + if "covariance_matrix" in self.__dict__: + new.covariance_matrix = self.covariance_matrix.expand(cov_shape) + if "scale_tril" in self.__dict__: + new.scale_tril = self.scale_tril.expand(cov_shape) + if "precision_matrix" in self.__dict__: + new.precision_matrix = self.precision_matrix.expand(cov_shape) + super(MultivariateNormal, new).__init__( + batch_shape, self.event_shape, validate_args=False + ) + new._validate_args = self._validate_args + return new + + @lazy_property + def scale_tril(self): + return self._unbroadcasted_scale_tril.expand( + self._batch_shape + self._event_shape + self._event_shape + ) + + @lazy_property + def covariance_matrix(self): + return torch.matmul( + self._unbroadcasted_scale_tril, self._unbroadcasted_scale_tril.mT + ).expand(self._batch_shape + self._event_shape + self._event_shape) + + @lazy_property + def precision_matrix(self): + return torch.cholesky_inverse(self._unbroadcasted_scale_tril).expand( + self._batch_shape + self._event_shape + self._event_shape + ) + + @property + def mean(self): + return self.loc + + @property + def mode(self): + return self.loc + + @property + def variance(self): + return ( + self._unbroadcasted_scale_tril.pow(2) + .sum(-1) + .expand(self._batch_shape + self._event_shape) + ) + + def rsample(self, sample_shape=torch.Size()): + shape = self._extended_shape(sample_shape) + eps = _standard_normal(shape, dtype=self.loc.dtype, device=self.loc.device) + return self.loc + _batch_mv(self._unbroadcasted_scale_tril, eps) + + def log_prob(self, value): + if self._validate_args: + self._validate_sample(value) + diff = value - self.loc + M = _batch_mahalanobis(self._unbroadcasted_scale_tril, diff) + half_log_det = ( + self._unbroadcasted_scale_tril.diagonal(dim1=-2, dim2=-1).log().sum(-1) + ) + return -0.5 * (self._event_shape[0] * math.log(2 * math.pi) + M) - half_log_det + + def entropy(self): + half_log_det = ( + self._unbroadcasted_scale_tril.diagonal(dim1=-2, dim2=-1).log().sum(-1) + ) + H = 0.5 * self._event_shape[0] * (1.0 + math.log(2 * math.pi)) + half_log_det + if len(self._batch_shape) == 0: + return H + else: + return H.expand(self._batch_shape) diff --git a/shared/package-files/00/00f43406163b7f97109987dd21cb2cbbc458190d24d5400ab5771dbf120bc2e8/blob b/shared/package-files/00/00f43406163b7f97109987dd21cb2cbbc458190d24d5400ab5771dbf120bc2e8/blob new file mode 100644 index 0000000000000000000000000000000000000000..ee92d8a790a1291c8da8edf14fdeac7871896bd7 --- /dev/null +++ b/shared/package-files/00/00f43406163b7f97109987dd21cb2cbbc458190d24d5400ab5771dbf120bc2e8/blob @@ -0,0 +1,39 @@ +#pragma once + +// @generated by torchgen/gen.py from Operator.h + +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { +namespace _ops { + + +struct TORCH_API reflection_pad3d_out { + using schema = at::Tensor & (const at::Tensor &, c10::SymIntArrayRef, at::Tensor &); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::reflection_pad3d") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "out") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "reflection_pad3d.out(Tensor self, SymInt[6] padding, *, Tensor(a!) out) -> Tensor(a!)") + static at::Tensor & call(const at::Tensor & self, c10::SymIntArrayRef padding, at::Tensor & out); + static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, c10::SymIntArrayRef padding, at::Tensor & out); +}; + +struct TORCH_API reflection_pad3d { + using schema = at::Tensor (const at::Tensor &, c10::SymIntArrayRef); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::reflection_pad3d") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "reflection_pad3d(Tensor self, SymInt[6] padding) -> Tensor") + static at::Tensor call(const at::Tensor & self, c10::SymIntArrayRef padding); + static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, c10::SymIntArrayRef padding); +}; + +}} // namespace at::_ops diff --git a/shared/package-files/00/00f606143ce899fd47e2dc09f310256ea1c3d73318f2f360207d07c24ecc5532/blob b/shared/package-files/00/00f606143ce899fd47e2dc09f310256ea1c3d73318f2f360207d07c24ecc5532/blob new file mode 100644 index 0000000000000000000000000000000000000000..9b19823c80752bcddf1a45b1ed40e2b3f8253be2 --- /dev/null +++ b/shared/package-files/00/00f606143ce899fd47e2dc09f310256ea1c3d73318f2f360207d07c24ecc5532/blob @@ -0,0 +1,24 @@ +#pragma once +// @generated by torchgen/gen.py from DispatchKeyFunction.h + +// NB: The implementing C++ file is RegisterDispatchKey.cpp + +// The only #includes we need are for custom classes that have defaults in the C++ API +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { + +namespace cuda { + +TORCH_API ::std::tuple _efficient_attention_backward(const at::Tensor & grad_out_, const at::Tensor & query, const at::Tensor & key, const at::Tensor & value, const c10::optional & bias, const at::Tensor & out, const c10::optional & cu_seqlens_q, const c10::optional & cu_seqlens_k, int64_t max_seqlen_q, int64_t max_seqlen_k, const at::Tensor & logsumexp, double dropout_p, const at::Tensor & philox_seed, const at::Tensor & philox_offset, int64_t custom_mask_type, bool bias_requires_grad, c10::optional scale=c10::nullopt, c10::optional num_splits_key=c10::nullopt); +TORCH_API ::std::tuple _efficient_attention_backward_symint(const at::Tensor & grad_out_, const at::Tensor & query, const at::Tensor & key, const at::Tensor & value, const c10::optional & bias, const at::Tensor & out, const c10::optional & cu_seqlens_q, const c10::optional & cu_seqlens_k, c10::SymInt max_seqlen_q, c10::SymInt max_seqlen_k, const at::Tensor & logsumexp, double dropout_p, const at::Tensor & philox_seed, const at::Tensor & philox_offset, int64_t custom_mask_type, bool bias_requires_grad, c10::optional scale=c10::nullopt, c10::optional num_splits_key=c10::nullopt); + +} // namespace cuda +} // namespace at diff --git a/shared/package-files/00/00f85a2c37151d5ef7d8f7646f868abb032fbea71b0edc1b3799fd477951d1a9/blob b/shared/package-files/00/00f85a2c37151d5ef7d8f7646f868abb032fbea71b0edc1b3799fd477951d1a9/blob new file mode 100644 index 0000000000000000000000000000000000000000..b6ed2d12c7d6b5ad04e0ee4ab5b8bbaf4c89f711 --- /dev/null +++ b/shared/package-files/00/00f85a2c37151d5ef7d8f7646f868abb032fbea71b0edc1b3799fd477951d1a9/blob @@ -0,0 +1,27 @@ +#pragma once + +// @generated by torchgen/gen.py from NativeMetaFunction.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace at { +namespace meta { + +struct TORCH_API structured_special_i1e : public TensorIteratorBase { + + + void meta(const at::Tensor & self); +}; + +} // namespace native +} // namespace at diff --git a/shared/package-files/00/00f8ffc8a237510a9d1fe301676ca26234d69a2712b3c7b75d72ac07783b3c44/blob b/shared/package-files/00/00f8ffc8a237510a9d1fe301676ca26234d69a2712b3c7b75d72ac07783b3c44/blob new file mode 100644 index 0000000000000000000000000000000000000000..2944b8817228e5f7eef0eb42a614129a5872cc72 --- /dev/null +++ b/shared/package-files/00/00f8ffc8a237510a9d1fe301676ca26234d69a2712b3c7b75d72ac07783b3c44/blob @@ -0,0 +1,47 @@ +#pragma once + +// @generated by torchgen/gen.py from Function.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + + +#include + +namespace at { + + +// aten::_convolution_mode(Tensor input, Tensor weight, Tensor? bias, SymInt[] stride, str padding, SymInt[] dilation, SymInt groups) -> Tensor +inline at::Tensor _convolution_mode(const at::Tensor & input, const at::Tensor & weight, const c10::optional & bias, at::IntArrayRef stride, c10::string_view padding, at::IntArrayRef dilation, int64_t groups) { + return at::_ops::_convolution_mode::call(input, weight, bias, c10::fromIntArrayRefSlow(stride), padding, c10::fromIntArrayRefSlow(dilation), groups); +} +namespace symint { + template ::value>> + at::Tensor _convolution_mode(const at::Tensor & input, const at::Tensor & weight, const c10::optional & bias, at::IntArrayRef stride, c10::string_view padding, at::IntArrayRef dilation, int64_t groups) { + return at::_ops::_convolution_mode::call(input, weight, bias, c10::fromIntArrayRefSlow(stride), padding, c10::fromIntArrayRefSlow(dilation), groups); + } +} + +// aten::_convolution_mode(Tensor input, Tensor weight, Tensor? bias, SymInt[] stride, str padding, SymInt[] dilation, SymInt groups) -> Tensor +inline at::Tensor _convolution_mode_symint(const at::Tensor & input, const at::Tensor & weight, const c10::optional & bias, c10::SymIntArrayRef stride, c10::string_view padding, c10::SymIntArrayRef dilation, c10::SymInt groups) { + return at::_ops::_convolution_mode::call(input, weight, bias, stride, padding, dilation, groups); +} +namespace symint { + template ::value>> + at::Tensor _convolution_mode(const at::Tensor & input, const at::Tensor & weight, const c10::optional & bias, c10::SymIntArrayRef stride, c10::string_view padding, c10::SymIntArrayRef dilation, c10::SymInt groups) { + return at::_ops::_convolution_mode::call(input, weight, bias, stride, padding, dilation, groups); + } +} + +} diff --git a/shared/package-files/00/00fc1faa5defe3021107b1e90a27ea2d5c96c1ea9ef068b4e64d9e32542a4542/blob b/shared/package-files/00/00fc1faa5defe3021107b1e90a27ea2d5c96c1ea9ef068b4e64d9e32542a4542/blob new file mode 100644 index 0000000000000000000000000000000000000000..e7e82e337718b577606b57ec9bccd096352e7c30 --- /dev/null +++ b/shared/package-files/00/00fc1faa5defe3021107b1e90a27ea2d5c96c1ea9ef068b4e64d9e32542a4542/blob @@ -0,0 +1,700 @@ +# encoding: utf-8 +""" +Prefiltering components. + +Prefilters transform user input before it is exec'd by Python. These +transforms are used to implement additional syntax such as !ls and %magic. +""" + +# Copyright (c) IPython Development Team. +# Distributed under the terms of the Modified BSD License. + +from keyword import iskeyword +import re + +from .autocall import IPyAutocall +from traitlets.config.configurable import Configurable +from .inputtransformer2 import ( + ESC_MAGIC, + ESC_QUOTE, + ESC_QUOTE2, + ESC_PAREN, +) +from .macro import Macro +from .splitinput import LineInfo + +from traitlets import ( + List, Integer, Unicode, Bool, Instance, CRegExp +) + +#----------------------------------------------------------------------------- +# Global utilities, errors and constants +#----------------------------------------------------------------------------- + + +class PrefilterError(Exception): + pass + + +# RegExp to identify potential function names +re_fun_name = re.compile(r'[^\W\d]([\w.]*) *$') + +# RegExp to exclude strings with this start from autocalling. In +# particular, all binary operators should be excluded, so that if foo is +# callable, foo OP bar doesn't become foo(OP bar), which is invalid. The +# characters '!=()' don't need to be checked for, as the checkPythonChars +# routine explicitly does so, to catch direct calls and rebindings of +# existing names. + +# Warning: the '-' HAS TO BE AT THE END of the first group, otherwise +# it affects the rest of the group in square brackets. +re_exclude_auto = re.compile(r'^[,&^\|\*/\+-]' + r'|^is |^not |^in |^and |^or ') + +# try to catch also methods for stuff in lists/tuples/dicts: off +# (experimental). For this to work, the line_split regexp would need +# to be modified so it wouldn't break things at '['. That line is +# nasty enough that I shouldn't change it until I can test it _well_. +#self.re_fun_name = re.compile (r'[a-zA-Z_]([a-zA-Z0-9_.\[\]]*) ?$') + + +# Handler Check Utilities +def is_shadowed(identifier, ip): + """Is the given identifier defined in one of the namespaces which shadow + the alias and magic namespaces? Note that an identifier is different + than ifun, because it can not contain a '.' character.""" + # This is much safer than calling ofind, which can change state + return (identifier in ip.user_ns \ + or identifier in ip.user_global_ns \ + or identifier in ip.ns_table['builtin']\ + or iskeyword(identifier)) + + +#----------------------------------------------------------------------------- +# Main Prefilter manager +#----------------------------------------------------------------------------- + + +class PrefilterManager(Configurable): + """Main prefilter component. + + The IPython prefilter is run on all user input before it is run. The + prefilter consumes lines of input and produces transformed lines of + input. + + The implementation consists of two phases: + + 1. Transformers + 2. Checkers and handlers + + Over time, we plan on deprecating the checkers and handlers and doing + everything in the transformers. + + The transformers are instances of :class:`PrefilterTransformer` and have + a single method :meth:`transform` that takes a line and returns a + transformed line. The transformation can be accomplished using any + tool, but our current ones use regular expressions for speed. + + After all the transformers have been run, the line is fed to the checkers, + which are instances of :class:`PrefilterChecker`. The line is passed to + the :meth:`check` method, which either returns `None` or a + :class:`PrefilterHandler` instance. If `None` is returned, the other + checkers are tried. If an :class:`PrefilterHandler` instance is returned, + the line is passed to the :meth:`handle` method of the returned + handler and no further checkers are tried. + + Both transformers and checkers have a `priority` attribute, that determines + the order in which they are called. Smaller priorities are tried first. + + Both transformers and checkers also have `enabled` attribute, which is + a boolean that determines if the instance is used. + + Users or developers can change the priority or enabled attribute of + transformers or checkers, but they must call the :meth:`sort_checkers` + or :meth:`sort_transformers` method after changing the priority. + """ + + multi_line_specials = Bool(True).tag(config=True) + shell = Instance('IPython.core.interactiveshell.InteractiveShellABC', allow_none=True) + + def __init__(self, shell=None, **kwargs): + super(PrefilterManager, self).__init__(shell=shell, **kwargs) + self.shell = shell + self._transformers = [] + self.init_handlers() + self.init_checkers() + + #------------------------------------------------------------------------- + # API for managing transformers + #------------------------------------------------------------------------- + + def sort_transformers(self): + """Sort the transformers by priority. + + This must be called after the priority of a transformer is changed. + The :meth:`register_transformer` method calls this automatically. + """ + self._transformers.sort(key=lambda x: x.priority) + + @property + def transformers(self): + """Return a list of checkers, sorted by priority.""" + return self._transformers + + def register_transformer(self, transformer): + """Register a transformer instance.""" + if transformer not in self._transformers: + self._transformers.append(transformer) + self.sort_transformers() + + def unregister_transformer(self, transformer): + """Unregister a transformer instance.""" + if transformer in self._transformers: + self._transformers.remove(transformer) + + #------------------------------------------------------------------------- + # API for managing checkers + #------------------------------------------------------------------------- + + def init_checkers(self): + """Create the default checkers.""" + self._checkers = [] + for checker in _default_checkers: + checker( + shell=self.shell, prefilter_manager=self, parent=self + ) + + def sort_checkers(self): + """Sort the checkers by priority. + + This must be called after the priority of a checker is changed. + The :meth:`register_checker` method calls this automatically. + """ + self._checkers.sort(key=lambda x: x.priority) + + @property + def checkers(self): + """Return a list of checkers, sorted by priority.""" + return self._checkers + + def register_checker(self, checker): + """Register a checker instance.""" + if checker not in self._checkers: + self._checkers.append(checker) + self.sort_checkers() + + def unregister_checker(self, checker): + """Unregister a checker instance.""" + if checker in self._checkers: + self._checkers.remove(checker) + + #------------------------------------------------------------------------- + # API for managing handlers + #------------------------------------------------------------------------- + + def init_handlers(self): + """Create the default handlers.""" + self._handlers = {} + self._esc_handlers = {} + for handler in _default_handlers: + handler( + shell=self.shell, prefilter_manager=self, parent=self + ) + + @property + def handlers(self): + """Return a dict of all the handlers.""" + return self._handlers + + def register_handler(self, name, handler, esc_strings): + """Register a handler instance by name with esc_strings.""" + self._handlers[name] = handler + for esc_str in esc_strings: + self._esc_handlers[esc_str] = handler + + def unregister_handler(self, name, handler, esc_strings): + """Unregister a handler instance by name with esc_strings.""" + try: + del self._handlers[name] + except KeyError: + pass + for esc_str in esc_strings: + h = self._esc_handlers.get(esc_str) + if h is handler: + del self._esc_handlers[esc_str] + + def get_handler_by_name(self, name): + """Get a handler by its name.""" + return self._handlers.get(name) + + def get_handler_by_esc(self, esc_str): + """Get a handler by its escape string.""" + return self._esc_handlers.get(esc_str) + + #------------------------------------------------------------------------- + # Main prefiltering API + #------------------------------------------------------------------------- + + def prefilter_line_info(self, line_info): + """Prefilter a line that has been converted to a LineInfo object. + + This implements the checker/handler part of the prefilter pipe. + """ + # print "prefilter_line_info: ", line_info + handler = self.find_handler(line_info) + return handler.handle(line_info) + + def find_handler(self, line_info): + """Find a handler for the line_info by trying checkers.""" + for checker in self.checkers: + if checker.enabled: + handler = checker.check(line_info) + if handler: + return handler + return self.get_handler_by_name('normal') + + def transform_line(self, line, continue_prompt): + """Calls the enabled transformers in order of increasing priority.""" + for transformer in self.transformers: + if transformer.enabled: + line = transformer.transform(line, continue_prompt) + return line + + def prefilter_line(self, line, continue_prompt=False): + """Prefilter a single input line as text. + + This method prefilters a single line of text by calling the + transformers and then the checkers/handlers. + """ + + # print "prefilter_line: ", line, continue_prompt + # All handlers *must* return a value, even if it's blank (''). + + # save the line away in case we crash, so the post-mortem handler can + # record it + self.shell._last_input_line = line + + if not line: + # Return immediately on purely empty lines, so that if the user + # previously typed some whitespace that started a continuation + # prompt, he can break out of that loop with just an empty line. + # This is how the default python prompt works. + return '' + + # At this point, we invoke our transformers. + if not continue_prompt or (continue_prompt and self.multi_line_specials): + line = self.transform_line(line, continue_prompt) + + # Now we compute line_info for the checkers and handlers + line_info = LineInfo(line, continue_prompt) + + # the input history needs to track even empty lines + stripped = line.strip() + + normal_handler = self.get_handler_by_name('normal') + if not stripped: + return normal_handler.handle(line_info) + + # special handlers are only allowed for single line statements + if continue_prompt and not self.multi_line_specials: + return normal_handler.handle(line_info) + + prefiltered = self.prefilter_line_info(line_info) + # print "prefiltered line: %r" % prefiltered + return prefiltered + + def prefilter_lines(self, lines, continue_prompt=False): + """Prefilter multiple input lines of text. + + This is the main entry point for prefiltering multiple lines of + input. This simply calls :meth:`prefilter_line` for each line of + input. + + This covers cases where there are multiple lines in the user entry, + which is the case when the user goes back to a multiline history + entry and presses enter. + """ + llines = lines.rstrip('\n').split('\n') + # We can get multiple lines in one shot, where multiline input 'blends' + # into one line, in cases like recalling from the readline history + # buffer. We need to make sure that in such cases, we correctly + # communicate downstream which line is first and which are continuation + # ones. + if len(llines) > 1: + out = '\n'.join([self.prefilter_line(line, lnum>0) + for lnum, line in enumerate(llines) ]) + else: + out = self.prefilter_line(llines[0], continue_prompt) + + return out + +#----------------------------------------------------------------------------- +# Prefilter transformers +#----------------------------------------------------------------------------- + + +class PrefilterTransformer(Configurable): + """Transform a line of user input.""" + + priority = Integer(100).tag(config=True) + # Transformers don't currently use shell or prefilter_manager, but as we + # move away from checkers and handlers, they will need them. + shell = Instance('IPython.core.interactiveshell.InteractiveShellABC', allow_none=True) + prefilter_manager = Instance('IPython.core.prefilter.PrefilterManager', allow_none=True) + enabled = Bool(True).tag(config=True) + + def __init__(self, shell=None, prefilter_manager=None, **kwargs): + super(PrefilterTransformer, self).__init__( + shell=shell, prefilter_manager=prefilter_manager, **kwargs + ) + self.prefilter_manager.register_transformer(self) + + def transform(self, line, continue_prompt): + """Transform a line, returning the new one.""" + return None + + def __repr__(self): + return "<%s(priority=%r, enabled=%r)>" % ( + self.__class__.__name__, self.priority, self.enabled) + + +#----------------------------------------------------------------------------- +# Prefilter checkers +#----------------------------------------------------------------------------- + + +class PrefilterChecker(Configurable): + """Inspect an input line and return a handler for that line.""" + + priority = Integer(100).tag(config=True) + shell = Instance('IPython.core.interactiveshell.InteractiveShellABC', allow_none=True) + prefilter_manager = Instance('IPython.core.prefilter.PrefilterManager', allow_none=True) + enabled = Bool(True).tag(config=True) + + def __init__(self, shell=None, prefilter_manager=None, **kwargs): + super(PrefilterChecker, self).__init__( + shell=shell, prefilter_manager=prefilter_manager, **kwargs + ) + self.prefilter_manager.register_checker(self) + + def check(self, line_info): + """Inspect line_info and return a handler instance or None.""" + return None + + def __repr__(self): + return "<%s(priority=%r, enabled=%r)>" % ( + self.__class__.__name__, self.priority, self.enabled) + + +class EmacsChecker(PrefilterChecker): + + priority = Integer(100).tag(config=True) + enabled = Bool(False).tag(config=True) + + def check(self, line_info): + "Emacs ipython-mode tags certain input lines." + if line_info.line.endswith('# PYTHON-MODE'): + return self.prefilter_manager.get_handler_by_name('emacs') + else: + return None + + +class MacroChecker(PrefilterChecker): + + priority = Integer(250).tag(config=True) + + def check(self, line_info): + obj = self.shell.user_ns.get(line_info.ifun) + if isinstance(obj, Macro): + return self.prefilter_manager.get_handler_by_name('macro') + else: + return None + + +class IPyAutocallChecker(PrefilterChecker): + + priority = Integer(300).tag(config=True) + + def check(self, line_info): + "Instances of IPyAutocall in user_ns get autocalled immediately" + obj = self.shell.user_ns.get(line_info.ifun, None) + if isinstance(obj, IPyAutocall): + obj.set_ip(self.shell) + return self.prefilter_manager.get_handler_by_name('auto') + else: + return None + + +class AssignmentChecker(PrefilterChecker): + + priority = Integer(600).tag(config=True) + + def check(self, line_info): + """Check to see if user is assigning to a var for the first time, in + which case we want to avoid any sort of automagic / autocall games. + + This allows users to assign to either alias or magic names true python + variables (the magic/alias systems always take second seat to true + python code). E.g. ls='hi', or ls,that=1,2""" + if line_info.the_rest: + if line_info.the_rest[0] in '=,': + return self.prefilter_manager.get_handler_by_name('normal') + else: + return None + + +class AutoMagicChecker(PrefilterChecker): + + priority = Integer(700).tag(config=True) + + def check(self, line_info): + """If the ifun is magic, and automagic is on, run it. Note: normal, + non-auto magic would already have been triggered via '%' in + check_esc_chars. This just checks for automagic. Also, before + triggering the magic handler, make sure that there is nothing in the + user namespace which could shadow it.""" + if not self.shell.automagic or not self.shell.find_magic(line_info.ifun): + return None + + # We have a likely magic method. Make sure we should actually call it. + if line_info.continue_prompt and not self.prefilter_manager.multi_line_specials: + return None + + head = line_info.ifun.split('.',1)[0] + if is_shadowed(head, self.shell): + return None + + return self.prefilter_manager.get_handler_by_name('magic') + + +class PythonOpsChecker(PrefilterChecker): + + priority = Integer(900).tag(config=True) + + def check(self, line_info): + """If the 'rest' of the line begins with a function call or pretty much + any python operator, we should simply execute the line (regardless of + whether or not there's a possible autocall expansion). This avoids + spurious (and very confusing) geattr() accesses.""" + if line_info.the_rest and line_info.the_rest[0] in '!=()<>,+*/%^&|': + return self.prefilter_manager.get_handler_by_name('normal') + else: + return None + + +class AutocallChecker(PrefilterChecker): + + priority = Integer(1000).tag(config=True) + + function_name_regexp = CRegExp(re_fun_name, + help="RegExp to identify potential function names." + ).tag(config=True) + exclude_regexp = CRegExp(re_exclude_auto, + help="RegExp to exclude strings with this start from autocalling." + ).tag(config=True) + + def check(self, line_info): + "Check if the initial word/function is callable and autocall is on." + if not self.shell.autocall: + return None + + oinfo = line_info.ofind(self.shell) # This can mutate state via getattr + if not oinfo.found: + return None + + ignored_funs = ['b', 'f', 'r', 'u', 'br', 'rb', 'fr', 'rf'] + ifun = line_info.ifun + line = line_info.line + if ifun.lower() in ignored_funs and (line.startswith(ifun + "'") or line.startswith(ifun + '"')): + return None + + if ( + callable(oinfo.obj) + and (not self.exclude_regexp.match(line_info.the_rest)) + and self.function_name_regexp.match(line_info.ifun) + ): + return self.prefilter_manager.get_handler_by_name("auto") + else: + return None + + +#----------------------------------------------------------------------------- +# Prefilter handlers +#----------------------------------------------------------------------------- + + +class PrefilterHandler(Configurable): + + handler_name = Unicode('normal') + esc_strings = List([]) + shell = Instance('IPython.core.interactiveshell.InteractiveShellABC', allow_none=True) + prefilter_manager = Instance('IPython.core.prefilter.PrefilterManager', allow_none=True) + + def __init__(self, shell=None, prefilter_manager=None, **kwargs): + super(PrefilterHandler, self).__init__( + shell=shell, prefilter_manager=prefilter_manager, **kwargs + ) + self.prefilter_manager.register_handler( + self.handler_name, + self, + self.esc_strings + ) + + def handle(self, line_info): + # print "normal: ", line_info + """Handle normal input lines. Use as a template for handlers.""" + + # With autoindent on, we need some way to exit the input loop, and I + # don't want to force the user to have to backspace all the way to + # clear the line. The rule will be in this case, that either two + # lines of pure whitespace in a row, or a line of pure whitespace but + # of a size different to the indent level, will exit the input loop. + line = line_info.line + continue_prompt = line_info.continue_prompt + + if (continue_prompt and + self.shell.autoindent and + line.isspace() and + 0 < abs(len(line) - self.shell.indent_current_nsp) <= 2): + line = '' + + return line + + def __str__(self): + return "<%s(name=%s)>" % (self.__class__.__name__, self.handler_name) + + +class MacroHandler(PrefilterHandler): + handler_name = Unicode("macro") + + def handle(self, line_info): + obj = self.shell.user_ns.get(line_info.ifun) + pre_space = line_info.pre_whitespace + line_sep = "\n" + pre_space + return pre_space + line_sep.join(obj.value.splitlines()) + + +class MagicHandler(PrefilterHandler): + + handler_name = Unicode('magic') + esc_strings = List([ESC_MAGIC]) + + def handle(self, line_info): + """Execute magic functions.""" + ifun = line_info.ifun + the_rest = line_info.the_rest + #Prepare arguments for get_ipython().run_line_magic(magic_name, magic_args) + t_arg_s = ifun + " " + the_rest + t_magic_name, _, t_magic_arg_s = t_arg_s.partition(' ') + t_magic_name = t_magic_name.lstrip(ESC_MAGIC) + cmd = '%sget_ipython().run_line_magic(%r, %r)' % (line_info.pre_whitespace, t_magic_name, t_magic_arg_s) + return cmd + + +class AutoHandler(PrefilterHandler): + + handler_name = Unicode('auto') + esc_strings = List([ESC_PAREN, ESC_QUOTE, ESC_QUOTE2]) + + def handle(self, line_info): + """Handle lines which can be auto-executed, quoting if requested.""" + line = line_info.line + ifun = line_info.ifun + the_rest = line_info.the_rest + esc = line_info.esc + continue_prompt = line_info.continue_prompt + obj = line_info.ofind(self.shell).obj + + # This should only be active for single-line input! + if continue_prompt: + return line + + force_auto = isinstance(obj, IPyAutocall) + + # User objects sometimes raise exceptions on attribute access other + # than AttributeError (we've seen it in the past), so it's safest to be + # ultra-conservative here and catch all. + try: + auto_rewrite = obj.rewrite + except Exception: + auto_rewrite = True + + if esc == ESC_QUOTE: + # Auto-quote splitting on whitespace + newcmd = '%s("%s")' % (ifun,'", "'.join(the_rest.split()) ) + elif esc == ESC_QUOTE2: + # Auto-quote whole string + newcmd = '%s("%s")' % (ifun,the_rest) + elif esc == ESC_PAREN: + newcmd = '%s(%s)' % (ifun,",".join(the_rest.split())) + else: + # Auto-paren. + if force_auto: + # Don't rewrite if it is already a call. + do_rewrite = not the_rest.startswith('(') + else: + if not the_rest: + # We only apply it to argument-less calls if the autocall + # parameter is set to 2. + do_rewrite = (self.shell.autocall >= 2) + elif the_rest.startswith('[') and hasattr(obj, '__getitem__'): + # Don't autocall in this case: item access for an object + # which is BOTH callable and implements __getitem__. + do_rewrite = False + else: + do_rewrite = True + + # Figure out the rewritten command + if do_rewrite: + if the_rest.endswith(';'): + newcmd = '%s(%s);' % (ifun.rstrip(),the_rest[:-1]) + else: + newcmd = '%s(%s)' % (ifun.rstrip(), the_rest) + else: + normal_handler = self.prefilter_manager.get_handler_by_name('normal') + return normal_handler.handle(line_info) + + # Display the rewritten call + if auto_rewrite: + self.shell.auto_rewrite_input(newcmd) + + return newcmd + + +class EmacsHandler(PrefilterHandler): + + handler_name = Unicode('emacs') + esc_strings = List([]) + + def handle(self, line_info): + """Handle input lines marked by python-mode.""" + + # Currently, nothing is done. Later more functionality can be added + # here if needed. + + # The input cache shouldn't be updated + return line_info.line + + +#----------------------------------------------------------------------------- +# Defaults +#----------------------------------------------------------------------------- + + +_default_checkers = [ + EmacsChecker, + MacroChecker, + IPyAutocallChecker, + AssignmentChecker, + AutoMagicChecker, + PythonOpsChecker, + AutocallChecker +] + +_default_handlers = [ + PrefilterHandler, + MacroHandler, + MagicHandler, + AutoHandler, + EmacsHandler +] diff --git a/shared/package-files/00/00fcd158a6346ee038c3de9e543ff8d42aa00acc805667b77de78a305447f0eb/blob b/shared/package-files/00/00fcd158a6346ee038c3de9e543ff8d42aa00acc805667b77de78a305447f0eb/blob new file mode 100644 index 0000000000000000000000000000000000000000..0ee2062845b749200c1444b8aa9ecec626df732d --- /dev/null +++ b/shared/package-files/00/00fcd158a6346ee038c3de9e543ff8d42aa00acc805667b77de78a305447f0eb/blob @@ -0,0 +1,251 @@ +y_arma11,y_arma14,y_arma41,y_arma22,y_arma50,y_arma02,y_arma11c,y_arma14c,y_arma41c,y_arma22c,y_arma50c,y_arma02c +-2.047076594847129505e-01,1.394072226185005814e+00,-7.618372133529945911e-01,-4.064523617925941412e-01,-9.835047173983663127e-01,6.143504692328910499e-01,4.259432631872511976e+00,6.738236941732065333e+00,3.921172305736134511e+00,4.841410872820988587e+00,3.567921955380871424e+00,5.020264181479198839e+00 +2.537649126243639586e-01,4.567375047627766360e-01,-1.169637832882710393e+00,-2.904655508294423649e-01,1.933152260847050830e-01,6.429869148939288959e-01,4.398428009976181663e+00,7.368314202772689114e+00,5.710735793018799633e+00,4.558666615338087702e+00,5.627433726992007834e+00,4.271942218168720551e+00 +-1.614848622683232593e-01,-1.272326703442733464e+00,-2.554150415613765990e+00,4.377894222244522737e-01,-3.224625683687642463e-01,-5.829343493568055479e-01,3.894220064383869140e+00,6.410706525591642446e+00,6.653104231835761162e+00,4.369696549146111941e+00,5.441687121317324127e+00,3.719432040526521988e+00 +-8.586475013185908001e-01,-9.458320913213410508e-01,-1.416810339850927747e+00,1.292133237669666590e+00,-2.434714935535151170e+00,3.225999093088858238e-01,4.254945463650283699e+00,6.774751472682821074e+00,5.813209651463687067e+00,4.848351385863497676e+00,3.693440719499076152e+00,5.799271295947738381e+00 +1.127289339992149531e+00,-6.883717809906914065e-02,-2.004237998790745490e-01,1.802924788488174057e+00,-1.990610824223469910e+00,-4.553547958839077037e-02,4.888509710140729325e+00,4.026927273300911381e+00,5.506526563168436361e+00,4.708763021171975538e+00,2.747097130265434117e+00,5.199862796144467225e+00 +2.926896038343052453e+00,-8.584562919036573536e-01,-1.274069813257599826e+00,-3.157042843910952135e-01,-2.664447937057304316e-01,5.833794675456229761e-01,6.113454539016629496e+00,2.075139727032463632e+00,6.999617863858643929e+00,4.004972492948537521e+00,4.783782184444534735e+00,5.428226532398705118e+00 +2.775771947041553389e+00,-1.796823860810985218e+00,-3.435812286850086217e+00,3.328747540357390733e-02,1.713166700014400745e-01,1.287328621636036230e+00,5.768913584533245320e+00,5.364144882553992133e+00,6.220457380072278220e+00,3.279857874780836013e+00,4.382208504444793817e+00,5.760983622424917350e+00 +2.396092869971668371e+00,-1.374140342963603212e+00,-3.324410934220093150e+00,6.241378334643327142e-01,-1.008235022896845523e+00,-2.571874757040343296e-01,6.783227456396678789e+00,6.453556693243496234e+00,4.760031787665699454e+00,1.397159712575776425e+00,3.955895170740389766e+00,4.892141935490703197e+00 +2.664703373581160939e+00,-2.274295006054621204e+00,2.847437087200943573e-01,-1.677062469844210035e+00,1.071593491473753934e+00,5.943089576180543565e-02,8.764846998978599757e+00,3.134175247222279470e+00,4.618905799269997559e+00,3.832999293510881422e+00,4.169523377113049989e+00,4.820177423393641192e+00 +3.514120165236296778e+00,-1.695939107720390027e+00,5.749749943751873982e-01,-1.372251161366488947e+00,1.414936450756299369e+00,8.067203104089537558e-02,6.664487842459541511e+00,2.089710848527895237e+00,7.375027854593720456e+00,8.576140496669221847e+00,6.748639486536131216e+00,2.669498198821129265e+00 +4.079031639245426888e+00,-1.383046694106316643e+00,-2.344893313337678364e+00,-6.250943658791198176e-01,1.328692743772108553e+00,1.289696408214198620e+00,5.123872851709446508e+00,4.754158166466891267e+00,7.226677542929837550e+00,7.811349700243606975e+00,6.399961038027319304e+00,2.505802874791816404e+00 +2.115568895475858469e+00,-1.285696195785905438e+00,-5.410382313438887536e+00,-9.582233749130680822e-01,-4.514660067095999096e-03,6.906817862356203763e-01,4.624298391542022379e+00,4.532322449938698483e+00,5.895034864771226069e+00,4.201755661206154180e+00,3.841171273307598000e+00,3.901458429730415567e+00 +1.407990916849725771e+00,-4.315387699941466426e-01,-2.434441803202210153e+00,-2.143241193463130134e-02,1.991430048897706861e-01,-3.245252085642317263e-01,3.298440951207898930e+00,3.023850958378810461e+00,6.011888360633888873e+00,2.048413650493551952e+00,5.931427026305052586e+00,5.352527421085418347e+00 +1.381153138273853553e+00,1.084288569595046825e+00,1.475497484267840553e+00,1.675123411059225464e+00,1.269439435330158350e+00,-1.045172753525086096e+00,3.103686242816811269e+00,4.080448938513448809e+00,6.668471493814188022e+00,3.319703108792883661e+00,7.769291575371815028e+00,3.920245059994244663e+00 +2.468901196498200612e+00,4.531380836694007819e-01,9.757983087292898539e-02,1.159459620823443338e+00,1.329155575330689176e+00,-1.830503306089610316e+00,3.658159191813463718e+00,6.346035248965537612e+00,7.077166516280438913e+00,4.554699042844648105e+00,5.492605970846351937e+00,4.318612795940402371e+00 +3.211626130273146806e+00,-2.190557335162672814e+00,-4.025770289739019070e+00,2.374106873340324220e-01,-1.204791600774974603e+00,-3.953349523769545404e-01,3.372537397371419665e+00,4.291890175742812730e+00,4.582735795002996326e+00,8.003629851130945383e+00,3.299960257085285065e+00,5.863216575797151719e+00 +7.173325572515190096e-01,-1.440903136015097230e+00,-4.563025185706400144e+00,-7.098001117370973390e-01,-4.208258195771114041e-01,2.594451641987153057e+00,4.269616605460259784e+00,1.966875208797961960e+00,3.226094930911747038e+00,6.020287567355888214e+00,3.980251475991546162e+00,6.606646644611915420e+00 +-5.344161775827541705e-01,6.575126326774392016e-01,-5.766210270892357936e-01,2.080044842860721221e+00,2.597569170595709132e+00,1.316246656649131541e-01,3.840933541237355975e+00,5.846674991729185145e+00,4.098018048564538773e+00,1.600830935090640228e+00,4.628502633768053265e+00,3.585462029244003368e+00 +1.138068288338715872e+00,5.410281705276032138e-02,2.214383099182642756e+00,1.981718727958543980e+00,1.324496153816917321e+00,-1.821106292140853622e+00,2.401856988014751337e+00,6.656277522679868497e+00,4.283437503067081487e+00,1.384202228703339532e+00,5.999512681027482586e+00,1.528291132932186436e+00 +9.991403387521694546e-01,-3.811617114262618733e-01,1.206231109078024222e-01,-2.586171993187719842e+00,-6.952960055817554164e-01,8.046298768301501925e-01,2.150521954723290996e+00,3.733293634828790175e+00,4.514158688834689848e+00,2.548048973349378077e+00,4.355070413414093622e+00,4.427199029031395838e+00 +5.611440100001408027e-02,5.262380750425947884e-01,-4.953603576685280174e+00,-4.320037329811369453e+00,-1.907598969450933768e-01,1.078018569695110784e+00,2.658257906111643365e+00,4.382200981413502561e+00,5.859367423091468297e+00,4.029777956216626933e+00,5.067531354897734097e+00,4.945705073361552628e+00 +3.301613052297280859e-01,1.746862891830231745e-01,-8.118789816136267490e+00,-3.003177430316123164e+00,7.712387043869168846e-01,-8.794142886128656356e-01,4.258293663630687398e+00,6.153065962604464367e+00,7.355119360103516968e+00,8.075010494827537855e+00,4.923466375553967822e+00,4.909788839978878272e+00 +3.663509651997355565e+00,-2.874794400657883831e+00,-3.617695985036168072e+00,3.937863948442860362e+00,5.309231030866365941e-01,-1.234990868812363196e+00,4.339908625421150745e+00,5.340219971922237185e+00,5.515921408322084218e+00,7.798414613260441719e+00,6.873233673651917286e+00,5.826629709744591601e+00 +2.863535086443183886e+00,-2.579467235640812817e+00,9.915726649245641955e-01,7.298812062776931064e+00,3.223797297234989312e-01,2.727270606602266056e+00,4.237569677073842023e+00,3.860558543165812484e+00,4.509396332971866705e+00,4.004854402537130653e+00,5.452430701800734525e+00,4.871357265495228184e+00 +1.213134378267161750e+00,2.413579806889860346e-01,1.303675711696499651e+00,2.444639467618930695e+00,8.915073927774812557e-01,5.015301818356774355e-01,4.572111121969630432e+00,4.512712257921455361e+00,5.355957290748269983e+00,4.794247150280835257e+00,3.660108072753280872e+00,2.429556238521846101e+00 +8.319915033095105494e-01,-5.188516244935171828e-01,-5.687570288109578875e+00,-3.038003124026212642e+00,-8.719733907399780382e-01,-1.464298441207599888e+00,4.048062396070275071e+00,5.403303064625879060e+00,6.407665900443153539e+00,3.134788283354405181e+00,4.228899286686077730e+00,5.406063202984769944e+00 +9.700496358803369912e-01,-2.724024236513598485e+00,-7.053649446370281240e+00,-3.612813816796582422e+00,2.879464430993158297e-01,3.946224160478077891e-01,4.524770878655016482e+00,3.790844656041213234e+00,7.195887404329030623e+00,2.361511342912992362e+00,3.900621344854551253e+00,6.058011910665634048e+00 +1.357224041730048292e+00,-3.094356072793469803e+00,-1.008363536011467332e+00,1.046340672032860963e+00,2.368592569932105540e+00,-3.138197009761437006e-01,4.525455283146966323e+00,3.669994645124985411e+00,6.551577792201502604e+00,7.779296198399537232e+00,3.376143193000717080e+00,3.340663942774611428e+00 +1.202178532925514798e+00,-1.850307710282078189e+00,3.886862348001593581e+00,1.589445207794040638e+00,1.217857516123329376e+00,-9.122994252851901464e-01,4.653375618486451870e+00,5.177928739455077256e+00,5.315906173013112301e+00,6.297915587978545560e+00,1.981820108745978359e+00,5.388309049864337119e+00 +2.245772790529634744e+00,-1.516478417599159467e+00,-3.673322539992257552e-01,-5.204825623456811323e-01,-1.025887496633735574e-01,2.428428862906994556e+00,4.180686233113284800e+00,3.392074251314660671e+00,5.699029251570543408e+00,5.296396093445565612e-01,4.542328457752607740e+00,6.241995262291350599e+00 +1.441119035565789019e+00,-1.826409292124326011e+00,-5.940822212463317875e+00,9.652051478386652894e-01,4.052444759094290805e-01,1.610732939294483357e+00,7.038160704560359804e+00,3.766346935888272185e+00,5.999371763645894085e+00,1.156864407980374487e+00,5.145335831238890378e+00,4.119984700183874970e+00 +-5.465696330630986921e-05,-1.719338771172416180e+00,-6.508425086827775985e+00,2.181828702209119619e+00,1.108177098201627686e+00,-1.781879468348538165e+00,4.807427395222168443e+00,4.255280106544435448e+00,7.009375617216063503e+00,5.319221720194350134e+00,4.137737097068860948e+00,3.233320057309073015e+00 +-2.661176385278094081e+00,-1.395987375772736128e+00,-1.270103392180484292e+00,1.110821262560730549e-01,-1.029079612725556148e+00,-1.728302907832516833e-01,3.457531085129489146e+00,7.444270232949445898e-02,4.591567366097629943e+00,5.417009442651860240e+00,3.131299035156448696e+00,3.515272342145693507e+00 +-4.686224156394166229e+00,-1.850331606786910221e+00,2.184759340112722548e+00,-2.041081623865537598e+00,-1.542782696707952095e+00,4.958978337833580552e-01,3.116982008029290707e+00,1.386033864121762438e+00,3.652533172280716833e+00,4.691688663117650648e+00,4.512583138494862922e+00,4.507587864330768745e+00 +-5.026691791720129920e+00,-9.200819435921128164e-01,-3.295321237037077688e-01,9.793109676417565135e-01,7.543043591655402835e-01,-1.011195992545088074e-01,3.457098235710537537e+00,6.072136861732305491e+00,3.598198391522849260e+00,4.228970068897724310e+00,4.217642302531044329e+00,5.607026952466911851e+00 +-3.511138640213175677e+00,-9.744145346579486944e-01,-5.043254897882222032e+00,6.789267989097660383e-01,3.161919450570618739e+00,-1.171798760336695056e+00,5.461214551316098564e+00,5.287352572723380106e+00,4.399439539341723382e+00,3.500205802814739364e+00,5.656071780409132721e+00,4.741463207851570161e+00 +-3.703237619293762162e+00,-4.488315090217092518e+00,-4.263381366707648112e+00,-1.872655445832931642e+00,1.413418391066825208e-01,-5.997420261799208951e-01,6.633267216554529888e+00,2.943362263037925697e+00,4.342340090444273493e+00,4.751667085587318873e+00,4.529073913784968042e+00,3.139337629007510344e+00 +-3.100678161902562735e+00,-2.501030560910058931e+00,3.785869496888783631e-02,-1.776633578233102639e+00,-6.457530033435663341e-01,3.069899785414676785e+00,5.720232385386712970e+00,5.392964007325414144e+00,4.158870978293464304e+00,5.953350079983978915e+00,3.232746935335669036e+00,5.658934085315204143e+00 +-3.347081575849269797e+00,-1.875566408155554532e-01,1.373805813135958065e+00,-1.175124539027547543e+00,-3.084582261338173481e-01,2.304849343261525796e+00,5.650071425020970040e+00,4.727432440567961081e+00,1.757391563622786812e+00,5.363571028525145223e+00,2.433652791019824235e+00,5.946684745186741949e+00 +-2.549657823098020248e+00,-1.580664376558950091e+00,-2.049692467577199917e+00,1.306927984545027899e+00,4.255303096775274185e-01,-2.131719678615784375e-01,6.492867362025509514e+00,1.882685262636422330e+00,4.711271395093374892e-01,5.254387646473788642e+00,4.361070860586611531e+00,6.288490364663671173e+00 +-4.155153224244511279e+00,-1.638103590486664984e+00,-6.264898634428784696e+00,1.951636392749369397e+00,-1.053489723650152143e+00,3.729657763428336770e-01,6.853313246252220381e+00,3.201130691610448054e+00,2.033728470151813905e+00,4.500078973468650823e+00,4.296945244227881489e+00,2.029974511760805456e+00 +-4.141704456103338927e+00,-1.009012869991860128e+00,-5.401447994645365291e+00,-2.514643434433178060e-01,-2.706026508554485677e+00,3.268482030258671456e-01,6.328235046023614530e+00,4.065915530392780752e+00,5.646001626406992102e+00,4.280884981122723865e+00,3.923160234900610277e+00,-2.746902120133274394e-01 +-4.718113904319099383e+00,-1.802684091603253824e+00,-1.506657146317793128e+00,-1.004083775292140324e+00,-2.609366810774318424e+00,7.097452710287838196e-01,5.863057920820553548e+00,3.192879991044643706e+00,4.833576665416502216e+00,4.142242653072421454e+00,3.255009115094919636e+00,4.959172727951663973e+00 +-5.049019775254445896e+00,-1.381563077028357345e+00,-3.607815631934923606e-01,1.537058909742779589e+00,-2.307742759492474427e+00,-1.690775288074842120e+00,5.308433259777813440e+00,3.269680422232153827e+00,1.538660360555280437e+00,1.342948121733243738e+00,5.136919446565984870e+00,5.150108154036455943e+00 +-5.433552651702444614e+00,2.818885562711463677e-02,-3.279417244823289224e+00,1.545791434687723731e+00,-1.477440056825851222e+00,8.359621473279092996e-01,5.133107815890593173e+00,2.991393703367609014e+00,-1.508745328376193129e-03,2.571244256838248532e+00,4.478464671550294263e+00,3.667520676780307909e+00 +-4.246275329602491766e+00,-6.130663520806225453e-01,-5.845062440614010590e+00,-1.952098650681894476e+00,-1.746264638512076361e+00,4.958869789032507303e-01,5.315079959506445739e+00,3.972743925412632215e+00,2.793269678504992193e+00,5.584940290483441316e+00,3.892535432986085286e+00,4.697240467623889693e+00 +-2.706499974809537523e+00,3.924922185885175718e-01,-4.105156923265349533e+00,-2.044592367564284086e+00,-3.178980144414182973e+00,-1.493057516814380037e+00,5.021757939751064548e+00,6.339447365323519712e+00,4.945394441279040265e+00,5.264834653484440352e+00,3.886343321092996739e+00,4.424725523759203583e+00 +-2.651467077068968337e+00,2.492099512157600394e+00,-7.841257565010852915e-01,-1.377536061630622255e+00,-3.839461700572829983e+00,2.582115106873133392e+00,5.587764431662366249e+00,5.405066853022743700e+00,3.860237202046896243e+00,4.107108869533949935e+00,5.487652977036796109e+00,4.996723475156893635e+00 +-1.921174944783671457e+00,9.412006395738451436e-01,-2.625864606616613028e-01,-1.331777564711734474e+00,-3.478711161053920087e+00,3.905701109020744077e+00,5.133713232906468527e+00,4.494368763835435487e+00,1.307926951608490818e+00,3.830865832317300601e+00,5.178034455680792902e+00,4.871516117668107881e+00 +2.481098347911347979e-02,4.798757746073640806e-01,-4.210669215598827897e+00,1.519657317589789836e+00,-2.204219357018442960e+00,6.409508337405410705e-01,5.855966104246856929e+00,4.718316150574986878e+00,-1.208460825345432532e+00,3.876182703520312245e+00,5.371607561800637143e+00,4.279769579332299401e+00 +5.608947015146614756e-01,3.307660883373833016e+00,-5.302269633643058810e+00,1.154513370240555448e+00,-2.508472975056526444e+00,-9.069255698958078593e-01,7.453500872994089477e+00,6.136685070718774782e+00,1.577779596919119953e-01,5.811348619317231012e+00,4.013359064508622787e+00,4.274173284761452862e+00 +6.918019772089871733e-01,1.466478696550987060e+00,-3.621146700997774914e+00,-1.135210265489079218e+00,-2.270093923835809324e+00,-2.154054312539678939e+00,8.548631459854339809e+00,8.580677927587142761e+00,3.573725713298050888e+00,7.419094220950942287e+00,2.303293360327956396e+00,2.738280109656968442e+00 +5.933258203294380362e-01,-1.131123560438463516e+00,-1.605861339065547178e+00,7.302998686819989205e-01,-2.052409032866207905e+00,8.576733138557379732e-01,8.266456399981672476e+00,6.358139262462048080e+00,2.805261999954581142e+00,6.240747420223197395e+00,3.704750869121015366e+00,4.521147653224271146e+00 +1.445654395659279334e+00,2.089564369019218382e-01,-6.108205565391249259e-01,1.528236749888444823e+00,-2.038589923301223017e+00,3.072549047348906104e+00,6.531145968474424635e+00,3.659707778937812517e+00,1.361490758831767067e-01,4.413772251719586315e+00,3.702561277299750042e+00,5.074465917376252300e+00 +2.763119467305571675e+00,1.169930847882693081e+00,-3.410135203575566543e+00,1.227364972010503097e+00,-3.034243912264597220e+00,-2.259853471281571657e+00,6.228711353324530187e+00,5.390345214270871210e+00,-7.765975881852327234e-02,3.032668654013584320e+00,3.620297372992901330e+00,3.283416564361951284e+00 +1.617596157559101133e+00,9.274198691471612355e-01,-4.341813534124730367e+00,1.443200242866820027e+00,-1.215922849984176546e+00,-3.882836332642096711e+00,5.969829029753539906e+00,7.359973068273208519e+00,2.975172798878381375e+00,3.885288949269857905e+00,3.261339717609220035e+00,4.941919813889841251e+00 +-6.576508653258907877e-01,1.632997792991522257e+00,-4.102480222204741622e+00,-2.327795448610795681e+00,-1.266255394890709596e+00,-1.779812888348156541e+00,3.960817346595896460e+00,7.353020846842392544e+00,4.432314530601574987e+00,6.348169316565152265e+00,2.502149813883460805e+00,6.128471791598121499e+00 +-1.013240803735802942e+00,-8.014628681214892580e-01,3.914986840899605802e-01,-4.182871213923220921e+00,-2.436187298675244861e+00,9.875968433588133699e-02,4.923257732371997264e+00,5.474074476059730188e+00,2.808478061409179549e+00,6.312024025740812228e+00,2.064002107289165000e+00,4.387602522912947833e+00 +6.197151744087525671e-03,-3.149234092173039734e+00,-1.654102488856168396e-01,-3.412852847139776769e-01,-1.374484405133386655e+00,3.008339685703273148e+00,7.066411960496671973e+00,5.893878504480790426e+00,-6.355295163345040521e-01,4.776525929809087856e+00,1.379400472880342399e+00,2.425387915421347351e+00 +-3.904493631610490012e-01,-1.264212846324545669e+00,-2.225130675970304228e+00,3.537047195554293033e+00,-1.110739285306775681e+00,1.763013865152736503e+00,7.669229880295137747e+00,7.033887082352526576e+00,-9.855532089657668138e-01,2.673791490967353468e+00,2.979947600959134135e-01,4.784590574609719482e+00 +3.385595454556616923e-01,8.543168756601026148e-01,-3.998827467911054701e+00,2.792529087814373145e+00,-8.980532521212729602e-01,-3.434307464143248279e+00,6.673272479165506255e+00,3.658839214659449279e+00,2.051941196236151566e+00,1.813070366847800319e+00,1.733569923426339532e+00,6.495342894923719967e+00 +5.457907858885175933e-01,1.406319903308074437e+00,-4.003999994455309519e-01,7.598421744986120219e-01,-2.194432074523073872e-01,-1.521827718638907312e-01,6.771372674723006746e+00,3.146117206284628764e+00,5.052401051425627898e+00,3.103934056600683444e+00,2.788192216146352820e+00,5.148535415200887755e+00 +4.558412795895107061e-01,1.104444297834384775e-01,3.593332594690472170e+00,-4.491949968717319219e-01,-1.249186860862924409e+00,4.848963876141733631e-01,7.417506132955815623e+00,5.706804425219697663e+00,1.215304517010838303e+00,4.780543049014910117e+00,1.268904798642988219e+00,4.344918043171323241e+00 +1.029599828608850798e+00,-3.071971053391180928e-01,3.348362969849801640e+00,-3.252650131375099285e+00,-7.798963774535212501e-01,7.979538575667203260e-01,4.762983994516790887e+00,5.907165620073715928e+00,-2.723269413874934486e+00,4.328361348759193206e+00,2.685950096418165955e-01,3.347897102570498884e+00 +1.859740361719270263e+00,7.446068548254567432e-01,-5.897576147674840064e-01,-2.397830480271299081e+00,-2.495209820399827194e+00,4.455774218736996417e-03,2.135666466920343343e+00,5.503827401310089407e+00,-2.574279522444243185e+00,4.861401535483356184e+00,1.201085947131323994e+00,2.655449252937117421e+00 +7.374741802790536482e-01,2.322398825206865025e-01,-6.388607919241386934e-01,1.558201954142270029e+00,-1.169242667594004859e+00,7.156079652442062233e-01,1.209797746695326470e+00,3.280608636259185751e+00,2.433976210884713609e+00,6.860566217677655843e+00,3.428522783072619262e+00,4.354001919376115026e+00 +1.950582162144144371e-01,1.650484120201193006e-01,9.187050848428093275e-01,2.397232901981297459e+00,8.846211368723200241e-02,1.915130839190936074e-01,2.395860524137094050e+00,4.892194719829086047e+00,5.158820345845164468e+00,6.636110962149698977e+00,3.735949827975016291e+00,6.185136809968994065e+00 +-2.166162878878472142e+00,3.580732411560658135e-01,3.184832216671073635e+00,1.162138682750387897e+00,3.518870334769891306e-02,-1.993834323159580979e+00,3.195440828486001195e+00,6.371795030099142387e+00,3.311349987162778508e+00,5.273050129739965897e+00,3.450213330997202288e+00,5.173169406007716020e+00 +-3.083572858198748712e+00,2.049828050997768880e+00,1.369940080228404966e+00,-1.968064312283646089e-02,-1.465151629194637373e+00,4.167797826275299600e-01,3.621458553235387345e+00,5.113646283697613981e+00,-2.572042403930123733e+00,3.535381998201279075e+00,4.275033910035618945e+00,4.819187497449219038e+00 +-3.759345714741513689e+00,3.866920217978569774e+00,-2.103677830170176399e+00,-4.413827482702367688e-02,-1.884494713061559912e+00,-1.664631160098107854e-01,3.824917394299513163e+00,6.739145715447541818e+00,-1.224305480377219979e+00,2.002436272864535738e+00,4.451854545236884064e+00,5.366281616039342950e+00 +-4.578524685542856076e+00,1.778297781524767363e+00,-2.342573708673762134e+00,-1.198012191420462891e+00,-1.087814814573651923e+00,-2.086338604224302173e+00,4.904593866914863654e+00,6.667415099684595781e+00,3.719124336327230829e+00,5.253414586500423589e+00,3.973608202969439951e+00,3.507768606291574276e+00 +-2.825684221751323832e+00,1.017035095562614178e+00,4.304519462972633548e-01,-1.308161149994459427e+00,1.808840797870643113e+00,-7.167306005669671354e-01,5.610262983927929881e+00,4.565759051248619471e+00,6.723464872045026297e+00,6.383075616093323745e+00,4.233965708217838575e+00,3.808504549699757824e+00 +-1.019503719482324655e+00,4.065875506696980501e+00,1.787319612937320334e+00,3.785871797822472073e-01,-4.859598417414798810e-01,1.860761205100296634e+00,4.634366340916597160e+00,5.953031621103274773e+00,2.001161800363860266e+00,3.602337542990413866e+00,3.525568024920474830e+00,4.793193174110071730e+00 +1.786485900516896486e-01,3.602429925837669522e+00,-3.578127110716060322e-02,1.737775079834362746e+00,-2.223910956932633631e+00,-6.312674771699231524e-01,4.791120446589096638e+00,6.647638521125487365e+00,-3.934713074554867518e+00,3.509959809463994773e+00,2.288498110193316837e+00,3.623256074928376869e+00 +1.377030533515761768e+00,1.868948230854079462e-01,-2.055257803764825919e+00,3.105518687464257077e+00,-2.031096529580538324e-01,-1.283138892990953739e-01,4.735750670689223618e+00,6.241461733830655056e+00,-2.176226623923146697e+00,3.986486597268589449e+00,2.201362078044586390e+00,5.134844960398845970e+00 +8.802257136493027989e-01,6.991610167673095733e-01,-9.424059896640486489e-01,2.691141223314705844e+00,5.549848900595333312e-01,9.033152868585698769e-01,6.019697038791218091e+00,6.081796153028275143e+00,3.477088450765857708e+00,4.767849061984209769e+00,2.942893996062047712e+00,6.421923977825514385e+00 +-1.381855267987889269e-01,3.358675920631863043e+00,-1.269793476586484893e-01,-1.901853822405958461e+00,-6.386590191962151497e-01,9.989271146097629117e-01,7.635877472799797339e+00,3.757307194184470678e+00,4.359092498585783737e+00,4.700958837177121374e+00,3.883273996083135504e+00,3.670302715800173754e+00 +-1.242603731882978346e+00,1.179047161150432732e+00,-6.655607401899660269e-03,-3.935150388695539458e+00,2.071500264828480820e-01,1.416157323149925595e+00,6.199934806643137009e+00,3.645732419870664653e+00,2.646933395806181366e-01,3.664391908397746533e+00,4.501513758231745932e+00,2.208611795199703298e+00 +-1.980575304377616641e+00,-1.023312785625449362e+00,-1.076612247841705505e+00,-1.100154803106146328e+00,3.105740538097445658e-01,-1.219956835939274509e+00,5.805317603722760289e+00,4.728494949076917919e+00,-3.770431797980794641e+00,4.421206940584860412e+00,2.599085846756127083e+00,5.651612737237668327e+00 +-1.516710654879325659e+00,-2.323655834268085751e-01,-1.979048757027758842e+00,1.308402345296667990e+00,4.294516415566841938e-01,-2.959675111221924393e-01,7.029773949233699248e+00,3.801580229547636414e+00,-1.745096512269221911e+00,5.483005158758311737e+00,3.949109605587119098e+00,7.534620038935655018e+00 +-1.008203449196294343e+00,1.018038906638925600e-01,-1.753742555218650301e+00,1.038464361603437247e+00,-6.402963602107262231e-01,-6.128757175426355897e-01,6.356158567751506894e+00,1.796323243505194789e+00,2.363618419278966876e+00,5.121392245046798131e+00,3.177370768889981711e+00,4.039345223032076326e+00 +-1.895911417887633732e+00,-1.353493576124875197e+00,-4.044122617485270688e-01,-1.680421006422703645e+00,-2.941734439100746057e-01,-1.290065374186449842e+00,6.494096475458992046e+00,3.748179576591863071e+00,4.345436684232510061e+00,6.504187099950051731e+00,4.161836780587097273e+00,3.639340715987385177e+00 +-1.010428440734555622e+00,-2.913311355246178458e+00,2.987635913468353333e-02,-3.279635424953385225e+00,-5.459629222529611692e-01,1.379276987703866197e+00,6.519992428468716739e+00,3.821967605340175211e+00,-1.366874441741663837e+00,5.596444265884471747e+00,3.368739435092725110e+00,4.269651927955164794e+00 +-3.836429733507723538e-02,8.992082546887905092e-01,1.676376391647649289e-01,7.869692148824882771e-01,1.483872795671443257e+00,-1.291049843292832788e+00,6.845329173990874594e+00,1.840953010689553970e+00,-4.601262519633497305e+00,2.963292356885109946e+00,4.284365403802066652e+00,3.582885009051825165e+00 +1.133727084981247302e+00,1.667861749572196572e+00,-1.002822474434478472e+00,4.399034951128379056e+00,7.289220369490914120e-01,1.313710382185457881e+00,7.786877049577780596e+00,2.650399780779336911e+00,-2.175503178058280973e+00,4.858432397219559107e+00,3.588870920164624501e+00,3.967739611535218813e+00 +3.028928456183230811e+00,-2.343504079657432015e+00,-1.735220721547378053e+00,1.502014569001267841e+00,-2.000598529814214821e+00,3.063481019302902730e+00,8.711264538275468539e+00,3.939224384803575507e+00,2.306019998494040379e+00,3.869607166962059530e+00,4.493807489500436070e+00,5.438974973144796721e+00 +1.912884418398078878e+00,-1.017257808087804083e+00,-1.563967274598344392e+00,-5.979828118169634443e-01,-1.818763994069724443e+00,-8.957388571460802584e-01,7.842133100651661692e+00,4.706804462653856547e+00,2.062018851046006684e+00,2.013173749054140593e+00,3.174823864850833566e+00,5.055864408312224612e+00 +1.936123025836812950e+00,-2.881807603031397713e-01,-6.322762488805153680e-01,-2.405318421708156351e-01,-1.117212170935863585e-01,-2.089224422518605184e+00,6.859814222292866859e+00,4.305888056446495860e+00,-1.504652401585081734e+00,2.724891608993822878e+00,1.953893529791669970e+00,5.706103435960124592e+00 +1.618221552723499768e+00,-8.002646754975277776e-01,-1.541544171952438314e+00,-5.183997404836993006e-01,-1.770290809661849929e+00,-7.887086637616680385e-01,5.784084225940442359e+00,3.699792675914003404e+00,-2.693492530826773645e+00,3.368124005382250985e+00,3.150094770688928847e+00,3.256005576777363686e+00 +2.080028156160730113e+00,1.305113373605160998e+00,-1.579242564349135458e+00,-1.031759963327423257e+00,-2.296390069112169030e+00,1.113842869659726453e+00,4.258537816670777687e+00,2.666290978369139530e+00,6.042940022593121796e-01,3.276888245125995969e+00,4.134579687760838063e+00,3.667555485766595069e+00 +2.067576750771584759e+00,1.650518389633325311e+00,-4.526871086243544617e-02,-5.336818663506125437e-01,-4.757304941173889912e-01,-2.213097572202314289e+00,4.381036304112623014e+00,3.610682949304262923e+00,3.614310001038989917e+00,3.483275795388367513e+00,3.583129797372695435e+00,6.389563758440964136e+00 +3.786017738921322096e+00,-4.475021169250423814e-01,1.094641211652286561e+00,1.816604243070493174e+00,-4.137960824756630185e-01,-6.128853266638312203e-01,4.872969010800280998e+00,4.909625339754276396e+00,2.644042578184389924e+00,4.099073312922418388e+00,3.757909776778407540e+00,6.151163093415396688e+00 +3.483896602799633424e+00,-1.711015863873070142e+00,-5.104956170019500084e-01,2.859627247942449380e+00,6.568479639301256778e-01,2.204250097643949413e-01,3.773568767145410785e+00,5.060001513972095744e+00,-4.371107711584041766e+00,4.335962442428765939e+00,2.918503197900284896e+00,5.090574584299498717e+00 +4.576394942912266117e+00,9.426496451287436074e-01,-3.019032842906256064e+00,1.798851426301030676e+00,1.871164952159827033e+00,2.498610384954699781e-01,4.798982163132473389e+00,5.230029489935797749e+00,-5.885922879260423457e+00,5.282686299998096580e+00,3.374482995803665730e+00,4.608386496870978455e+00 +4.163200436344271615e+00,2.165441207107301036e+00,-2.376162131368675379e+00,-1.205931204947915392e-01,1.637935602027619009e+00,2.460981688298094383e+00,3.263146420542350601e+00,4.191488902458624821e+00,-1.815598761535369476e+00,6.212258418129863458e+00,3.817028694278706613e+00,3.317411050370447256e+00 +3.928017036429528375e+00,1.333673631104954627e+00,-6.458178088186522503e-02,-2.614809517409371509e+00,5.404482446485152636e-01,9.982797489639411159e-01,1.248171468675098428e+00,4.857115197313684796e+00,2.164447559332584703e+00,6.784390463654808912e+00,3.026009329226857947e+00,4.269082725882513252e+00 +3.342461135564160024e+00,1.813969413192767943e+00,1.271570493954519376e+00,-3.241552141702179313e+00,-4.107566534691114990e-01,4.554059273203925340e-01,1.474089932010938409e+00,5.396862418488867164e+00,-1.335624732277542748e-01,2.423500390873732258e+00,2.723503842105398753e+00,5.101459630326847794e+00 +1.799652716973078714e+00,6.944756218125076597e-01,-4.194005994748716826e-01,-1.083790345331669958e-02,6.616246977677708863e-03,-1.257618932044302529e+00,3.330856688646777641e+00,4.323617273943576755e+00,-3.618646261984716617e+00,1.108704578913732419e+00,2.418932105367774810e+00,5.699769803981489247e+00 +1.672723233610053040e+00,-4.900712705065484592e-02,-2.612987182637256378e+00,3.631112288887047956e+00,-1.299422808443319033e-01,-2.561113511042099944e+00,5.022410746851131869e+00,5.238189687817999207e+00,-5.493461308644604912e+00,5.161521639309378351e+00,1.877491626970969385e+00,4.035544796621502783e+00 +1.611958406255827869e+00,-3.091732562761747571e-01,-2.765880768238858867e+00,2.818067235798883186e+00,-2.986442384781843873e-01,-9.983095628402852695e-01,7.515330779140204420e+00,6.175506103179614570e+00,-1.835135034308899904e+00,4.823193971936775348e+00,2.719501996436998859e+00,4.329517824313737329e+00 +-3.032516886443232806e-01,-5.896004093191060669e-01,2.372919865267558714e-01,-5.532374295282154186e-01,-3.508148009550304258e-01,9.537541883800372267e-01,7.701903546473513273e+00,6.350400019395164186e+00,9.933807002980103995e-01,3.613308445084823628e+00,3.691216874039355833e+00,4.982059011101596546e+00 +-1.337959007393631605e+00,-1.002276626933851666e+00,9.579227200033104683e-01,-1.678868230406534767e+00,1.037460164619667724e+00,1.764842439121176110e+00,7.461032443895634358e+00,5.762777110943723358e+00,5.819435959838257233e-01,2.926436880405554497e+00,3.826542669273639952e+00,4.704638029968001511e+00 +-1.233022460530211362e+00,-5.743711226531966751e-02,-1.380807697986606186e+00,-3.842982498171382044e+00,-3.134900402257079222e-01,-1.635880325408218816e+00,6.701998499399708820e+00,6.226440851859729619e+00,-2.691285694757140412e+00,5.804829449411999853e+00,1.525138823745268990e+00,3.493815860942671936e+00 +-1.865205496337602131e+00,1.431710762843489970e+00,-2.718995054907896503e+00,-4.593443294069448513e+00,-1.383122156873124453e+00,1.309052096583117608e-01,2.337293587335182110e+00,6.260320734918286334e+00,-2.818298318179969009e+00,5.260742496647727862e+00,3.769612237166608537e-01,5.288363853086943678e+00 +-2.206628938695722297e+00,1.551514493449068777e+00,-2.413132556106665660e+00,1.178316695476375520e+00,1.457335410974213152e-01,1.204115957202990028e+00,4.698235367745162705e-02,4.896590014458261031e+00,-1.378430015980652179e+00,3.170740511370718551e+00,2.494619471374078135e+00,6.962789005562388667e+00 +-1.860135976104381417e+00,1.798906615382426022e+00,1.434350091326882515e+00,5.291584491944156809e+00,6.768586675674830300e-01,2.077446917403265036e-01,2.813578563378360542e-01,4.655291061699078803e+00,-8.382086229604519545e-01,3.621502355422674846e+00,2.593844517273804939e+00,1.607291002811817471e+00 +-3.124042680743386313e-01,7.577307867890251680e-01,2.121353399933311845e+00,1.350895633914932281e+00,-2.789513697782862178e-01,6.753067582859945128e-02,5.177064883997037903e-01,4.187754565173992916e+00,-5.103936229277277192e-01,4.061669028788871039e+00,4.315741458371293859e-01,2.824313347012796793e+00 +1.130011797480357849e+00,-8.391072593324183648e-01,-4.237611371298919405e-01,-1.933216574495729256e+00,2.742387868777405036e-01,-2.994752019428656986e-01,2.576689234901710535e+00,4.197275424097892227e+00,-2.993473679205946425e+00,4.366762917006224320e+00,4.797295118434252714e-01,5.492514421382309386e+00 +6.013461290273439674e-01,-7.688129699543496676e-01,-4.897451212908877416e+00,-2.480162142973378891e+00,2.630291790748110259e+00,-6.105555302220355696e-02,2.831441988274062460e+00,4.603751886326594267e+00,-4.760866155975504554e+00,4.405816125861661270e+00,3.255181258612026340e+00,4.946983860710324699e+00 +1.826389000794743867e+00,1.360554260325545606e+00,-2.665441211971080637e+00,-2.956296864889385922e+00,2.293554557599212451e+00,-3.452188178759939552e-01,4.107295149898662956e+00,3.829840697084754275e+00,-5.231379965522782172e+00,3.965474815393268848e+00,4.403908204209738386e+00,3.258035887312124679e+00 +1.394651957441010781e+00,2.188037568200167815e+00,3.918724289346340317e-01,1.396245913849412656e-01,1.029139151119064621e+00,3.966988293802046206e-01,4.213206276829068564e+00,2.317514670608773919e+00,-2.288681983437580669e+00,4.481009799782624370e+00,3.195088291628812360e+00,6.864843505746224928e+00 +1.317933650233626075e+00,6.196489704735804738e-01,5.453711560110501289e-01,2.872940919956571193e+00,-2.861319974669730426e-01,-4.446493412264039269e-01,5.341245468866937074e+00,2.402731574217447097e+00,-5.277416786616697664e-01,4.779774807980386342e+00,4.143791484593146279e+00,5.334646907298598251e+00 +2.078369651602372858e+00,1.055758634535370666e+00,-3.462383431273311274e+00,1.678371156089661920e+00,1.137865298635378108e+00,-6.250099977772415327e-01,7.340207577136370176e+00,3.994784883241460527e+00,-1.744308929395895547e+00,3.878048144569627986e+00,5.605253434021879144e+00,2.521198941506532343e+00 +3.149956991405951090e-01,3.999108922925000975e-01,-3.508493449203125003e+00,-1.183807484020850787e+00,2.048243675682622555e+00,-1.041283196264988664e+00,8.555754908569184636e+00,5.741224396017981846e+00,-4.554342668069114808e+00,6.039359007999831164e+00,7.062085973272534289e+00,4.566203609589495116e+00 +-1.335484915511098825e+00,-9.496044867575319515e-01,-2.101464349861162262e+00,-6.019396382394653910e-01,2.167658385589843473e+00,1.143199269311364175e+00,8.813808214112786033e+00,5.019559988327137567e+00,-6.275070551017204679e+00,6.788630174725600597e+00,5.175258844591393625e+00,3.385675944182517050e+00 +-1.762311053362322077e+00,1.495196654900621480e+00,-6.786751093886460584e-01,1.226921069235455297e+00,1.144931843234056057e+00,2.092742335952447963e+00,7.687264647442435539e+00,2.181909398040426940e+00,-3.808404812229323255e+00,3.953596456987713559e+00,6.473631774814190720e+00,5.310460369457939755e+00 +-1.242235850301085520e+00,4.067472821829554164e-01,-1.266287029602956693e+00,-4.473018400253331306e-01,1.520755709265585010e+00,-9.731500771403120975e-01,5.208368016111156074e+00,3.098806325055673216e+00,-3.095765099554673938e+00,4.673366002556873511e+00,7.936264835799946127e+00,6.124787052766116346e+00 +-1.047907593483522248e+00,-2.688763226369760506e+00,-3.113089820761621773e+00,-2.512693119715510015e-01,1.846380876804381677e+00,-2.282894962031603470e+00,5.906650769498869025e+00,7.191220081857573554e+00,-2.519878654915281402e+00,6.553610623994441831e+00,8.380986906793040703e+00,3.584350310865875411e+00 +-1.844627464125473404e-01,1.122766995630271047e-01,-4.121025287637391621e+00,1.797875294197349483e+00,1.585009272754673182e+00,6.660819244520836957e-01,6.893875111118499710e+00,6.874602615116323534e+00,-4.767729824381190085e+00,6.979311980368485102e+00,6.773564231786926904e+00,6.240392836728278603e+00 +-1.553126461549380499e+00,1.428128698225768156e+00,-3.387762219870578129e+00,-5.811216978785013199e-01,2.980713220670671015e-01,1.450360386619919950e-01,5.111534095669602706e+00,4.052598079611519744e+00,-4.344976218930746370e+00,5.539882879186871278e+00,5.024728618775607281e+00,4.627643543827098860e+00 +-3.994786779790023168e+00,-3.030500860844554722e+00,-1.574365772133774488e+00,-2.334190637396902357e+00,1.041007653499785857e-01,5.435714176373549478e-01,5.284802151532128178e+00,5.099647470951653716e+00,-3.371047890540608272e+00,2.211015009308235690e+00,6.168632169582965119e+00,4.081638605238643080e+00 +-4.951401337488436916e+00,-4.281597413464874435e+00,-1.446965890712374803e+00,-1.532118915967320305e+00,9.840892849850390034e-01,1.695384535337644216e+00,5.045181307419701611e+00,6.578181144299732885e+00,-1.598630209145178505e+00,2.396734116344834131e+00,8.386117100329082419e+00,6.105214003038710757e+00 +-3.768335176734624703e+00,2.821499338348825159e-01,-3.841967183343979908e+00,1.219078443502037423e+00,3.382258767711604719e+00,-3.293032198175086522e-01,5.688952638614140689e+00,5.508928573275908569e+00,-3.851911527026880222e+00,4.279345597822666214e+00,7.042749744856436678e+00,2.811021302569785441e+00 +-2.000378725346092956e+00,1.721205612915869709e+00,-4.147184173872245694e+00,1.613977079281301741e+00,1.245829365421335488e+00,-3.110864252931751506e-01,6.006974816112244930e+00,5.176304910092258460e+00,-5.261539750925154024e+00,4.346664796174861678e+00,5.904321977862433179e+00,4.917188698982512207e+00 +-1.529114688558853796e+00,-5.520735524876592137e-01,-2.656566963244266777e+00,-6.190376217729887109e-02,8.875057108964315988e-01,-1.866651543240889222e-01,4.284550674581560692e+00,5.405435297673074402e+00,-4.775343473267573913e+00,3.799120905352531885e+00,7.318339719949468858e+00,4.545836912879165581e+00 +-1.382077426139134202e+00,-1.460745776425036890e+00,-2.296335121286509073e-01,2.238441972820927328e-01,1.636529721440337148e+00,-6.973505035377320915e-01,4.318230763979286735e+00,4.610885275325962596e+00,-4.158230463276119337e+00,2.544854833773063874e+00,7.518444240314048344e+00,2.399475115996510866e+00 +-9.776006139457309452e-01,-1.267066756597080124e+00,7.938082447649477125e-01,-1.413220720731109603e+00,2.171566498567953474e+00,-2.290059544218771670e+00,5.087184242756512376e+00,4.886844020442945968e+00,-2.652016073078577563e+00,3.729252890668482756e+00,4.806585388871521758e+00,5.511388409605797456e+00 +-1.302065558268684420e+00,-4.226338953756406114e-01,-1.123615705427960965e+00,-9.783303329218313582e-01,1.007122282374927735e+00,2.021121699101357638e+00,5.785845498026464639e+00,7.340906335593324172e+00,-3.094773528188479617e+00,8.037933946174717903e+00,4.708212886471146774e+00,5.125970724634678177e+00 +-1.605904370796716885e+00,-1.232593778691533970e+00,-4.337633722520346069e+00,2.543933438651938550e-01,2.444625552455861772e+00,1.588729289098186337e+00,3.946041794826312454e+00,6.208758917985891301e+00,-4.361938518167198353e+00,5.252633179210799419e+00,4.261297571469822465e+00,3.252001104075056492e+00 +-1.367407857803576876e+00,4.737473641267302416e-01,-2.935007695235578140e+00,-1.540156451526306203e+00,3.867695856989417535e+00,-2.178328585195230538e+00,4.309242335980648875e+00,2.485156214386876172e+00,-4.796033594615051854e+00,3.794170355583786236e+00,5.729969752339677314e+00,4.005477881434223342e+00 +-2.255653640435242302e+00,2.505874133578036123e+00,8.426518445301535432e-02,-1.024343935297204800e+00,2.751911341281242152e+00,2.095966177392705743e-01,4.137847859460531019e+00,3.843512617322950575e+00,-3.612947540317437145e+00,3.221189136472135672e+00,5.671551942901556842e+00,3.375065468211977837e+00 +-3.921030993293422640e+00,1.630507909858670834e-01,9.695086723449175548e-01,1.016718128066200100e+00,9.242379484877115692e-01,7.640466204237250647e-02,3.887114122371945868e+00,7.938872834349187890e+00,-3.930522720000167780e+00,2.642365263037671497e-01,5.839611272192583691e+00,2.237288727564263002e+00 +-1.936331010084744397e+00,-1.525296869443791614e+00,-1.887927094574153530e+00,2.889296467732927809e+00,6.674888846926972930e-01,-2.226209497065793741e+00,5.147626517807525559e+00,8.101203583561597199e+00,-4.036529054131140271e+00,1.460043503492038042e+00,4.555431949381168799e+00,5.518934066493400792e+00 +1.089177159792090732e-01,-1.480781935838115571e+00,-2.662620779159475592e+00,1.034614556451587619e+00,1.577832789279951964e+00,-8.318449178559828017e-01,4.720014009671788635e+00,6.953736907057773919e+00,-4.647597512732412284e+00,5.850995166966205474e+00,3.801198928568325641e+00,3.967097800413919018e+00 +8.857813357540065269e-01,1.626430617356565023e+00,-1.705199505776184621e+00,-3.030289740963192813e+00,2.396803525729377604e+00,1.417714739066025853e+00,5.888658474261237785e+00,5.147574616784824642e+00,-4.378121367908963890e+00,6.743064673446346191e+00,5.278554693669795128e+00,2.382535524532037208e+00 +1.379769462219410325e+00,2.641558084995923483e+00,1.825251076082315738e+00,-7.221922592021288168e-01,2.285832806744356738e+00,2.454150858434434923e+00,8.429248908043021515e+00,5.832642052619546824e+00,-4.493401982967590413e+00,7.640750679033470050e+00,7.192202538343089202e+00,3.930856752560546674e+00 +2.535850865204160254e+00,1.747903449949556043e+00,2.352021208472720559e+00,3.861460703360300784e+00,1.219586203910399957e+00,2.687019828144873168e-01,7.327886179081454010e+00,5.419198983552933058e+00,-3.686637380756415894e+00,7.427129093163848950e+00,7.238967956017155814e+00,5.079134620182847115e+00 +1.918686482430989937e+00,1.901521804749375377e-01,-2.233122763915323938e-01,3.527070754360397853e+00,4.868582213573210415e-01,-1.998178446545642029e+00,6.021843205344657335e+00,4.060183028189632282e+00,-1.173286360505831460e+00,3.527551104234933455e+00,5.874570741275926267e+00,8.095694785062841348e+00 +9.834708323740255498e-01,-1.767532034523958906e+00,-2.275029374245874259e+00,-6.330186885629789373e-01,4.817738872638802627e-01,-1.738891492324635024e+00,4.938549126197735895e+00,4.321312469822547797e+00,-2.291676683720837104e+00,3.359429581762446659e+00,6.659601894279155054e+00,4.369361129868212679e+00 +1.130922016234996885e+00,3.501437177607990003e-01,-2.197358340644391950e-01,-1.733438673028740773e+00,-4.798647781829542547e-01,-9.449763468903303598e-02,4.346695488232400706e+00,3.764062693634334877e+00,-4.867940086837689861e+00,3.469323980260952567e+00,8.250621485366245622e+00,3.199225863983878870e+00 +1.987774937541078035e-01,1.621324503807580752e+00,1.471824066182197965e+00,-1.574909450028733282e+00,-1.444874973655196015e+00,1.828513539814531796e+00,4.486520860130791988e+00,5.335209395860640136e+00,-6.103478888992684759e+00,5.295324495597192538e+00,5.824635096502237985e+00,5.422301366413537771e+00 +1.181252098985606569e+00,4.134968344910459059e+00,-3.613664434624985766e-02,-1.855481006435167224e+00,-1.404220683081923049e+00,-6.819517137232335990e-01,5.418137778231014501e+00,7.113217943178534064e+00,-3.589890359574850365e+00,8.317154553906529912e+00,5.537201981927316830e+00,3.586261854092550827e+00 +1.856101904956906079e+00,3.925455888329151044e+00,-1.552381011240772102e+00,1.217705537328990228e+00,-5.337796791751941994e-01,-2.701922740527604727e+00,5.226323506836971333e+00,5.226959111586891638e+00,-4.693813412962200005e-01,6.616116507490185761e+00,4.891452878561917572e+00,6.033164740847288599e+00 +9.164264286591120579e-01,9.674231528967307536e-01,-2.080074393406138089e+00,2.693222771650090053e+00,-5.630122689619707632e-01,5.148341904779039080e-01,6.093970864738022186e+00,4.375989109329739613e+00,-2.262852418509282870e+00,3.253090895327358734e+00,5.143223292101271049e+00,4.424456203474296245e+00 +6.455961493516636507e-01,1.280927382243076229e+00,-1.905045654688751533e+00,1.415314383325836811e+00,-1.366699782267320806e+00,1.488353364690308878e+00,5.993014095948725029e+00,5.663699500937534381e+00,-5.375949927543592466e+00,4.127864241623477426e+00,5.749506903894103793e+00,1.749369021285917647e+00 +1.579146930776830771e-01,1.672634254975262857e+00,-1.481153727250525964e+00,1.130489333255395579e+00,-8.576220968497063613e-01,8.751866702420707522e-01,5.507422646264366506e+00,5.434873638195527157e+00,-5.476225810067839816e+00,4.600462707919646732e+00,4.738172189305659643e+00,6.056550584723551012e+00 +-2.909607925415798046e-01,8.724720745357827933e-01,-2.368999111916266997e+00,-1.715903225118668995e+00,-2.148380708258881278e+00,1.183998800131415230e+00,5.349573112733391866e+00,4.165787047009397170e+00,-3.323558655156205077e+00,3.223375661647526425e+00,4.119277002685489464e+00,4.599970682298828883e+00 +-3.306645713722670132e-01,1.909979759437071767e+00,-2.031465225505575400e+00,-3.587823934881999577e+00,-2.860600747815385425e+00,-1.987472501142117043e+00,6.256079522580288099e+00,5.830789907284640528e+00,-5.847171202702261539e-01,2.975383640935380214e+00,5.490481902136949977e+00,4.387879926982361845e+00 +4.263228177411126918e-01,2.157561582795937571e+00,-3.316935045948693705e+00,-2.940545435776955152e+00,-1.864903705361835584e+00,-2.524928902417629573e+00,6.628072144779578068e+00,6.395597652102816610e+00,-2.696110597254691044e+00,5.952264941109109309e+00,4.257662994441343329e+00,3.703930638641808493e+00 +1.193366732033157351e+00,9.826325589930737792e-01,-2.516527984552010544e+00,-1.153359427414173854e+00,-1.706924925159805539e+00,9.752757465543318016e-01,6.304456315745788686e+00,5.489217295081757264e+00,-4.712329429705231831e+00,8.394840572117590938e+00,2.978300494010345023e+00,3.193680706741855779e+00 +3.602778714187879761e-01,1.836253113768347767e+00,-1.211580301569618046e+00,8.376741731740589003e-01,-2.925237604631134580e+00,3.386650484928459992e+00,5.494203647555168324e+00,4.661456842424625435e+00,-4.605837326283065636e+00,5.816965219020976186e+00,3.351541411691269179e+00,7.093379900479445332e+00 +7.232824621865587833e-01,2.360273753448378642e+00,-2.119738764212126370e+00,3.166679016710597150e+00,-1.933442555463390722e+00,7.646785509822175975e-01,5.160871861802658778e+00,3.943309158431016037e+00,-2.819566607777573175e+00,4.778156170584292539e+00,6.104584871203494245e+00,3.806052101117367137e+00 +4.895188127295140856e-01,1.598400661269894441e+00,-4.059440643799568704e+00,1.761520509834790804e+00,-6.930824119684197981e-01,-1.602894020209124637e+00,5.354020572274483136e+00,5.675753062682611372e+00,-2.074769113012784771e+00,4.534992326556606557e+00,6.374140926240183802e+00,2.995667537325232388e+00 +-1.417146712806542030e+00,1.162540749823484543e+00,-2.821661381645873767e+00,-1.864701162965589631e+00,-2.148300520105935973e+00,-3.204283294137773574e-01,6.828004225253447856e+00,4.848636180667226014e+00,-4.807445855863754502e+00,4.322166784119967353e+00,3.357618936239717744e+00,7.477707704377309028e+00 +-1.223100535472626760e+00,2.399805049786160716e+00,-1.881675152841982834e+00,-2.051458864990816977e+00,-3.036353204927186411e+00,9.162349161972946909e-01,6.747155584887854829e+00,4.424131394752608415e+00,-5.172862866739350807e+00,3.714503085883650080e+00,4.530739860216478121e+00,5.588621204537695952e+00 +-2.331620117532256398e+00,3.091363422104554726e+00,2.498570506945987368e-01,1.156413474997385782e+00,-2.338453850701846637e+00,8.381982775322298629e-01,5.346875066248663266e+00,6.416893309367024401e+00,-4.329012813825567463e+00,3.400418611958983206e+00,5.652205932632920593e+00,4.984056855741751058e+00 +-2.663511555637592121e+00,2.035013611904984643e+00,2.174964038665803123e-01,2.002099711433644291e+00,-2.770177392028112084e+00,-3.737854810035730058e-01,4.668187886431102385e+00,4.793161363316138512e+00,-2.160875966280075389e+00,3.039640789342107574e+00,5.039753264893064078e+00,4.928799220242923163e+00 +-1.080341765991819303e+00,1.594274693509639906e+00,-2.597492751680845480e+00,-5.159732943759440804e-01,-1.862695010933665074e+00,3.223788650687369195e-01,4.396700210807002129e+00,4.087088907698947615e+00,-2.788140969679977488e+00,2.753411555394968069e+00,5.138471736541990964e+00,4.463078872331661451e+00 +7.757674270661434335e-01,8.185867493298183417e-01,-4.025774562613181118e+00,-1.778381660850697710e+00,-3.344381828802922119e+00,2.261965511720037125e-01,4.697408133444811895e+00,4.072430739626219598e+00,-4.819173401705640458e+00,3.401845223177136557e+00,4.451556870688682999e+00,6.392728433143465949e+00 +7.611104818252114601e-01,-8.286425486551746156e-02,-8.714099597121982566e-01,-1.392322392271790887e+00,-2.010274344700349047e+00,-1.187859749674115672e+00,4.220067923014012123e+00,4.198593555867003779e+00,-6.339609891012745635e+00,4.219375112814422124e+00,4.609282730777004566e+00,3.743959361957657883e+00 +6.790603894908642246e-02,3.587434096184727306e+00,1.621506077846056160e+00,2.664330740287865318e+00,-8.178962447624227305e-01,-2.098826921279402513e-01,3.445800902112551078e+00,4.990575469785755836e+00,-4.415085684552428447e+00,7.354874196964784616e+00,3.987913881285179318e+00,2.078377777453091824e+00 +-2.114987211631105812e-01,5.188606737658716384e+00,-1.843969134213113703e-01,3.702957121339581548e+00,-2.006425116542370102e+00,2.737147109700642122e+00,1.169552537800597314e+00,4.655034887063085769e+00,-2.251466020449346850e+00,7.997480528203591454e+00,4.994447217168600517e+00,5.452196236741163382e+00 +-2.044273108467230760e+00,5.835049444426541054e-01,-6.446928228212241763e+00,7.850216573166128864e-01,-1.431515617724336220e+00,-8.556040301668343950e-03,2.805575485367272748e+00,5.545649097145647133e+00,-2.639006556732358177e+00,4.314394547457116147e+00,6.591809101603595344e+00,5.870140067503667680e+00 +-1.101726457346012822e-01,-1.620274964016493735e+00,-6.641148523763781064e+00,-1.094626423534234005e+00,-1.244275022996923497e+00,-2.347922786427476094e+00,2.986861694153729374e+00,6.013670007454654076e+00,-4.749572626239835671e+00,8.989575797021882586e-01,5.871049258764507783e+00,3.692157962858390707e+00 +-1.355492099570392295e-01,-7.710785816490806077e-01,-7.460042509833926250e-01,-1.431969779711422142e+00,-6.658354460507525108e-01,-5.212556798169548644e-01,3.640715501686690558e+00,4.199800461076788949e+00,-6.923924389413915748e+00,2.409415786856320629e+00,4.723429037241177575e+00,2.118230114873473902e+00 +1.066566345600753696e+00,-7.877368489464272594e-01,2.450416683951243790e+00,-7.293212181132470162e-01,-1.831209305352095917e+00,2.128019456441309631e-01,4.630997173162287872e+00,3.153504864869932423e+00,-5.121705788364117495e+00,4.961928494411546708e+00,5.848549132384527560e+00,4.270064162359655136e+00 +1.193425803725096435e+00,-1.896760202919263172e+00,-8.562759139084471505e-01,1.806142938563724432e+00,-1.942094921675173724e+00,1.854619225282396755e-01,3.595501587468281190e+00,4.159012662003547689e+00,-2.807186266658452389e+00,6.385983535919036669e+00,7.004357507056047538e+00,6.747016245236693521e+00 +2.083761271791886305e+00,-1.276720735151101849e+00,-5.479757520210992716e+00,2.606765689959579468e+00,-1.441777419428688312e+00,-1.139184854626122068e+00,3.426172540266504640e+00,5.032483969662179923e+00,-1.070486597603295564e+00,3.698943296325017283e+00,4.604898685711097173e+00,5.158872725905403023e+00 +3.913190663892308852e+00,-1.838204721789715279e+00,-4.340440974661147422e+00,8.709417064315086998e-01,-1.368377580730800069e+00,7.857745914260003683e-01,4.206649879981476658e+00,6.144795896611343622e+00,-2.978755867683351433e+00,3.100088655314563901e+00,3.913506554336225740e+00,3.186174085507160747e+00 +4.353600527808068499e+00,-3.456748851778082887e+00,-9.091876232287394721e-01,-1.666746966739525604e+00,-3.835541755542447806e+00,7.176915106309048609e-01,5.999160702075048590e+00,6.123954378276296850e+00,-3.942832587262444122e+00,6.505938216379314909e+00,4.494098247601696627e+00,4.785774580268420841e+00 +5.751111549400718559e+00,-2.606365152484285463e+00,2.712259588367511576e+00,-3.002823022246964513e+00,-2.501744939896656028e+00,-5.772774549715806169e-02,7.052118926317236358e+00,4.556194363128761360e+00,-4.652746919986396890e+00,8.969322605193864817e+00,3.338448377151303603e+00,3.847965444282013703e+00 +4.412564108108409044e+00,-2.197886789007060138e+00,-5.546879011168140972e-01,-1.945269973105419936e+00,-1.544695102302105383e+00,2.213139708179573395e-01,4.681231933766181186e+00,4.183559885287595925e+00,-2.610332668439563797e+00,7.894978062034469168e+00,3.369021545659768524e+00,4.544912566977936663e+00 +3.799001718987409681e+00,-2.137054923626828806e+00,-4.457079794441984433e+00,1.226395757840899492e+00,-2.030637715223882811e+00,8.683575779812516271e-02,3.111532903220851853e+00,5.466003107294981511e+00,-2.524675485755767390e+00,4.537313889249458221e+00,2.228549041068664138e+00,6.596994726986956437e+00 +2.235099628414229045e+00,-1.228748151889619278e+00,-6.116059378706810712e+00,2.226761373624125628e+00,-3.167429537191252198e+00,-8.899723588492577941e-02,2.739760515153621956e+00,5.488751323872038235e+00,-3.267075187526828017e+00,3.180835210134046687e+00,3.677150338628789594e+00,3.917626231455117569e+00 +1.584180587095145309e-01,-7.852655966666166609e-01,-1.812135908497644499e+00,1.811381571465614071e+00,-3.868721454666545601e+00,-1.305486931701104858e+00,5.212141177367930034e+00,5.083612625330649948e+00,-4.227537965591771751e+00,2.436317686035841312e+00,4.677542309159430367e+00,2.750568805364736136e+00 +-7.766652041322625877e-01,3.440854525018116616e-01,1.291619621175252419e+00,2.833256115689901211e+00,-2.566560115440099654e+00,4.448779037142117643e-01,4.720370609089600933e+00,4.390812785928678963e+00,-4.009024438940521406e+00,4.226275748530937015e+00,5.640016549047624395e+00,4.977936640280186786e+00 +-1.666461426108118760e+00,1.785540568414713203e+00,1.805973667163951024e+00,3.702551833821285943e-01,-2.318949619335108014e+00,2.193260776215153474e+00,6.501093851038027616e+00,4.097104561187784988e+00,-3.380629817883458621e+00,4.993965235226390575e+00,5.038063111393355165e+00,5.840642169186212485e+00 +-2.410407352193815633e+00,1.827937464828485625e+00,-2.753275686170967518e+00,-1.916569669564210932e+00,-4.188875821867550364e-01,-1.434728816777196769e+00,7.222656113864077909e+00,3.863332368140850015e+00,-3.557266307242549885e+00,4.348824044871342664e+00,5.264486958202708067e+00,4.345164796256563378e+00 +-1.666239550604287967e+00,-6.080677676092065553e-01,-6.016779562497917233e+00,-1.597834161041584933e+00,-1.273227400451314217e+00,-8.484560339955301567e-01,6.599063039814783593e+00,4.026283348567725184e+00,-4.751951651617574157e+00,5.398147519999094257e+00,4.362588794554010718e+00,4.096358997545670455e+00 +-1.655180023490592456e+00,-2.622239271382690529e+00,-3.750602427130766081e+00,-1.738716375420507276e+00,-2.284581807216647942e+00,2.062685576388656017e+00,5.465498868731979876e+00,5.571345962541135677e+00,-5.342053777125773451e+00,5.617987145165654006e+00,4.189733685873055613e+00,3.577745219813466715e+00 +-2.004071539620203346e+00,-5.295128212567417059e-01,6.047322567267358062e-01,-1.965503770718391330e+00,-2.096982664784231787e+00,1.269103252111400681e-01,6.751060902271214914e+00,5.910331031458312623e+00,-6.200308696641878115e+00,5.715923284776542879e+00,4.030748268924964073e+00,4.600455274492318836e+00 +-2.074304412279668330e+00,1.360712017343177704e+00,9.251475424004964587e-01,-2.383440075185935259e-01,-1.083413596973536785e+00,-9.697599544848316544e-01,6.441411052097585355e+00,5.461601793406312133e+00,-5.208872431540392256e+00,3.472725521286179617e+00,4.326691175634730158e+00,4.200401906248015571e+00 +-2.612709753918561972e+00,-1.702468264429593536e-01,-3.373551225247855889e+00,7.280554488963435489e-01,2.319313567379489571e-01,8.094720158030519475e-01,6.446830655778663655e+00,5.538956232612101793e+00,-4.981796819407129817e+00,2.406619465325531948e+00,4.497009142654491143e+00,3.232925210389196558e+00 +-5.287188450741622248e-01,-6.095815948953712260e-01,-6.264637216247125551e+00,8.323919370189192257e-02,6.473154449270844824e-01,7.835103380678738461e-01,5.984142948224764780e+00,5.229714827305749658e+00,-5.223713406750631449e+00,1.843460253666439286e+00,3.559375867868571408e+00,5.720746949205340215e+00 +1.427558787308593757e+00,-1.557302632852491930e-01,-4.597806285564796092e+00,-1.317988961575996321e+00,-2.188784664657661416e+00,-1.067990096138581313e+00,4.565907732054268031e+00,3.579763228869906388e+00,-6.308078353552398099e+00,3.078447130025423473e+00,4.832425975578442667e+00,5.011868797950294052e+00 +2.764127317348216373e+00,-2.686501783861952930e+00,-8.781008760933330937e-01,-1.878669373366243622e+00,-1.627916373166509167e+00,-2.543525014225115344e-01,2.474722339252600101e+00,4.017719734625418759e+00,-5.754602740312238396e+00,5.835979325068624490e+00,6.232338477435537705e+00,3.576325938558922779e+00 +1.543226017616112777e+00,-2.610207787022556847e+00,6.607750716330882401e-01,-1.309906651928841814e+00,-1.785712370039657992e+00,1.285798377024816475e+00,2.558548751022986067e+00,5.707837790419183932e+00,-3.563140784313889142e+00,6.480571766391602040e+00,6.253921768985826191e+00,3.881109340114460515e+00 +1.816779137249918685e-01,3.486292015042397052e-01,-2.840740209899347946e+00,3.379650278242442574e-01,-8.198855256058732444e-01,-7.181831308890092025e-01,2.723290370302909214e+00,4.875980960146384824e+00,-2.913466572202566773e+00,4.859607613288064343e+00,5.097350440448430220e+00,3.619998990410613793e+00 +-4.815905563663037681e-01,1.928041997345812497e+00,-4.815165219484332404e+00,2.363014709460953711e+00,-2.363669136181059116e+00,-1.316525815903691443e+00,1.826417649917365882e+00,4.500876629176228327e+00,-5.308566677002851009e+00,2.653997718300394659e+00,3.362139387239098554e+00,3.670391412629564254e+00 +-7.891240805373729295e-01,3.029472701355132802e+00,-3.758047625023254845e+00,2.288737409872124040e+00,-1.964455413069789991e+00,1.455759453557631034e+00,1.522305917526569630e-01,6.006149330688311139e+00,-7.122756661281028912e+00,3.790575847005788646e+00,2.664256832658303153e+00,3.063278519312641279e+00 +-1.427442697307999442e+00,1.422722195605895079e+00,-3.664943911779382502e-01,6.045914555489941833e-01,-2.351577888029317887e+00,1.028308835477044436e+00,5.875058199155538396e-01,5.281385630745823789e+00,-4.937230596280533845e+00,5.133190913151953083e+00,5.076220016262959156e+00,5.934188040842376388e+00 +-2.056090676664585004e+00,5.489115262117170158e-01,-1.190441230292740515e+00,-8.992542381752988145e-01,-2.054960448025206610e+00,-6.049953351586672134e-01,2.227411624213786467e-01,3.636772975192758217e+00,-3.001759071036718574e+00,5.036880885972359501e+00,5.495733033675129775e+00,5.145021568904277309e+00 +-9.582695723029276413e-01,1.852360103617485931e+00,-3.063441926180963559e+00,-1.953418429471264206e+00,-2.071154166554376896e+00,-8.119869804624716414e-01,1.230599694952299483e+00,4.824080340429043545e+00,-2.341051401377775676e+00,5.870680100001074209e+00,4.469277296861590365e+00,1.075704134029249914e+00 +-1.582376910602060760e-01,2.189889734009316857e+00,-4.747345179362759460e+00,-3.151931765461429835e-01,-4.509538900066918377e-01,-2.835531601968044879e-01,3.784604545548090115e+00,5.318221682007409967e+00,-6.180781124865310616e+00,5.646261655890591591e+00,5.054598689700086744e+00,3.793705868482695642e+00 +6.959286950578849051e-01,6.932436058180180272e-01,-2.546648440975166849e+00,2.062745429629262883e+00,-2.740780178961054858e+00,-3.269385040430629052e-01,6.430060983904160032e+00,4.100766536154779374e+00,-6.582948750427798146e+00,4.814588188534153268e+00,6.198388469805136580e+00,6.932549558323367833e+00 +1.685347181800349592e+00,-1.541952554884603810e+00,-1.621865943421660017e+00,1.936196794573352475e+00,-3.265755400220438531e+00,-9.629537655635460602e-01,8.370956373988427401e+00,3.038401085353682696e+00,-5.588498992214349315e+00,4.263243556096690590e+00,5.805831702509976822e+00,6.569832060772085036e+00 +5.619516977521017420e-01,-2.315973686782937246e-01,-3.281274591059599288e+00,-2.220697764081182579e-01,-4.628198926143993752e-01,2.151012543333026272e-01,7.745727657241503472e+00,2.685129616860215673e+00,-2.731165510437814525e+00,2.595087672753301433e+00,5.201334641044449647e+00,3.219474986801178940e+00 +-1.349268180125596794e+00,1.655809891178515958e+00,-5.231539015833455153e+00,-1.165785651985337124e+00,1.252610657179511477e+00,-4.897586746070302643e-01,8.129168315619942575e+00,2.922562657270405762e+00,-4.085018491545849173e+00,2.790472003681623292e+00,5.383394530934806355e+00,3.586778506060198879e+00 +-2.100389066768324486e-01,-1.494682972458925896e+00,-3.584572825600751411e+00,-1.401587609857073202e+00,2.251384033992794853e-01,-5.934183954548903905e-01,7.441139800707047947e+00,3.377305662599260572e+00,-5.913173941404689771e+00,4.668216539632784823e+00,6.737978412044867582e+00,6.493094468850287626e+00 +5.485587735747301519e-01,-2.068089318784515740e+00,-2.243471552217256360e+00,4.381068794323735860e-01,-5.229656391900302514e-01,-1.652041200608006299e+00,7.053254100833267870e+00,4.537533579414166240e+00,-8.793919469542744949e+00,5.559195251967260276e+00,5.876154813035684654e+00,5.726585109741426649e+00 +1.627196506847609303e+00,-5.942359193839545917e-01,-2.204020140251610194e+00,9.430541241391486862e-01,4.904723649761351667e-01,-2.143035632598147555e-01,5.841940752562459593e+00,5.217452086683557866e+00,-7.019671504862639466e+00,4.844290408304894768e+00,4.823209524717708696e+00,5.144027609039376614e+00 +1.046652319512691109e+00,-1.417153156446207207e+00,-3.026556964533268612e+00,5.928952139307762659e-01,1.397674651075489383e+00,1.968044498640865614e+00,5.644068693543877302e+00,4.831472166896566556e+00,-3.728254800048016904e+00,2.836757308576917325e+00,6.056575880500338904e+00,2.951545081531402381e+00 +8.954242013556753532e-01,-6.795137874097305630e-01,-4.097073586783594124e+00,2.247506211259183928e+00,5.553576947692639987e-01,1.975155891931058783e+00,7.154470288911317866e+00,5.087541508707205118e+00,-1.767290320286429406e+00,4.937862198091091948e+00,4.949358407465503262e+00,2.594159642289888712e+00 +2.024594371026763318e-01,-7.194769430688547907e-01,-3.691388889817488916e+00,1.247845108867251085e+00,-5.504762302810077834e-01,2.528715780911335309e-01,7.945662466242399802e+00,4.113873776637209545e+00,-5.456182505782537717e+00,5.985536488560954993e+00,4.227285404794214330e+00,3.250246637205136402e+00 +-1.218874410964381649e+00,-1.758523559724021856e+00,-1.962711156225795950e+00,-6.279759711458277049e-01,-7.583446693541391337e-01,-1.969618325843885298e+00,6.209907318174950674e+00,5.171693078300720003e+00,-8.264793271933069008e+00,6.769228940532217464e+00,4.723855349476290932e+00,4.573308323698332956e+00 +-2.148197705717832307e+00,-4.649936575244809633e-01,-1.035598528720012679e+00,-1.263971379281882079e+00,-1.440673375841695913e-01,-7.451968988208304001e-01,5.160471704650104741e+00,8.829560451716705671e+00,-8.539634940588666012e+00,6.936680962381640114e+00,3.235429173871033015e+00,4.781272951395972193e+00 +-4.544314759852930763e+00,-8.545989354614920153e-01,-2.071564460370118876e+00,-1.859713842565478226e+00,-4.399036977135762916e-01,2.182765786583092726e+00,4.372573258042296906e+00,6.440370574082606048e+00,-4.042071270042837838e+00,4.212542412812976700e+00,2.781187122013275559e+00,4.479168097457306708e+00 +-4.486765194885098396e+00,-2.890474908541991184e-01,-3.304044548606963172e+00,-3.223399180927805752e+00,-1.384748085255008476e+00,-1.868236729530169393e-01,2.959165170569567849e+00,4.369281965863372363e+00,-1.220165504047932892e+00,1.617402290075530047e+00,5.815718881738204615e+00,4.828299432327773921e+00 +-4.170539930389231209e+00,-7.684023046047836480e-01,-3.367635804336707395e+00,-1.180843434519597057e+00,-8.993294612879940697e-01,-7.435772416320318712e-02,1.629105066454298978e+00,4.767559151104483917e+00,-2.219961471007064091e+00,4.903561968792375936e-01,5.598205773850448708e+00,4.913656571866479084e+00 +-3.523686550790576799e+00,-3.056594155900486331e+00,-2.051846010921451136e+00,4.101145198083537835e-01,-3.884020341704730317e-01,1.523945307494584789e+00,3.781118856231072911e+00,5.366156690733308920e+00,-5.953217837094241460e+00,5.092017483868774619e+00,4.999319843892386039e+00,6.942958589801051517e+00 +-1.231878446629818269e+00,-8.628479855229758133e-01,-1.852650007446912106e-01,4.164919293050346472e-01,-1.818600026041566453e+00,-6.325278618971902356e-01,5.727470622257770927e+00,6.606226639230827757e+00,-5.685092000716643668e+00,8.653686802421905355e+00,5.247871113133442122e+00,4.355589457239776863e+00 +1.956579062862333629e-01,-1.001402484624956735e+00,-1.648018653455826765e+00,2.434358954106604633e-01,-2.561738949798213039e+00,-6.890056798907446822e-01,4.056488502898882409e+00,6.690025192103395746e+00,-2.331567658168778756e+00,5.552714407733484236e+00,6.007846107145587311e+00,2.146593937367936356e+00 +-1.337066816391991875e-01,-2.047520375519126468e+00,-3.749752336434909239e+00,-3.931332829248479488e-01,-1.077515842127684920e+00,1.542742312933534254e+00,2.580269691490353345e+00,5.901132988743353458e+00,-7.691250593657414925e-01,2.210681287616310886e+00,6.434215027836306611e+00,4.875300410899473746e+00 +9.668771311119851442e-01,-6.273495735455852929e-01,-3.464873707554443349e+00,3.764108608449281967e-01,-9.895920052136638612e-01,1.161514522980211739e+00,3.628069278143565946e+00,6.131490020509800409e+00,-2.807926682618690606e+00,3.781176319494426785e+00,5.644086292870081678e+00,6.295275496957128958e+00 +1.023428666895920713e+00,-1.490947232034514069e+00,-1.063370549377949059e+00,2.724388074533869997e-01,-4.805155746626946778e-01,-1.755875309538191154e+00,3.654881850994777803e+00,4.689417980765189675e+00,-5.528393825976275266e+00,4.667400875369982494e+00,5.661798326079645172e+00,3.049022038497731568e+00 +2.150110557047250737e+00,-1.621289848912258469e+00,-2.964810620807755148e-01,-1.087686635188899409e+00,-9.241544841718276615e-01,6.180224836607822736e-01,2.664532191692702057e+00,4.131871114110042598e+00,-5.334562974188926887e+00,4.024744383922982394e+00,6.436296956384975232e+00,3.522493084638647964e+00 +1.266245098542744696e+00,-8.409693056241445142e-01,-4.467070844934712959e-01,-9.450716491339775649e-01,-2.703589839154055818e-01,-1.247291591611538131e+00,2.352935829618759911e+00,5.294486498515911244e+00,-2.184654645284028973e+00,4.832681676656637393e+00,6.616047156565080023e+00,5.649768473177916306e+00 +1.256567595988527186e+00,-5.209123436247662386e-01,-3.554136627479215882e+00,9.851981865032902741e-01,6.066463566938561369e-01,-2.551671700953049182e+00,1.672367682222062335e+00,2.991517995066215185e+00,-1.891614166973339728e+00,5.547414844407583701e+00,7.085151694555714030e+00,4.583695315487106292e+00 +2.417146698983693831e+00,3.423420420221744420e-01,-5.468012133391138896e+00,1.912905303796538226e+00,6.560968323400628854e-01,1.772509328255130079e+00,1.402301657971260163e+00,3.194428186749342480e+00,-4.548483482978877390e+00,5.542356401725575310e+00,6.663883921111593445e+00,4.853820641199992458e+00 +1.999619757842334700e+00,7.041442580822797614e-01,-2.990899524647014918e+00,-1.416389906301699919e-01,1.065260057237635394e+00,2.783868292014194612e+00,2.188410837817223786e+00,5.161519878274964057e+00,-7.214884734592693860e+00,3.448410263284237054e+00,6.816941834764617347e+00,6.767420930176283989e+00 +9.646047438525601203e-01,3.112914907040450485e-01,-7.596712250334166638e-01,-1.123555366811338718e+00,-1.525906179172539012e+00,-4.163455596841435513e-01,3.793433139321964020e+00,5.691750360447885626e+00,-5.329084179349628414e+00,2.839667799187655994e+00,6.447140902238344573e+00,5.071253234787926445e+00 +1.035829306169633535e+00,-2.566617040964844776e-01,6.788594751020946561e-01,-1.970825217969614851e+00,-7.148301052070493711e-01,-2.998344115800775533e+00,5.006537963053346196e+00,6.376420985584982049e+00,-2.529233866513506790e+00,1.454425914995181479e+00,7.646398408348217046e+00,3.384971377637188361e+00 +-2.080360628734734263e-02,-8.295629174762977343e-01,-2.782322861236620426e+00,-1.588768468010897106e+00,3.621706258074112172e-01,-9.711881462604883275e-01,3.767405040453775111e+00,4.703163164051236578e+00,-1.541082078909195019e-01,3.066442966190603858e+00,7.223949483958030271e+00,5.153175615421303313e+00 +-2.176668615489226077e+00,-2.628618509971152317e-01,-4.108035577763894608e+00,1.697196899449041174e+00,-3.187822838173301143e+00,-2.520907834412116078e-01,4.623391059460301378e+00,4.388386902732331230e+00,-2.616420880557068784e+00,1.018395404878577715e+01,5.566905158542308385e+00,5.490643348955582148e+00 +-1.645649893157671961e+00,-1.107320912818145486e-01,-3.029372871602020290e+00,2.739496055782805417e+00,-4.118440239559833849e+00,1.035907301016749438e+00,4.832636701292732262e+00,3.721206062337678144e+00,-4.841557479246949569e+00,9.145626172885091165e+00,5.354959420757586130e+00,4.607999112388111662e+00 +7.534819207450915712e-03,-1.807902225159827014e-01,-1.471331302585488165e+00,-2.877547850274730923e-01,-2.540128763284053015e+00,1.359912408171636944e+00,4.065396168114132180e+00,3.073067398277013140e+00,-5.552206172695045794e+00,5.626049868871110249e-01,8.077022293538270503e+00,2.753384930472553282e+00 +1.471081049679962449e+00,-7.594261866225597846e-01,-3.180930202323744016e-01,-4.211102352125222659e+00,-1.921930323566371390e+00,-4.543019441167683858e-01,4.572059863224049003e+00,6.011934241154983205e+00,-1.318420469346104795e+00,-6.846078514769136092e-01,6.252954475747578122e+00,6.060362421801588795e+00 +1.581846486994021195e+00,-1.260619695530512008e+00,-1.641419606323505143e+00,-3.646624699638710609e+00,-2.492475649143024885e+00,-7.179682574043153576e-01,3.321180551913100132e+00,6.104450065015529781e+00,3.719103162558639042e-01,4.445272293410903686e+00,4.173886015269443917e+00,6.095660541184315662e+00 +8.681041898081029995e-01,-2.368645667974292213e+00,-2.154724203230645063e+00,6.095112830632625212e-01,-3.475142993412908332e+00,-1.507253315314915909e-01,4.119815713223559328e+00,3.784732117363433179e+00,-1.764107174036215753e-01,4.822307205518326256e+00,5.689716050834727312e+00,2.054433501081257329e+00 +7.464971289730815140e-01,-9.377553478592648428e-01,-2.369222972776465763e+00,3.080844885536041744e+00,-2.529406287482803162e+00,1.845371391610271861e+00,3.968941913572073155e+00,2.010025383505255725e+00,-2.710883466293171118e+00,5.545202534322686283e+00,6.088343999382616722e+00,4.926708257184033712e+00 +-2.586553280014266543e-01,2.427463824807717163e+00,-2.090201914853412557e+00,2.880203708208450841e+00,-1.997387761319864730e+00,-1.450964694687729151e-01,4.754551282526016109e+00,8.089492130796367420e-01,-1.601383943903980978e+00,5.737130497143407837e+00,4.782675577584496018e+00,3.677885129263262609e+00 +-2.248670046397965194e+00,1.597540861553059521e+00,-8.412007692607432752e-01,-6.086934482895658416e-01,-7.480078423641318697e-01,1.489591720044582956e+00,6.654717642939098177e+00,3.186448218260451437e+00,4.658021322860088631e-01,4.823697145528843322e+00,3.414984659017686663e+00,5.487437335735822153e+00 +-3.348281158520842737e+00,-5.568998104568737562e-01,-6.790211283644319584e-01,-2.212927024942085374e+00,-1.704558916373672073e+00,2.041808125015635689e+00,5.846991335580540294e+00,3.337831596232551767e+00,2.098744541113711559e+00,3.277236079611692610e+00,3.458622460117518838e+00,7.928515531651342485e+00 +-1.442897591944459768e+00,6.003522344310079362e-01,-1.966815026637589447e+00,1.775244020653421240e+00,-2.148144986929362954e+00,-2.434428890479605201e+00,5.420332938498821918e+00,3.619542836945243813e+00,-2.954857026603994186e-01,-8.673261466362269800e-03,4.306900508165536046e+00,4.791877210409132282e+00 +-1.155569605286546508e+00,1.618056367957397379e+00,-2.721818127545465149e+00,2.202103774385237411e+00,-1.438884608281588706e+00,-2.209300241018751887e+00,5.135802701613227939e+00,5.306944258591969721e+00,-3.018768166747916482e+00,2.699741853299243655e+00,4.617001162087944088e+00,2.222352491173781530e+00 +-3.488644218277279663e+00,-1.118599074445602914e+00,-3.376181105811175254e+00,9.934883595704468995e-02,-8.931507530256683758e-01,8.389966878750507728e-01,5.211812976787111751e+00,6.012687555812719964e+00,-1.814331686260396204e+00,5.796907755573260879e+00,5.797227449713707514e+00,3.538194632175998056e+00 +-4.525915842193184879e+00,-2.527108622493257961e+00,-9.006577877899080153e-01,-8.372490761748259125e-01,-6.829973961814596040e-01,-6.776843756425867671e-01,5.850405858604291964e+00,5.002963190238576274e+00,2.325373448708869972e+00,7.853608908550089751e+00,5.246662491251034233e+00,4.548401650003722096e+00 +-3.528879989993250366e+00,-4.378075977148361830e-01,-2.926237906261348609e-01,-1.590005961376358634e+00,-1.022521221361091692e+00,8.323101314925480665e-01,5.232798442089570123e+00,4.633711673012578913e+00,4.109426929386743588e+00,8.901357845062772611e+00,5.209590230851312675e+00,4.065213765574621441e+00 +-2.562622331885585858e+00,3.925845799236387101e-01,-1.507726935910974619e+00,-8.850671985609452896e-01,-1.397999139484211950e+00,-6.484968177871324180e-01,3.983304983396819043e+00,4.828507420812822915e+00,5.769515094244930253e-01,7.067279836372568624e+00,6.981173134628340549e+00,4.550353080264919470e+00 +-1.856378488901909929e+00,-9.512754879744240721e-01,-4.717032237780617088e+00,-9.504417158092401952e-01,-6.267080868992039866e-01,-1.558303820395119388e+00,3.427519950071115318e+00,5.866323724575988052e+00,-3.580441950275538687e+00,4.626256440073035492e+00,4.503333861719587716e+00,4.957952609674167732e+00 +-2.736969358397962626e+00,-1.946944243544922237e+00,-3.753120219952545078e+00,-6.556130942003135509e-03,-1.224376561236242056e+00,1.725091624855116246e-01,2.406053051552568434e+00,4.804445006333999402e+00,-2.561227109038436645e+00,3.115903428004852316e+00,3.301671559239126807e+00,5.966307568101433034e+00 +-2.561640507428150748e+00,-5.380962687630519437e-01,-2.159943664332669488e+00,1.762954755872925938e+00,-1.427884855214213600e+00,-1.638143791690184425e+00,2.398718774257984521e+00,2.981422967539768543e+00,3.296672324359814610e+00,3.678250983605063418e+00,3.692330793902033115e+00,3.753516855710442357e+00 +-9.913390773313958126e-01,-2.876758355812701340e-01,-1.429933999842839754e+00,1.642212480845887779e+00,-3.644403502179132115e-01,1.377236017855435035e+00,1.477832309500654695e+00,4.353594444037942601e+00,5.389545340331116208e+00,4.054115218922375696e+00,6.148688400590705427e+00,3.721102504340284334e+00 +-1.056769796014828788e+00,-2.885595533548593883e-01,-2.794503445044823398e+00,1.083090011598699220e+00,-1.380432962374760208e+00,2.497806290360156112e+00,4.167258891973620649e+00,5.486485952944832434e+00,2.519490343192760662e-01,3.409630610888273239e+00,6.497457287133940440e+00,4.337604040259845029e+00 +2.274903620720447606e-02,1.178709472965589811e+00,-2.191907922540886844e+00,1.147040859111712274e+00,-1.401092978881083306e+00,-3.073230208175671940e+00,3.143035241306364913e+00,6.164143814132094334e+00,-4.478989164556971048e+00,3.865238097566201070e+00,4.555747830634098605e+00,2.919483985102220736e+00 +-7.017977424499139971e-01,5.864426458347609117e-01,-1.052410741057273169e+00,-1.888349389452816274e+00,2.640406417979324072e-02,-1.251767083818635218e+00,1.900322526990273708e+00,4.288786027707171655e+00,-3.078458539960412743e+00,4.917959417157974578e+00,4.466967039398555883e+00,5.277507025041583866e+00 +-4.761575079868316518e-01,2.033879914173334136e+00,-2.119219470474186462e+00,-1.503623604112065859e+00,1.245419952932540264e+00,8.331834933385302566e-01,3.225788328670577521e+00,2.650018181237939974e+00,2.432707009371110729e+00,3.829198120567822716e+00,6.021729223149659305e+00,6.293117544191258794e+00 +-4.431170435912721306e-01,3.345382851260067625e+00,-3.650137045873923736e+00,-1.583532031681139873e+00,-1.326217744881488247e-01,9.462570124815141703e-01,4.987162622205646656e+00,4.128336989800555301e+00,4.831569541643758292e+00,3.211246100750840160e+00,5.343902502998335358e+00,4.456169118280133290e+00 +2.268017495856458066e-01,2.729099977591017634e+00,-4.479510528684834902e+00,-1.726598591179099307e-01,8.178885935778972271e-01,1.721393428966342398e+00,5.703450235584239358e+00,1.609590439570473652e+00,8.657061566026498234e-01,5.832052241539065207e+00,3.275055400053695998e+00,5.038320002771330408e+00 +6.307699118156784301e-02,3.615462745775235298e+00,-1.710251122774081978e+00,3.217555815846976586e+00,1.736861623118536535e+00,4.848628069717411115e-01,4.543319198418916294e+00,2.863637671601732659e+00,-2.504718404866137504e+00,8.080870330493329590e+00,3.499845759335292961e+00,6.471067310492218283e+00 diff --git a/shared/package-files/00/00fde747ccd3855e21cd2250b0021d2f4d33261ef15a9c0d8582f8d029c03dd5/blob b/shared/package-files/00/00fde747ccd3855e21cd2250b0021d2f4d33261ef15a9c0d8582f8d029c03dd5/blob new file mode 100644 index 0000000000000000000000000000000000000000..bfa7c81872489faadb894545b47cc4dd56be8a60 --- /dev/null +++ b/shared/package-files/00/00fde747ccd3855e21cd2250b0021d2f4d33261ef15a9c0d8582f8d029c03dd5/blob @@ -0,0 +1,22 @@ +#pragma once + +// @generated by torchgen/gen.py from NativeFunction.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + +namespace at { +namespace native { +TORCH_API at::Tensor & permute_copy_out(const at::Tensor & self, at::IntArrayRef dims, at::Tensor & out); +TORCH_API at::Tensor permute_copy(const at::Tensor & self, at::IntArrayRef dims); +} // namespace native +} // namespace at diff --git a/shared/package-files/01/0100e1361990204d140ca8c8dde0a80d6289972abe0fbad47cc9ea6417fa7a35/blob b/shared/package-files/01/0100e1361990204d140ca8c8dde0a80d6289972abe0fbad47cc9ea6417fa7a35/blob new file mode 100644 index 0000000000000000000000000000000000000000..b1bb63168535f2303b16d5e6c3696b9b6a46b7d5 Binary files /dev/null and b/shared/package-files/01/0100e1361990204d140ca8c8dde0a80d6289972abe0fbad47cc9ea6417fa7a35/blob differ diff --git a/shared/package-files/01/010660e6883f1db66531eebb1b79442ae7c2873f072f38d65a67df47f0cf2ce2/blob b/shared/package-files/01/010660e6883f1db66531eebb1b79442ae7c2873f072f38d65a67df47f0cf2ce2/blob new file mode 100644 index 0000000000000000000000000000000000000000..7d7130d50ef5bad2321393f1a2e7df99143abdd7 --- /dev/null +++ b/shared/package-files/01/010660e6883f1db66531eebb1b79442ae7c2873f072f38d65a67df47f0cf2ce2/blob @@ -0,0 +1,40 @@ +from functools import lru_cache +from typing import Callable, Iterable, Iterator, TypeVar, Union, overload + +import setuptools.extern.jaraco.text as text +from setuptools.extern.packaging.requirements import Requirement + +_T = TypeVar("_T") +_StrOrIter = Union[str, Iterable[str]] + + +parse_req: Callable[[str], Requirement] = lru_cache()(Requirement) +# Setuptools parses the same requirement many times +# (e.g. first for validation than for normalisation), +# so it might be worth to cache. + + +def parse_strings(strs: _StrOrIter) -> Iterator[str]: + """ + Yield requirement strings for each specification in `strs`. + + `strs` must be a string, or a (possibly-nested) iterable thereof. + """ + return text.join_continuation(map(text.drop_comment, text.yield_lines(strs))) + + +@overload +def parse(strs: _StrOrIter) -> Iterator[Requirement]: + ... + + +@overload +def parse(strs: _StrOrIter, parser: Callable[[str], _T]) -> Iterator[_T]: + ... + + +def parse(strs, parser=parse_req): + """ + Replacement for ``pkg_resources.parse_requirements`` that uses ``packaging``. + """ + return map(parser, parse_strings(strs)) diff --git a/shared/package-files/01/0109ddd971797c962747c06e38245ca02b7defe53700fb841958b265389edd54/blob b/shared/package-files/01/0109ddd971797c962747c06e38245ca02b7defe53700fb841958b265389edd54/blob new file mode 100644 index 0000000000000000000000000000000000000000..2bc1225b7e4b8428854b5f39b26a1f0ab6766d30 --- /dev/null +++ b/shared/package-files/01/0109ddd971797c962747c06e38245ca02b7defe53700fb841958b265389edd54/blob @@ -0,0 +1,24 @@ +from numba.core.extending import overload +from numba.core import types +from numba.misc.special import literally, literal_unroll +from numba.core.errors import TypingError + + +@overload(literally) +def _ov_literally(obj): + if isinstance(obj, (types.Literal, types.InitialValue)): + return lambda obj: obj + else: + m = "Invalid use of non-Literal type in literally({})".format(obj) + raise TypingError(m) + + +@overload(literal_unroll) +def literal_unroll_impl(container): + if isinstance(container, types.Poison): + m = f"Invalid use of non-Literal type in literal_unroll({container})" + raise TypingError(m) + + def impl(container): + return container + return impl diff --git a/shared/package-files/01/010b365e985701a5392bc83c5cbdbbcf22cfd4bdd53981f500fd5a0a0d6e7f8f/blob b/shared/package-files/01/010b365e985701a5392bc83c5cbdbbcf22cfd4bdd53981f500fd5a0a0d6e7f8f/blob new file mode 100644 index 0000000000000000000000000000000000000000..b2958441fe7a098eeb66fe183b62bd4ff0edbbe2 --- /dev/null +++ b/shared/package-files/01/010b365e985701a5392bc83c5cbdbbcf22cfd4bdd53981f500fd5a0a0d6e7f8f/blob @@ -0,0 +1,10 @@ +from os.path import dirname +import unittest +from unittest.suite import TestSuite + +from numba.testing import load_testsuite + +def load_tests(loader, tests, pattern): + suite = TestSuite() + suite.addTests(load_testsuite(loader, dirname(__file__))) + return suite diff --git a/shared/package-files/01/010ee267c74a93d41f9cb74ff6274abf5a23cf433f4b0a4bed701499b1e87434/blob b/shared/package-files/01/010ee267c74a93d41f9cb74ff6274abf5a23cf433f4b0a4bed701499b1e87434/blob new file mode 100644 index 0000000000000000000000000000000000000000..ee6e69fe8461edfa580f682761118c8afe2add3a Binary files /dev/null and b/shared/package-files/01/010ee267c74a93d41f9cb74ff6274abf5a23cf433f4b0a4bed701499b1e87434/blob differ diff --git a/shared/package-files/01/010f85e35196c228e8306014cf51126be0a5542cf90199980e1621c646b8b5be/blob b/shared/package-files/01/010f85e35196c228e8306014cf51126be0a5542cf90199980e1621c646b8b5be/blob new file mode 100644 index 0000000000000000000000000000000000000000..e40ed94c353a457eedcfcc5cc2b77ecc87cfbf19 --- /dev/null +++ b/shared/package-files/01/010f85e35196c228e8306014cf51126be0a5542cf90199980e1621c646b8b5be/blob @@ -0,0 +1,25 @@ +#pragma once +// @generated by torchgen/gen.py from DispatchKeyFunction.h + +// NB: The implementing C++ file is RegisterDispatchKey.cpp + +// The only #includes we need are for custom classes that have defaults in the C++ API +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { + +namespace cuda { + +TORCH_API at::Tensor special_scaled_modified_bessel_k1(const at::Tensor & x); +TORCH_API at::Tensor & special_scaled_modified_bessel_k1_out(at::Tensor & out, const at::Tensor & x); +TORCH_API at::Tensor & special_scaled_modified_bessel_k1_outf(const at::Tensor & x, at::Tensor & out); + +} // namespace cuda +} // namespace at diff --git a/shared/package-files/01/01184b3a424096383be93b049923078c13ec2bbb3cfd6977e68c29b64b8170b8/blob b/shared/package-files/01/01184b3a424096383be93b049923078c13ec2bbb3cfd6977e68c29b64b8170b8/blob new file mode 100644 index 0000000000000000000000000000000000000000..9ad6b88069afd2be5fb84ec8faf4fb4d880e1982 --- /dev/null +++ b/shared/package-files/01/01184b3a424096383be93b049923078c13ec2bbb3cfd6977e68c29b64b8170b8/blob @@ -0,0 +1,13 @@ +triton +triton/_C +triton/common +triton/compiler +triton/compiler/backends +triton/language +triton/language/extra +triton/ops +triton/ops/blocksparse +triton/runtime +triton/runtime/backends +triton/third_party +triton/tools diff --git a/shared/package-files/01/0118e54ceeb00658ad30aadda236e3e629d7d27a333e5b248ae6f127e790299c/blob b/shared/package-files/01/0118e54ceeb00658ad30aadda236e3e629d7d27a333e5b248ae6f127e790299c/blob new file mode 100644 index 0000000000000000000000000000000000000000..e15f06ee05b5f704ac20e8bda7653fbf9d2dd7a6 --- /dev/null +++ b/shared/package-files/01/0118e54ceeb00658ad30aadda236e3e629d7d27a333e5b248ae6f127e790299c/blob @@ -0,0 +1,203 @@ +""" +Implement code coverage support. + +Currently contains logic to extend ``coverage`` with lines covered by the +compiler. +""" + +from typing import Optional, Sequence, Callable, no_type_check +from collections.abc import Mapping +from dataclasses import dataclass, field +from abc import ABC, abstractmethod + +from numba.core import ir, config + + +try: + import coverage +except ImportError: + coverage_available = False +else: + coverage_available = True + + +@no_type_check +def get_active_coverage(): + """Get active coverage instance or return None if not found. + """ + cov = None + if coverage_available: + cov = coverage.Coverage.current() + return cov + + +_the_registry: Callable[[], Optional["NotifyLocBase"]] = [] + + +def get_registered_loc_notify() -> Sequence["NotifyLocBase"]: + """ + Returns a list of the registered NotifyLocBase instances. + """ + if not config.JIT_COVERAGE: + # Coverage disabled. + return [] + return list(filter(lambda x: x is not None, + (factory() for factory in _the_registry))) + + +class NotifyLocBase(ABC): + """Interface for notifying visiting of a ``numba.core.ir.Loc``.""" + + @abstractmethod + def notify(self, loc: ir.Loc) -> None: + pass + + @abstractmethod + def close(self) -> None: + pass + + +class NotifyCompilerCoverage(NotifyLocBase): + """ + Use to notify ``coverage`` about compiled lines. + + The compiled lines are under the "numba_compiled" context in the coverage + data. + """ + + def __init__(self, collector): + self._collector = collector + + # see https://github.com/nedbat/coveragepy/blob/e7c05fe91ee36c0c94e144bb88d25db4fc3d02fd/coverage/collector.py#L261 # noqa E501 + tracer_kwargs = collector.core.tracer_kwargs.copy() + tracer_kwargs.update( + dict( + data=collector.data, + lock_data=collector.lock_data, + unlock_data=collector.unlock_data, + trace_arcs=collector.branch, + should_trace=collector.should_trace, + should_trace_cache=collector.should_trace_cache, + warn=collector.warn, + should_start_context=collector.should_start_context, + switch_context=collector.switch_context, + packed_arcs=collector.core.packed_arcs, + ) + ) + self._tracer = NumbaTracer(**tracer_kwargs) + collector.tracers.append(self._tracer) + + def notify(self, loc: ir.Loc): + tracer = self._tracer + if loc.filename.endswith(".py"): + tracer.switch_context("numba_compiled") + tracer.trace(loc) + tracer.switch_context(None) + + def close(self): + pass + + +@_the_registry.append +def _register_coverage_notifier(): + cov = get_active_coverage() + if cov is not None: + col = cov._collector + # Is coverage started? + if col.tracers: + return NotifyCompilerCoverage(col) + + +if coverage_available: + + @dataclass(kw_only=True) + class NumbaTracer(coverage.types.Tracer): + """ + Not actually a tracer as in the coverage implementation, which will + setup a Python trace function. This implementation pretends to trace + but instead receives fake trace events for each line the compiler has + visited. + + See coverage.PyTracer + """ + + data: coverage.types.TTraceData + trace_arcs: bool + should_trace: coverage.types.TShouldTraceFn + should_trace_cache: Mapping[ + str, coverage.types.TFileDisposition | None + ] + should_start_context: coverage.types.TShouldStartContextFn | None + switch_context: Callable[[str | None], None] | None + lock_data: Callable[[], None] + unlock_data: Callable[[], None] + warn: coverage.types.TWarnFn + packed_arcs: bool + # ref: https://github.com/numba/numba/issues/10589 + tool_id: Optional[int] = None + + _activity: bool = field(default=False) + + def start(self) -> coverage.types.TTraceFn | None: + """Start this tracer, return a trace function if based on + sys.settrace.""" + return None + + def stop(self) -> None: + """Stop this tracer.""" + return None + + def activity(self) -> bool: + """Has there been any activity?""" + return self._activity + + def reset_activity(self) -> None: + """Reset the activity() flag.""" + self._activity = False + + def get_stats(self) -> dict[str, int] | None: + """Return a dictionary of statistics, or None.""" + return None + + def trace(self, loc: ir.Loc) -> None: + """Insert coverage data given source location. + """ + # Check whether the file should be traced + disp = self.should_trace_cache.get(loc.filename) + if disp is None: + disp = self.should_trace(loc.filename, None) + self.should_trace_cache[loc.filename] = disp + if not disp.trace: + # Bail if not tracing the file + return + # Insert trace data + tracename = disp.source_filename + self.lock_data() + cur_file_data = self.data.setdefault(tracename, set()) + if self.trace_arcs: + if self.packed_arcs: + cur_file_data.add(_pack_arcs(loc.line, loc.line)) + else: + cur_file_data.add((loc.line, loc.line)) + else: + cur_file_data.add(loc.line) + self.unlock_data() + # Mark activity for this tracer + self._activity = True + + def _pack_arcs(l1: int, l2: int) -> int: + """Pack arcs into a single integer for compatibility with .packed_arcs + option. + + See + https://github.com/nedbat/coveragepy/blob/e7c05fe91ee36c0c94e144bb88d25db4fc3d02fd/coverage/ctracer/tracer.c#L171 + """ + packed = 0 + if l1 < 0: + packed |= 1 << 40 + l1 = -l1 + if l2 < 0: + packed |= 1 << 41 + l2 = -l2 + packed |= (l2 << 20) + l1 + return packed diff --git a/shared/package-files/01/0119733d4aac10239c94e7056e6825ce31002880252987045837292c4539a691/blob b/shared/package-files/01/0119733d4aac10239c94e7056e6825ce31002880252987045837292c4539a691/blob new file mode 100644 index 0000000000000000000000000000000000000000..4396b7921f3ee091716197b132b9d6b8eeb7161b --- /dev/null +++ b/shared/package-files/01/0119733d4aac10239c94e7056e6825ce31002880252987045837292c4539a691/blob @@ -0,0 +1,658 @@ +import hashlib +import io +import os +import re +import shutil +import tempfile +import warnings +from functools import partial +from importlib import resources +from pathlib import Path +from pickle import dumps, loads +from unittest.mock import Mock +from urllib.error import HTTPError +from urllib.parse import urlparse + +import numpy as np +import pytest + +from sklearn.datasets import ( + clear_data_home, + fetch_file, + get_data_home, + load_breast_cancer, + load_diabetes, + load_digits, + load_files, + load_iris, + load_linnerud, + load_sample_image, + load_sample_images, + load_wine, +) +from sklearn.datasets._base import ( + RemoteFileMetadata, + _derive_folder_and_filename_from_url, + _fetch_remote, + load_csv_data, + load_gzip_compressed_csv_data, +) +from sklearn.datasets.tests.test_common import check_as_frame +from sklearn.preprocessing import scale +from sklearn.utils import Bunch + + +class _DummyPath: + """Minimal class that implements the os.PathLike interface.""" + + def __init__(self, path): + self.path = path + + def __fspath__(self): + return self.path + + +def _remove_dir(path): + if os.path.isdir(path): + shutil.rmtree(path) + + +@pytest.fixture(scope="module") +def data_home(tmpdir_factory): + tmp_file = str(tmpdir_factory.mktemp("scikit_learn_data_home_test")) + yield tmp_file + _remove_dir(tmp_file) + + +@pytest.fixture(scope="module") +def load_files_root(tmpdir_factory): + tmp_file = str(tmpdir_factory.mktemp("scikit_learn_load_files_test")) + yield tmp_file + _remove_dir(tmp_file) + + +@pytest.fixture +def test_category_dir_1(load_files_root): + test_category_dir1 = tempfile.mkdtemp(dir=load_files_root) + sample_file = tempfile.NamedTemporaryFile(dir=test_category_dir1, delete=False) + sample_file.write(b"Hello World!\n") + sample_file.close() + yield str(test_category_dir1) + _remove_dir(test_category_dir1) + + +@pytest.fixture +def test_category_dir_2(load_files_root): + test_category_dir2 = tempfile.mkdtemp(dir=load_files_root) + yield str(test_category_dir2) + _remove_dir(test_category_dir2) + + +@pytest.mark.parametrize("path_container", [None, Path, _DummyPath]) +def test_data_home(path_container, data_home): + # get_data_home will point to a pre-existing folder + if path_container is not None: + data_home = path_container(data_home) + data_home = get_data_home(data_home=data_home) + assert data_home == data_home + assert os.path.exists(data_home) + + # clear_data_home will delete both the content and the folder it-self + if path_container is not None: + data_home = path_container(data_home) + clear_data_home(data_home=data_home) + assert not os.path.exists(data_home) + + # if the folder is missing it will be created again + data_home = get_data_home(data_home=data_home) + assert os.path.exists(data_home) + + +def test_default_empty_load_files(load_files_root): + res = load_files(load_files_root) + assert len(res.filenames) == 0 + assert len(res.target_names) == 0 + assert res.DESCR is None + + +def test_default_load_files(test_category_dir_1, test_category_dir_2, load_files_root): + res = load_files(load_files_root) + assert len(res.filenames) == 1 + assert len(res.target_names) == 2 + assert res.DESCR is None + assert res.data == [b"Hello World!\n"] + + +def test_load_files_w_categories_desc_and_encoding( + test_category_dir_1, test_category_dir_2, load_files_root +): + category = os.path.abspath(test_category_dir_1).split(os.sep).pop() + res = load_files( + load_files_root, description="test", categories=[category], encoding="utf-8" + ) + + assert len(res.filenames) == 1 + assert len(res.target_names) == 1 + assert res.DESCR == "test" + assert res.data == ["Hello World!\n"] + + +def test_load_files_wo_load_content( + test_category_dir_1, test_category_dir_2, load_files_root +): + res = load_files(load_files_root, load_content=False) + assert len(res.filenames) == 1 + assert len(res.target_names) == 2 + assert res.DESCR is None + assert res.get("data") is None + + +@pytest.mark.parametrize("allowed_extensions", ([".txt"], [".txt", ".json"])) +def test_load_files_allowed_extensions(tmp_path, allowed_extensions): + """Check the behaviour of `allowed_extension` in `load_files`.""" + d = tmp_path / "sub" + d.mkdir() + files = ("file1.txt", "file2.json", "file3.json", "file4.md") + paths = [d / f for f in files] + for p in paths: + p.write_bytes(b"hello") + res = load_files(tmp_path, allowed_extensions=allowed_extensions) + assert set([str(p) for p in paths if p.suffix in allowed_extensions]) == set( + res.filenames + ) + + +@pytest.mark.parametrize( + "filename, expected_n_samples, expected_n_features, expected_target_names", + [ + ("wine_data.csv", 178, 13, ["class_0", "class_1", "class_2"]), + ("iris.csv", 150, 4, ["setosa", "versicolor", "virginica"]), + ("breast_cancer.csv", 569, 30, ["malignant", "benign"]), + ], +) +def test_load_csv_data( + filename, expected_n_samples, expected_n_features, expected_target_names +): + actual_data, actual_target, actual_target_names = load_csv_data(filename) + assert actual_data.shape[0] == expected_n_samples + assert actual_data.shape[1] == expected_n_features + assert actual_target.shape[0] == expected_n_samples + np.testing.assert_array_equal(actual_target_names, expected_target_names) + + +def test_load_csv_data_with_descr(): + data_file_name = "iris.csv" + descr_file_name = "iris.rst" + + res_without_descr = load_csv_data(data_file_name=data_file_name) + res_with_descr = load_csv_data( + data_file_name=data_file_name, descr_file_name=descr_file_name + ) + assert len(res_with_descr) == 4 + assert len(res_without_descr) == 3 + + np.testing.assert_array_equal(res_with_descr[0], res_without_descr[0]) + np.testing.assert_array_equal(res_with_descr[1], res_without_descr[1]) + np.testing.assert_array_equal(res_with_descr[2], res_without_descr[2]) + + assert res_with_descr[-1].startswith(".. _iris_dataset:") + + +@pytest.mark.parametrize( + "filename, kwargs, expected_shape", + [ + ("diabetes_data_raw.csv.gz", {}, [442, 10]), + ("diabetes_target.csv.gz", {}, [442]), + ("digits.csv.gz", {"delimiter": ","}, [1797, 65]), + ], +) +def test_load_gzip_compressed_csv_data(filename, kwargs, expected_shape): + actual_data = load_gzip_compressed_csv_data(filename, **kwargs) + assert actual_data.shape == tuple(expected_shape) + + +def test_load_gzip_compressed_csv_data_with_descr(): + data_file_name = "diabetes_target.csv.gz" + descr_file_name = "diabetes.rst" + + expected_data = load_gzip_compressed_csv_data(data_file_name=data_file_name) + actual_data, descr = load_gzip_compressed_csv_data( + data_file_name=data_file_name, + descr_file_name=descr_file_name, + ) + + np.testing.assert_array_equal(actual_data, expected_data) + assert descr.startswith(".. _diabetes_dataset:") + + +def test_load_sample_images(): + try: + res = load_sample_images() + assert len(res.images) == 2 + assert len(res.filenames) == 2 + images = res.images + + # assert is china image + assert np.all(images[0][0, 0, :] == np.array([174, 201, 231], dtype=np.uint8)) + # assert is flower image + assert np.all(images[1][0, 0, :] == np.array([2, 19, 13], dtype=np.uint8)) + assert res.DESCR + except ImportError: + warnings.warn("Could not load sample images, PIL is not available.") + + +def test_load_sample_image(): + try: + china = load_sample_image("china.jpg") + assert china.dtype == "uint8" + assert china.shape == (427, 640, 3) + except ImportError: + warnings.warn("Could not load sample images, PIL is not available.") + + +def test_load_diabetes_raw(): + """Test to check that we load a scaled version by default but that we can + get an unscaled version when setting `scaled=False`.""" + diabetes_raw = load_diabetes(scaled=False) + assert diabetes_raw.data.shape == (442, 10) + assert diabetes_raw.target.size == 442 + assert len(diabetes_raw.feature_names) == 10 + assert diabetes_raw.DESCR + + diabetes_default = load_diabetes() + + np.testing.assert_allclose( + scale(diabetes_raw.data) / (442**0.5), diabetes_default.data, atol=1e-04 + ) + + +@pytest.mark.parametrize( + "loader_func, data_shape, target_shape, n_target, has_descr, filenames", + [ + (load_breast_cancer, (569, 30), (569,), 2, True, ["filename"]), + (load_wine, (178, 13), (178,), 3, True, []), + (load_iris, (150, 4), (150,), 3, True, ["filename"]), + ( + load_linnerud, + (20, 3), + (20, 3), + 3, + True, + ["data_filename", "target_filename"], + ), + (load_diabetes, (442, 10), (442,), None, True, []), + (load_digits, (1797, 64), (1797,), 10, True, []), + (partial(load_digits, n_class=9), (1617, 64), (1617,), 10, True, []), + ], +) +def test_loader(loader_func, data_shape, target_shape, n_target, has_descr, filenames): + bunch = loader_func() + + assert isinstance(bunch, Bunch) + assert bunch.data.shape == data_shape + assert bunch.target.shape == target_shape + if hasattr(bunch, "feature_names"): + assert len(bunch.feature_names) == data_shape[1] + if n_target is not None: + assert len(bunch.target_names) == n_target + if has_descr: + assert bunch.DESCR + if filenames: + assert "data_module" in bunch + assert all( + [ + f in bunch + and (resources.files(bunch["data_module"]) / bunch[f]).is_file() + for f in filenames + ] + ) + + +@pytest.mark.parametrize( + "loader_func, data_dtype, target_dtype", + [ + (load_breast_cancer, np.float64, int), + (load_diabetes, np.float64, np.float64), + (load_digits, np.float64, int), + (load_iris, np.float64, int), + (load_linnerud, np.float64, np.float64), + (load_wine, np.float64, int), + ], +) +def test_toy_dataset_frame_dtype(loader_func, data_dtype, target_dtype): + default_result = loader_func() + check_as_frame( + default_result, + loader_func, + expected_data_dtype=data_dtype, + expected_target_dtype=target_dtype, + ) + + +def test_loads_dumps_bunch(): + bunch = Bunch(x="x") + bunch_from_pkl = loads(dumps(bunch)) + bunch_from_pkl.x = "y" + assert bunch_from_pkl["x"] == bunch_from_pkl.x + + +def test_bunch_pickle_generated_with_0_16_and_read_with_0_17(): + bunch = Bunch(key="original") + # This reproduces a problem when Bunch pickles have been created + # with scikit-learn 0.16 and are read with 0.17. Basically there + # is a surprising behaviour because reading bunch.key uses + # bunch.__dict__ (which is non empty for 0.16 Bunch objects) + # whereas assigning into bunch.key uses bunch.__setattr__. See + # https://github.com/scikit-learn/scikit-learn/issues/6196 for + # more details + bunch.__dict__["key"] = "set from __dict__" + bunch_from_pkl = loads(dumps(bunch)) + # After loading from pickle the __dict__ should have been ignored + assert bunch_from_pkl.key == "original" + assert bunch_from_pkl["key"] == "original" + # Making sure that changing the attr does change the value + # associated with __getitem__ as well + bunch_from_pkl.key = "changed" + assert bunch_from_pkl.key == "changed" + assert bunch_from_pkl["key"] == "changed" + + +def test_bunch_dir(): + # check that dir (important for autocomplete) shows attributes + data = load_iris() + assert "data" in dir(data) + + +def test_load_boston_error(): + """Check that we raise the ethical warning when trying to import `load_boston`.""" + msg = "The Boston housing prices dataset has an ethical problem" + with pytest.raises(ImportError, match=msg): + from sklearn.datasets import load_boston # noqa: F401 + + # other non-existing function should raise the usual import error + msg = "cannot import name 'non_existing_function' from 'sklearn.datasets'" + with pytest.raises(ImportError, match=msg): + from sklearn.datasets import non_existing_function # noqa: F401 + + +def test_fetch_remote_raise_warnings_with_invalid_url(monkeypatch): + """Check retry mechanism in _fetch_remote.""" + + url = "https://scikit-learn.org/this_file_does_not_exist.tar.gz" + invalid_remote_file = RemoteFileMetadata("invalid_file", url, None) + urlretrieve_mock = Mock( + side_effect=HTTPError( + url=url, code=404, msg="Not Found", hdrs=None, fp=io.BytesIO() + ) + ) + monkeypatch.setattr("sklearn.datasets._base.urlretrieve", urlretrieve_mock) + + with pytest.warns(UserWarning, match="Retry downloading") as record: + with pytest.raises(HTTPError, match="HTTP Error 404"): + _fetch_remote(invalid_remote_file, n_retries=3, delay=0) + + assert urlretrieve_mock.call_count == 4 + + for r in record: + assert str(r.message) == f"Retry downloading from url: {url}" + assert len(record) == 3 + + +def test_derive_folder_and_filename_from_url(): + folder, filename = _derive_folder_and_filename_from_url( + "https://example.com/file.tar.gz" + ) + assert folder == "example.com" + assert filename == "file.tar.gz" + + folder, filename = _derive_folder_and_filename_from_url( + "https://example.com/نمونه نماینده.data" + ) + assert folder == "example.com" + assert filename == "نمونه-نماینده.data" + + folder, filename = _derive_folder_and_filename_from_url( + "https://example.com/path/to-/.file.tar.gz" + ) + assert folder == "example.com/path_to" + assert filename == "file.tar.gz" + + folder, filename = _derive_folder_and_filename_from_url("https://example.com/") + assert folder == "example.com" + assert filename == "downloaded_file" + + folder, filename = _derive_folder_and_filename_from_url("https://example.com") + assert folder == "example.com" + assert filename == "downloaded_file" + + folder, filename = _derive_folder_and_filename_from_url( + "https://example.com/path/@to/data.json?param=value" + ) + assert folder == "example.com/path_to" + assert filename == "data.json" + + folder, filename = _derive_folder_and_filename_from_url( + "https://example.com/path/@@to._/-_.data.json.#anchor" + ) + assert folder == "example.com/path_to" + assert filename == "data.json" + + folder, filename = _derive_folder_and_filename_from_url( + "https://example.com//some_file.txt" + ) + assert folder == "example.com" + assert filename == "some_file.txt" + + folder, filename = _derive_folder_and_filename_from_url( + "http://example/../some_file.txt" + ) + assert folder == "example" + assert filename == "some_file.txt" + + folder, filename = _derive_folder_and_filename_from_url( + "https://example.com/!.'.,/some_file.txt" + ) + assert folder == "example.com" + assert filename == "some_file.txt" + + folder, filename = _derive_folder_and_filename_from_url( + "https://example.com/a/!.'.,/b/some_file.txt" + ) + assert folder == "example.com/a_b" + assert filename == "some_file.txt" + + folder, filename = _derive_folder_and_filename_from_url("https://example.com/!.'.,") + assert folder == "example.com" + assert filename == "downloaded_file" + + with pytest.raises(ValueError, match="Invalid URL"): + _derive_folder_and_filename_from_url("https:/../") + + +def _mock_urlretrieve(server_side): + def _urlretrieve_mock(url, local_path): + server_root = Path(server_side) + file_path = urlparse(url).path.strip("/") + if not (server_root / file_path).exists(): + raise HTTPError(url, 404, "Not Found", None, None) + shutil.copy(server_root / file_path, local_path) + + return Mock(side_effect=_urlretrieve_mock) + + +def test_fetch_file_using_data_home(monkeypatch, tmpdir): + tmpdir = Path(tmpdir) + server_side = tmpdir / "server_side" + server_side.mkdir() + data_file = server_side / "data.jsonl" + server_data = '{"a": 1, "b": 2}\n' + data_file.write_text(server_data, encoding="utf-8") + + server_subfolder = server_side / "subfolder" + server_subfolder.mkdir() + other_data_file = server_subfolder / "other_file.txt" + other_data_file.write_text("Some important text data.", encoding="utf-8") + + data_home = tmpdir / "data_home" + data_home.mkdir() + + urlretrieve_mock = _mock_urlretrieve(server_side) + monkeypatch.setattr("sklearn.datasets._base.urlretrieve", urlretrieve_mock) + + monkeypatch.setattr( + "sklearn.datasets._base.get_data_home", Mock(return_value=data_home) + ) + fetched_file_path = fetch_file( + "https://example.com/data.jsonl", + ) + assert fetched_file_path == data_home / "example.com" / "data.jsonl" + assert fetched_file_path.read_text(encoding="utf-8") == server_data + + fetched_file_path = fetch_file( + "https://example.com/subfolder/other_file.txt", + ) + assert ( + fetched_file_path == data_home / "example.com" / "subfolder" / "other_file.txt" + ) + assert fetched_file_path.read_text(encoding="utf-8") == other_data_file.read_text( + "utf-8" + ) + + expected_warning_msg = re.escape( + "Retry downloading from url: https://example.com/subfolder/invalid.txt" + ) + with pytest.raises(HTTPError): + with pytest.warns(match=expected_warning_msg): + fetch_file( + "https://example.com/subfolder/invalid.txt", + delay=0, + ) + + local_subfolder = data_home / "example.com" / "subfolder" + assert sorted(local_subfolder.iterdir()) == [local_subfolder / "other_file.txt"] + + +def test_fetch_file_without_sha256(monkeypatch, tmpdir): + server_side = tmpdir.mkdir("server_side") + data_file = Path(server_side / "data.jsonl") + server_data = '{"a": 1, "b": 2}\n' + data_file.write_text(server_data, encoding="utf-8") + + client_side = tmpdir.mkdir("client_side") + + urlretrieve_mock = _mock_urlretrieve(server_side) + monkeypatch.setattr("sklearn.datasets._base.urlretrieve", urlretrieve_mock) + + # The first call should trigger a download: + fetched_file_path = fetch_file( + "https://example.com/data.jsonl", + folder=client_side, + ) + assert fetched_file_path == client_side / "data.jsonl" + assert fetched_file_path.read_text(encoding="utf-8") == server_data + assert urlretrieve_mock.call_count == 1 + + # Fetching again the same file to the same folder should do nothing: + fetched_file_path = fetch_file( + "https://example.com/data.jsonl", + folder=client_side, + ) + assert fetched_file_path == client_side / "data.jsonl" + assert fetched_file_path.read_text(encoding="utf-8") == server_data + assert urlretrieve_mock.call_count == 1 + + # Deleting and calling again should re-download + fetched_file_path.unlink() + fetched_file_path = fetch_file( + "https://example.com/data.jsonl", + folder=client_side, + ) + assert fetched_file_path == client_side / "data.jsonl" + assert fetched_file_path.read_text(encoding="utf-8") == server_data + assert urlretrieve_mock.call_count == 2 + + +def test_fetch_file_with_sha256(monkeypatch, tmpdir): + server_side = tmpdir.mkdir("server_side") + data_file = Path(server_side / "data.jsonl") + server_data = '{"a": 1, "b": 2}\n' + data_file.write_text(server_data, encoding="utf-8") + expected_sha256 = hashlib.sha256(data_file.read_bytes()).hexdigest() + + client_side = tmpdir.mkdir("client_side") + + urlretrieve_mock = _mock_urlretrieve(server_side) + monkeypatch.setattr("sklearn.datasets._base.urlretrieve", urlretrieve_mock) + + # The first call should trigger a download. + fetched_file_path = fetch_file( + "https://example.com/data.jsonl", folder=client_side, sha256=expected_sha256 + ) + assert fetched_file_path == client_side / "data.jsonl" + assert fetched_file_path.read_text(encoding="utf-8") == server_data + assert urlretrieve_mock.call_count == 1 + + # Fetching again the same file to the same folder should do nothing when + # the sha256 match: + fetched_file_path = fetch_file( + "https://example.com/data.jsonl", folder=client_side, sha256=expected_sha256 + ) + assert fetched_file_path == client_side / "data.jsonl" + assert fetched_file_path.read_text(encoding="utf-8") == server_data + assert urlretrieve_mock.call_count == 1 + + # Corrupting the local data should yield a warning and trigger a new download: + fetched_file_path.write_text("corrupted contents", encoding="utf-8") + expected_msg = ( + r"SHA256 checksum of existing local file data.jsonl " + rf"\(.*\) differs from expected \({expected_sha256}\): " + r"re-downloading from https://example.com/data.jsonl \." + ) + with pytest.warns(match=expected_msg): + fetched_file_path = fetch_file( + "https://example.com/data.jsonl", folder=client_side, sha256=expected_sha256 + ) + assert fetched_file_path == client_side / "data.jsonl" + assert fetched_file_path.read_text(encoding="utf-8") == server_data + assert urlretrieve_mock.call_count == 2 + + # Calling again should do nothing: + fetched_file_path = fetch_file( + "https://example.com/data.jsonl", folder=client_side, sha256=expected_sha256 + ) + assert fetched_file_path == client_side / "data.jsonl" + assert fetched_file_path.read_text(encoding="utf-8") == server_data + assert urlretrieve_mock.call_count == 2 + + # Deleting the local file and calling again should redownload without warning: + fetched_file_path.unlink() + fetched_file_path = fetch_file( + "https://example.com/data.jsonl", folder=client_side, sha256=expected_sha256 + ) + assert fetched_file_path == client_side / "data.jsonl" + assert fetched_file_path.read_text(encoding="utf-8") == server_data + assert urlretrieve_mock.call_count == 3 + + # Calling without a sha256 should also work without redownloading: + fetched_file_path = fetch_file( + "https://example.com/data.jsonl", + folder=client_side, + ) + assert fetched_file_path == client_side / "data.jsonl" + assert fetched_file_path.read_text(encoding="utf-8") == server_data + assert urlretrieve_mock.call_count == 3 + + # Calling with a wrong sha256 should raise an informative exception: + non_matching_sha256 = "deadbabecafebeef" + expected_warning_msg = "differs from expected" + expected_error_msg = re.escape( + f"The SHA256 checksum of data.jsonl ({expected_sha256}) differs from " + f"expected ({non_matching_sha256})." + ) + with pytest.raises(OSError, match=expected_error_msg): + with pytest.warns(match=expected_warning_msg): + fetch_file( + "https://example.com/data.jsonl", + folder=client_side, + sha256=non_matching_sha256, + ) diff --git a/shared/package-files/01/01199baeb6f7b05537cb251f06d23e5c694a11097b81b051fe78045a0f8d3456/blob b/shared/package-files/01/01199baeb6f7b05537cb251f06d23e5c694a11097b81b051fe78045a0f8d3456/blob new file mode 100644 index 0000000000000000000000000000000000000000..33eade4617cf139bdb6367af36de0206cfb338e8 --- /dev/null +++ b/shared/package-files/01/01199baeb6f7b05537cb251f06d23e5c694a11097b81b051fe78045a0f8d3456/blob @@ -0,0 +1,1836 @@ +from collections import namedtuple +import contextlib +import itertools +import math +import sys +import ctypes as ct +import numpy as np + +from numba import jit, typeof, njit, literal_unroll, literally +import unittest +from numba.core import types, errors +from numba.tests.support import TestCase, MemoryLeakMixin +from numba.experimental import jitclass +from numba.core.extending import overload + + +Point = namedtuple('Point', ('a', 'b')) + + +def noop(x): + pass + +def unbox_usecase(x): + """ + Expect a list of numbers + """ + res = 0 + for v in x: + res += v + return res + +def unbox_usecase2(x): + """ + Expect a list of tuples + """ + res = 0 + for v in x: + res += len(v) + return res + +def unbox_usecase3(x): + """ + Expect a (number, list of numbers) tuple. + """ + a, b = x + res = a + for v in b: + res += v + return res + +def unbox_usecase4(x): + """ + Expect a (number, list of tuples) tuple. + """ + a, b = x + res = a + for v in b: + res += len(v) + return res + + +def create_list(x, y, z): + return [x, y, z] + +def create_nested_list(x, y, z, a, b, c): + return [[x, y, z], [a, b, c]] + +def list_comprehension1(): + return sum([x**2 for x in range(10)]) + +def list_comprehension2(): + return sum([x for x in range(10) if x % 2 == 0]) + +def list_comprehension3(): + return sum([math.pow(x, 2) for x in range(10)]) + +def list_comprehension4(): + return sum([x * y for x in range(10) for y in range(10)]) + +def list_comprehension5(): + return [x * 2 for x in range(10)] + +def list_comprehension6(): + return [[x for x in range(y)] for y in range(3)] + + +def list_constructor(n): + return list(range(n)) + +def list_constructor_empty(): + # cannot be typed, list is empty and no typing information is present to + # infer a type + return list() + +def list_constructor_empty_but_typeable(n): + # can be typed, list is empty but later append has typing info that allows + # for inference + y = list() + return y.append(n) + +def list_append(n): + l = [] + l.append(42) + for i in range(n): + l.append(i) + return l + +def list_append_heterogeneous(n): + l = [] + l.append(42.0) + for i in range(n): + l.append(i) + return l + +def list_extend(n): + l = [] + # A non-list iterable and a list + l.extend(range(n)) + l.extend(l[:-1]) + l.extend(range(n, 0, -1)) + return l + +def list_extend_heterogeneous(n): + l = [] + # Extend with various iterables, including lists, with different types + l.extend(range(n)) + l.extend(l[:-1]) + l.extend((5, 42)) + l.extend([123.0]) + return l + +def list_pop0(n): + l = list(range(n)) + res = 0 + while len(l) > 0: + res += len(l) * l.pop() + return res + +def list_pop1(n, i): + l = list(range(n)) + x = l.pop(i) + return x, l + +def list_len(n): + l = list(range(n)) + return len(l) + +def list_getitem(n): + l = list(range(n)) + res = 0 + # Positive indices + for i in range(len(l)): + res += i * l[i] + # Negative indices + for i in range(-len(l), 0): + res -= i * l[i] + return res + +def list_setitem(n): + l = list(range(n)) + res = 0 + # Positive indices + for i in range(len(l)): + l[i] = i * l[i] + # Negative indices + for i in range(-len(l), 0): + l[i] = i * l[i] + for i in range(len(l)): + res += l[i] + return res + +def list_getslice2(n, start, stop): + l = list(range(n)) + return l[start:stop] + +def list_getslice3(n, start, stop, step): + l = list(range(n)) + return l[start:stop:step] + +def list_setslice2(n, n_source, start, stop): + # Generic setslice with size change + l = list(range(n)) + v = list(range(100, 100 + n_source)) + l[start:stop] = v + return l + +def list_setslice3(n, start, stop, step): + l = list(range(n)) + v = l[start:stop:step] + for i in range(len(v)): + v[i] += 100 + l[start:stop:step] = v + return l + +def list_setslice3_arbitrary(n, n_src, start, stop, step): + l = list(range(n)) + l[start:stop:step] = list(range(100, 100 + n_src)) + return l + +def list_delslice0(n): + l = list(range(n)) + del l[:] + return l + +def list_delslice1(n, start, stop): + l = list(range(n)) + del l[start:] + del l[:stop] + return l + +def list_delslice2(n, start, stop): + l = list(range(n)) + del l[start:stop] + return l + +def list_clear(n): + l = list(range(n)) + l.clear() + return l + +def list_copy(n): + l = list(range(n)) + ll = l.copy() + l.append(42) + return l, ll + +def list_iteration(n): + l = list(range(n)) + res = 0 + for i, v in enumerate(l): + res += i * v + return res + +def list_contains(n): + l = list(range(n)) + return (0 in l, 1 in l, n - 1 in l, n in l, + 0 not in l, 1 not in l, n - 1 not in l, n not in l, + ) + +def list_index1(n, v): + l = list(range(n, 0, -1)) + return l.index(v) + +def list_index2(n, v, start): + l = list(range(n, 0, -1)) + return l.index(v, start) + +def list_index3(n, v, start, stop): + l = list(range(n, 0, -1)) + return l.index(v, start, stop) + +def list_remove(n, v): + l = list(range(n - 1, -1, -1)) + l.remove(v) + return l + +def list_insert(n, pos, v): + l = list(range(0, n)) + l.insert(pos, v) + return l + +def list_count(n, v): + l = [] + for x in range(n): + l.append(x & 3) + return l.count(v) + +def list_reverse(n): + l = list(range(n)) + l.reverse() + return l + +def list_add(m, n): + a = list(range(0, m)) + b = list(range(100, 100 + n)) + res = a + b + res.append(42) # check result is a copy + return a, b, res + +def list_add_heterogeneous(): + a = [1] + b = [2.0] + c = a + b + d = b + a + # check result is a copy + a.append(3) + b.append(4.0) + return a, b, c, d + +def list_add_inplace(m, n): + a = list(range(0, m)) + b = list(range(100, 100 + n)) + a += b + return a, b + +def list_add_inplace_heterogeneous(): + a = [1] + b = [2.0] + a += b + b += a + return a, b + +def list_mul(n, v): + a = list(range(n)) + return a * v + +def list_mul2(n, v): + a = list(range(n)) + return v * a + +def list_mul_inplace(n, v): + a = list(range(n)) + a *= v + return a + +def list_bool(n): + a = list(range(n)) + return bool(a), (True if a else False) + +def eq_usecase(a, b): + return list(a) == list(b) + +def ne_usecase(a, b): + return list(a) != list(b) + +def gt_usecase(a, b): + return list(a) > list(b) + +def ge_usecase(a, b): + return list(a) >= list(b) + +def lt_usecase(a, b): + return list(a) < list(b) + +def le_usecase(a, b): + return list(a) <= list(b) + +def identity_usecase(n): + a = list(range(n)) + b = a + c = a[:] + return (a is b), (a is not b), (a is c), (a is not c) + +def bool_list_usecase(): + # Exercise getitem, setitem, iteration with bool values (issue #1373) + l = [False] + l[0] = True + x = False + for v in l: + x = x ^ v + return l, x + +def reflect_simple(l, ll): + x = l.pop() + y = l.pop() + l[0] = 42. + l.extend(ll) + return l, x, y + +def reflect_conditional(l, ll): + # `l` may or may not actually reflect a Python list + if ll[0]: + l = [11., 22., 33., 44.] + x = l.pop() + y = l.pop() + l[0] = 42. + l.extend(ll) + return l, x, y + +def reflect_exception(l): + l.append(42) + raise ZeroDivisionError + +def reflect_dual(l, ll): + l.append(ll.pop()) + return l is ll + + +class TestLists(MemoryLeakMixin, TestCase): + + def test_create_list(self): + pyfunc = create_list + cfunc = njit((types.int32, types.int32, types.int32))(pyfunc) + self.assertEqual(cfunc(1, 2, 3), pyfunc(1, 2, 3)) + + def test_create_nested_list(self): + pyfunc = create_nested_list + cfunc = njit((types.int32, types.int32, types.int32, + types.int32, types.int32, types.int32))(pyfunc) + self.assertEqual(cfunc(1, 2, 3, 4, 5, 6), pyfunc(1, 2, 3, 4, 5, 6)) + + def check_unary_with_size(self, pyfunc, precise=True): + cfunc = jit(nopython=True)(pyfunc) + # Use various sizes, to stress the allocation algorithm + for n in [0, 3, 16, 70, 400]: + eq = self.assertPreciseEqual if precise else self.assertEqual + eq(cfunc(n), pyfunc(n)) + + def test_constructor(self): + self.check_unary_with_size(list_constructor) + + def test_constructor_empty(self): + self.disable_leak_check() + cfunc = jit(nopython=True)(list_constructor_empty) + with self.assertRaises(errors.TypingError) as raises: + cfunc() + errmsg = str(raises.exception) + self.assertIn("Cannot infer the type of variable", errmsg) + self.assertIn("list(undefined)", errmsg) + # check error message went in + self.assertIn("For Numba to be able to compile a list", errmsg) + + def test_constructor_empty_but_typeable(self): + args = [np.int32(1), 10., 1 + 3j, [7], [17., 14.], np.array([10])] + pyfunc = list_constructor_empty_but_typeable + for arg in args: + cfunc = jit(nopython=True)(pyfunc) + expected = pyfunc(arg) + got = cfunc(arg) + self.assertPreciseEqual(got, expected) + + def test_append(self): + self.check_unary_with_size(list_append) + + def test_append_heterogeneous(self): + self.check_unary_with_size(list_append_heterogeneous, precise=False) + + def test_extend(self): + self.check_unary_with_size(list_extend) + + def test_extend_heterogeneous(self): + self.check_unary_with_size(list_extend_heterogeneous, precise=False) + + def test_pop0(self): + self.check_unary_with_size(list_pop0) + + def test_pop1(self): + pyfunc = list_pop1 + cfunc = jit(nopython=True)(pyfunc) + for n in [5, 40]: + for i in [0, 1, n - 2, n - 1, -1, -2, -n + 3, -n + 1]: + expected = pyfunc(n, i) + self.assertPreciseEqual(cfunc(n, i), expected) + + def test_pop_errors(self): + # XXX References are leaked when an exception is raised + self.disable_leak_check() + cfunc = jit(nopython=True)(list_pop1) + with self.assertRaises(IndexError) as cm: + cfunc(0, 5) + self.assertEqual(str(cm.exception), "pop from empty list") + with self.assertRaises(IndexError) as cm: + cfunc(1, 5) + self.assertEqual(str(cm.exception), "pop index out of range") + + def test_insert(self): + pyfunc = list_insert + cfunc = jit(nopython=True)(pyfunc) + for n in [5, 40]: + indices = [0, 1, n - 2, n - 1, n + 1, -1, -2, -n + 3, -n - 1] + for i in indices: + expected = pyfunc(n, i, 42) + self.assertPreciseEqual(cfunc(n, i, 42), expected) + + def test_len(self): + self.check_unary_with_size(list_len) + + def test_getitem(self): + self.check_unary_with_size(list_getitem) + + def test_setitem(self): + self.check_unary_with_size(list_setitem) + + def check_slicing2(self, pyfunc): + cfunc = jit(nopython=True)(pyfunc) + sizes = [5, 40] + for n in sizes: + indices = [0, 1, n - 2, -1, -2, -n + 3, -n - 1, -n] + for start, stop in itertools.product(indices, indices): + expected = pyfunc(n, start, stop) + self.assertPreciseEqual(cfunc(n, start, stop), expected) + + def test_getslice2(self): + self.check_slicing2(list_getslice2) + + def test_setslice2(self): + pyfunc = list_setslice2 + cfunc = jit(nopython=True)(pyfunc) + sizes = [5, 40] + for n, n_src in itertools.product(sizes, sizes): + indices = [0, 1, n - 2, -1, -2, -n + 3, -n - 1, -n] + for start, stop in itertools.product(indices, indices): + expected = pyfunc(n, n_src, start, stop) + self.assertPreciseEqual(cfunc(n, n_src, start, stop), expected) + + def test_getslice3(self): + pyfunc = list_getslice3 + cfunc = jit(nopython=True)(pyfunc) + for n in [10]: + indices = [0, 1, n - 2, -1, -2, -n + 3, -n - 1, -n] + steps = [4, 1, -1, 2, -3] + for start, stop, step in itertools.product(indices, indices, steps): + expected = pyfunc(n, start, stop, step) + self.assertPreciseEqual(cfunc(n, start, stop, step), expected) + + def test_setslice3(self): + pyfunc = list_setslice3 + cfunc = jit(nopython=True)(pyfunc) + for n in [10]: + indices = [0, 1, n - 2, -1, -2, -n + 3, -n - 1, -n] + steps = [4, 1, -1, 2, -3] + for start, stop, step in itertools.product(indices, indices, steps): + expected = pyfunc(n, start, stop, step) + self.assertPreciseEqual(cfunc(n, start, stop, step), expected) + + def test_setslice3_resize(self): + # XXX References are leaked when an exception is raised + self.disable_leak_check() + pyfunc = list_setslice3_arbitrary + cfunc = jit(nopython=True)(pyfunc) + # step == 1 => can resize + cfunc(5, 10, 0, 2, 1) + # step != 1 => cannot resize + with self.assertRaises(ValueError) as cm: + cfunc(5, 100, 0, 3, 2) + self.assertIn("cannot resize", str(cm.exception)) + + def test_delslice0(self): + self.check_unary_with_size(list_delslice0) + + def test_delslice1(self): + self.check_slicing2(list_delslice1) + + def test_delslice2(self): + self.check_slicing2(list_delslice2) + + def test_invalid_slice(self): + self.disable_leak_check() + pyfunc = list_getslice3 + cfunc = jit(nopython=True)(pyfunc) + with self.assertRaises(ValueError) as cm: + cfunc(10, 1, 2, 0) + self.assertEqual(str(cm.exception), "slice step cannot be zero") + + def test_iteration(self): + self.check_unary_with_size(list_iteration) + + def test_reverse(self): + self.check_unary_with_size(list_reverse) + + def test_contains(self): + self.check_unary_with_size(list_contains) + + def check_index_result(self, pyfunc, cfunc, args): + try: + expected = pyfunc(*args) + except ValueError: + with self.assertRaises(ValueError): + cfunc(*args) + else: + self.assertPreciseEqual(cfunc(*args), expected) + + def test_index1(self): + self.disable_leak_check() + pyfunc = list_index1 + cfunc = jit(nopython=True)(pyfunc) + for v in (0, 1, 5, 10, 99999999): + self.check_index_result(pyfunc, cfunc, (16, v)) + + def test_index2(self): + self.disable_leak_check() + pyfunc = list_index2 + cfunc = jit(nopython=True)(pyfunc) + n = 16 + for v in (0, 1, 5, 10, 99999999): + indices = [0, 1, n - 2, n - 1, n + 1, -1, -2, -n + 3, -n - 1] + for start in indices: + self.check_index_result(pyfunc, cfunc, (16, v, start)) + + def test_index3(self): + self.disable_leak_check() + pyfunc = list_index3 + cfunc = jit(nopython=True)(pyfunc) + n = 16 + for v in (0, 1, 5, 10, 99999999): + indices = [0, 1, n - 2, n - 1, n + 1, -1, -2, -n + 3, -n - 1] + for start, stop in itertools.product(indices, indices): + self.check_index_result(pyfunc, cfunc, (16, v, start, stop)) + + def test_index_exception1(self): + pyfunc = list_index3 + cfunc = jit(nopython=True)(pyfunc) + msg = 'arg "start" must be an Integer.' + with self.assertRaisesRegex(errors.TypingError, msg): + cfunc(10, 0, 'invalid', 5) + + def test_index_exception2(self): + pyfunc = list_index3 + cfunc = jit(nopython=True)(pyfunc) + msg = 'arg "stop" must be an Integer.' + with self.assertRaisesRegex(errors.TypingError, msg): + cfunc(10, 0, 0, 'invalid') + + def test_remove(self): + pyfunc = list_remove + cfunc = jit(nopython=True)(pyfunc) + n = 16 + for v in (0, 1, 5, 15): + expected = pyfunc(n, v) + self.assertPreciseEqual(cfunc(n, v), expected) + + def test_remove_error(self): + self.disable_leak_check() + pyfunc = list_remove + cfunc = jit(nopython=True)(pyfunc) + with self.assertRaises(ValueError) as cm: + cfunc(10, 42) + self.assertEqual(str(cm.exception), "list.remove(x): x not in list") + + def test_count(self): + pyfunc = list_count + cfunc = jit(nopython=True)(pyfunc) + for v in range(5): + self.assertPreciseEqual(cfunc(18, v), pyfunc(18, v)) + + def test_clear(self): + self.check_unary_with_size(list_clear) + + def test_copy(self): + self.check_unary_with_size(list_copy) + + def check_add(self, pyfunc): + cfunc = jit(nopython=True)(pyfunc) + sizes = [0, 3, 50, 300] + for m, n in itertools.product(sizes, sizes): + expected = pyfunc(m, n) + self.assertPreciseEqual(cfunc(m, n), expected) + + def test_add(self): + self.check_add(list_add) + + def test_add_heterogeneous(self): + pyfunc = list_add_heterogeneous + cfunc = jit(nopython=True)(pyfunc) + expected = pyfunc() + self.assertEqual(cfunc(), expected) + + def test_add_inplace(self): + self.check_add(list_add_inplace) + + def test_add_inplace_heterogeneous(self): + pyfunc = list_add_inplace_heterogeneous + cfunc = jit(nopython=True)(pyfunc) + expected = pyfunc() + self.assertEqual(cfunc(), expected) + + def check_mul(self, pyfunc): + cfunc = jit(nopython=True)(pyfunc) + for n in [0, 3, 50, 300]: + for v in [1, 2, 3, 0, -1, -42]: + expected = pyfunc(n, v) + self.assertPreciseEqual(cfunc(n, v), expected) + + def test_mul(self): + self.check_mul(list_mul) + + def test_mul2(self): + self.check_mul(list_mul2) + + def test_mul_inplace(self): + self.check_mul(list_mul_inplace) + + @unittest.skipUnless(sys.maxsize >= 2**32, + "need a 64-bit system to test for MemoryError") + def test_mul_error(self): + self.disable_leak_check() + pyfunc = list_mul + cfunc = jit(nopython=True)(pyfunc) + # Fail in malloc() + with self.assertRaises(MemoryError): + cfunc(1, 2**58) + if sys.platform.startswith('darwin'): + libc = ct.CDLL('libc.dylib') + libc.printf("###Please ignore the above error message i.e. \ +can't allocate region. It is in fact the purpose of this test to \ +request more memory than can be provided###\n".encode("UTF-8")) + # Overflow size computation when multiplying by item size + with self.assertRaises(MemoryError): + cfunc(1, 2**62) + + def test_bool(self): + pyfunc = list_bool + cfunc = jit(nopython=True)(pyfunc) + for n in [0, 1, 3]: + expected = pyfunc(n) + self.assertPreciseEqual(cfunc(n), expected) + + def test_list_passing(self): + # Check one can pass a list from a Numba function to another + @jit(nopython=True) + def inner(lst): + return len(lst), lst[-1] + + @jit(nopython=True) + def outer(n): + l = list(range(n)) + return inner(l) + + self.assertPreciseEqual(outer(5), (5, 4)) + + def _test_compare(self, pyfunc): + def eq(args): + self.assertIs(cfunc(*args), pyfunc(*args), + "mismatch for arguments %s" % (args,)) + + cfunc = jit(nopython=True)(pyfunc) + eq(((1, 2), (1, 2))) + eq(((1, 2, 3), (1, 2))) + eq(((1, 2), (1, 2, 3))) + eq(((1, 2, 4), (1, 2, 3))) + eq(((1.0, 2.0, 3.0), (1, 2, 3))) + eq(((1.0, 2.0, 3.5), (1, 2, 3))) + + def test_eq(self): + self._test_compare(eq_usecase) + + def test_ne(self): + self._test_compare(ne_usecase) + + def test_le(self): + self._test_compare(le_usecase) + + def test_lt(self): + self._test_compare(lt_usecase) + + def test_ge(self): + self._test_compare(ge_usecase) + + def test_gt(self): + self._test_compare(gt_usecase) + + def test_identity(self): + pyfunc = identity_usecase + cfunc = jit(nopython=True)(pyfunc) + self.assertPreciseEqual(cfunc(3), pyfunc(3)) + + def test_bool_list(self): + # Check lists of bools compile and run successfully + pyfunc = bool_list_usecase + cfunc = jit(nopython=True)(pyfunc) + self.assertPreciseEqual(cfunc(), pyfunc()) + + +class TestUnboxing(MemoryLeakMixin, TestCase): + """ + Test unboxing of Python lists into native Numba lists. + """ + + @contextlib.contextmanager + def assert_type_error(self, msg): + with self.assertRaises(TypeError) as raises: + yield + if msg is not None: + self.assertRegex(str(raises.exception), msg) + + def check_unary(self, pyfunc): + cfunc = jit(nopython=True)(pyfunc) + def check(arg): + expected = pyfunc(arg) + got = cfunc(arg) + self.assertPreciseEqual(got, expected) + return check + + def test_numbers(self): + check = self.check_unary(unbox_usecase) + check([1, 2]) + check([1j, 2.5j]) + + def test_tuples(self): + check = self.check_unary(unbox_usecase2) + check([(1, 2), (3, 4)]) + check([(1, 2j), (3, 4j)]) + check([(), (), ()]) + + def test_list_inside_tuple(self): + check = self.check_unary(unbox_usecase3) + check((1, [2, 3, 4])) + + def test_list_of_tuples_inside_tuple(self): + check = self.check_unary(unbox_usecase4) + check((1, [(2,), (3,)])) + + def test_errors(self): + # See #1545 and #1594: error checking should ensure the list is + # homogeneous + msg = "can't unbox heterogeneous list" + pyfunc = noop + cfunc = jit(nopython=True)(pyfunc) + lst = [1, 2.5] + with self.assert_type_error(msg): + cfunc(lst) + # The list hasn't been changed (bogus reflecting) + self.assertEqual(lst, [1, 2.5]) + with self.assert_type_error(msg): + cfunc([1, 2j]) + # Same when the list is nested in a tuple or namedtuple + with self.assert_type_error(msg): + cfunc((1, [1, 2j])) + with self.assert_type_error(msg): + cfunc(Point(1, [1, 2j])) + # Issue #1638: tuples of different size. + # Note the check is really on the tuple side. + lst = [(1,), (2, 3)] + with self.assertRaises(TypeError) as raises: + cfunc(lst) + msg = ("can't unbox heterogeneous list: " + "UniTuple({0} x 1) != UniTuple({0} x 2)") + self.assertEqual(str(raises.exception), msg.format(types.intp)) + + + +class TestListReflection(MemoryLeakMixin, TestCase): + """ + Test reflection of native Numba lists on Python list objects. + """ + + def check_reflection(self, pyfunc): + cfunc = jit(nopython=True)(pyfunc) + samples = [([1., 2., 3., 4.], [0.]), + ([1., 2., 3., 4.], [5., 6., 7., 8., 9.]), + ] + for dest, src in samples: + expected = list(dest) + got = list(dest) + pyres = pyfunc(expected, src) + with self.assertRefCount(got, src): + cres = cfunc(got, src) + self.assertPreciseEqual(cres, pyres) + self.assertPreciseEqual(expected, got) + self.assertEqual(pyres[0] is expected, cres[0] is got) + del pyres, cres + + def test_reflect_simple(self): + self.check_reflection(reflect_simple) + + def test_reflect_conditional(self): + self.check_reflection(reflect_conditional) + + def test_reflect_exception(self): + """ + When the function exits with an exception, lists should still be + reflected. + """ + pyfunc = reflect_exception + cfunc = jit(nopython=True)(pyfunc) + l = [1, 2, 3] + with self.assertRefCount(l): + with self.assertRaises(ZeroDivisionError): + cfunc(l) + self.assertPreciseEqual(l, [1, 2, 3, 42]) + + def test_reflect_same_list(self): + """ + When the same list object is reflected twice, behaviour should + be consistent. + """ + pyfunc = reflect_dual + cfunc = jit(nopython=True)(pyfunc) + pylist = [1, 2, 3] + clist = pylist[:] + expected = pyfunc(pylist, pylist) + got = cfunc(clist, clist) + self.assertPreciseEqual(expected, got) + self.assertPreciseEqual(pylist, clist) + self.assertRefCountEqual(pylist, clist) + + def test_reflect_clean(self): + """ + When the list wasn't mutated, no reflection should take place. + """ + cfunc = jit(nopython=True)(noop) + # Use a complex, as Python integers can be cached + l = [12.5j] + ids = [id(x) for x in l] + cfunc(l) + self.assertEqual([id(x) for x in l], ids) + + +class ManagedListTestCase(MemoryLeakMixin, TestCase): + + def assert_list_element_precise_equal(self, expect, got): + self.assertEqual(len(expect), len(got)) + for a, b in zip(expect, got): + self.assertPreciseEqual(a, b) + + +class TestListManagedElements(ManagedListTestCase): + "Test list containing objects that need refct" + + def _check_element_equal(self, pyfunc): + cfunc = jit(nopython=True)(pyfunc) + con = [np.arange(3).astype(np.intp), np.arange(5).astype(np.intp)] + expect = list(con) + pyfunc(expect) + got = list(con) + cfunc(got) + self.assert_list_element_precise_equal( + expect=expect, got=got + ) + + def test_reflect_passthru(self): + def pyfunc(con): + pass + self._check_element_equal(pyfunc) + + def test_reflect_appended(self): + def pyfunc(con): + con.append(np.arange(10).astype(np.intp)) + + self._check_element_equal(pyfunc) + + def test_reflect_setitem(self): + def pyfunc(con): + con[1] = np.arange(10) + + self._check_element_equal(pyfunc) + + def test_reflect_popped(self): + def pyfunc(con): + con.pop() + + self._check_element_equal(pyfunc) + + def test_reflect_insert(self): + """make sure list.insert() doesn't crash for refcounted objects (see #7553) + """ + + def pyfunc(con): + con.insert(1, np.arange(4).astype(np.intp)) + + self._check_element_equal(pyfunc) + + def test_append(self): + def pyfunc(): + con = [] + for i in range(300): + con.append(np.arange(i, ).astype(np.intp)) + return con + + cfunc = jit(nopython=True)(pyfunc) + expect = pyfunc() + got = cfunc() + + self.assert_list_element_precise_equal( + expect=expect, got=got + ) + + def test_append_noret(self): + # This test make sure local dtor works + def pyfunc(): + con = [] + for i in range(300): + con.append(np.arange(i)) + c = 0.0 + for arr in con: + c += arr.sum() / (1 + arr.size) + return c + + cfunc = jit(nopython=True)(pyfunc) + expect = pyfunc() + got = cfunc() + + self.assertEqual(expect, got) + + def test_reassign_refct(self): + def pyfunc(): + con = [] + for i in range(5): + con.append(np.arange(2)) + con[0] = np.arange(4) + return con + + cfunc = jit(nopython=True)(pyfunc) + expect = pyfunc() + got = cfunc() + + self.assert_list_element_precise_equal( + expect=expect, got=got + ) + + def test_get_slice(self): + def pyfunc(): + con = [] + for i in range(5): + con.append(np.arange(2)) + return con[2:4] + + cfunc = jit(nopython=True)(pyfunc) + expect = pyfunc() + got = cfunc() + + self.assert_list_element_precise_equal( + expect=expect, got=got + ) + + def test_set_slice(self): + def pyfunc(): + con = [] + for i in range(5): + con.append(np.arange(2)) + con[1:3] = con[2:4] + return con + + cfunc = jit(nopython=True)(pyfunc) + expect = pyfunc() + got = cfunc() + + self.assert_list_element_precise_equal( + expect=expect, got=got + ) + + def test_pop(self): + def pyfunc(): + con = [] + for i in range(20): + con.append(np.arange(i + 1)) + while len(con) > 2: + con.pop() + return con + + cfunc = jit(nopython=True)(pyfunc) + expect = pyfunc() + got = cfunc() + + self.assert_list_element_precise_equal( + expect=expect, got=got + ) + + def test_pop_loc(self): + def pyfunc(): + con = [] + for i in range(1000): + con.append(np.arange(i + 1)) + while len(con) > 2: + con.pop(1) + return con + + cfunc = jit(nopython=True)(pyfunc) + expect = pyfunc() + got = cfunc() + + self.assert_list_element_precise_equal( + expect=expect, got=got + ) + + def test_del_range(self): + def pyfunc(): + con = [] + for i in range(20): + con.append(np.arange(i + 1)) + del con[3:10] + return con + + cfunc = jit(nopython=True)(pyfunc) + expect = pyfunc() + got = cfunc() + + self.assert_list_element_precise_equal( + expect=expect, got=got + ) + + def test_list_of_list(self): + def pyfunc(): + con = [] + for i in range(10): + con.append([0] * i) + return con + + cfunc = jit(nopython=True)(pyfunc) + expect = pyfunc() + got = cfunc() + + self.assertEqual(expect, got) + + + +def expect_reflection_failure(fn): + def wrapped(self, *args, **kwargs): + self.disable_leak_check() + with self.assertRaises(TypeError) as raises: + fn(self, *args, **kwargs) + expect_msg = 'cannot reflect element of reflected container' + self.assertIn(expect_msg, str(raises.exception)) + + return wrapped + + +class TestListOfList(ManagedListTestCase): + + def compile_and_test(self, pyfunc, *args): + from copy import deepcopy + expect_args = deepcopy(args) + expect = pyfunc(*expect_args) + + njit_args = deepcopy(args) + cfunc = jit(nopython=True)(pyfunc) + got = cfunc(*njit_args) + + self.assert_list_element_precise_equal( + expect=expect, got=got + ) + # Check reflection + self.assert_list_element_precise_equal( + expect=expect_args, got=njit_args + ) + + def test_returning_list_of_list(self): + def pyfunc(): + a = [[np.arange(i)] for i in range(4)] + return a + + self.compile_and_test(pyfunc) + + @expect_reflection_failure + def test_heterogeneous_list_error(self): + def pyfunc(x): + return x[1] + + cfunc = jit(nopython=True)(pyfunc) + l2 = [[np.zeros(i) for i in range(5)], + [np.ones(i)+1j for i in range(5)]] + l3 = [[np.zeros(i) for i in range(5)], [(1,)]] + l4 = [[1], [{1}]] + l5 = [[1], [{'a': 1}]] + + # TODO: this triggers a reflection error. + # Remove this line when nested reflection is supported + cfunc(l2) + + # error_cases + with self.assertRaises(TypeError) as raises: + cfunc(l2) + + self.assertIn( + ("reflected list(array(float64, 1d, C)) != " + "reflected list(array(complex128, 1d, C))"), + str(raises.exception) + ) + + with self.assertRaises(TypeError) as raises: + cfunc(l3) + + self.assertIn( + ("reflected list(array(float64, 1d, C)) != " + "reflected list((int64 x 1))"), + str(raises.exception) + ) + + with self.assertRaises(TypeError) as raises: + cfunc(l4) + self.assertIn( + "reflected list(int64) != reflected list(reflected set(int64))", + str(raises.exception) + ) + + with self.assertRaises(ValueError) as raises: + cfunc(l5) + self.assertIn( + "Cannot type list element of ", + str(raises.exception) + ) + + @expect_reflection_failure + def test_list_of_list_reflected(self): + def pyfunc(l1, l2): + l1.append(l2) + l1[-1].append(123) + + cfunc = jit(nopython=True)(pyfunc) + l1 = [[0, 1], [2, 3]] + l2 = [4, 5] + expect = list(l1), list(l2) + got = list(l1), list(l2) + pyfunc(*expect) + cfunc(*got) + self.assertEqual(expect, got) + + @expect_reflection_failure + def test_heterogeneous_list(self): + def pyfunc(x): + return x[1] + + l1 = [[np.zeros(i) for i in range(5)], [np.ones(i) for i in range(5)]] + + cfunc = jit(nopython=True)(pyfunc) + l1_got = cfunc(l1) + self.assertPreciseEqual(pyfunc(l1), l1_got) + + @expect_reflection_failure + def test_c01(self): + def bar(x): + return x.pop() + + r = [[np.zeros(0)], [np.zeros(10)*1j]] + # TODO: this triggers a reflection error. + # Remove this line when nested reflection is supported + self.compile_and_test(bar, r) + + with self.assertRaises(TypeError) as raises: + self.compile_and_test(bar, r) + self.assertIn( + ("reflected list(array(float64, 1d, C)) != " + "reflected list(array(complex128, 1d, C))"), + str(raises.exception), + ) + + def test_c02(self): + def bar(x): + x.append(x) + return x + + r = [[np.zeros(0)]] + + with self.assertRaises(errors.TypingError) as raises: + self.compile_and_test(bar, r) + self.assertIn( + "Invalid use of BoundFunction(list.append", + str(raises.exception), + ) + + def test_c03(self): + def bar(x): + f = x + f[0] = 1 + return f + + r = [[np.arange(3)]] + + with self.assertRaises(errors.TypingError) as raises: + self.compile_and_test(bar, r) + self.assertIn( + "invalid setitem with value of {} to element of {}".format( + typeof(1), + typeof(r[0]), + ), + str(raises.exception), + ) + + def test_c04(self): + def bar(x): + f = x + f[0][0] = 10 + return f + + r = [[np.arange(3)]] + with self.assertRaises(errors.TypingError) as raises: + self.compile_and_test(bar, r) + self.assertIn( + "invalid setitem with value of {} to element of {}".format( + typeof(10), + typeof(r[0][0]), + ), + str(raises.exception), + ) + + @expect_reflection_failure + def test_c05(self): + def bar(x): + f = x + f[0][0] = np.array([x for x in np.arange(10).astype(np.intp)]) + return f + + r = [[np.arange(3).astype(np.intp)]] + self.compile_and_test(bar, r) + + def test_c06(self): + def bar(x): + f = x + f[0][0] = np.array([x + 1j for x in np.arange(10)]) + return f + + r = [[np.arange(3)]] + with self.assertRaises(errors.TypingError) as raises: + self.compile_and_test(bar, r) + self.assertIn("invalid setitem with value", str(raises.exception)) + + @expect_reflection_failure + def test_c07(self): + self.disable_leak_check() + + def bar(x): + return x[-7] + + r = [[np.arange(3)]] + cfunc = jit(nopython=True)(bar) + with self.assertRaises(IndexError) as raises: + cfunc(r) + self.assertIn("getitem out of range", str(raises.exception)) + + def test_c08(self): + self.disable_leak_check() + + def bar(x): + x[5] = 7 + return x + + r = [1, 2, 3] + cfunc = jit(nopython=True)(bar) + with self.assertRaises(IndexError) as raises: + cfunc(r) + self.assertIn("setitem out of range", str(raises.exception)) + + def test_c09(self): + def bar(x): + x[-2] = 7j + return x + + r = [1, 2, 3] + with self.assertRaises(errors.TypingError) as raises: + self.compile_and_test(bar, r) + self.assertIn("invalid setitem with value", str(raises.exception)) + + @expect_reflection_failure + def test_c10(self): + def bar(x): + x[0], x[1] = x[1], x[0] + return x + + r = [[1, 2, 3], [4, 5, 6]] + self.compile_and_test(bar, r) + + @expect_reflection_failure + def test_c11(self): + def bar(x): + x[:] = x[::-1] + return x + + r = [[1, 2, 3], [4, 5, 6]] + self.compile_and_test(bar, r) + + def test_c12(self): + def bar(x): + del x[-1] + return x + + r = [x for x in range(10)] + self.compile_and_test(bar, r) + + +class Item(object): + def __init__(self, many, scalar): + self.many = many + self.scalar = scalar + + +class Container(object): + def __init__(self, n): + self.data = [[np.arange(i).astype(np.float64)] for i in range(n)] + + def more(self, n): + for i in range(n): + self.data.append([np.arange(i).astype(np.float64)]) + + +class TestListAndJitClasses(ManagedListTestCase): + def make_jitclass_element(self): + spec = [ + ('many', types.float64[:]), + ('scalar', types.float64), + ] + JCItem = jitclass(spec)(Item) + return JCItem + + def make_jitclass_container(self): + spec = { + 'data': types.List(dtype=types.List(types.float64[::1])), + } + JCContainer = jitclass(spec)(Container) + return JCContainer + + def assert_list_element_with_tester(self, tester, expect, got): + for x, y in zip(expect, got): + tester(x, y) + + def test_jitclass_instance_elements(self): + JCItem = self.make_jitclass_element() + + def pyfunc(xs): + xs[1], xs[0] = xs[0], xs[1] + return xs + + def eq(x, y): + self.assertPreciseEqual(x.many, y.many) + self.assertPreciseEqual(x.scalar, y.scalar) + + cfunc = jit(nopython=True)(pyfunc) + + arg = [JCItem(many=np.random.random(n + 1), scalar=n * 1.2) + for n in range(5)] + + expect_arg = list(arg) + got_arg = list(arg) + + expect_res = pyfunc(expect_arg) + got_res = cfunc(got_arg) + + self.assert_list_element_with_tester(eq, expect_arg, got_arg) + self.assert_list_element_with_tester(eq, expect_res, got_res) + + def test_jitclass_containing_list(self): + JCContainer = self.make_jitclass_container() + + expect = Container(n=4) + got = JCContainer(n=4) + self.assert_list_element_precise_equal(got.data, expect.data) + expect.more(3) + got.more(3) + self.assert_list_element_precise_equal(got.data, expect.data) + + +class TestListInitialValues(MemoryLeakMixin, TestCase): + """Tests that lists carry their initial value if present""" + + def test_homogeneous_and_literal(self): + def bar(l): + ... + + @overload(bar) + def ol_bar(l): + if l.initial_value is None: + return lambda l: literally(l) + self.assertTrue(isinstance(l, types.List)) + self.assertEqual(l.initial_value, [1, 2, 3]) + self.assertEqual(hasattr(l, 'literal_value'), False) + return lambda l: l + + @njit + def foo(): + # keys and values all have literal representation + x = [1, 2, 3] + bar(x) + + foo() + + def test_heterogeneous_but_castable_to_homogeneous(self): + def bar(l): + ... + + @overload(bar) + def ol_bar(l): + self.assertTrue(isinstance(l, types.List)) + self.assertEqual(l.initial_value, None) + self.assertEqual(hasattr(l, 'literal_value'), False) + return lambda l: l + + @njit + def foo(): + # This list will be typed based on 1j, i.e. complex128 + # as the values are not all literals, there's no "initial_value" + # available irrespective of whether it's possible to rip this + # information out of the bytecode. + x = [1j, 2, 3] + bar(x) + + foo() + + def test_mutation_not_carried(self): + def bar(d): + ... + + @overload(bar) + def ol_bar(d): + if d.initial_value is None: + return lambda d: literally(d) + self.assertTrue(isinstance(d, types.List)) + self.assertEqual(d.initial_value, [1, 2, 3]) + return lambda d: d + + @njit + def foo(): + # This list is mutated, check the initial_value carries + # correctly and is not mutated + x = [1, 2, 3] + x.append(4) + bar(x) + + foo() + + def test_mutation_not_carried_single_function(self): + # this is another pattern for using literally + + @njit + def nop(*args): + pass + + for fn, iv in (nop, None), (literally, [1, 2, 3]): + @njit + def baz(x): + pass + + def bar(z): + pass + + @overload(bar) + def ol_bar(z): + def impl(z): + fn(z) + baz(z) + return impl + + @njit + def foo(): + x = [1, 2, 3] + bar(x) + x.append(2) + return x + + foo() + # baz should be specialised based on literally being invoked and + # the literal/unliteral arriving at the call site + larg = baz.signatures[0][0] + self.assertEqual(larg.initial_value, iv) + + def test_list_of_list_ctor(self): + # see issue 6082 + @njit + def bar(x): + pass + + @njit + def foo(): + x = [[1, 2, 3, 4, 5], [1, 2, 3, 4, 6]] + bar(x) + + foo() + larg = bar.signatures[0][0] + self.assertEqual(larg.initial_value, None) + self.assertEqual(larg.dtype.initial_value, None) + + +class TestLiteralLists(MemoryLeakMixin, TestCase): + + def test_basic_compile(self): + @njit + def foo(): + l = [1, 'a'] + + foo() + + def test_literal_value_passthrough(self): + + def bar(x): + pass + + @overload(bar) + def ol_bar(x): + self.assertTrue(isinstance(x, types.LiteralList)) + lv = x.literal_value + self.assertTrue(isinstance(lv, list)) + self.assertEqual(lv[0], types.literal(1)) + self.assertEqual(lv[1], types.literal('a')) + self.assertEqual(lv[2], types.Array(types.float64, 1, 'C')) + self.assertEqual(lv[3], types.List(types.intp, reflected=False, + initial_value=[1, 2, 3])) + self.assertTrue(isinstance(lv[4], types.LiteralList)) + self.assertEqual(lv[4].literal_value[0], types.literal('cat')) + self.assertEqual(lv[4].literal_value[1], types.literal(10)) + return lambda x: x + + @njit + def foo(): + otherhomogeneouslist = [1, 2, 3] + otherheterogeneouslist = ['cat', 10] + zeros = np.zeros(5) + l = [1, 'a', zeros, otherhomogeneouslist, otherheterogeneouslist] + bar(l) + + foo() + + def test_literal_value_involved_passthrough(self): + + def bar(x): + pass + + @overload(bar) + def ol_bar(x): + self.assertTrue(isinstance(x, types.LiteralStrKeyDict)) + dlv = x.literal_value + inner_literal = {types.literal('g'): types.literal('h'), + types.literal('i'): + types.Array(types.float64, 1, 'C')} + inner_dict = types.LiteralStrKeyDict(inner_literal) + outer_literal = {types.literal('a'): + types.LiteralList([types.literal(1), + types.literal('a'), + types.DictType( + types.unicode_type, + types.intp, + initial_value={'f': 1}), + inner_dict]), + types.literal('b'): types.literal(2), + types.literal('c'): types.List(types.complex128, + reflected=False)} + def check_same(a, b): + if (isinstance(a, types.LiteralList) and + isinstance(b, types.LiteralList)): + for i, j in zip(a.literal_value, b.literal_value): + check_same(a.literal_value, b.literal_value) + elif (isinstance(a, list) and + isinstance(b, list)): + for i, j in zip(a, b): + check_same(i, j) + elif (isinstance(a, types.LiteralStrKeyDict) and + isinstance(b, types.LiteralStrKeyDict)): + for (ki, vi), (kj, vj) in zip(a.literal_value.items(), + b.literal_value.items()): + check_same(ki, kj) + check_same(vi, vj) + elif (isinstance(a, dict) and + isinstance(b, dict)): + for (ki, vi), (kj, vj) in zip(a.items(), b.items()): + check_same(ki, kj) + check_same(vi, vj) + else: + self.assertEqual(a, b) + check_same(dlv, outer_literal) + return lambda x: x + + @njit + def foo(): + # this stretches what's possible with LiteralStrKeyDict and + # LiteralList, it's nested and contains typed.Dict and np arrays + # as well as more constant type things. + l = {'a': [1, 'a', {'f': 1}, {'g': 'h', 'i': np.zeros(5)}], 'b': 2, + 'c': [1j, 2j, 3j]} + bar(l) + + foo() + + def test_mutation_failure(self): + + def staticsetitem(): + l = ['a', 1] + l[0] = 'b' + + def delitem(): + l = ['a', 1] + del l[0] + + def append(): + l = ['a', 1] + l.append(2j) + + def extend(): + l = ['a', 1] + l.extend([2j, 3j]) + + def insert(): + l = ['a', 1] + l.insert(0, 2j) + + def remove(): + l = ['a', 1] + l.remove('a') + + def pop(): + l = ['a', 1] + l.pop() + + def clear(): + l = ['a', 1] + l.clear() + + def sort(): + l = ['a', 1] + l.sort() + + def reverse(): + l = ['a', 1] + l.reverse() + + illegals = (staticsetitem, delitem, append, extend, insert, remove, pop, + clear, sort, reverse) + + for test in illegals: + with self.subTest(test.__name__): + with self.assertRaises(errors.TypingError) as raises: + njit(test)() + expect = "Cannot mutate a literal list" + self.assertIn(expect, str(raises.exception)) + + def test_count(self): + @njit + def foo(): + l = ['a', 1, 'a', 2, 'a', 3, 'b', 4, 'b', 5, 'c'] + r = [] + for x in 'abc': + r.append(l.count(x)) + return r + + self.assertEqual(foo.py_func(), foo()) + + def test_len(self): + @njit + def foo(): + l = ['a', 1, 'a', 2, 'a', 3, 'b', 4, 'b', 5, 'c'] + return len(l) + + self.assertEqual(foo.py_func(), foo()) + + def test_contains(self): + @njit + def foo(): + l = ['a', 1, 'a', 2, 'a', 3, 'b', 4, 'b', 5, 'c'] + r = [] + for x in literal_unroll(('a', 'd', 2, 6)): + r.append(x in l) + return r + + self.assertEqual(foo.py_func(), foo()) + + def test_getitem(self): + + @njit + def foo(x): + l = ['a', 1] + return l[x] + + with self.assertRaises(errors.TypingError) as raises: + foo(0) + expect = "Cannot __getitem__ on a literal list" + self.assertIn(expect, str(raises.exception)) + + def test_staticgetitem(self): + + @njit + def foo(): + l = ['a', 1] + return l[0], l[1] + + self.assertEqual(foo.py_func(), foo()) + + def test_staticgetitem_slice(self): + # this is forbidden by typing as there's no way to serialize a list of + # any kind as required by returning a (static) slice of a LiteralList + @njit + def foo(): + l = ['a', 'b', 1] + return l[:2] + + with self.assertRaises(errors.TypingError) as raises: + foo() + expect = "Cannot __getitem__ on a literal list" + self.assertIn(expect, str(raises.exception)) + + def test_setitem(self): + + @njit + def foo(x): + l = ['a', 1] + l[x] = 'b' + + with self.assertRaises(errors.TypingError) as raises: + foo(0) + expect = "Cannot mutate a literal list" + self.assertIn(expect, str(raises.exception)) + + def test_unify(self): + + @njit + def foo(x): + if x + 1 > 3: + l = ['a', 1] + else: + l = ['b', 2] + return l[0] + + for x in (-100, 100): + self.assertEqual(foo.py_func(x), foo(x)) + + def test_not_unify(self): + + @njit + def foo(x): + if x + 1 > 3: + l = ['a', 1, 2j] + else: + l = ['b', 2] + return l[0], l[1], l[0], l[1] # defeat py310 inliner + + with self.assertRaises(errors.TypingError) as raises: + foo(100) + expect = "Cannot unify LiteralList" + self.assertIn(expect, str(raises.exception)) + + def test_index(self): + @njit + def foo(): + l = ['a', 1] + l.index('a') + + with self.assertRaises(errors.TypingError) as raises: + foo() + expect = "list.index is unsupported for literal lists" + self.assertIn(expect, str(raises.exception)) + + def test_copy(self): + @njit + def foo(): + l = ['a', 1].copy() + return l[0], l[1] + + self.assertEqual(foo(), foo.py_func()) + + def test_tuple_not_in_mro(self): + # Related to #6094, make sure that LiteralList does not inherit from + # types.BaseTuple as this breaks isinstance checks. + def bar(x): + pass + + @overload(bar) + def ol_bar(x): + self.assertFalse(isinstance(x, types.BaseTuple)) + self.assertTrue(isinstance(x, types.LiteralList)) + return lambda x: ... + + @njit + def foo(): + l = ['a', 1] + bar(l) + + foo() + + +if __name__ == '__main__': + unittest.main() diff --git a/shared/package-files/01/0119ee8bcb2ffffa9ccd32528aa4b1c016b3a62f980488256871d5b7861a3245/blob b/shared/package-files/01/0119ee8bcb2ffffa9ccd32528aa4b1c016b3a62f980488256871d5b7861a3245/blob new file mode 100644 index 0000000000000000000000000000000000000000..0bc5f5d729c3eab45dcfbe665e022236f0c70638 --- /dev/null +++ b/shared/package-files/01/0119ee8bcb2ffffa9ccd32528aa4b1c016b3a62f980488256871d5b7861a3245/blob @@ -0,0 +1,80 @@ +"""Mauna Loa Weekly Atmospheric CO2 Data""" +import pandas as pd + +from statsmodels.datasets import utils as du + +__docformat__ = "restructuredtext" + +COPYRIGHT = """This is public domain.""" +TITLE = """Mauna Loa Weekly Atmospheric CO2 Data""" +SOURCE = """ +Data obtained from http://cdiac.ornl.gov/trends/co2/sio-keel-flask/sio-keel-flaskmlo_c.html + +Obtained on 3/15/2014. + +Citation: + +Keeling, C.D. and T.P. Whorf. 2004. Atmospheric CO2 concentrations derived from flask air samples at sites in the SIO network. In Trends: A Compendium of Data on Global Change. Carbon Dioxide Information Analysis Center, Oak Ridge National Laboratory, U.S. Department of Energy, Oak Ridge, Tennessee, U.S.A. +""" + +DESCRSHORT = """Atmospheric CO2 from Continuous Air Samples at Mauna Loa Observatory, Hawaii, U.S.A.""" + +DESCRLONG = """ +Atmospheric CO2 from Continuous Air Samples at Mauna Loa Observatory, Hawaii, U.S.A. + +Period of Record: March 1958 - December 2001 + +Methods: An Applied Physics Corporation (APC) nondispersive infrared gas analyzer was used to obtain atmospheric CO2 concentrations, based on continuous data (four measurements per hour) from atop intake lines on several towers. Steady data periods of not less than six hours per day are required; if no such six-hour periods are available on any given day, then no data are used that day. Weekly averages were calculated for most weeks throughout the approximately 44 years of record. The continuous data for year 2000 is compared with flask data from the same site in the graphics section.""" + +# suggested notes +NOTE = """:: + + Number of observations: 2225 + Number of variables: 2 + Variable name definitions: + + date - sample date in YYMMDD format + co2 - CO2 Concentration ppmv + + The data returned by load_pandas contains the dates as the index. +""" + + +def load_pandas(): + """ + Load the data and return a Dataset class instance. + + Returns + ------- + Dataset + A `Dataset` instance with ``data`` and ``names`` attributes. + + Notes + ----- + The Dataset instance does not contain endog and exog attributes. + """ + data = _get_data() + index = pd.date_range(start=str(data["date"][0]), periods=len(data), freq="W-SAT") + dataset = data[["co2"]] + dataset.index = index + return du.Dataset(data=dataset, names=list(data.columns)) + + +def load(): + """ + Load the data and return a Dataset class instance. + + Returns + ------- + Dataset + A `Dataset` instance with ``data`` and ``names`` attributes. + + Notes + ----- + The Dataset instance does not contain endog and exog attributes. + """ + return load_pandas() + + +def _get_data(): + return du.load_csv(__file__, "co2.csv") diff --git a/shared/package-files/01/011f6ff5216357224d088479a171f92da40f48df7a8d9365f342def6c7e4b7cd/blob b/shared/package-files/01/011f6ff5216357224d088479a171f92da40f48df7a8d9365f342def6c7e4b7cd/blob new file mode 100644 index 0000000000000000000000000000000000000000..12fcef85a8a2cdb1d7a7b78eb371562a8849e5f3 --- /dev/null +++ b/shared/package-files/01/011f6ff5216357224d088479a171f92da40f48df7a8d9365f342def6c7e4b7cd/blob @@ -0,0 +1,567 @@ +import functools +from typing import List, Optional, Set, Union + +import torch +from torch import Tensor +from torch._inductor import utils +from torch._subclasses.fake_tensor import FakeTensor +from torch.utils._mode_utils import no_dispatch +from torch.utils._triton import has_triton + +from ..pattern_matcher import ( + fwd_only, + joint_fwd_bwd, + Match, + MatchContext, + register_replacement, +) +from ..utils import is_view + +aten = torch.ops.aten + + +# This flag is only used for testing purpose. +# Changing it to True will ignore comparing do_bench times +# between original pattern and padded one. +_skip_do_bench_times = False + + +def fetch_fake_tensors(match, kwarg_names) -> List[Tensor]: + kwargs = match.kwargs + return [kwargs[name].meta["val"] for name in kwarg_names] + + +def unwrap_fake_args(*arg_names): + def decorator(func): + def wrapper(match): + fake_tensors = fetch_fake_tensors(match, arg_names) + return func(*fake_tensors) + + return wrapper + + return decorator + + +def get_alignment_size(x: Tensor) -> int: + if x.dtype == torch.float16 or x.dtype == torch.half or x.dtype == torch.bfloat16: + return 8 + elif x.dtype == torch.float32 or x.dtype == torch.float: + return 4 + else: + return 0 + + +def check_device(a: Tensor, b: Tensor) -> bool: + return a.is_cuda and b.is_cuda + + +def check_dtype(a: Tensor, b: Tensor) -> bool: + return a.is_floating_point() and b.is_floating_point() + + +def _result_layout_affects_graph_output(match: Match) -> bool: + """ + Check if the matched GEMM operation potentially affects the graph output strides. + returns True if the matched op's output buffer does not pass through functions which certainly + redefine the memory layout before being part of the graph output. + """ + + if match.ctx is not None: + assert isinstance(match.ctx, MatchContext) + search_node: torch.fx.Node = match.output_node() + else: + return True + + assert search_node is not None + seen: Set[torch.fx.Node] = set() + + def find_output(node: torch.fx.Node, is_start_node=False): + if not isinstance(node, torch.fx.Node): + return False + if node in seen: + return False + seen.add(node) + if node.op == "output": + return True + if node.op != "call_function": + return False + if not is_start_node and ( + (not isinstance(node.target, torch._ops.OpOverload)) + or (not is_view(node.target)) + ): + return False + if node.users is not None and len(node.users) > 0: + for n in node.users: + if find_output(n): + return True + return False + + return find_output(search_node, True) + + +def should_pad_common( + mat1: Tensor, mat2: Tensor, input: Optional[Tensor] = None +) -> bool: + # It's fine we have symbolic shapes or strides as long as they + # have hints. Later, we will make sure we only pad non-symbolic dimensions. + def valid_shape_and_stride(t: Optional[Tensor]) -> bool: + if t is None: + return True + + symbolic_cnt = 0 + for x in t.size(): + if isinstance(x, int): + continue + elif utils.is_symbolic(x): + if not x.node.has_hint(): + return False + symbolic_cnt += 1 + else: + return False + # filter out cases where all dimentions are symbolic + if symbolic_cnt == len(t.size()): + return False + return all( + isinstance(x, int) or (utils.is_symbolic(x) and x.node.has_hint()) + for x in t.stride() + ) + + return ( + torch._inductor.config.shape_padding + and check_device(mat1, mat2) + and check_dtype(mat1, mat2) + and all(valid_shape_and_stride(t) for t in (mat1, mat2, input)) + ) + + +def get_padded_length(x: Union[int, torch.SymInt], alignment_size) -> int: + # we don't pad x if it is symbolic + if isinstance(x, torch.SymInt) or alignment_size == 0 or x % alignment_size == 0: + return 0 + return int((x // alignment_size + 1) * alignment_size) - x + + +def pad_dim(x: Tensor, padded_length: int, dim: int) -> Tensor: + if padded_length == 0: + return x + pad = x.new_zeros(*x.shape[:dim], padded_length, *x.shape[dim + 1 :]) + return torch.cat([x, pad], dim=dim) + + +def addmm_pattern( + input: Tensor, mat1: Tensor, mat2: Tensor, beta: float, alpha: float +) -> Tensor: + return aten.addmm(input, mat1, mat2, beta=beta, alpha=alpha) + + +def should_pad_addmm(match: Match) -> bool: + if ( + torch._inductor.config.keep_output_stride + and _result_layout_affects_graph_output(match) + ): + return False + mat1, mat2, input = fetch_fake_tensors(match, ("mat1", "mat2", "input")) + return should_pad_common(mat1, mat2, input) and should_pad_bench( + mat1, mat2, torch.ops.aten.addmm, input=input + ) + + +def addmm_replace( + input: Optional[Tensor], mat1: Tensor, mat2: Tensor, beta=1.0, alpha=1.0 +) -> Tensor: + m_padded_length = get_padded_length(mat1.shape[0], get_alignment_size(mat1)) + k_padded_length = get_padded_length(mat1.shape[1], get_alignment_size(mat1)) + n_padded_length = get_padded_length(mat2.shape[1], get_alignment_size(mat2)) + + if m_padded_length != 0 or k_padded_length != 0 or n_padded_length != 0: + return pad_addmm( + input, + mat1, + mat2, + m_padded_length, + k_padded_length, + n_padded_length, + beta, + alpha, + ) + + return aten.addmm(input, mat1, mat2, beta=beta, alpha=alpha) + + +def pad_addmm( + input: Optional[Tensor], + mat1: Tensor, + mat2: Tensor, + m_padded_length: int, + k_padded_length: int, + n_padded_length: int, + beta=1.0, + alpha=1.0, +): + # addmm decomp with padding will go through pad_addmm multiple times if multiple dimensions are needed to be padded + if k_padded_length != 0: + mat1 = pad_dim(mat1, k_padded_length, 1) + mat2 = pad_dim(mat2, k_padded_length, 0) + elif n_padded_length != 0: + mat2 = pad_dim(mat2, n_padded_length, 1) + elif m_padded_length != 0: + mat1 = pad_dim(mat1, m_padded_length, 0) + + # the add broadcasts, so we only pad if the dimension != 1 + if input is not None and k_padded_length == 0: + if n_padded_length != 0: + if input.dim() == 2 and input.shape[1] != 1: + input = pad_dim(input, n_padded_length, 1) + elif input.dim() == 1 and input.shape[0] != 1: + input = pad_dim(input, n_padded_length, 0) + elif m_padded_length != 0 and input.dim() == 2 and input.shape[0] != 1: + input = pad_dim(input, m_padded_length, 0) + + if k_padded_length != 0: + return addmm_replace(input, mat1, mat2, beta=beta, alpha=alpha) + elif n_padded_length != 0: + return addmm_replace(input, mat1, mat2, beta=beta, alpha=alpha)[ + :, :-n_padded_length + ] + else: + return addmm_replace(input, mat1, mat2, beta=beta, alpha=alpha)[ + :-m_padded_length, : + ] + + +def is_mm_compute_bound(M: int, K: int, N: int, dtype: torch.dtype) -> bool: + denominator = M * K + N * K + M * N + if denominator == 0: + return False + arithmetic_intensity = (M * N * K) / denominator + + # Fails with AMD + try: + machine_balance = ( + 1000 * utils.get_device_tflops(dtype) + ) / utils.get_gpu_dram_gbps() + except Exception: + return True + + # dram_gbps might be underestimating bandwidth because of cache. + # if we estimate machine balance too low we might miss some speedups, + # if we extimate too high there will be unnecessary compilation time increase. + # TODO - finetune coefficient here. As a reference point, Triton mm model assumes + # 80% of reads are in cache and cache is 4x faster than dram_gbps + machine_balance = machine_balance * 0.5 + + return arithmetic_intensity > machine_balance + + +@functools.lru_cache(None) +def get_pad_cache(): + return torch._inductor.codecache.LocalCache() + + +def get_cached_should_pad(key): + return get_pad_cache().lookup(key) + + +def set_cached_should_pad(key, value): + return get_pad_cache().set_value(key, value=value) + + +def should_pad_bench_key( + mat1: Tensor, mat2: Tensor, op, input: Optional[Tensor] = None +) -> str: + def tensor_key(t): + return (t.shape, t.stride(), t.dtype) + + tf32_key = ( + None if mat1.dtype != torch.float32 else torch.backends.cuda.matmul.allow_tf32 + ) + key = ( + tensor_key(mat1), + tensor_key(mat2), + op, + input if input is None else tensor_key(input), + tf32_key, + ) + + return str(key) + + +def should_pad_bench( + mat1: Tensor, mat2: Tensor, op, input: Optional[Tensor] = None +) -> bool: + if not has_triton(): + return False + + do_bench = functools.partial( + utils.do_bench, + warmup=5, + ) + + with no_dispatch(): + if op is torch.ops.aten.mm or op is torch.ops.aten.addmm: + m = mat1.shape[0] + k = mat1.shape[1] + n = mat2.shape[1] + + m_padded_length = get_padded_length(m, get_alignment_size(mat1)) + k_padded_length = get_padded_length(k, get_alignment_size(mat1)) + n_padded_length = get_padded_length(n, get_alignment_size(mat2)) + elif op is torch.ops.aten.bmm: + m = mat1.shape[1] + k = mat1.shape[2] + n = mat2.shape[2] + + m_padded_length = get_padded_length(m, get_alignment_size(mat1)) + k_padded_length = get_padded_length(k, get_alignment_size(mat1)) + n_padded_length = get_padded_length(n, get_alignment_size(mat2)) + else: + return False + + if m_padded_length == k_padded_length == n_padded_length == 0: + return False + + if not is_mm_compute_bound(m, k, n, mat1.dtype): + return False + + # We don't want to look up the cache for cases that are trivially false + # since it does file io + key = should_pad_bench_key(mat1, mat2, op, input) + + cached_pad = get_cached_should_pad(key) + if cached_pad is not None: + return cached_pad + + def realize_symbols(ds): + return [d if isinstance(d, int) else d.node.hint for d in ds] + + def realize_tensor(t): + if isinstance(t, FakeTensor): + size_hints = realize_symbols(t.size()) + stride_hint = realize_symbols(t.stride()) + real_size = ( + sum((d - 1) * s for d, s in zip(size_hints, stride_hint)) + 1 + ) + real_t = torch.randn(real_size, dtype=t.dtype, device=t.device) + return torch.as_strided(real_t, size_hints, stride_hint) + else: + return torch.randn_like(t) + + mat1 = realize_tensor(mat1) + mat2 = realize_tensor(mat2) + if op is torch.ops.aten.bmm or op is torch.ops.aten.mm: + ori_time = do_bench( + lambda: op(mat1, mat2), + ) + else: + if input is not None: + input = realize_tensor(input) + ori_time = do_bench( + lambda: op(input, mat1, mat2), + ) + + mat1_pad = torch.randn_like(mat1) + mat2_pad = torch.randn_like(mat2) + + if op is torch.ops.aten.addmm: + input_pad = None + if input is not None and input.is_cuda: + input_pad = torch.randn_like(input) + pad_time = do_bench( + lambda: pad_addmm( + input_pad, + mat1_pad, + mat2_pad, + m_padded_length, + k_padded_length, + n_padded_length, + ), + ) + elif op is torch.ops.aten.mm: + pad_time = do_bench( + lambda: pad_mm( + mat1_pad, + mat2_pad, + m_padded_length, + k_padded_length, + n_padded_length, + ), + ) + else: + pad_time = do_bench( + lambda: pad_bmm( + mat1_pad, + mat2_pad, + m_padded_length, + k_padded_length, + n_padded_length, + ), + ) + + # Shape padding introduces additional memory ops. Based on microbenchmarks, 1.1x represents a reasonable + # tradeoff between performance improvement from shape padding and overhead from additional memory ops + # TODO: Build a learned model which would be better than this heuristic + should_pad = _skip_do_bench_times or ori_time > pad_time * 1.1 + set_cached_should_pad(key, should_pad) + + return should_pad + + +def mm_pattern(mat1: Tensor, mat2: Tensor) -> Tensor: + return aten.mm(mat1, mat2) + + +def should_pad_mm(match: Match) -> bool: + if ( + torch._inductor.config.keep_output_stride + and _result_layout_affects_graph_output(match) + ): + return False + mat1, mat2 = fetch_fake_tensors(match, ("mat1", "mat2")) + return should_pad_common(mat1, mat2) and should_pad_bench( + mat1, mat2, torch.ops.aten.mm + ) + + +def mm_replace(mat1: Tensor, mat2: Tensor) -> Tensor: + m_padded_length = get_padded_length(mat1.shape[0], get_alignment_size(mat1)) + k_padded_length = get_padded_length(mat1.shape[1], get_alignment_size(mat1)) + n_padded_length = get_padded_length(mat2.shape[1], get_alignment_size(mat2)) + + return pad_mm(mat1, mat2, m_padded_length, k_padded_length, n_padded_length) + + +def pad_mm( + mat1: Tensor, + mat2: Tensor, + m_padded_length: int, + k_padded_length: int, + n_padded_length: int, +) -> Tensor: + # mm_replace will go through pad_mm multiple times if multiple dimensions are needed to be padded + if k_padded_length != 0: + mat1 = pad_dim(mat1, k_padded_length, 1) + mat2 = pad_dim(mat2, k_padded_length, 0) + return torch.ops.aten.mm(mat1, mat2) + elif n_padded_length != 0: + mat2 = pad_dim(mat2, n_padded_length, 1) + return torch.ops.aten.mm(mat1, mat2)[:, :-n_padded_length] + else: + mat1 = pad_dim(mat1, m_padded_length, 0) + return torch.ops.aten.mm(mat1, mat2)[:-m_padded_length, :] + + +def bmm_pattern(mat1: Tensor, mat2: Tensor) -> Tensor: + return aten.bmm(mat1, mat2) + + +def should_pad_bmm(match: Match) -> bool: + if ( + torch._inductor.config.keep_output_stride + and _result_layout_affects_graph_output(match) + ): + return False + mat1, mat2 = fetch_fake_tensors(match, ("mat1", "mat2")) + return should_pad_common(mat1, mat2) and should_pad_bench( + mat1, mat2, torch.ops.aten.bmm + ) + + +def bmm_replace(mat1: Tensor, mat2: Tensor) -> Tensor: + m_padded_length = get_padded_length(mat1.shape[1], get_alignment_size(mat1)) + k_padded_length = get_padded_length(mat1.shape[2], get_alignment_size(mat1)) + n_padded_length = get_padded_length(mat2.shape[2], get_alignment_size(mat2)) + + if m_padded_length != 0 or k_padded_length != 0 or n_padded_length != 0: + return pad_bmm(mat1, mat2, m_padded_length, k_padded_length, n_padded_length) + + return aten.bmm(mat1, mat2) + + +def pad_bmm( + mat1: Tensor, + mat2: Tensor, + m_padded_length: int, + k_padded_length: int, + n_padded_length: int, +) -> Tensor: + # bmm_replace will go through pad_bmm multiple times if multiple dimensions are needed to be padded + if k_padded_length != 0: + mat1 = pad_dim(mat1, k_padded_length, 2) + mat2 = pad_dim(mat2, k_padded_length, 1) + + return aten.bmm(mat1, mat2) + elif n_padded_length != 0: + mat2 = pad_dim(mat2, n_padded_length, 2) + return aten.bmm(mat1, mat2)[:, :, :-n_padded_length].contiguous() + else: + mat1 = pad_dim(mat1, m_padded_length, 1) + return aten.bmm(mat1, mat2)[:, :-m_padded_length, :].contiguous() + + +@functools.lru_cache(None) +def _pad_mm_init(): + from .joint_graph import patterns + + if torch.cuda.is_available(): + # workaround https://github.com/pytorch/pytorch/issues/97894 + device = "cuda" + else: + device = "cpu" + + # sizes/values dont actually matter for initial trace + # once we get a possible match we re-trace with the actual values and verify the match still holds + + dim2a = functools.partial(torch.empty, (4, 4), device=device, requires_grad=True) + dim2b = functools.partial(torch.empty, (4, 4), device=device, requires_grad=True) + + dim3a = functools.partial(torch.empty, (4, 4, 4), device=device, requires_grad=True) + dim3b = functools.partial(torch.empty, (4, 4, 4), device=device, requires_grad=True) + + dim1a = functools.partial(torch.empty, (4), device=device, requires_grad=True) + + # workaround https://github.com/pytorch/pytorch/issues/97894 + # 0.113377 is a "magic" value that lets us recover the lost input arg relationship + rep = {"beta": 0.213377, "alpha": 0.113377} + + for pattern, replacement, args, workaround, extra_check in [ + ( + mm_pattern, + mm_replace, + [dim2a(), dim2b()], + {}, + should_pad_mm, + ), + ( + bmm_pattern, + bmm_replace, + [dim3a(), dim3b()], + {}, + should_pad_bmm, + ), + ( + addmm_pattern, + addmm_replace, + [dim1a(), dim2a(), dim2b()], + rep, + should_pad_addmm, + ), + ]: + assert isinstance(workaround, dict) # mypy is unable to infer the type properly + register_replacement( + pattern, + replacement, + args, + joint_fwd_bwd, + patterns, + extra_check=extra_check, + scalar_workaround=workaround, + ) + register_replacement( + pattern, + replacement, + args, + fwd_only, + patterns, + extra_check=extra_check, + scalar_workaround=workaround, + ) diff --git a/shared/package-files/01/011f797851fdbeea927ef2d064df8be628de6b6e4d3810a85eac3cb393bdc4b4/blob b/shared/package-files/01/011f797851fdbeea927ef2d064df8be628de6b6e4d3810a85eac3cb393bdc4b4/blob new file mode 100644 index 0000000000000000000000000000000000000000..6256ecfd1e2c9ac4cfa3fac359cd12dce85b759c --- /dev/null +++ b/shared/package-files/01/011f797851fdbeea927ef2d064df8be628de6b6e4d3810a85eac3cb393bdc4b4/blob @@ -0,0 +1,91 @@ +######################## BEGIN LICENSE BLOCK ######################## +# The Original Code is Mozilla Universal charset detector code. +# +# The Initial Developer of the Original Code is +# Netscape Communications Corporation. +# Portions created by the Initial Developer are Copyright (C) 2001 +# the Initial Developer. All Rights Reserved. +# +# Contributor(s): +# Mark Pilgrim - port to Python +# Shy Shalom - original C code +# Proofpoint, Inc. +# +# 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 .charsetprober import CharSetProber +from .enums import ProbingState, MachineState + + +class MultiByteCharSetProber(CharSetProber): + """ + MultiByteCharSetProber + """ + + def __init__(self, lang_filter=None): + super(MultiByteCharSetProber, self).__init__(lang_filter=lang_filter) + self.distribution_analyzer = None + self.coding_sm = None + self._last_char = [0, 0] + + def reset(self): + super(MultiByteCharSetProber, self).reset() + if self.coding_sm: + self.coding_sm.reset() + if self.distribution_analyzer: + self.distribution_analyzer.reset() + self._last_char = [0, 0] + + @property + def charset_name(self): + raise NotImplementedError + + @property + def language(self): + raise NotImplementedError + + def feed(self, byte_str): + for i in range(len(byte_str)): + coding_state = self.coding_sm.next_state(byte_str[i]) + if coding_state == MachineState.ERROR: + self.logger.debug('%s %s prober hit error at byte %s', + self.charset_name, self.language, i) + self._state = ProbingState.NOT_ME + break + elif coding_state == MachineState.ITS_ME: + self._state = ProbingState.FOUND_IT + break + elif coding_state == MachineState.START: + char_len = self.coding_sm.get_current_charlen() + if i == 0: + self._last_char[1] = byte_str[0] + self.distribution_analyzer.feed(self._last_char, char_len) + else: + self.distribution_analyzer.feed(byte_str[i - 1:i + 1], + char_len) + + self._last_char[0] = byte_str[-1] + + if self.state == ProbingState.DETECTING: + if (self.distribution_analyzer.got_enough_data() and + (self.get_confidence() > self.SHORTCUT_THRESHOLD)): + self._state = ProbingState.FOUND_IT + + return self.state + + def get_confidence(self): + return self.distribution_analyzer.get_confidence() diff --git a/shared/package-files/01/0120895405d38add75d1dc319406347793911dfb091aed14585f76fe77c3d9e4/blob b/shared/package-files/01/0120895405d38add75d1dc319406347793911dfb091aed14585f76fe77c3d9e4/blob new file mode 100644 index 0000000000000000000000000000000000000000..8c8272df7b8a2eeb35ab4e7ab376870999c776c6 --- /dev/null +++ b/shared/package-files/01/0120895405d38add75d1dc319406347793911dfb091aed14585f76fe77c3d9e4/blob @@ -0,0 +1,1018 @@ +# This file is part of Hypothesis, which may be found at +# https://github.com/HypothesisWorks/hypothesis/ +# +# Copyright the Hypothesis Authors. +# Individual contributors are listed in AUTHORS.rst and the git log. +# +# This Source Code Form is subject to the terms of the Mozilla Public License, +# v. 2.0. If a copy of the MPL was not distributed with this file, You can +# obtain one at https://mozilla.org/MPL/2.0/. + +"""This module provides support for a stateful style of testing, where tests +attempt to find a sequence of operations that cause a breakage rather than just +a single value. + +Notably, the set of steps available at any point may depend on the +execution to date. +""" +import collections +import inspect +from copy import copy +from functools import lru_cache +from io import StringIO +from time import perf_counter +from typing import ( + Any, + Callable, + ClassVar, + Dict, + Iterable, + List, + Optional, + Sequence, + Union, + overload, +) +from unittest import TestCase + +import attr + +from hypothesis import strategies as st +from hypothesis._settings import ( + HealthCheck, + Verbosity, + note_deprecation, + settings as Settings, +) +from hypothesis.control import _current_build_context, current_build_context +from hypothesis.core import TestFunc, given +from hypothesis.errors import InvalidArgument, InvalidDefinition +from hypothesis.internal.compat import add_note +from hypothesis.internal.conjecture import utils as cu +from hypothesis.internal.conjecture.engine import BUFFER_SIZE +from hypothesis.internal.healthcheck import fail_health_check +from hypothesis.internal.observability import TESTCASE_CALLBACKS +from hypothesis.internal.reflection import ( + function_digest, + get_pretty_function_description, + nicerepr, + proxies, +) +from hypothesis.internal.validation import check_type +from hypothesis.reporting import current_verbosity, report +from hypothesis.strategies._internal.featureflags import FeatureStrategy +from hypothesis.strategies._internal.strategies import ( + Ex, + Ex_Inv, + OneOfStrategy, + SearchStrategy, + check_strategy, +) +from hypothesis.vendor.pretty import RepresentationPrinter + +STATE_MACHINE_RUN_LABEL = cu.calc_label_from_name("another state machine step") +SHOULD_CONTINUE_LABEL = cu.calc_label_from_name("should we continue drawing") + + +class _OmittedArgument: + """Sentinel class to prevent overlapping overloads in type hints. See comments + above the overloads of @rule.""" + + +class TestCaseProperty: # pragma: no cover + def __get__(self, obj, typ=None): + if obj is not None: + typ = type(obj) + return typ._to_test_case() + + def __set__(self, obj, value): + raise AttributeError("Cannot set TestCase") + + def __delete__(self, obj): + raise AttributeError("Cannot delete TestCase") + + +def run_state_machine_as_test(state_machine_factory, *, settings=None, _min_steps=0): + """Run a state machine definition as a test, either silently doing nothing + or printing a minimal breaking program and raising an exception. + + state_machine_factory is anything which returns an instance of + RuleBasedStateMachine when called with no arguments - it can be a class or a + function. settings will be used to control the execution of the test. + """ + if settings is None: + try: + settings = state_machine_factory.TestCase.settings + check_type(Settings, settings, "state_machine_factory.TestCase.settings") + except AttributeError: + settings = Settings(deadline=None, suppress_health_check=list(HealthCheck)) + check_type(Settings, settings, "settings") + check_type(int, _min_steps, "_min_steps") + if _min_steps < 0: + # Because settings can vary via e.g. profiles, settings.stateful_step_count + # overrides this argument and we don't bother cross-validating. + raise InvalidArgument(f"_min_steps={_min_steps} must be non-negative.") + + @settings + @given(st.data()) + def run_state_machine(factory, data): + cd = data.conjecture_data + machine = factory() + check_type(RuleBasedStateMachine, machine, "state_machine_factory()") + cd.hypothesis_runner = machine + machine._observability_predicates = cd._observability_predicates # alias + + print_steps = ( + current_build_context().is_final or current_verbosity() >= Verbosity.debug + ) + cd._stateful_repr_parts = [] + + def output(s): + if print_steps: + report(s) + if TESTCASE_CALLBACKS: + cd._stateful_repr_parts.append(s) + + try: + output(f"state = {machine.__class__.__name__}()") + machine.check_invariants(settings, output, cd._stateful_run_times) + max_steps = settings.stateful_step_count + steps_run = 0 + + while True: + # We basically always want to run the maximum number of steps, + # but need to leave a small probability of terminating early + # in order to allow for reducing the number of steps once we + # find a failing test case, so we stop with probability of + # 2 ** -16 during normal operation but force a stop when we've + # generated enough steps. + cd.start_example(STATE_MACHINE_RUN_LABEL) + must_stop = None + if steps_run >= max_steps: + must_stop = True + elif steps_run <= _min_steps: + must_stop = False + elif cd._bytes_drawn > (0.8 * BUFFER_SIZE): + # Better to stop after fewer steps, than always overrun and retry. + # See https://github.com/HypothesisWorks/hypothesis/issues/3618 + must_stop = True + + start_draw = perf_counter() + if cd.draw_boolean(p=2**-16, forced=must_stop): + break + steps_run += 1 + + # Choose a rule to run, preferring an initialize rule if there are + # any which have not been run yet. + if machine._initialize_rules_to_run: + init_rules = [ + st.tuples(st.just(rule), st.fixed_dictionaries(rule.arguments)) + for rule in machine._initialize_rules_to_run + ] + rule, data = cd.draw(st.one_of(init_rules)) + machine._initialize_rules_to_run.remove(rule) + else: + rule, data = cd.draw(machine._rules_strategy) + draw_label = f"generate:rule:{rule.function.__name__}" + cd.draw_times.setdefault(draw_label, 0.0) + cd.draw_times[draw_label] += perf_counter() - start_draw + + # Pretty-print the values this rule was called with *before* calling + # _add_result_to_targets, to avoid printing arguments which are also + # a return value using the variable name they are assigned to. + # See https://github.com/HypothesisWorks/hypothesis/issues/2341 + if print_steps or TESTCASE_CALLBACKS: + data_to_print = { + k: machine._pretty_print(v) for k, v in data.items() + } + + # Assign 'result' here in case executing the rule fails below + result = multiple() + try: + data = dict(data) + for k, v in list(data.items()): + if isinstance(v, VarReference): + data[k] = machine.names_to_values[v.name] + + label = f"execute:rule:{rule.function.__name__}" + start = perf_counter() + result = rule.function(machine, **data) + cd._stateful_run_times[label] += perf_counter() - start + + if rule.targets: + if isinstance(result, MultipleResults): + for single_result in result.values: + machine._add_result_to_targets( + rule.targets, single_result + ) + else: + machine._add_result_to_targets(rule.targets, result) + elif result is not None: + fail_health_check( + settings, + "Rules should return None if they have no target bundle, " + f"but {rule.function.__qualname__} returned {result!r}", + HealthCheck.return_value, + ) + finally: + if print_steps or TESTCASE_CALLBACKS: + # 'result' is only used if the step has target bundles. + # If it does, and the result is a 'MultipleResult', + # then 'print_step' prints a multi-variable assignment. + output(machine._repr_step(rule, data_to_print, result)) + machine.check_invariants(settings, output, cd._stateful_run_times) + cd.stop_example() + finally: + output("state.teardown()") + machine.teardown() + + # Use a machine digest to identify stateful tests in the example database + run_state_machine.hypothesis.inner_test._hypothesis_internal_add_digest = ( + function_digest(state_machine_factory) + ) + # Copy some attributes so @seed and @reproduce_failure "just work" + run_state_machine._hypothesis_internal_use_seed = getattr( + state_machine_factory, "_hypothesis_internal_use_seed", None + ) + run_state_machine._hypothesis_internal_use_reproduce_failure = getattr( + state_machine_factory, "_hypothesis_internal_use_reproduce_failure", None + ) + run_state_machine._hypothesis_internal_print_given_args = False + + run_state_machine(state_machine_factory) + + +class StateMachineMeta(type): + def __setattr__(cls, name, value): + if name == "settings" and isinstance(value, Settings): + descr = f"settings({value.show_changed()})" + raise AttributeError( + f"Assigning {cls.__name__}.settings = {descr} does nothing. Assign " + f"to {cls.__name__}.TestCase.settings, or use @{descr} as a decorator " + f"on the {cls.__name__} class." + ) + return super().__setattr__(name, value) + + +class RuleBasedStateMachine(metaclass=StateMachineMeta): + """A RuleBasedStateMachine gives you a structured way to define state machines. + + The idea is that a state machine carries the system under test and some supporting + data. This data can be stored in instance variables or + divided into Bundles. The state machine has a set of rules which may read data + from bundles (or just from normal strategies), push data onto + bundles, change the state of the machine, or verify properties. + At any given point a random applicable rule will be executed. + """ + + _rules_per_class: ClassVar[Dict[type, List[classmethod]]] = {} + _invariants_per_class: ClassVar[Dict[type, List[classmethod]]] = {} + _initializers_per_class: ClassVar[Dict[type, List[classmethod]]] = {} + + def __init__(self) -> None: + if not self.rules(): + raise InvalidDefinition(f"Type {type(self).__name__} defines no rules") + self.bundles: Dict[str, list] = {} + self.names_counters: collections.Counter = collections.Counter() + self.names_list: list[str] = [] + self.names_to_values: Dict[str, Any] = {} + self.__stream = StringIO() + self.__printer = RepresentationPrinter( + self.__stream, context=_current_build_context.value + ) + self._initialize_rules_to_run = copy(self.initialize_rules()) + self._rules_strategy = RuleStrategy(self) + + if isinstance(s := vars(type(self)).get("settings"), Settings): + tname = type(self).__name__ + descr = f"settings({s.show_changed()})" + raise InvalidDefinition( + f"Assigning settings = {descr} as a class attribute does nothing. " + f"Assign to {tname}.TestCase.settings, or use @{descr} as a decorator " + f"on the {tname} class." + ) + + def _pretty_print(self, value): + if isinstance(value, VarReference): + return value.name + self.__stream.seek(0) + self.__stream.truncate(0) + self.__printer.output_width = 0 + self.__printer.buffer_width = 0 + self.__printer.buffer.clear() + self.__printer.pretty(value) + self.__printer.flush() + return self.__stream.getvalue() + + def __repr__(self): + return f"{type(self).__name__}({nicerepr(self.bundles)})" + + def _new_name(self, target): + result = f"{target}_{self.names_counters[target]}" + self.names_counters[target] += 1 + self.names_list.append(result) + return result + + def _last_names(self, n): + len_ = len(self.names_list) + assert len_ >= n + return self.names_list[len_ - n :] + + def bundle(self, name): + return self.bundles.setdefault(name, []) + + @classmethod + def initialize_rules(cls): + try: + return cls._initializers_per_class[cls] + except KeyError: + pass + + cls._initializers_per_class[cls] = [] + for _, v in inspect.getmembers(cls): + r = getattr(v, INITIALIZE_RULE_MARKER, None) + if r is not None: + cls._initializers_per_class[cls].append(r) + return cls._initializers_per_class[cls] + + @classmethod + def rules(cls): + try: + return cls._rules_per_class[cls] + except KeyError: + pass + + cls._rules_per_class[cls] = [] + for _, v in inspect.getmembers(cls): + r = getattr(v, RULE_MARKER, None) + if r is not None: + cls._rules_per_class[cls].append(r) + return cls._rules_per_class[cls] + + @classmethod + def invariants(cls): + try: + return cls._invariants_per_class[cls] + except KeyError: + pass + + target = [] + for _, v in inspect.getmembers(cls): + i = getattr(v, INVARIANT_MARKER, None) + if i is not None: + target.append(i) + cls._invariants_per_class[cls] = target + return cls._invariants_per_class[cls] + + def _repr_step(self, rule, data, result): + output_assignment = "" + if rule.targets: + if isinstance(result, MultipleResults): + if len(result.values) == 1: + output_assignment = f"({self._last_names(1)[0]},) = " + elif result.values: + number_of_last_names = len(rule.targets) * len(result.values) + output_names = self._last_names(number_of_last_names) + output_assignment = ", ".join(output_names) + " = " + else: + output_assignment = self._last_names(1)[0] + " = " + args = ", ".join("%s=%s" % kv for kv in data.items()) + return f"{output_assignment}state.{rule.function.__name__}({args})" + + def _add_result_to_targets(self, targets, result): + for target in targets: + name = self._new_name(target) + + def printer(obj, p, cycle, name=name): + return p.text(name) + + self.__printer.singleton_pprinters.setdefault(id(result), printer) + self.names_to_values[name] = result + self.bundles.setdefault(target, []).append(VarReference(name)) + + def check_invariants(self, settings, output, runtimes): + for invar in self.invariants(): + if self._initialize_rules_to_run and not invar.check_during_init: + continue + if not all(precond(self) for precond in invar.preconditions): + continue + name = invar.function.__name__ + if ( + current_build_context().is_final + or settings.verbosity >= Verbosity.debug + or TESTCASE_CALLBACKS + ): + output(f"state.{name}()") + start = perf_counter() + result = invar.function(self) + runtimes[f"execute:invariant:{name}"] += perf_counter() - start + if result is not None: + fail_health_check( + settings, + "The return value of an @invariant is always ignored, but " + f"{invar.function.__qualname__} returned {result!r} " + "instead of None", + HealthCheck.return_value, + ) + + def teardown(self): + """Called after a run has finished executing to clean up any necessary + state. + + Does nothing by default. + """ + + TestCase = TestCaseProperty() + + @classmethod + @lru_cache + def _to_test_case(cls): + class StateMachineTestCase(TestCase): + settings = Settings(deadline=None, suppress_health_check=list(HealthCheck)) + + def runTest(self): + run_state_machine_as_test(cls, settings=self.settings) + + runTest.is_hypothesis_test = True + + StateMachineTestCase.__name__ = cls.__name__ + ".TestCase" + StateMachineTestCase.__qualname__ = cls.__qualname__ + ".TestCase" + return StateMachineTestCase + + +@attr.s(repr=False) +class Rule: + targets = attr.ib() + function = attr.ib(repr=get_pretty_function_description) + arguments = attr.ib() + preconditions = attr.ib() + bundles = attr.ib(init=False) + + def __attrs_post_init__(self): + self.arguments_strategies = {} + bundles = [] + for k, v in sorted(self.arguments.items()): + assert not isinstance(v, BundleReferenceStrategy) + if isinstance(v, Bundle): + bundles.append(v) + consume = isinstance(v, BundleConsumer) + v = BundleReferenceStrategy(v.name, consume=consume) + self.arguments_strategies[k] = v + self.bundles = tuple(bundles) + + def __repr__(self) -> str: + rep = get_pretty_function_description + bits = [f"{k}={rep(v)}" for k, v in attr.asdict(self).items() if v] + return f"{self.__class__.__name__}({', '.join(bits)})" + + +self_strategy = st.runner() + + +class BundleReferenceStrategy(SearchStrategy): + def __init__(self, name: str, *, consume: bool = False): + self.name = name + self.consume = consume + + def do_draw(self, data): + machine = data.draw(self_strategy) + bundle = machine.bundle(self.name) + if not bundle: + data.mark_invalid(f"Cannot draw from empty bundle {self.name!r}") + # Shrink towards the right rather than the left. This makes it easier + # to delete data generated earlier, as when the error is towards the + # end there can be a lot of hard to remove padding. + position = data.draw_integer(0, len(bundle) - 1, shrink_towards=len(bundle)) + if self.consume: + return bundle.pop(position) # pragma: no cover # coverage is flaky here + else: + return bundle[position] + + +class Bundle(SearchStrategy[Ex]): + """A collection of values for use in stateful testing. + + Bundles are a kind of strategy where values can be added by rules, + and (like any strategy) used as inputs to future rules. + + The ``name`` argument they are passed is the they are referred to + internally by the state machine; no two bundles may have + the same name. It is idiomatic to use the attribute + being assigned to as the name of the Bundle:: + + class MyStateMachine(RuleBasedStateMachine): + keys = Bundle("keys") + + Bundles can contain the same value more than once; this becomes + relevant when using :func:`~hypothesis.stateful.consumes` to remove + values again. + + If the ``consume`` argument is set to True, then all values that are + drawn from this bundle will be consumed (as above) when requested. + """ + + def __init__(self, name: str, *, consume: bool = False) -> None: + self.name = name + self.__reference_strategy = BundleReferenceStrategy(name, consume=consume) + + def do_draw(self, data): + machine = data.draw(self_strategy) + reference = data.draw(self.__reference_strategy) + return machine.names_to_values[reference.name] + + def __repr__(self): + consume = self.__reference_strategy.consume + if consume is False: + return f"Bundle(name={self.name!r})" + return f"Bundle(name={self.name!r}, {consume=})" + + def calc_is_empty(self, recur): + # We assume that a bundle will grow over time + return False + + def available(self, data): + # ``self_strategy`` is an instance of the ``st.runner()`` strategy. + # Hence drawing from it only returns the current state machine without + # modifying the underlying buffer. + machine = data.draw(self_strategy) + return bool(machine.bundle(self.name)) + + +class BundleConsumer(Bundle[Ex]): + def __init__(self, bundle: Bundle[Ex]) -> None: + super().__init__(bundle.name, consume=True) + + +def consumes(bundle: Bundle[Ex]) -> SearchStrategy[Ex]: + """When introducing a rule in a RuleBasedStateMachine, this function can + be used to mark bundles from which each value used in a step with the + given rule should be removed. This function returns a strategy object + that can be manipulated and combined like any other. + + For example, a rule declared with + + ``@rule(value1=b1, value2=consumes(b2), value3=lists(consumes(b3)))`` + + will consume a value from Bundle ``b2`` and several values from Bundle + ``b3`` to populate ``value2`` and ``value3`` each time it is executed. + """ + if not isinstance(bundle, Bundle): + raise TypeError("Argument to be consumed must be a bundle.") + return BundleConsumer(bundle) + + +@attr.s() +class MultipleResults(Iterable[Ex]): + values = attr.ib() + + def __iter__(self): + return iter(self.values) + + +# We need to use an invariant typevar here to avoid a mypy error, as covariant +# typevars cannot be used as parameters. +def multiple(*args: Ex_Inv) -> MultipleResults[Ex_Inv]: + """This function can be used to pass multiple results to the target(s) of + a rule. Just use ``return multiple(result1, result2, ...)`` in your rule. + + It is also possible to use ``return multiple()`` with no arguments in + order to end a rule without passing any result. + """ + return MultipleResults(args) + + +def _convert_targets(targets, target): + """Single validator and converter for target arguments.""" + if target is not None: + if targets: + raise InvalidArgument( + "Passing both targets=%r and target=%r is redundant - pass " + "targets=%r instead." % (targets, target, (*targets, target)) + ) + targets = (target,) + + converted_targets = [] + for t in targets: + if not isinstance(t, Bundle): + msg = "Got invalid target %r of type %r, but all targets must be Bundles." + if isinstance(t, OneOfStrategy): + msg += ( + "\nIt looks like you passed `one_of(a, b)` or `a | b` as " + "a target. You should instead pass `targets=(a, b)` to " + "add the return value of this rule to both the `a` and " + "`b` bundles, or define a rule for each target if it " + "should be added to exactly one." + ) + raise InvalidArgument(msg % (t, type(t))) + while isinstance(t, Bundle): + if isinstance(t, BundleConsumer): + note_deprecation( + f"Using consumes({t.name}) doesn't makes sense in this context. " + "This will be an error in a future version of Hypothesis.", + since="2021-09-08", + has_codemod=False, + stacklevel=2, + ) + t = t.name + converted_targets.append(t) + return tuple(converted_targets) + + +RULE_MARKER = "hypothesis_stateful_rule" +INITIALIZE_RULE_MARKER = "hypothesis_stateful_initialize_rule" +PRECONDITIONS_MARKER = "hypothesis_stateful_preconditions" +INVARIANT_MARKER = "hypothesis_stateful_invariant" + + +_RuleType = Callable[..., Union[MultipleResults[Ex], Ex]] +_RuleWrapper = Callable[[_RuleType[Ex]], _RuleType[Ex]] + + +# We cannot exclude `target` or `targets` from any of these signatures because +# otherwise they would be matched against the `kwargs`, either leading to +# overlapping overloads of incompatible return types, or a concrete +# implementation that does not accept all overloaded variant signatures. +# Although it is possible to reorder the variants to fix the former, it will +# always lead to the latter, as then the omitted parameter could be typed as +# a `SearchStrategy`, which the concrete implementation does not accept. +# +# Omitted `targets` parameters, where the default value is used, are typed with +# a special `_OmittedArgument` type. We cannot type them as `Tuple[()]`, because +# `Tuple[()]` is a subtype of `Sequence[Bundle[Ex]]`, leading to signature +# overlaps with incompatible return types. The `_OmittedArgument` type will never be +# encountered at runtime, and exists solely to annotate the default of `targets`. +# PEP 661 (Sentinel Values) might provide a more elegant alternative in the future. +# +# We could've also annotated `targets` as `Tuple[_OmittedArgument]`, but then when +# both `target` and `targets` are provided, mypy describes the type error as an +# invalid argument type for `targets` (expected `Tuple[_OmittedArgument]`, got ...). +# By annotating it as a bare `_OmittedArgument` type, mypy's error will warn that +# there is no overloaded signature matching the call, which is more descriptive. +# +# When `target` xor `targets` is provided, the function to decorate must return +# a value whose type matches the one stored in the bundle. When neither are +# provided, the function to decorate must return nothing. There is no variant +# for providing `target` and `targets`, as these parameters are mutually exclusive. +@overload +def rule( + *, + targets: Sequence[Bundle[Ex]], + target: None = ..., + **kwargs: SearchStrategy, +) -> _RuleWrapper[Ex]: # pragma: no cover + ... + + +@overload +def rule( + *, target: Bundle[Ex], targets: _OmittedArgument = ..., **kwargs: SearchStrategy +) -> _RuleWrapper[Ex]: # pragma: no cover + ... + + +@overload +def rule( + *, + target: None = ..., + targets: _OmittedArgument = ..., + **kwargs: SearchStrategy, +) -> Callable[[Callable[..., None]], Callable[..., None]]: # pragma: no cover + ... + + +def rule( + *, + targets: Union[Sequence[Bundle[Ex]], _OmittedArgument] = (), + target: Optional[Bundle[Ex]] = None, + **kwargs: SearchStrategy, +) -> Union[_RuleWrapper[Ex], Callable[[Callable[..., None]], Callable[..., None]]]: + """Decorator for RuleBasedStateMachine. Any Bundle present in ``target`` or + ``targets`` will define where the end result of this function should go. If + both are empty then the end result will be discarded. + + ``target`` must be a Bundle, or if the result should be replicated to multiple + bundles you can pass a tuple of them as the ``targets`` argument. + It is invalid to use both arguments for a single rule. If the result + should go to exactly one of several bundles, define a separate rule for + each case. + + kwargs then define the arguments that will be passed to the function + invocation. If their value is a Bundle, or if it is ``consumes(b)`` + where ``b`` is a Bundle, then values that have previously been produced + for that bundle will be provided. If ``consumes`` is used, the value + will also be removed from the bundle. + + Any other kwargs should be strategies and values from them will be + provided. + """ + converted_targets = _convert_targets(targets, target) + for k, v in kwargs.items(): + check_strategy(v, name=k) + + def accept(f): + if getattr(f, INVARIANT_MARKER, None): + raise InvalidDefinition( + "A function cannot be used for both a rule and an invariant.", + Settings.default, + ) + existing_rule = getattr(f, RULE_MARKER, None) + existing_initialize_rule = getattr(f, INITIALIZE_RULE_MARKER, None) + if existing_rule is not None or existing_initialize_rule is not None: + raise InvalidDefinition( + "A function cannot be used for two distinct rules. ", Settings.default + ) + preconditions = getattr(f, PRECONDITIONS_MARKER, ()) + rule = Rule( + targets=converted_targets, + arguments=kwargs, + function=f, + preconditions=preconditions, + ) + + @proxies(f) + def rule_wrapper(*args, **kwargs): + return f(*args, **kwargs) + + setattr(rule_wrapper, RULE_MARKER, rule) + return rule_wrapper + + return accept + + +# See also comments of `rule`'s overloads. +@overload +def initialize( + *, + targets: Sequence[Bundle[Ex]], + target: None = ..., + **kwargs: SearchStrategy, +) -> _RuleWrapper[Ex]: # pragma: no cover + ... + + +@overload +def initialize( + *, target: Bundle[Ex], targets: _OmittedArgument = ..., **kwargs: SearchStrategy +) -> _RuleWrapper[Ex]: # pragma: no cover + ... + + +@overload +def initialize( + *, + target: None = ..., + targets: _OmittedArgument = ..., + **kwargs: SearchStrategy, +) -> Callable[[Callable[..., None]], Callable[..., None]]: # pragma: no cover + ... + + +def initialize( + *, + targets: Union[Sequence[Bundle[Ex]], _OmittedArgument] = (), + target: Optional[Bundle[Ex]] = None, + **kwargs: SearchStrategy, +) -> Union[_RuleWrapper[Ex], Callable[[Callable[..., None]], Callable[..., None]]]: + """Decorator for RuleBasedStateMachine. + + An initialize decorator behaves like a rule, but all ``@initialize()`` decorated + methods will be called before any ``@rule()`` decorated methods, in an arbitrary + order. Each ``@initialize()`` method will be called exactly once per run, unless + one raises an exception - after which only the ``.teardown()`` method will be run. + ``@initialize()`` methods may not have preconditions. + """ + converted_targets = _convert_targets(targets, target) + for k, v in kwargs.items(): + check_strategy(v, name=k) + + def accept(f): + if getattr(f, INVARIANT_MARKER, None): + raise InvalidDefinition( + "A function cannot be used for both a rule and an invariant.", + Settings.default, + ) + existing_rule = getattr(f, RULE_MARKER, None) + existing_initialize_rule = getattr(f, INITIALIZE_RULE_MARKER, None) + if existing_rule is not None or existing_initialize_rule is not None: + raise InvalidDefinition( + "A function cannot be used for two distinct rules. ", Settings.default + ) + preconditions = getattr(f, PRECONDITIONS_MARKER, ()) + if preconditions: + raise InvalidDefinition( + "An initialization rule cannot have a precondition. ", Settings.default + ) + rule = Rule( + targets=converted_targets, + arguments=kwargs, + function=f, + preconditions=preconditions, + ) + + @proxies(f) + def rule_wrapper(*args, **kwargs): + return f(*args, **kwargs) + + setattr(rule_wrapper, INITIALIZE_RULE_MARKER, rule) + return rule_wrapper + + return accept + + +@attr.s() +class VarReference: + name = attr.ib() + + +# There are multiple alternatives for annotating the `precond` type, all of them +# have drawbacks. See https://github.com/HypothesisWorks/hypothesis/pull/3068#issuecomment-906642371 +def precondition(precond: Callable[[Any], bool]) -> Callable[[TestFunc], TestFunc]: + """Decorator to apply a precondition for rules in a RuleBasedStateMachine. + Specifies a precondition for a rule to be considered as a valid step in the + state machine, which is more efficient than using :func:`~hypothesis.assume` + within the rule. The ``precond`` function will be called with the instance of + RuleBasedStateMachine and should return True or False. Usually it will need + to look at attributes on that instance. + + For example:: + + class MyTestMachine(RuleBasedStateMachine): + state = 1 + + @precondition(lambda self: self.state != 0) + @rule(numerator=integers()) + def divide_with(self, numerator): + self.state = numerator / self.state + + If multiple preconditions are applied to a single rule, it is only considered + a valid step when all of them return True. Preconditions may be applied to + invariants as well as rules. + """ + + def decorator(f): + @proxies(f) + def precondition_wrapper(*args, **kwargs): + return f(*args, **kwargs) + + existing_initialize_rule = getattr(f, INITIALIZE_RULE_MARKER, None) + if existing_initialize_rule is not None: + raise InvalidDefinition( + "An initialization rule cannot have a precondition. ", Settings.default + ) + + rule = getattr(f, RULE_MARKER, None) + invariant = getattr(f, INVARIANT_MARKER, None) + if rule is not None: + assert invariant is None + new_rule = attr.evolve(rule, preconditions=(*rule.preconditions, precond)) + setattr(precondition_wrapper, RULE_MARKER, new_rule) + elif invariant is not None: + assert rule is None + new_invariant = attr.evolve( + invariant, preconditions=(*invariant.preconditions, precond) + ) + setattr(precondition_wrapper, INVARIANT_MARKER, new_invariant) + else: + setattr( + precondition_wrapper, + PRECONDITIONS_MARKER, + (*getattr(f, PRECONDITIONS_MARKER, ()), precond), + ) + + return precondition_wrapper + + return decorator + + +@attr.s() +class Invariant: + function = attr.ib(repr=get_pretty_function_description) + preconditions = attr.ib() + check_during_init = attr.ib() + + +def invariant(*, check_during_init: bool = False) -> Callable[[TestFunc], TestFunc]: + """Decorator to apply an invariant for rules in a RuleBasedStateMachine. + The decorated function will be run after every rule and can raise an + exception to indicate failed invariants. + + For example:: + + class MyTestMachine(RuleBasedStateMachine): + state = 1 + + @invariant() + def is_nonzero(self): + assert self.state != 0 + + By default, invariants are only checked after all + :func:`@initialize() ` rules have been run. + Pass ``check_during_init=True`` for invariants which can also be checked + during initialization. + """ + check_type(bool, check_during_init, "check_during_init") + + def accept(f): + if getattr(f, RULE_MARKER, None) or getattr(f, INITIALIZE_RULE_MARKER, None): + raise InvalidDefinition( + "A function cannot be used for both a rule and an invariant.", + Settings.default, + ) + existing_invariant = getattr(f, INVARIANT_MARKER, None) + if existing_invariant is not None: + raise InvalidDefinition( + "A function cannot be used for two distinct invariants.", + Settings.default, + ) + preconditions = getattr(f, PRECONDITIONS_MARKER, ()) + invar = Invariant( + function=f, + preconditions=preconditions, + check_during_init=check_during_init, + ) + + @proxies(f) + def invariant_wrapper(*args, **kwargs): + return f(*args, **kwargs) + + setattr(invariant_wrapper, INVARIANT_MARKER, invar) + return invariant_wrapper + + return accept + + +LOOP_LABEL = cu.calc_label_from_name("RuleStrategy loop iteration") + + +class RuleStrategy(SearchStrategy): + def __init__(self, machine): + super().__init__() + self.machine = machine + self.rules = list(machine.rules()) + + self.enabled_rules_strategy = st.shared( + FeatureStrategy(at_least_one_of={r.function.__name__ for r in self.rules}), + key=("enabled rules", machine), + ) + + # The order is a bit arbitrary. Primarily we're trying to group rules + # that write to the same location together, and to put rules with no + # target first as they have less effect on the structure. We order from + # fewer to more arguments on grounds that it will plausibly need less + # data. This probably won't work especially well and we could be + # smarter about it, but it's better than just doing it in definition + # order. + self.rules.sort( + key=lambda rule: ( + sorted(rule.targets), + len(rule.arguments), + rule.function.__name__, + ) + ) + + def __repr__(self): + return f"{self.__class__.__name__}(machine={self.machine.__class__.__name__}({{...}}))" + + def do_draw(self, data): + if not any(self.is_valid(rule) for rule in self.rules): + msg = f"No progress can be made from state {self.machine!r}" + raise InvalidDefinition(msg) from None + + feature_flags = data.draw(self.enabled_rules_strategy) + + def rule_is_enabled(r): + # Note: The order of the filters here is actually quite important, + # because checking is_enabled makes choices, so increases the size of + # the choice sequence. This means that if we are in a case where many + # rules are invalid we would make a lot more choices if we ask if they + # are enabled before we ask if they are valid, so our test cases would + # be artificially large. + return self.is_valid(r) and feature_flags.is_enabled(r.function.__name__) + + rule = data.draw(st.sampled_from(self.rules).filter(rule_is_enabled)) + + arguments = {} + for k, strat in rule.arguments_strategies.items(): + try: + arguments[k] = data.draw(strat) + except Exception as err: + rname = rule.function.__name__ + add_note(err, f"while generating {k!r} from {strat!r} for rule {rname}") + raise + return (rule, arguments) + + def is_valid(self, rule): + predicates = self.machine._observability_predicates + desc = f"{self.machine.__class__.__qualname__}, rule {rule.function.__name__}," + for pred in rule.preconditions: + meets_precond = pred(self.machine) + where = f"{desc} precondition {get_pretty_function_description(pred)}" + predicates[where]["satisfied" if meets_precond else "unsatisfied"] += 1 + if not meets_precond: + return False + + for b in rule.bundles: + bundle = self.machine.bundle(b.name) + if not bundle: + return False + return True diff --git a/shared/package-files/01/0123e78b73cf563d490f271124d9ca4bfc87e9b7994085291336457cd8697456/blob b/shared/package-files/01/0123e78b73cf563d490f271124d9ca4bfc87e9b7994085291336457cd8697456/blob new file mode 100644 index 0000000000000000000000000000000000000000..4cf19034dd55ae9c2ece9208e984880874b8ed15 --- /dev/null +++ b/shared/package-files/01/0123e78b73cf563d490f271124d9ca4bfc87e9b7994085291336457cd8697456/blob @@ -0,0 +1,39 @@ +#pragma once + +// @generated by torchgen/gen.py from Function.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + + +#include + +namespace at { + + +// aten::_addmm_activation.out(Tensor self, Tensor mat1, Tensor mat2, *, Scalar beta=1, Scalar alpha=1, bool use_gelu=False, Tensor(a!) out) -> Tensor(a!) +inline at::Tensor & _addmm_activation_out(at::Tensor & out, const at::Tensor & self, const at::Tensor & mat1, const at::Tensor & mat2, const at::Scalar & beta=1, const at::Scalar & alpha=1, bool use_gelu=false) { + return at::_ops::_addmm_activation_out::call(self, mat1, mat2, beta, alpha, use_gelu, out); +} +// aten::_addmm_activation.out(Tensor self, Tensor mat1, Tensor mat2, *, Scalar beta=1, Scalar alpha=1, bool use_gelu=False, Tensor(a!) out) -> Tensor(a!) +inline at::Tensor & _addmm_activation_outf(const at::Tensor & self, const at::Tensor & mat1, const at::Tensor & mat2, const at::Scalar & beta, const at::Scalar & alpha, bool use_gelu, at::Tensor & out) { + return at::_ops::_addmm_activation_out::call(self, mat1, mat2, beta, alpha, use_gelu, out); +} + +// aten::_addmm_activation(Tensor self, Tensor mat1, Tensor mat2, *, Scalar beta=1, Scalar alpha=1, bool use_gelu=False) -> Tensor +inline at::Tensor _addmm_activation(const at::Tensor & self, const at::Tensor & mat1, const at::Tensor & mat2, const at::Scalar & beta=1, const at::Scalar & alpha=1, bool use_gelu=false) { + return at::_ops::_addmm_activation::call(self, mat1, mat2, beta, alpha, use_gelu); +} + +} diff --git a/shared/package-files/01/012572c99c622482f0edb4c8555a49c7c276f773371e4e45df78a51a7d1ef347/blob b/shared/package-files/01/012572c99c622482f0edb4c8555a49c7c276f773371e4e45df78a51a7d1ef347/blob new file mode 100644 index 0000000000000000000000000000000000000000..fe61e8116b71e073351939ed7a499ee752398f1c --- /dev/null +++ b/shared/package-files/01/012572c99c622482f0edb4c8555a49c7c276f773371e4e45df78a51a7d1ef347/blob @@ -0,0 +1,132 @@ +import itertools +import logging +import os +import posixpath +import urllib.parse +from typing import List + +from pip._vendor.packaging.utils import canonicalize_name + +from pip._internal.models.index import PyPI +from pip._internal.utils.compat import has_tls +from pip._internal.utils.misc import normalize_path, redact_auth_from_url + +logger = logging.getLogger(__name__) + + +class SearchScope: + + """ + Encapsulates the locations that pip is configured to search. + """ + + __slots__ = ["find_links", "index_urls", "no_index"] + + @classmethod + def create( + cls, + find_links: List[str], + index_urls: List[str], + no_index: bool, + ) -> "SearchScope": + """ + Create a SearchScope object after normalizing the `find_links`. + """ + # Build find_links. If an argument starts with ~, it may be + # a local file relative to a home directory. So try normalizing + # it and if it exists, use the normalized version. + # This is deliberately conservative - it might be fine just to + # blindly normalize anything starting with a ~... + built_find_links: List[str] = [] + for link in find_links: + if link.startswith("~"): + new_link = normalize_path(link) + if os.path.exists(new_link): + link = new_link + built_find_links.append(link) + + # If we don't have TLS enabled, then WARN if anyplace we're looking + # relies on TLS. + if not has_tls(): + for link in itertools.chain(index_urls, built_find_links): + parsed = urllib.parse.urlparse(link) + if parsed.scheme == "https": + logger.warning( + "pip is configured with locations that require " + "TLS/SSL, however the ssl module in Python is not " + "available." + ) + break + + return cls( + find_links=built_find_links, + index_urls=index_urls, + no_index=no_index, + ) + + def __init__( + self, + find_links: List[str], + index_urls: List[str], + no_index: bool, + ) -> None: + self.find_links = find_links + self.index_urls = index_urls + self.no_index = no_index + + def get_formatted_locations(self) -> str: + lines = [] + redacted_index_urls = [] + if self.index_urls and self.index_urls != [PyPI.simple_url]: + for url in self.index_urls: + redacted_index_url = redact_auth_from_url(url) + + # Parse the URL + purl = urllib.parse.urlsplit(redacted_index_url) + + # URL is generally invalid if scheme and netloc is missing + # there are issues with Python and URL parsing, so this test + # is a bit crude. See bpo-20271, bpo-23505. Python doesn't + # always parse invalid URLs correctly - it should raise + # exceptions for malformed URLs + if not purl.scheme and not purl.netloc: + logger.warning( + 'The index url "%s" seems invalid, please provide a scheme.', + redacted_index_url, + ) + + redacted_index_urls.append(redacted_index_url) + + lines.append( + "Looking in indexes: {}".format(", ".join(redacted_index_urls)) + ) + + if self.find_links: + lines.append( + "Looking in links: {}".format( + ", ".join(redact_auth_from_url(url) for url in self.find_links) + ) + ) + return "\n".join(lines) + + def get_index_urls_locations(self, project_name: str) -> List[str]: + """Returns the locations found via self.index_urls + + Checks the url_name on the main (first in the list) index and + use this url_name to produce all locations + """ + + def mkurl_pypi_url(url: str) -> str: + loc = posixpath.join( + url, urllib.parse.quote(canonicalize_name(project_name)) + ) + # For maximum compatibility with easy_install, ensure the path + # ends in a trailing slash. Although this isn't in the spec + # (and PyPI can handle it without the slash) some other index + # implementations might break if they relied on easy_install's + # behavior. + if not loc.endswith("/"): + loc = loc + "/" + return loc + + return [mkurl_pypi_url(url) for url in self.index_urls] diff --git a/shared/package-files/01/0126edd507c28db6ebd58d149616f124c7b67c1f9a4548909274a09e149ce761/blob b/shared/package-files/01/0126edd507c28db6ebd58d149616f124c7b67c1f9a4548909274a09e149ce761/blob new file mode 100644 index 0000000000000000000000000000000000000000..0bc1f2ea7b141a270a7b5f826442d96d9841e72c --- /dev/null +++ b/shared/package-files/01/0126edd507c28db6ebd58d149616f124c7b67c1f9a4548909274a09e149ce761/blob @@ -0,0 +1,53 @@ +#pragma once + +#include + +#include +#include + +namespace torch { +namespace data { +namespace transforms { + +/// A transformation of a batch to a new batch. +template +class BatchTransform { + public: + using InputBatchType = InputBatch; + using OutputBatchType = OutputBatch; + + virtual ~BatchTransform() = default; + + /// Applies the transformation to the given `input_batch`. + virtual OutputBatch apply_batch(InputBatch input_batch) = 0; +}; + +/// A transformation of individual input examples to individual output examples. +/// +/// Just like a `Dataset` is a `BatchDataset`, a `Transform` is a +/// `BatchTransform` that can operate on the level of individual examples rather +/// than entire batches. The batch-level transform is implemented (by default) +/// in terms of the example-level transform, though this can be customized. +template +class Transform + : public BatchTransform, std::vector> { + public: + using InputType = Input; + using OutputType = Output; + + /// Applies the transformation to the given `input`. + virtual OutputType apply(InputType input) = 0; + + /// Applies the `transformation` over the entire `input_batch`. + std::vector apply_batch(std::vector input_batch) override { + std::vector output_batch; + output_batch.reserve(input_batch.size()); + for (auto&& input : input_batch) { + output_batch.push_back(apply(std::move(input))); + } + return output_batch; + } +}; +} // namespace transforms +} // namespace data +} // namespace torch diff --git a/shared/package-files/01/012809e03a3669c09f681f273d2b8e18a3914553c534db41353828b2686b3299/blob b/shared/package-files/01/012809e03a3669c09f681f273d2b8e18a3914553c534db41353828b2686b3299/blob new file mode 100644 index 0000000000000000000000000000000000000000..faa4335faa8a175810200a3fa1b018a032d98804 --- /dev/null +++ b/shared/package-files/01/012809e03a3669c09f681f273d2b8e18a3914553c534db41353828b2686b3299/blob @@ -0,0 +1,338 @@ +"""Implementation of magic functions related to History. +""" +#----------------------------------------------------------------------------- +# Copyright (c) 2012, IPython Development Team. +# +# Distributed under the terms of the Modified BSD License. +# +# The full license is in the file COPYING.txt, distributed with this software. +#----------------------------------------------------------------------------- + +#----------------------------------------------------------------------------- +# Imports +#----------------------------------------------------------------------------- + +# Stdlib +import os +import sys +from io import open as io_open +import fnmatch + +# Our own packages +from IPython.core.error import StdinNotImplementedError +from IPython.core.magic import Magics, magics_class, line_magic +from IPython.core.magic_arguments import (argument, magic_arguments, + parse_argstring) +from IPython.testing.skipdoctest import skip_doctest +from IPython.utils import io + +#----------------------------------------------------------------------------- +# Magics class implementation +#----------------------------------------------------------------------------- + + +_unspecified = object() + + +@magics_class +class HistoryMagics(Magics): + + @magic_arguments() + @argument( + '-n', dest='print_nums', action='store_true', default=False, + help=""" + print line numbers for each input. + This feature is only available if numbered prompts are in use. + """) + @argument( + '-o', dest='get_output', action='store_true', default=False, + help="also print outputs for each input.") + @argument( + '-p', dest='pyprompts', action='store_true', default=False, + help=""" + print classic '>>>' python prompts before each input. + This is useful for making documentation, and in conjunction + with -o, for producing doctest-ready output. + """) + @argument( + '-t', dest='raw', action='store_false', default=True, + help=""" + print the 'translated' history, as IPython understands it. + IPython filters your input and converts it all into valid Python + source before executing it (things like magics or aliases are turned + into function calls, for example). With this option, you'll see the + native history instead of the user-entered version: '%%cd /' will be + seen as 'get_ipython().run_line_magic("cd", "/")' instead of '%%cd /'. + """) + @argument( + '-f', dest='filename', + help=""" + FILENAME: instead of printing the output to the screen, redirect + it to the given file. The file is always overwritten, though *when + it can*, IPython asks for confirmation first. In particular, running + the command 'history -f FILENAME' from the IPython Notebook + interface will replace FILENAME even if it already exists *without* + confirmation. + """) + @argument( + '-g', dest='pattern', nargs='*', default=None, + help=""" + treat the arg as a glob pattern to search for in (full) history. + This includes the saved history (almost all commands ever written). + The pattern may contain '?' to match one unknown character and '*' + to match any number of unknown characters. Use '%%hist -g' to show + full saved history (may be very long). + """) + @argument( + '-l', dest='limit', type=int, nargs='?', default=_unspecified, + help=""" + get the last n lines from all sessions. Specify n as a single + arg, or the default is the last 10 lines. + """) + @argument( + '-u', dest='unique', action='store_true', + help=""" + when searching history using `-g`, show only unique history. + """) + @argument('range', nargs='*') + @skip_doctest + @line_magic + def history(self, parameter_s = ''): + """Print input history (_i variables), with most recent last. + + By default, input history is printed without line numbers so it can be + directly pasted into an editor. Use -n to show them. + + By default, all input history from the current session is displayed. + Ranges of history can be indicated using the syntax: + + ``4`` + Line 4, current session + ``4-6`` + Lines 4-6, current session + ``243/1-5`` + Lines 1-5, session 243 + ``~2/7`` + Line 7, session 2 before current + ``~8/1-~6/5`` + From the first line of 8 sessions ago, to the fifth line of 6 + sessions ago. + + Multiple ranges can be entered, separated by spaces + + The same syntax is used by %macro, %save, %edit, %rerun + + Examples + -------- + :: + + In [6]: %history -n 4-6 + 4:a = 12 + 5:print a**2 + 6:%history -n 4-6 + + """ + + args = parse_argstring(self.history, parameter_s) + + # For brevity + history_manager = self.shell.history_manager + + def _format_lineno(session, line): + """Helper function to format line numbers properly.""" + if session in (0, history_manager.session_number): + return str(line) + return "%s/%s" % (session, line) + + # Check if output to specific file was requested. + outfname = args.filename + if not outfname: + outfile = sys.stdout # default + # We don't want to close stdout at the end! + close_at_end = False + else: + outfname = os.path.expanduser(outfname) + if os.path.exists(outfname): + try: + ans = io.ask_yes_no("File %r exists. Overwrite?" % outfname) + except StdinNotImplementedError: + ans = True + if not ans: + print('Aborting.') + return + print("Overwriting file.") + outfile = io_open(outfname, 'w', encoding='utf-8') + close_at_end = True + + print_nums = args.print_nums + get_output = args.get_output + pyprompts = args.pyprompts + raw = args.raw + + pattern = None + limit = None if args.limit is _unspecified else args.limit + + range_pattern = False + if args.pattern is not None and not args.range: + if args.pattern: + pattern = "*" + " ".join(args.pattern) + "*" + else: + pattern = "*" + hist = history_manager.search(pattern, raw=raw, output=get_output, + n=limit, unique=args.unique) + print_nums = True + elif args.limit is not _unspecified: + n = 10 if limit is None else limit + hist = history_manager.get_tail(n, raw=raw, output=get_output) + else: + if args.pattern: + range_pattern = "*" + " ".join(args.pattern) + "*" + print_nums = True + hist = history_manager.get_range_by_str( + " ".join(args.range), raw, get_output + ) + + # We could be displaying the entire history, so let's not try to pull + # it into a list in memory. Anything that needs more space will just + # misalign. + width = 4 + + for session, lineno, inline in hist: + # Print user history with tabs expanded to 4 spaces. The GUI + # clients use hard tabs for easier usability in auto-indented code, + # but we want to produce PEP-8 compliant history for safe pasting + # into an editor. + if get_output: + inline, output = inline + if range_pattern: + if not fnmatch.fnmatch(inline, range_pattern): + continue + inline = inline.expandtabs(4).rstrip() + + multiline = "\n" in inline + line_sep = '\n' if multiline else ' ' + if print_nums: + print(u'%s:%s' % (_format_lineno(session, lineno).rjust(width), + line_sep), file=outfile, end=u'') + if pyprompts: + print(u">>> ", end=u"", file=outfile) + if multiline: + inline = "\n... ".join(inline.splitlines()) + "\n..." + print(inline, file=outfile) + if get_output and output: + print(output, file=outfile) + + if close_at_end: + outfile.close() + + @line_magic + def recall(self, arg): + r"""Repeat a command, or get command to input line for editing. + + %recall and %rep are equivalent. + + - %recall (no arguments): + + Place a string version of last computation result (stored in the + special '_' variable) to the next input prompt. Allows you to create + elaborate command lines without using copy-paste:: + + In[1]: l = ["hei", "vaan"] + In[2]: "".join(l) + Out[2]: heivaan + In[3]: %recall + In[4]: heivaan_ <== cursor blinking + + %recall 45 + + Place history line 45 on the next input prompt. Use %hist to find + out the number. + + %recall 1-4 + + Combine the specified lines into one cell, and place it on the next + input prompt. See %history for the slice syntax. + + %recall foo+bar + + If foo+bar can be evaluated in the user namespace, the result is + placed at the next input prompt. Otherwise, the history is searched + for lines which contain that substring, and the most recent one is + placed at the next input prompt. + """ + if not arg: # Last output + self.shell.set_next_input(str(self.shell.user_ns["_"])) + return + # Get history range + histlines = self.shell.history_manager.get_range_by_str(arg) + cmd = "\n".join(x[2] for x in histlines) + if cmd: + self.shell.set_next_input(cmd.rstrip()) + return + + try: # Variable in user namespace + cmd = str(eval(arg, self.shell.user_ns)) + except Exception: # Search for term in history + histlines = self.shell.history_manager.search("*"+arg+"*") + for h in reversed([x[2] for x in histlines]): + if 'recall' in h or 'rep' in h: + continue + self.shell.set_next_input(h.rstrip()) + return + else: + self.shell.set_next_input(cmd.rstrip()) + return + print("Couldn't evaluate or find in history:", arg) + + @line_magic + def rerun(self, parameter_s=''): + """Re-run previous input + + By default, you can specify ranges of input history to be repeated + (as with %history). With no arguments, it will repeat the last line. + + Options: + + -l : Repeat the last n lines of input, not including the + current command. + + -g foo : Repeat the most recent line which contains foo + """ + opts, args = self.parse_options(parameter_s, 'l:g:', mode='string') + if "l" in opts: # Last n lines + try: + n = int(opts["l"]) + except ValueError: + print("Number of lines must be an integer") + return + + if n == 0: + print("Requested 0 last lines - nothing to run") + return + elif n < 0: + print("Number of lines to rerun cannot be negative") + return + + hist = self.shell.history_manager.get_tail(n) + elif "g" in opts: # Search + p = "*"+opts['g']+"*" + hist = list(self.shell.history_manager.search(p)) + for l in reversed(hist): + if "rerun" not in l[2]: + hist = [l] # The last match which isn't a %rerun + break + else: + hist = [] # No matches except %rerun + elif args: # Specify history ranges + hist = self.shell.history_manager.get_range_by_str(args) + else: # Last line + hist = self.shell.history_manager.get_tail(1) + hist = [x[2] for x in hist] + if not hist: + print("No lines in history match specification") + return + histlines = "\n".join(hist) + print("=== Executing: ===") + print(histlines) + print("=== Output: ===") + self.shell.run_cell("\n".join(hist), store_history=False) diff --git a/shared/package-files/01/01296303033d08404c5fa6c0dc5a96a12bf8b0e7118eecfc6537cb4a3a3f17a6/blob b/shared/package-files/01/01296303033d08404c5fa6c0dc5a96a12bf8b0e7118eecfc6537cb4a3a3f17a6/blob new file mode 100644 index 0000000000000000000000000000000000000000..bbca4ee1b88b1b756ea27140d2944d349049c37c --- /dev/null +++ b/shared/package-files/01/01296303033d08404c5fa6c0dc5a96a12bf8b0e7118eecfc6537cb4a3a3f17a6/blob @@ -0,0 +1,280 @@ +import numpy as np +import pytest + +import pandas.util._test_decorators as td + +from pandas import ( + DataFrame, + NaT, + Series, + Timestamp, + date_range, + period_range, +) +import pandas._testing as tm + + +class TestDataFrameValues: + @td.skip_array_manager_invalid_test + def test_values(self, float_frame, using_copy_on_write): + if using_copy_on_write: + with pytest.raises(ValueError, match="read-only"): + float_frame.values[:, 0] = 5.0 + assert (float_frame.values[:, 0] != 5).all() + else: + float_frame.values[:, 0] = 5.0 + assert (float_frame.values[:, 0] == 5).all() + + def test_more_values(self, float_string_frame): + values = float_string_frame.values + assert values.shape[1] == len(float_string_frame.columns) + + def test_values_mixed_dtypes(self, float_frame, float_string_frame): + frame = float_frame + arr = frame.values + + frame_cols = frame.columns + for i, row in enumerate(arr): + for j, value in enumerate(row): + col = frame_cols[j] + if np.isnan(value): + assert np.isnan(frame[col].iloc[i]) + else: + assert value == frame[col].iloc[i] + + # mixed type + arr = float_string_frame[["foo", "A"]].values + assert arr[0, 0] == "bar" + + df = DataFrame({"complex": [1j, 2j, 3j], "real": [1, 2, 3]}) + arr = df.values + assert arr[0, 0] == 1j + + def test_values_duplicates(self): + df = DataFrame( + [[1, 2, "a", "b"], [1, 2, "a", "b"]], columns=["one", "one", "two", "two"] + ) + + result = df.values + expected = np.array([[1, 2, "a", "b"], [1, 2, "a", "b"]], dtype=object) + + tm.assert_numpy_array_equal(result, expected) + + def test_values_with_duplicate_columns(self): + df = DataFrame([[1, 2.5], [3, 4.5]], index=[1, 2], columns=["x", "x"]) + result = df.values + expected = np.array([[1, 2.5], [3, 4.5]]) + assert (result == expected).all().all() + + @pytest.mark.parametrize("constructor", [date_range, period_range]) + def test_values_casts_datetimelike_to_object(self, constructor): + series = Series(constructor("2000-01-01", periods=10, freq="D")) + + expected = series.astype("object") + + df = DataFrame( + {"a": series, "b": np.random.default_rng(2).standard_normal(len(series))} + ) + + result = df.values.squeeze() + assert (result[:, 0] == expected.values).all() + + df = DataFrame({"a": series, "b": ["foo"] * len(series)}) + + result = df.values.squeeze() + assert (result[:, 0] == expected.values).all() + + def test_frame_values_with_tz(self): + tz = "US/Central" + df = DataFrame({"A": date_range("2000", periods=4, tz=tz)}) + result = df.values + expected = np.array( + [ + [Timestamp("2000-01-01", tz=tz)], + [Timestamp("2000-01-02", tz=tz)], + [Timestamp("2000-01-03", tz=tz)], + [Timestamp("2000-01-04", tz=tz)], + ] + ) + tm.assert_numpy_array_equal(result, expected) + + # two columns, homogeneous + + df["B"] = df["A"] + result = df.values + expected = np.concatenate([expected, expected], axis=1) + tm.assert_numpy_array_equal(result, expected) + + # three columns, heterogeneous + est = "US/Eastern" + df["C"] = df["A"].dt.tz_convert(est) + + new = np.array( + [ + [Timestamp("2000-01-01T01:00:00", tz=est)], + [Timestamp("2000-01-02T01:00:00", tz=est)], + [Timestamp("2000-01-03T01:00:00", tz=est)], + [Timestamp("2000-01-04T01:00:00", tz=est)], + ] + ) + expected = np.concatenate([expected, new], axis=1) + result = df.values + tm.assert_numpy_array_equal(result, expected) + + def test_interleave_with_tzaware(self, timezone_frame): + # interleave with object + result = timezone_frame.assign(D="foo").values + expected = np.array( + [ + [ + Timestamp("2013-01-01 00:00:00"), + Timestamp("2013-01-02 00:00:00"), + Timestamp("2013-01-03 00:00:00"), + ], + [ + Timestamp("2013-01-01 00:00:00-0500", tz="US/Eastern"), + NaT, + Timestamp("2013-01-03 00:00:00-0500", tz="US/Eastern"), + ], + [ + Timestamp("2013-01-01 00:00:00+0100", tz="CET"), + NaT, + Timestamp("2013-01-03 00:00:00+0100", tz="CET"), + ], + ["foo", "foo", "foo"], + ], + dtype=object, + ).T + tm.assert_numpy_array_equal(result, expected) + + # interleave with only datetime64[ns] + result = timezone_frame.values + expected = np.array( + [ + [ + Timestamp("2013-01-01 00:00:00"), + Timestamp("2013-01-02 00:00:00"), + Timestamp("2013-01-03 00:00:00"), + ], + [ + Timestamp("2013-01-01 00:00:00-0500", tz="US/Eastern"), + NaT, + Timestamp("2013-01-03 00:00:00-0500", tz="US/Eastern"), + ], + [ + Timestamp("2013-01-01 00:00:00+0100", tz="CET"), + NaT, + Timestamp("2013-01-03 00:00:00+0100", tz="CET"), + ], + ], + dtype=object, + ).T + tm.assert_numpy_array_equal(result, expected) + + def test_values_interleave_non_unique_cols(self): + df = DataFrame( + [[Timestamp("20130101"), 3.5], [Timestamp("20130102"), 4.5]], + columns=["x", "x"], + index=[1, 2], + ) + + df_unique = df.copy() + df_unique.columns = ["x", "y"] + assert df_unique.values.shape == df.values.shape + tm.assert_numpy_array_equal(df_unique.values[0], df.values[0]) + tm.assert_numpy_array_equal(df_unique.values[1], df.values[1]) + + def test_values_numeric_cols(self, float_frame): + float_frame["foo"] = "bar" + + values = float_frame[["A", "B", "C", "D"]].values + assert values.dtype == np.float64 + + def test_values_lcd(self, mixed_float_frame, mixed_int_frame): + # mixed lcd + values = mixed_float_frame[["A", "B", "C", "D"]].values + assert values.dtype == np.float64 + + values = mixed_float_frame[["A", "B", "C"]].values + assert values.dtype == np.float32 + + values = mixed_float_frame[["C"]].values + assert values.dtype == np.float16 + + # GH#10364 + # B uint64 forces float because there are other signed int types + values = mixed_int_frame[["A", "B", "C", "D"]].values + assert values.dtype == np.float64 + + values = mixed_int_frame[["A", "D"]].values + assert values.dtype == np.int64 + + # B uint64 forces float because there are other signed int types + values = mixed_int_frame[["A", "B", "C"]].values + assert values.dtype == np.float64 + + # as B and C are both unsigned, no forcing to float is needed + values = mixed_int_frame[["B", "C"]].values + assert values.dtype == np.uint64 + + values = mixed_int_frame[["A", "C"]].values + assert values.dtype == np.int32 + + values = mixed_int_frame[["C", "D"]].values + assert values.dtype == np.int64 + + values = mixed_int_frame[["A"]].values + assert values.dtype == np.int32 + + values = mixed_int_frame[["C"]].values + assert values.dtype == np.uint8 + + +class TestPrivateValues: + @td.skip_array_manager_invalid_test + def test_private_values_dt64tz(self, using_copy_on_write): + dta = date_range("2000", periods=4, tz="US/Central")._data.reshape(-1, 1) + + df = DataFrame(dta, columns=["A"]) + tm.assert_equal(df._values, dta) + + if using_copy_on_write: + assert not np.shares_memory(df._values._ndarray, dta._ndarray) + else: + # we have a view + assert np.shares_memory(df._values._ndarray, dta._ndarray) + + # TimedeltaArray + tda = dta - dta + df2 = df - df + tm.assert_equal(df2._values, tda) + + @td.skip_array_manager_invalid_test + def test_private_values_dt64tz_multicol(self, using_copy_on_write): + dta = date_range("2000", periods=8, tz="US/Central")._data.reshape(-1, 2) + + df = DataFrame(dta, columns=["A", "B"]) + tm.assert_equal(df._values, dta) + + if using_copy_on_write: + assert not np.shares_memory(df._values._ndarray, dta._ndarray) + else: + # we have a view + assert np.shares_memory(df._values._ndarray, dta._ndarray) + + # TimedeltaArray + tda = dta - dta + df2 = df - df + tm.assert_equal(df2._values, tda) + + def test_private_values_dt64_multiblock(self): + dta = date_range("2000", periods=8)._data + + df = DataFrame({"A": dta[:4]}, copy=False) + df["B"] = dta[4:] + + assert len(df._mgr.arrays) == 2 + + result = df._values + expected = dta.reshape(2, 4).T + tm.assert_equal(result, expected) diff --git a/shared/package-files/01/012aa73c4278fd1dd8ef0a0123bbd6f377f241c25f3998c69fa986d225459d35/blob b/shared/package-files/01/012aa73c4278fd1dd8ef0a0123bbd6f377f241c25f3998c69fa986d225459d35/blob new file mode 100644 index 0000000000000000000000000000000000000000..a9c0d7b840e402186378c89844a5871fe695d28d --- /dev/null +++ b/shared/package-files/01/012aa73c4278fd1dd8ef0a0123bbd6f377f241c25f3998c69fa986d225459d35/blob @@ -0,0 +1,24 @@ +#pragma once +// @generated by torchgen/gen.py from DispatchKeyFunction.h + +// NB: The implementing C++ file is RegisterDispatchKey.cpp + +// The only #includes we need are for custom classes that have defaults in the C++ API +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { + +namespace compositeexplicitautograd { + +TORCH_API at::Tensor & _neg_view_copy_out(at::Tensor & out, const at::Tensor & self); +TORCH_API at::Tensor & _neg_view_copy_outf(const at::Tensor & self, at::Tensor & out); + +} // namespace compositeexplicitautograd +} // namespace at diff --git a/shared/package-files/01/012b0f4b0fb37d8a53f0f4092949e7bcf3843ef7e3bf430ad4ecd32d822bdcc1/blob b/shared/package-files/01/012b0f4b0fb37d8a53f0f4092949e7bcf3843ef7e3bf430ad4ecd32d822bdcc1/blob new file mode 100644 index 0000000000000000000000000000000000000000..c4e46d342fc80e384eb0feb94c8cfb0539cc3d2e --- /dev/null +++ b/shared/package-files/01/012b0f4b0fb37d8a53f0f4092949e7bcf3843ef7e3bf430ad4ecd32d822bdcc1/blob @@ -0,0 +1,23 @@ +#pragma once +// @generated by torchgen/gen.py from DispatchKeyFunction.h + +// NB: The implementing C++ file is RegisterDispatchKey.cpp + +// The only #includes we need are for custom classes that have defaults in the C++ API +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { + +namespace compositeexplicitautograd { + +TORCH_API at::Tensor & polygamma_(at::Tensor & self, int64_t n); + +} // namespace compositeexplicitautograd +} // namespace at diff --git a/shared/package-files/01/012b7137c411d9057e8f3877de2f5f5a22ef737a42e8fbe439d75b39c9a408c9/blob b/shared/package-files/01/012b7137c411d9057e8f3877de2f5f5a22ef737a42e8fbe439d75b39c9a408c9/blob new file mode 100644 index 0000000000000000000000000000000000000000..60054dd6baba4124d234d32e8f7408ad10bc64f8 --- /dev/null +++ b/shared/package-files/01/012b7137c411d9057e8f3877de2f5f5a22ef737a42e8fbe439d75b39c9a408c9/blob @@ -0,0 +1,25 @@ +#pragma once +// @generated by torchgen/gen.py from DispatchKeyFunction.h + +// NB: The implementing C++ file is RegisterDispatchKey.cpp + +// The only #includes we need are for custom classes that have defaults in the C++ API +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { + +namespace cpu { + +TORCH_API at::Tensor avg_pool3d(const at::Tensor & self, at::IntArrayRef kernel_size, at::IntArrayRef stride={}, at::IntArrayRef padding=0, bool ceil_mode=false, bool count_include_pad=true, c10::optional divisor_override=c10::nullopt); +TORCH_API at::Tensor & avg_pool3d_out(at::Tensor & out, const at::Tensor & self, at::IntArrayRef kernel_size, at::IntArrayRef stride={}, at::IntArrayRef padding=0, bool ceil_mode=false, bool count_include_pad=true, c10::optional divisor_override=c10::nullopt); +TORCH_API at::Tensor & avg_pool3d_outf(const at::Tensor & self, at::IntArrayRef kernel_size, at::IntArrayRef stride, at::IntArrayRef padding, bool ceil_mode, bool count_include_pad, c10::optional divisor_override, at::Tensor & out); + +} // namespace cpu +} // namespace at diff --git a/shared/package-files/01/012d3ab1b4d0875dfaa040d9f7ac08bc21a7aaec9860e1cda8af2e855c9ddbce/blob b/shared/package-files/01/012d3ab1b4d0875dfaa040d9f7ac08bc21a7aaec9860e1cda8af2e855c9ddbce/blob new file mode 100644 index 0000000000000000000000000000000000000000..ae60620e1ab9ffcc6dc595b4c2eba9fa2b4cb6a0 Binary files /dev/null and b/shared/package-files/01/012d3ab1b4d0875dfaa040d9f7ac08bc21a7aaec9860e1cda8af2e855c9ddbce/blob differ diff --git a/shared/package-files/01/012fe2e41d936cf7334b56e9eac6c4b3596155b9fe8b937ca3e7a31989081141/blob b/shared/package-files/01/012fe2e41d936cf7334b56e9eac6c4b3596155b9fe8b937ca3e7a31989081141/blob new file mode 100644 index 0000000000000000000000000000000000000000..18473147563ef2303b57d0815459f2e6e1101c13 Binary files /dev/null and b/shared/package-files/01/012fe2e41d936cf7334b56e9eac6c4b3596155b9fe8b937ca3e7a31989081141/blob differ diff --git a/shared/package-files/01/01306ee80ca57f6636b569dd90e87f98f1c5d4e44b4c4864d2ec42ba9d4af028/blob b/shared/package-files/01/01306ee80ca57f6636b569dd90e87f98f1c5d4e44b4c4864d2ec42ba9d4af028/blob new file mode 100644 index 0000000000000000000000000000000000000000..9965c914daa4f590ae5a173217814396f124ae64 --- /dev/null +++ b/shared/package-files/01/01306ee80ca57f6636b569dd90e87f98f1c5d4e44b4c4864d2ec42ba9d4af028/blob @@ -0,0 +1,175 @@ +from io import BytesIO +import platform + +import numpy as np + +from matplotlib.testing.decorators import image_comparison +import matplotlib.pyplot as plt +import matplotlib.path as mpath +import matplotlib.patches as mpatches +from matplotlib.ticker import FuncFormatter + + +@image_comparison(['bbox_inches_tight'], remove_text=True, + savefig_kwarg={'bbox_inches': 'tight'}) +def test_bbox_inches_tight(): + #: Test that a figure saved using bbox_inches='tight' is clipped correctly + data = [[66386, 174296, 75131, 577908, 32015], + [58230, 381139, 78045, 99308, 160454], + [89135, 80552, 152558, 497981, 603535], + [78415, 81858, 150656, 193263, 69638], + [139361, 331509, 343164, 781380, 52269]] + + col_labels = row_labels = [''] * 5 + + rows = len(data) + ind = np.arange(len(col_labels)) + 0.3 # the x locations for the groups + cell_text = [] + width = 0.4 # the width of the bars + yoff = np.zeros(len(col_labels)) + # the bottom values for stacked bar chart + fig, ax = plt.subplots(1, 1) + for row in range(rows): + ax.bar(ind, data[row], width, bottom=yoff, align='edge', color='b') + yoff = yoff + data[row] + cell_text.append(['']) + plt.xticks([]) + plt.xlim(0, 5) + plt.legend([''] * 5, loc=(1.2, 0.2)) + fig.legend([''] * 5, bbox_to_anchor=(0, 0.2), loc='lower left') + # Add a table at the bottom of the axes + cell_text.reverse() + plt.table(cellText=cell_text, rowLabels=row_labels, colLabels=col_labels, + loc='bottom') + + +@image_comparison(['bbox_inches_tight_suptile_legend'], + savefig_kwarg={'bbox_inches': 'tight'}, + tol=0 if platform.machine() == 'x86_64' else 0.02) +def test_bbox_inches_tight_suptile_legend(): + plt.plot(np.arange(10), label='a straight line') + plt.legend(bbox_to_anchor=(0.9, 1), loc='upper left') + plt.title('Axis title') + plt.suptitle('Figure title') + + # put an extra long y tick on to see that the bbox is accounted for + def y_formatter(y, pos): + if int(y) == 4: + return 'The number 4' + else: + return str(y) + plt.gca().yaxis.set_major_formatter(FuncFormatter(y_formatter)) + + plt.xlabel('X axis') + + +@image_comparison(['bbox_inches_tight_suptile_non_default.png'], + savefig_kwarg={'bbox_inches': 'tight'}, + tol=0.1) # large tolerance because only testing clipping. +def test_bbox_inches_tight_suptitle_non_default(): + fig, ax = plt.subplots() + fig.suptitle('Booo', x=0.5, y=1.1) + + +@image_comparison(['bbox_inches_tight_layout.png'], remove_text=True, + style='mpl20', + savefig_kwarg=dict(bbox_inches='tight', pad_inches='layout')) +def test_bbox_inches_tight_layout_constrained(): + fig, ax = plt.subplots(layout='constrained') + fig.get_layout_engine().set(h_pad=0.5) + ax.set_aspect('equal') + + +def test_bbox_inches_tight_layout_notconstrained(tmp_path): + # pad_inches='layout' should be ignored when not using constrained/ + # compressed layout. Smoke test that savefig doesn't error in this case. + fig, ax = plt.subplots() + fig.savefig(tmp_path / 'foo.png', bbox_inches='tight', pad_inches='layout') + + +@image_comparison(['bbox_inches_tight_clipping'], + remove_text=True, savefig_kwarg={'bbox_inches': 'tight'}) +def test_bbox_inches_tight_clipping(): + # tests bbox clipping on scatter points, and path clipping on a patch + # to generate an appropriately tight bbox + plt.scatter(np.arange(10), np.arange(10)) + ax = plt.gca() + ax.set_xlim(0, 5) + ax.set_ylim(0, 5) + + # make a massive rectangle and clip it with a path + patch = mpatches.Rectangle([-50, -50], 100, 100, + transform=ax.transData, + facecolor='blue', alpha=0.5) + + path = mpath.Path.unit_regular_star(5).deepcopy() + path.vertices *= 0.25 + patch.set_clip_path(path, transform=ax.transAxes) + plt.gcf().artists.append(patch) + + +@image_comparison(['bbox_inches_tight_raster'], tol=0.15, # For Ghostscript 10.06+. + remove_text=True, savefig_kwarg={'bbox_inches': 'tight'}) +def test_bbox_inches_tight_raster(): + """Test rasterization with tight_layout""" + fig, ax = plt.subplots() + ax.plot([1.0, 2.0], rasterized=True) + + +def test_only_on_non_finite_bbox(): + fig, ax = plt.subplots() + ax.annotate("", xy=(0, float('nan'))) + ax.set_axis_off() + # we only need to test that it does not error out on save + fig.savefig(BytesIO(), bbox_inches='tight', format='png') + + +def test_tight_pcolorfast(): + fig, ax = plt.subplots() + ax.pcolorfast(np.arange(4).reshape((2, 2))) + ax.set(ylim=(0, .1)) + buf = BytesIO() + fig.savefig(buf, bbox_inches="tight") + buf.seek(0) + height, width, _ = plt.imread(buf).shape + # Previously, the bbox would include the area of the image clipped out by + # the axes, resulting in a very tall image given the y limits of (0, 0.1). + assert width > height + + +def test_noop_tight_bbox(): + from PIL import Image + x_size, y_size = (10, 7) + dpi = 100 + # make the figure just the right size up front + fig = plt.figure(frameon=False, dpi=dpi, figsize=(x_size/dpi, y_size/dpi)) + ax = fig.add_axes((0, 0, 1, 1)) + ax.set_axis_off() + ax.xaxis.set_visible(False) + ax.yaxis.set_visible(False) + + data = np.arange(x_size * y_size).reshape(y_size, x_size) + ax.imshow(data, rasterized=True) + + # When a rasterized Artist is included, a mixed-mode renderer does + # additional bbox adjustment. It should also be a no-op, and not affect the + # next save. + fig.savefig(BytesIO(), bbox_inches='tight', pad_inches=0, format='pdf') + + out = BytesIO() + fig.savefig(out, bbox_inches='tight', pad_inches=0) + out.seek(0) + im = np.asarray(Image.open(out)) + assert (im[:, :, 3] == 255).all() + assert not (im[:, :, :3] == 255).all() + assert im.shape == (7, 10, 4) + + +@image_comparison(['bbox_inches_fixed_aspect'], extensions=['png'], + remove_text=True, savefig_kwarg={'bbox_inches': 'tight'}) +def test_bbox_inches_fixed_aspect(): + with plt.rc_context({'figure.constrained_layout.use': True}): + fig, ax = plt.subplots() + ax.plot([0, 1]) + ax.set_xlim(0, 1) + ax.set_aspect('equal') diff --git a/shared/package-files/01/01338dd2f78b4b74c33200447d76ba197f010cbd7500d673b6aba62cf33a7ce8/blob b/shared/package-files/01/01338dd2f78b4b74c33200447d76ba197f010cbd7500d673b6aba62cf33a7ce8/blob new file mode 100644 index 0000000000000000000000000000000000000000..9a6158e760f0e5cfa36dfc7dc303b9ec788241a6 --- /dev/null +++ b/shared/package-files/01/01338dd2f78b4b74c33200447d76ba197f010cbd7500d673b6aba62cf33a7ce8/blob @@ -0,0 +1,873 @@ +#!/usr/bin/env python3 + +# Copyright (c) Facebook, Inc. and its affiliates. +# All rights reserved. +# +# This source code is licensed under the BSD-style license found in the +# LICENSE file in the root directory of this source tree. + +import abc +import logging +import os +import re +import shutil +import signal +import subprocess +import sys +import tempfile +import time +from contextlib import nullcontext +from dataclasses import dataclass, field +from enum import IntFlag +from multiprocessing import synchronize +from types import FrameType +from typing import Any, Callable, Dict, Optional, Set, Tuple, Union +from abc import ABC, abstractmethod + +import torch.multiprocessing as mp +from torch.distributed.elastic.multiprocessing.errors import ProcessFailure, record +from torch.distributed.elastic.multiprocessing.redirects import ( + redirect_stderr, + redirect_stdout, +) + +from torch.distributed.elastic.multiprocessing.subprocess_handler import SubprocessHandler, get_subprocess_handler +from torch.distributed.elastic.multiprocessing.tail_log import TailLog + +IS_WINDOWS = sys.platform == "win32" +IS_MACOS = sys.platform == "darwin" + + +log = logging.getLogger(__name__) + +__all__ = [ + "DefaultLogsSpecs", + "SignalException", + "Std", + "to_map", + "RunProcsResult", + "PContext", + "get_std_cm", + "MultiprocessContext", + "SubprocessContext", +] + +class SignalException(Exception): + """ + Exception is raised inside the torchelastic agent process by the termination handler + if the death signal got received by the process. + """ + + def __init__(self, msg: str, sigval: signal.Signals) -> None: + super().__init__(msg) + self.sigval = sigval + + +def _terminate_process_handler(signum: int, frame: Optional[FrameType]) -> None: + """Termination handler that raises exceptions on the main process. + + When the process receives death signal(SIGTERM, SIGINT), this termination handler will + be invoked. It raises the ``SignalException`` exception that should be processed by the + user code. Python does not terminate process after the termination handler is finished, + so the exception should not be silently ignored, otherwise the process will never + be terminated. + """ + sigval = signal.Signals(signum) + raise SignalException(f"Process {os.getpid()} got signal: {sigval}", sigval=sigval) + + +def _get_kill_signal() -> signal.Signals: + """Get the kill signal. SIGKILL for unix, CTRL_C_EVENT for windows.""" + if IS_WINDOWS: + return signal.CTRL_C_EVENT # type: ignore[attr-defined] # noqa: F821 + else: + return signal.SIGKILL + + +def _get_default_signal() -> signal.Signals: + """Get the default termination signal. SIGTERM for unix, CTRL_C_EVENT for windows.""" + if IS_WINDOWS: + return signal.CTRL_C_EVENT # type: ignore[attr-defined] # noqa: F821 + else: + return signal.SIGTERM + + +def _validate_full_rank(d: Dict[int, Any], nprocs: int, what: str): + actual_keys = set(d.keys()) + expected_keys = set(range(nprocs)) + + if actual_keys != expected_keys: + raise RuntimeError( + f"{what}, local rank mapping mismatch," + f" expected: {expected_keys}, actual: {actual_keys}" + ) + + +_MAPPING_REGEX = r"^(\d:[0123],)*(\d:[0123])$" +_VALUE_REGEX = r"^[0123]$" + + +class Std(IntFlag): + NONE = 0 + OUT = 1 + ERR = 2 + ALL = OUT | ERR + + @classmethod + def from_str(cls, vm: str) -> Union["Std", Dict[int, "Std"]]: + """ + Example: + :: + + from_str("0") -> Std.NONE + from_str("1") -> Std.OUT + from_str("0:3,1:0,2:1,3:2") -> {0: Std.ALL, 1: Std.NONE, 2: Std.OUT, 3: Std.ERR} + + Any other input raises an exception + """ + + def to_std(v: str) -> Std: # type: ignore[return] + s = Std(int(v)) + if s in Std: + return s + # return None -> should NEVER reach here since we regex check input + + if re.match(_VALUE_REGEX, vm): # vm is a number (e.g. 0) + return to_std(vm) + elif re.match(_MAPPING_REGEX, vm): # vm is a mapping (e.g. 0:1,1:2) + d: Dict[int, Std] = {} + for m in vm.split(","): + i, v = m.split(":") + d[int(i)] = to_std(v) + return d + else: + raise ValueError( + f"{vm} does not match: <{_VALUE_REGEX}> or <{_MAPPING_REGEX}>" + ) + + +def to_map( + val_or_map: Union[Std, Dict[int, Std]], local_world_size: int +) -> Dict[int, Std]: + """ + Certain APIs take redirect settings either as a single value (e.g. apply to all + local ranks) or as an explicit user-provided mapping. This method is a convenience + method that converts a value or mapping into a mapping. + + Example: + :: + + to_map(Std.OUT, local_world_size=2) # returns: {0: Std.OUT, 1: Std.OUT} + to_map({1: Std.OUT}, local_world_size=2) # returns: {0: Std.NONE, 1: Std.OUT} + to_map({0: Std.OUT, 1: Std.OUT}, local_world_size=2) # returns: {0: Std.OUT, 1: Std.OUT} + """ + if isinstance(val_or_map, Std): + return dict.fromkeys(range(local_world_size), val_or_map) + else: + map = {} + for i in range(local_world_size): + map[i] = val_or_map.get(i, Std.NONE) + return map + + +@dataclass +class LogsDest: + """ + For each log type, holds mapping of local rank ids to file paths. + """ + stdouts: Dict[int, str] = field(default_factory=dict) + stderrs: Dict[int, str] = field(default_factory=dict) + tee_stdouts: Dict[int, str] = field(default_factory=dict) + tee_stderrs: Dict[int, str] = field(default_factory=dict) + error_files: Dict[int, str] = field(default_factory=dict) + + +class LogsSpecs(ABC): + """ + Defines logs processing and redirection for each worker process. + + Args: + log_dir: + Base directory where logs will be written. + redirects: + Streams to redirect to files. Pass a single ``Std`` + enum to redirect for all workers, or a mapping keyed + by local_rank to selectively redirect. + tee: + Streams to duplicate to stdout/stderr. + Pass a single ``Std`` enum to duplicate streams for all workers, + or a mapping keyed by local_rank to selectively duplicate. + """ + + def __init__( + self, + log_dir: Optional[str] = None, + redirects: Union[Std, Dict[int, Std]] = Std.NONE, + tee: Union[Std, Dict[int, Std]] = Std.NONE, + local_ranks_filter: Optional[Set[int]] = None, + ) -> None: + self._root_log_dir = log_dir + self._redirects = redirects + self._tee = tee + self._local_ranks_filter = local_ranks_filter + + @abstractmethod + def reify(self, envs: Dict[int, Dict[str, str]],) -> LogsDest: + """ + Given the environment variables, builds destination of log files for each of the local ranks. + + Envs parameter contains env variables dict for each of the local ranks, where entries are defined in: + :func:`~torchelastic.distributed.elastic.agent.server.local_elastic_agent.LocalElasticAgent._start_workers`. + """ + pass + + @property + @abstractmethod + def root_log_dir(self) -> str: + pass + +class DefaultLogsSpecs(LogsSpecs): + """ + Default LogsSpecs implementation: + + - `log_dir` will be created if it doesn't exist + - Generates nested folders for each attempt and rank. + """ + def __init__( + self, + log_dir: Optional[str] = None, + redirects: Union[Std, Dict[int, Std]] = Std.NONE, + tee: Union[Std, Dict[int, Std]] = Std.NONE, + local_ranks_filter: Optional[Set[int]] = None, + ) -> None: + if log_dir != os.devnull: + if not log_dir: + log_dir = tempfile.mkdtemp(prefix="torchelastic_") + elif not os.path.exists(log_dir): + os.makedirs(log_dir) + else: + if os.path.isfile(log_dir): + raise NotADirectoryError(f"log_dir: {log_dir} is a file") + super().__init__(log_dir, redirects, tee, local_ranks_filter) + # initialized only once + self._run_log_dir = None + + @property + def root_log_dir(self) -> str: + return str(self._root_log_dir) + + def _make_log_dir(self, log_dir: Optional[str], rdzv_run_id: str): + base_log_dir = log_dir or tempfile.mkdtemp(prefix="torchelastic_") + os.makedirs(base_log_dir, exist_ok=True) + dir = tempfile.mkdtemp(prefix=f"{rdzv_run_id}_", dir=base_log_dir) + log.info("log directory set to: %s", dir) + return dir + + def reify(self, envs: Dict[int, Dict[str, str]],) -> LogsDest: + """ + Uses following scheme to build log destination paths: + + - `//attempt_//stdout.log` + - `//attempt_//stderr.log` + - `//attempt_//error.json` + """ + nprocs = len(envs) + global_env = {} # use only to query properies that are not dependent on a rank + if nprocs > 0: + global_env = envs[0] + else: + log.warning("Empty envs map provided when defining logging destinations.") + # Keys are always defined, but values can be missing in unit tests + run_id = global_env.get("TORCHELASTIC_RUN_ID", "test_run_id") + restart_count = global_env.get("TORCHELASTIC_RESTART_COUNT", "0") + + attempt_log_dir: str = "" + if self._root_log_dir != os.devnull: + if not self._run_log_dir: + self._run_log_dir = self._make_log_dir(self._root_log_dir, run_id) + + attempt_log_dir = os.path.join(self._run_log_dir, f"attempt_{restart_count}") # type: ignore[call-overload] + shutil.rmtree(attempt_log_dir, ignore_errors=True) + os.makedirs(attempt_log_dir) + + if self._root_log_dir == os.devnull: + attempt_log_dir = os.devnull + + # create subdirs for each local rank in the logs_dir + # logs_dir + # |- 0 + # |- error.json + # |- stdout.log + # |- stderr.log + # |- ... + # |- (nprocs-1) + redirs = to_map(self._redirects, nprocs) + ts = to_map(self._tee, nprocs) + + # to tee stdout/stderr we first redirect into a file + # then tail -f stdout.log/stderr.log so add tee settings to redirects + for local_rank, tee_std in ts.items(): + redirect_std = redirs[local_rank] + redirs[local_rank] = redirect_std | tee_std + + SYS_STREAM = "" # special case to indicate to output to console + stdouts = dict.fromkeys(range(nprocs), SYS_STREAM) + stderrs = dict.fromkeys(range(nprocs), SYS_STREAM) + tee_stdouts: Dict[int, str] = {} + tee_stderrs: Dict[int, str] = {} + error_files = {} + + for local_rank in range(nprocs): + + if attempt_log_dir == os.devnull: + tee_stdouts[local_rank] = os.devnull + tee_stderrs[local_rank] = os.devnull + error_files[local_rank] = os.devnull + envs[local_rank]["TORCHELASTIC_ERROR_FILE"] = "" + else: + clogdir = os.path.join(attempt_log_dir, str(local_rank)) + os.mkdir(clogdir) + + rd = redirs[local_rank] + if (rd & Std.OUT) == Std.OUT: + stdouts[local_rank] = os.path.join(clogdir, "stdout.log") + if (rd & Std.ERR) == Std.ERR: + stderrs[local_rank] = os.path.join(clogdir, "stderr.log") + + t = ts[local_rank] + if t & Std.OUT == Std.OUT: + tee_stdouts[local_rank] = stdouts[local_rank] + if t & Std.ERR == Std.ERR: + tee_stderrs[local_rank] = stderrs[local_rank] + + if self._local_ranks_filter and local_rank not in self._local_ranks_filter: + # If stream is tee'd, only write to file, but don't tail + if local_rank in tee_stdouts: + tee_stdouts.pop(local_rank, None) + if local_rank in tee_stderrs: + tee_stderrs.pop(local_rank, None) + + # If stream is not redirected, don't print + if stdouts[local_rank] == SYS_STREAM: + stdouts[local_rank] = os.devnull + if stderrs[local_rank] == SYS_STREAM: + stderrs[local_rank] = os.devnull + + error_file = os.path.join(clogdir, "error.json") + error_files[local_rank] = error_file + log.info("Setting worker%s reply file to: %s", local_rank, error_file) + envs[local_rank]["TORCHELASTIC_ERROR_FILE"] = error_file + + return LogsDest(stdouts, stderrs, tee_stdouts, tee_stderrs, error_files) + + def __repr__(self) -> str: + return ( + f"DefaultLogsSpecs(root_log_dir={self._root_log_dir}, redirects={self._redirects}, " + f"tee={self._tee}, local_ranks_filter={self._local_ranks_filter})" + ) + + def __eq__(self, other: object) -> bool: + if not isinstance(other, DefaultLogsSpecs): + return False + + return ( + self._root_log_dir == other._root_log_dir + and self._redirects == other._redirects + and self._tee == other._tee + and self._local_ranks_filter == other._local_ranks_filter + ) + + +@dataclass +class RunProcsResult: + """ + Results of a completed run of processes started with ``start_processes()``. Returned by ``PContext``. + + Note the following: + + 1. All fields are mapped by local rank + 2. ``return_values`` - only populated for functions (not the binaries). + 3. ``stdouts`` - path to stdout.log (empty string if no redirect) + 4. ``stderrs`` - path to stderr.log (empty string if no redirect) + + """ + + return_values: Dict[int, Any] = field(default_factory=dict) + failures: Dict[int, ProcessFailure] = field(default_factory=dict) + stdouts: Dict[int, str] = field(default_factory=dict) + stderrs: Dict[int, str] = field(default_factory=dict) + + def is_failed(self) -> bool: + return len(self.failures) > 0 + + +class PContext(abc.ABC): + """ + The base class that standardizes operations over a set of processes that are launched via different mechanisms. + + The name ``PContext`` is intentional to disambiguate with ``torch.multiprocessing.ProcessContext``. + + .. warning:: stdouts and stderrs should ALWAYS be a superset of + tee_stdouts and tee_stderrs (respectively) this is b/c + tee is implemented as a redirect + tail -f + """ + + def __init__( + self, + name: str, + entrypoint: Union[Callable, str], + args: Dict[int, Tuple], + envs: Dict[int, Dict[str, str]], + logs_specs: LogsSpecs, + log_line_prefixes: Optional[Dict[int, str]] = None, + + ): + self.name = name + # validate that all mappings have the same number of keys and + # all local ranks are accounted for + nprocs = len(args) + + # TODO log_line_prefixes can be exanded too + logs_dest = logs_specs.reify(envs) + + _validate_full_rank(logs_dest.stdouts, nprocs, "stdouts") + _validate_full_rank(logs_dest.stderrs, nprocs, "stderrs") + + self.entrypoint = entrypoint + self.args = args + self.envs = envs + self.stdouts = logs_dest.stdouts + self.stderrs = logs_dest.stderrs + self.error_files = logs_dest.error_files + self.nprocs = nprocs + + self._stdout_tail = TailLog(name, logs_dest.tee_stdouts, sys.stdout, log_line_prefixes) + self._stderr_tail = TailLog(name, logs_dest.tee_stderrs, sys.stderr, log_line_prefixes) + + def start(self) -> None: + """Start processes using parameters defined in the constructor.""" + signal.signal(signal.SIGTERM, _terminate_process_handler) + signal.signal(signal.SIGINT, _terminate_process_handler) + if not IS_WINDOWS: + signal.signal(signal.SIGHUP, _terminate_process_handler) + signal.signal(signal.SIGQUIT, _terminate_process_handler) + self._start() + self._stdout_tail.start() + self._stderr_tail.start() + + @abc.abstractmethod + def _start(self) -> None: + """Start processes using strategy defined in a particular context.""" + raise NotImplementedError() + + @abc.abstractmethod + def _poll(self) -> Optional[RunProcsResult]: + """ + Poll the run status of the processes running under this context. + This method follows an "all-or-nothing" policy and returns + a ``RunProcessResults`` object if either all processes complete + successfully or any process fails. Returns ``None`` if + all processes are still running. + """ + raise NotImplementedError() + + def wait(self, timeout: float = -1, period: float = 1) -> Optional[RunProcsResult]: + """ + Wait for the specified ``timeout`` seconds, polling every ``period`` seconds + for the processes to be done. Returns ``None`` if the processes are still running + on timeout expiry. Negative timeout values are interpreted as "wait-forever". + A timeout value of zero simply queries the status of the processes (e.g. equivalent + to a poll). + + ..note: Multiprocessing library registers SIGTERM and SIGINT signal handlers that raise + ``SignalException`` when the signals received. It is up to the consumer of the code + to properly handle the exception. It is important not to swallow the exception otherwise + the process would not terminate. Example of the typical workflow can be: + + .. code-block:: python + pc = start_processes(...) + try: + pc.wait(1) + .. do some other work + except SignalException as e: + pc.shutdown(e.sigval, timeout=30) + + If SIGTERM or SIGINT occurs, the code above will try to shutdown child processes by propagating + received signal. If child processes will not terminate in the timeout time, the process will send + the SIGKILL. + """ + if timeout == 0: + return self._poll() + + if timeout < 0: + timeout = sys.maxsize + + expiry = time.time() + timeout + while time.time() < expiry: + pr = self._poll() + if pr: + return pr + time.sleep(period) + + return None + + @abc.abstractmethod + def pids(self) -> Dict[int, int]: + """Return pids of processes mapped by their respective local_ranks.""" + raise NotImplementedError() + + @abc.abstractmethod + def _close(self, death_sig: signal.Signals, timeout: int = 30) -> None: + r""" + Terminates all processes managed by this context and cleans up any + meta resources (e.g. redirect, error_file files). + """ + raise NotImplementedError() + + def close( + self, death_sig: Optional[signal.Signals] = None, timeout: int = 30 + ) -> None: + r""" + Terminates all processes managed by this context and cleans up any + meta resources (e.g. redirect, error_file files). + + Args: + death_sig: Death signal to terminate processes. + timeout: Time to wait for processes to finish, if process is + still alive after this time, it will be terminated via SIGKILL. + """ + if not death_sig: + death_sig = _get_default_signal() + self._close(death_sig=death_sig, timeout=timeout) + if self._stdout_tail: + self._stdout_tail.stop() + if self._stderr_tail: + self._stderr_tail.stop() + + +def get_std_cm(std_rd: str, redirect_fn): + if IS_WINDOWS or IS_MACOS or not std_rd: + return nullcontext() + else: + return redirect_fn(std_rd) + + +def _wrap( + local_rank: int, + fn: Callable, + args: Dict[int, Tuple], + envs: Dict[int, Dict[str, str]], + stdout_redirects: Dict[int, str], # redirect file for stdout (to console if None) + stderr_redirects: Dict[int, str], # redirect file for stderr (to console if None) + ret_vals: Dict[int, mp.SimpleQueue], + queue_finished_reading_event: synchronize.Event, +) -> None: + # get the per-rank params up front so we fail fast if no mapping is found + args_ = args[local_rank] + env_ = envs[local_rank] + ret_val_ = ret_vals[local_rank] + + stdout_rd = stdout_redirects[local_rank] + stderr_rd = stderr_redirects[local_rank] + + stdout_cm = get_std_cm(stdout_rd, redirect_stdout) + stderr_cm = get_std_cm(stderr_rd, redirect_stderr) + + for k, v in env_.items(): + os.environ[k] = v + + with stdout_cm, stderr_cm: + ret = record(fn)(*args_) + ret_val_.put(ret) + queue_finished_reading_event.wait() + + +class MultiprocessContext(PContext): + """``PContext`` holding worker processes invoked as a function.""" + + def __init__( + self, + name: str, + entrypoint: Callable, + args: Dict[int, Tuple], + envs: Dict[int, Dict[str, str]], + start_method: str, + logs_specs: LogsSpecs, + log_line_prefixes: Optional[Dict[int, str]] = None, + ): + super().__init__( + name, + entrypoint, + args, + envs, + logs_specs, + log_line_prefixes, + ) + + self.start_method = start_method + # each ret_val queue will always contain a single element. + self._ret_vals = { + local_rank: mp.get_context(self.start_method).SimpleQueue() + for local_rank in range(self.nprocs) + } + + # see comments in ``join()`` for what this is + self._return_values: Dict[int, Any] = {} + self._pc: Optional[mp.ProcessContext] = None + # Note: set method should ONLY be invoked for the use case when all processes finished + # successfully. If any process died on event.wait() calling set() method will deadlock. + self._worker_finished_event = mp.get_context(self.start_method).Event() + + def _start(self): + if self._pc: + raise ValueError( + "The process context already initialized." + " Most likely the start method got called twice." + ) + self._pc = mp.start_processes( + fn=_wrap, + args=( + self.entrypoint, + self.args, + self.envs, + self.stdouts, + self.stderrs, + self._ret_vals, + self._worker_finished_event, + ), + nprocs=self.nprocs, + join=False, + daemon=False, + start_method=self.start_method, + ) + + def _is_done(self) -> bool: + return len(self._return_values) == self.nprocs + + def _poll(self) -> Optional[RunProcsResult]: + assert self._pc is not None # assertion for mypy type checker + + try: + # torch.mp.ProcessContext Throws an Exception if some/all of + # worker processes failed + # timeout < 0 checks worker status and return immediately + # Join will never return success since we use synchronize.Event to wait + # for all processes to finish. + self._pc.join(-1) + + # IMPORTANT: we use multiprocessing.Queue to carry worker return values + # back to the parent, the worker process will wait before terminating + # until all the buffered items are fed by the feeder thread to the underlying + # pipe. Hence to prevent deadlocks on large return values, + # we opportunistically try queue.get on each join call + # See: https://docs.python.org/2/library/multiprocessing.html#all-platforms + for local_rank in range(0, self.nprocs): + return_queue = self._ret_vals[local_rank] + if not return_queue.empty(): + # save the return values temporarily into a member var + self._return_values[local_rank] = return_queue.get() + + if self._is_done(): + # we should ALWAYS have ALL the return values when all the processes are done + self._worker_finished_event.set() + # Wait untill all processes are finished. At this point workers finished executing + # user function + self._pc.join() + _validate_full_rank( + self._return_values, self.nprocs, "return_value queue" + ) + self.close() + return RunProcsResult( + return_values=self._return_values, + stdouts=self.stdouts, + stderrs=self.stderrs, + ) + else: + return None + except (mp.ProcessRaisedException, mp.ProcessExitedException) as e: + failed_local_rank = e.error_index + + # entrypoint for MultiprocessContext will always be a Callable + fn_name = self.entrypoint.__qualname__ # type: ignore[union-attr] + failed_proc = self._pc.processes[failed_local_rank] + error_filepath = self.error_files[failed_local_rank] + + log.exception( + "failed (exitcode: %s)" + " local_rank: %s (pid: %s)" + " of fn: %s (start_method: %s)", + failed_proc.exitcode, + failed_local_rank, e.pid, + fn_name, self.start_method, + ) + + self.close() + return RunProcsResult( + failures={ + failed_local_rank: ProcessFailure( + local_rank=failed_local_rank, + pid=e.pid, + exitcode=failed_proc.exitcode, + error_file=error_filepath, + ) + }, + stdouts=self.stdouts, + stderrs=self.stderrs, + ) + + def pids(self) -> Dict[int, int]: + assert self._pc is not None # assertion for mypy type checking + return dict(enumerate(self._pc.pids())) + + def _close(self, death_sig: signal.Signals, timeout: int = 30) -> None: + if not self._pc: + return + for proc in self._pc.processes: + if proc.is_alive(): + log.warning("Closing process %s via signal %s", proc.pid, death_sig.name) + try: + os.kill(proc.pid, death_sig) + except ProcessLookupError: + # If the process exited because of some reason, + # `ProcessLookupError` will be raised, it is safe to ignore it. + pass + end = time.monotonic() + timeout + for proc in self._pc.processes: + time_to_wait = end - time.monotonic() + if time_to_wait <= 0: + break + proc.join(time_to_wait) + for proc in self._pc.processes: + if proc.is_alive(): + log.warning( + "Unable to shutdown process %s via %s, forcefully exiting via %s", + proc.pid, death_sig, _get_kill_signal() + ) + try: + os.kill(proc.pid, _get_kill_signal()) + except ProcessLookupError: + # If the process exited because of some reason, + # `ProcessLookupError` will be raised, it is safe to ignore it. + pass + proc.join() + +class SubprocessContext(PContext): + """``PContext`` holding worker processes invoked as a binary.""" + + def __init__( + self, + name: str, + entrypoint: str, + args: Dict[int, Tuple], + envs: Dict[int, Dict[str, str]], + logs_specs: LogsSpecs, + log_line_prefixes: Optional[Dict[int, str]] = None, + + ): + super().__init__( + name, + entrypoint, + args, + envs, + logs_specs, + log_line_prefixes, + ) + + # state vector; _vdone[local_rank] -> is local_rank finished or not + self._running_local_ranks: Set[int] = set(range(self.nprocs)) + self._failures: Dict[int, ProcessFailure] = {} + self.subprocess_handlers: Dict[int, SubprocessHandler] = {} + + def _start(self): + if self.subprocess_handlers: + raise ValueError( + "The subprocess handlers already initialized. Most likely the start method got called twice." + ) + self.subprocess_handlers = { + local_rank: get_subprocess_handler( + entrypoint=self.entrypoint, # type: ignore[arg-type] # entrypoint is always a str + args=self.args[local_rank], + env=self.envs[local_rank], + stdout=self.stdouts[local_rank], + stderr=self.stderrs[local_rank], + local_rank_id=local_rank, + ) + for local_rank in range(self.nprocs) + } + + def _poll(self) -> Optional[RunProcsResult]: + done_local_ranks = set() + for local_rank in self._running_local_ranks: + handler = self.subprocess_handlers[local_rank] + exitcode = handler.proc.poll() + if exitcode is not None: + done_local_ranks.add(local_rank) + if exitcode != 0: # failed or signaled + self._failures[local_rank] = ProcessFailure( + local_rank=local_rank, + pid=handler.proc.pid, + exitcode=exitcode, + error_file=self.error_files[local_rank], + ) + # else: --> succeeded; nothing to do + + self._running_local_ranks.difference_update(done_local_ranks) + + # if ALL procs are finished or ANY have failed + if not self._running_local_ranks or self._failures: + self.close() # terminate all running procs + result = RunProcsResult( + failures=self._failures, + stdouts=self.stdouts, + stderrs=self.stderrs, + ) + if result.is_failed(): + first_failure = min(result.failures.values(), key=lambda f: f.timestamp) + log.error( + "failed (exitcode: %s)" + " local_rank: %s (pid: %s)" + " of binary: %s", + first_failure.exitcode, first_failure.local_rank, first_failure.pid, self.entrypoint + ) + else: + # Populate return with dummy values. This provides consistency with MultiprocessingHandler + result.return_values = dict.fromkeys(range(self.nprocs)) + + return result + else: # there are no failures and procs still running + return None + + def pids(self) -> Dict[int, int]: + return { + local_rank: sh.proc.pid + for local_rank, sh in self.subprocess_handlers.items() + } + + def _close(self, death_sig: signal.Signals, timeout: int = 30) -> None: + if not self.subprocess_handlers: + return + for handler in self.subprocess_handlers.values(): + if handler.proc.poll() is None: + log.warning( + "Sending process %s closing signal %s", handler.proc.pid, death_sig.name + ) + handler.close(death_sig=death_sig) + end = time.monotonic() + timeout + for handler in self.subprocess_handlers.values(): + time_to_wait = end - time.monotonic() + if time_to_wait <= 0: + break + try: + handler.proc.wait(time_to_wait) + except subprocess.TimeoutExpired: + # Ignore the timeout expired exception, since + # the child process will be forcefully terminated via SIGKILL + pass + for handler in self.subprocess_handlers.values(): + if handler.proc.poll() is None: + log.warning( + "Unable to shutdown process %s via %s, forcefully exiting via %s", + handler.proc.pid, death_sig, _get_kill_signal() + ) + handler.close(death_sig=_get_kill_signal()) + handler.proc.wait() diff --git a/shared/package-files/01/013646bea14fcc6ebcf35cf88b46ef339f1987ab16610c2bd19189790c934e58/blob b/shared/package-files/01/013646bea14fcc6ebcf35cf88b46ef339f1987ab16610c2bd19189790c934e58/blob new file mode 100644 index 0000000000000000000000000000000000000000..3342f66aeb062306857148333c89506890d70b2c --- /dev/null +++ b/shared/package-files/01/013646bea14fcc6ebcf35cf88b46ef339f1987ab16610c2bd19189790c934e58/blob @@ -0,0 +1,893 @@ +error(0.005244734343616636041) D0 +error(0.009495650439115321806) D0 D1 +error(0.01174504765676305171) D0 D4 +error(0.003759809683008936108) D0 D4 ^ D5 +error(0.01247236404322864256) D0 D7 +error(0.001892034723106007701) D0 D7 ^ D5 +error(0.0008573348358031663294) D0 D8 +error(0.001318876521974188558) D0 D8 ^ D5 +error(0.006924908974555257259) D1 D2 +error(0.005110154260349804647) D1 D2 ^ D10 +error(0.02916939022395684256) D1 D7 +error(0.00180923525914891822) D1 D7 ^ D9 +error(0.003036465159879479358) D1 D7 ^ D9 D10 +error(0.0008081745137478229743) D1 D7 ^ D10 +error(0.0004190860370757995622) D1 D8 +error(0.001490643433224822382) D1 D8 ^ D9 +error(0.002017439005751810698) D1 D8 ^ D10 +error(0.001728759399508619614) D1 D11 +error(0.001449023211709686695) D1 D11 ^ D10 +error(0.01178408494128844672) D1 L0 +error(0.003352373094173388777) D1 L0 ^ D9 +error(0.01538944265975773946) D2 +error(0.005371861303803349141) D2 D3 +error(0.01756847529309895142) D2 D8 +error(0.003253365025029324783) D2 D8 ^ D10 +error(0.003707520787255918181) D2 D11 +error(0.00311878905192998707) D2 D11 ^ D10 +error(0.01680952766602322734) D3 D11 +error(0.005522193180419092753) D3 L0 +error(0.01218739322361575561) D4 +error(0.0173296491843901411) D4 D7 +error(0.0193581303106237744) D4 D7 ^ D5 +error(0.01309757907203012821) D4 D12 +error(0.003221516506290710968) D4 D12 ^ D13 +error(0.006405944107513558174) D4 D15 +error(0.00817183242086269232) D4 D15 ^ D5 +error(0.003133073946867561896) D4 D15 ^ D13 +error(0.0006888883138486812238) D4 D15 ^ D13 ^ D5 +error(0.0009601017666707132312) D4 D16 +error(0.000854370735000143885) D4 D16 ^ D5 D13 +error(0.0004741246161638219261) D4 D16 ^ D13 +error(0.009504744826615776562) D4 ^ D5 +error(0.0007648512721493256304) D4 ^ D13 +error(0.003169824356772648656) D5 D13 ^ D4 +error(0.04043081034147843339) D5 +error(0.01169930805459320176) D5 D6 +error(0.001323142636729812346) D5 D6 ^ D4 +error(0.01087503386380428427) D5 D6 ^ D8 +error(0.001848530690090685472) D5 D6 ^ D8 D16 +error(0.001856075324445966403) D5 D6 ^ D16 +error(0.0003137159041512685583) D5 D6 ^ D16 ^ D4 +error(0.01558419609543277087) D5 D10 +error(0.009744119707144982198) D5 D10 ^ D7 D8 +error(0.02279220200844257749) D5 D13 +error(0.001488961618448497943) D5 D13 ^ D15 D16 +error(0.001531352171358075229) D5 D13 ^ D16 +error(0.002979184944838254249) D5 D17 +error(0.001916893783627156679) D5 D17 ^ D7 D15 +error(0.0001869345823219428185) D5 D17 ^ D7 D16 +error(0.0002543596755888904493) D5 D17 ^ D15 D16 +error(0.001904820730676128537) D5 D18 +error(0.001976644388877274623) D5 D18 ^ D7 D8 +error(0.0006014269677141524748) D5 D18 ^ D7 D15 +error(0.001319379888311604477) D5 D18 ^ D7 D16 +error(0.0005257704059546327051) D5 D18 ^ D8 D16 +error(0.001845601675876747897) D5 D18 ^ D15 D16 +error(0.004064271610288137243) D5 ^ D0 +error(0.004909016057861446958) D5 ^ D8 +error(0.0006818254208268925915) D5 ^ D15 L0 +error(0.004301117587431575739) D7 D15 ^ D5 +error(0.0343447340148326577) D6 +error(0.002390306305552239788) D6 D13 +error(0.0006029620322041566232) D6 D13 ^ D4 +error(0.002407428788310306007) D6 D13 ^ D16 +error(0.0001889916903862594799) D6 D13 ^ D16 ^ D4 +error(0.02551108346343008634) D6 D14 +error(0.002303061456115196304) D6 D14 ^ D16 +error(0.00120025549782614132) D6 D18 +error(0.0002584297321567436139) D6 D18 ^ D7 D16 +error(0.001116941506213237761) D6 D18 ^ D8 D16 +error(0.01420109343014649278) D6 ^ D8 +error(0.0004940548234322715429) D6 ^ D16 +error(0.0009773629053240386749) D6 ^ D16 ^ D8 +error(0.005000000000000000104) D7 D8 +error(0.00161247140171787021) D7 D8 ^ D5 +error(0.001209153209857843914) D7 D8 ^ D9 +error(0.0008131660872061990085) D7 D8 ^ D10 +error(0.00228883398972040816) D7 D8 ^ D10 D18 +error(0.0003173181493339865557) D7 D8 ^ D10 ^ D9 +error(0.0002159475451978183126) D7 D8 ^ D18 +error(0.02979764026993177856) D7 D15 +error(0.004822726463618352312) D7 D15 ^ D17 D18 +error(0.002701888779290216071) D7 D16 +error(0.001136231318871422022) D7 D16 ^ D17 D18 +error(0.000972237476194364467) D7 D19 +error(0.001353805965267947413) D7 D19 ^ D10 D18 +error(4.60661558852525237e-05) D7 D19 ^ D18 +error(0.01000000000000000021) D7 L0 +error(0.01358736137087923623) D7 L0 ^ D9 +error(0.0003049970504562500117) D7 L0 ^ D17 +error(0.003474384044873775768) D9 D17 ^ D7 L0 +error(0.01927256915394524872) D8 +error(0.01580153594151016694) D8 D11 +error(0.01468667037922046989) D8 D11 ^ D10 +error(0.02147827847675571472) D8 D16 +error(0.003106327090157647713) D8 D16 ^ D18 +error(0.003234697932083938163) D8 D19 +error(0.003373490407387488149) D8 D19 ^ D10 +error(0.004108975948125093147) D8 D19 ^ D18 +error(0.001733457623872466154) D8 D19 ^ D18 ^ D10 +error(0.03666006652227220969) D9 +error(0.008296187157128438738) D9 D10 +error(0.001368278441375544519) D9 D10 ^ D1 L0 +error(0.01009549502411480337) D9 D10 ^ D7 L0 +error(0.02643920077157271148) D9 D17 +error(0.02723279885413622953) D10 +error(0.002566698707180307439) D10 D17 +error(0.002085090359685817536) D10 D17 ^ D7 L0 +error(0.0007137802092043168609) D10 D17 ^ D19 L0 +error(0.001038532334963673549) D10 D17 ^ D19 L0 ^ D7 L0 +error(0.01905055614029557351) D10 D18 +error(0.0008339187507327511456) D10 D18 ^ D7 L0 +error(0.001952103134337229446) D10 D18 ^ D19 L0 +error(0.0111005601594806446) D10 ^ D11 L0 +error(0.000310143818792318047) D10 ^ D11 L0 ^ D1 L0 ^ D9 +error(0.001067669372781608573) D10 ^ D19 L0 +error(0.003363392958977172616) D11 D19 ^ D10 +error(0.0178590916355138192) D11 D19 +error(0.01006455827711810573) D11 L0 +error(0.001107931091934729944) D11 L0 ^ D1 L0 ^ D9 +error(0.01238060773132331101) D12 +error(0.01733638920184899304) D12 D15 +error(0.02007634700723412435) D12 D15 ^ D13 +error(0.01309757907203012821) D12 D20 +error(0.003221516506290710968) D12 D20 ^ D21 +error(0.006405944107513558174) D12 D23 +error(0.00817183242086269232) D12 D23 ^ D13 +error(0.003133073946867561896) D12 D23 ^ D21 +error(0.0006888883138486812238) D12 D23 ^ D21 ^ D13 +error(0.0009601017666707132312) D12 D24 +error(0.000854370735000143885) D12 D24 ^ D13 D21 +error(0.0004741246161638219261) D12 D24 ^ D21 +error(0.01207070266934146853) D12 ^ D13 +error(0.0007648512721493256304) D12 ^ D21 +error(0.003169824356772648656) D13 D21 ^ D12 +error(0.01565801448195945633) D13 +error(0.01172028158188173456) D13 D14 +error(7.046870587543194815e-05) D13 D14 ^ D12 +error(0.0002615934920829612528) D13 D14 ^ D15 D16 +error(0.01089052759554807667) D13 D14 ^ D16 +error(0.001848530690090685472) D13 D14 ^ D16 D24 +error(0.001856075324445966403) D13 D14 ^ D24 +error(0.0003137159041512685583) D13 D14 ^ D24 ^ D12 +error(0.01441046174696460243) D13 D18 +error(0.01032959589799900373) D13 D18 ^ D15 D16 +error(0.02279220200844257749) D13 D21 +error(0.001488961618448497943) D13 D21 ^ D23 D24 +error(0.001531352171358075229) D13 D21 ^ D24 +error(0.002979184944838254249) D13 D25 +error(0.001916893783627156679) D13 D25 ^ D15 D23 +error(0.0001869345823219428185) D13 D25 ^ D15 D24 +error(0.0002543596755888904493) D13 D25 ^ D23 D24 +error(0.001904820730676128537) D13 D26 +error(0.001976644388877274623) D13 D26 ^ D15 D16 +error(0.0006014269677141524748) D13 D26 ^ D15 D23 +error(0.001319379888311604477) D13 D26 ^ D15 D24 +error(0.0005257704059546327051) D13 D26 ^ D16 D24 +error(0.001845601675876747897) D13 D26 ^ D23 D24 +error(0.0006818254208268925915) D13 ^ D23 L0 +error(0.004301117587431575739) D15 D23 ^ D13 +error(0.01010252734854268086) D14 +error(0.002390306305552239788) D14 D21 +error(0.0006029620322041566232) D14 D21 ^ D12 +error(0.002407428788310306007) D14 D21 ^ D24 +error(0.0001889916903862594799) D14 D21 ^ D24 ^ D12 +error(0.02551108346343008634) D14 D22 +error(0.002303061456115196304) D14 D22 ^ D24 +error(0.00120025549782614132) D14 D26 +error(0.0002584297321567436139) D14 D26 ^ D15 D24 +error(0.001116941506213237761) D14 D26 ^ D16 D24 +error(0.01088400880819501149) D14 ^ D16 +error(0.0004940548234322715429) D14 ^ D24 +error(0.0009773629053240386749) D14 ^ D24 ^ D16 +error(0.009701150545301108485) D15 D16 +error(0.0001089099398904180008) D15 D16 ^ D5 +error(0.0003379851821271760356) D15 D16 ^ D13 +error(0.001028780097136624671) D15 D16 ^ D17 D18 +error(0.00228883398972040816) D15 D16 ^ D18 D26 +error(0.0002159475451978183126) D15 D16 ^ D26 +error(0.02979764026993177856) D15 D23 +error(0.004822726463618352312) D15 D23 ^ D25 D26 +error(0.002701888779290216071) D15 D24 +error(0.001136231318871422022) D15 D24 ^ D25 D26 +error(0.000972237476194364467) D15 D27 +error(0.001353805965267947413) D15 D27 ^ D18 D26 +error(4.60661558852525237e-05) D15 D27 ^ D26 +error(0.01200915566688168408) D15 L0 +error(0.01267141414585852902) D15 L0 ^ D17 +error(0.0003049970504562500117) D15 L0 ^ D25 +error(0.003474384044873775768) D17 D25 ^ D15 L0 +error(0.01760690989830183267) D16 +error(0.01761034888769726428) D16 D19 +error(0.01677373156352225669) D16 D19 ^ D18 +error(0.02147827847675571472) D16 D24 +error(0.003106327090157647713) D16 D24 ^ D26 +error(0.003234697932083938163) D16 D27 +error(0.003373490407387488149) D16 D27 ^ D18 +error(0.004108975948125093147) D16 D27 ^ D26 +error(0.001733457623872466154) D16 D27 ^ D26 ^ D18 +error(0.007592331923338608603) D17 +error(0.006958356509377302233) D17 D18 +error(0.0006072550393666976314) D17 D18 ^ D7 L0 +error(0.01199870467680090938) D17 D18 ^ D15 L0 +error(0.0007883610290700396794) D17 D18 ^ D19 L0 +error(0.0006337473548558848454) D17 D18 ^ D19 L0 ^ D7 L0 +error(0.02643920077157271148) D17 D25 +error(8.570995328558527859e-05) D17 ^ D5 ^ D15 L0 +error(0.00100458663257940381) D17 ^ D15 L0 ^ D7 L0 +error(0.01138557969942347037) D18 +error(0.002566698707180307439) D18 D25 +error(0.002085090359685817536) D18 D25 ^ D15 L0 +error(0.0007137802092043168609) D18 D25 ^ D27 L0 +error(0.001038532334963673549) D18 D25 ^ D27 L0 ^ D15 L0 +error(0.01905055614029557351) D18 D26 +error(0.0008339187507327511456) D18 D26 ^ D15 L0 +error(0.001952103134337229446) D18 D26 ^ D27 L0 +error(0.000125594406637713306) D18 ^ D6 ^ D8 +error(0.0002542444322934897831) D18 ^ D6 ^ D16 +error(0.007176519871716447417) D18 ^ D19 L0 +error(0.001067669372781608573) D18 ^ D27 L0 +error(0.003363392958977172616) D19 D27 ^ D18 +error(0.0178590916355138192) D19 D27 +error(0.01442846781429796103) D19 L0 +error(0.01238060773132331101) D20 +error(0.01733638920184899304) D20 D23 +error(0.02007634700723412435) D20 D23 ^ D21 +error(0.01309757907203012821) D20 D28 +error(0.003221516506290710968) D20 D28 ^ D29 +error(0.006405944107513558174) D20 D31 +error(0.00817183242086269232) D20 D31 ^ D21 +error(0.003133073946867561896) D20 D31 ^ D29 +error(0.0006888883138486812238) D20 D31 ^ D29 ^ D21 +error(0.0009601017666707132312) D20 D32 +error(0.000854370735000143885) D20 D32 ^ D21 D29 +error(0.0004741246161638219261) D20 D32 ^ D29 +error(0.01207070266934146853) D20 ^ D21 +error(0.0007648512721493256304) D20 ^ D29 +error(0.003169824356772648656) D21 D29 ^ D20 +error(0.01565801448195945633) D21 +error(0.01172028158188173456) D21 D22 +error(7.046870587543194815e-05) D21 D22 ^ D20 +error(0.0002615934920829612528) D21 D22 ^ D23 D24 +error(0.01089052759554807667) D21 D22 ^ D24 +error(0.001848530690090685472) D21 D22 ^ D24 D32 +error(0.001856075324445966403) D21 D22 ^ D32 +error(0.0003137159041512685583) D21 D22 ^ D32 ^ D20 +error(0.01441046174696460243) D21 D26 +error(0.01032959589799900373) D21 D26 ^ D23 D24 +error(0.02279220200844257749) D21 D29 +error(0.001488961618448497943) D21 D29 ^ D31 D32 +error(0.001531352171358075229) D21 D29 ^ D32 +error(0.002979184944838254249) D21 D33 +error(0.001916893783627156679) D21 D33 ^ D23 D31 +error(0.0001869345823219428185) D21 D33 ^ D23 D32 +error(0.0002543596755888904493) D21 D33 ^ D31 D32 +error(0.001904820730676128537) D21 D34 +error(0.001976644388877274623) D21 D34 ^ D23 D24 +error(0.0006014269677141524748) D21 D34 ^ D23 D31 +error(0.001319379888311604477) D21 D34 ^ D23 D32 +error(0.0005257704059546327051) D21 D34 ^ D24 D32 +error(0.001845601675876747897) D21 D34 ^ D31 D32 +error(0.0006818254208268925915) D21 ^ D31 L0 +error(0.004301117587431575739) D23 D31 ^ D21 +error(0.01010252734854268086) D22 +error(0.002390306305552239788) D22 D29 +error(0.0006029620322041566232) D22 D29 ^ D20 +error(0.002407428788310306007) D22 D29 ^ D32 +error(0.0001889916903862594799) D22 D29 ^ D32 ^ D20 +error(0.02551108346343008634) D22 D30 +error(0.002303061456115196304) D22 D30 ^ D32 +error(0.00120025549782614132) D22 D34 +error(0.0002584297321567436139) D22 D34 ^ D23 D32 +error(0.001116941506213237761) D22 D34 ^ D24 D32 +error(0.01088400880819501149) D22 ^ D24 +error(0.0004940548234322715429) D22 ^ D32 +error(0.0009773629053240386749) D22 ^ D32 ^ D24 +error(0.009701150545301108485) D23 D24 +error(0.0001089099398904180008) D23 D24 ^ D13 +error(0.0003379851821271760356) D23 D24 ^ D21 +error(0.001028780097136624671) D23 D24 ^ D25 D26 +error(0.00228883398972040816) D23 D24 ^ D26 D34 +error(0.0002159475451978183126) D23 D24 ^ D34 +error(0.02979764026993177856) D23 D31 +error(0.004822726463618352312) D23 D31 ^ D33 D34 +error(0.002701888779290216071) D23 D32 +error(0.001136231318871422022) D23 D32 ^ D33 D34 +error(0.000972237476194364467) D23 D35 +error(0.001353805965267947413) D23 D35 ^ D26 D34 +error(4.60661558852525237e-05) D23 D35 ^ D34 +error(0.01200915566688168408) D23 L0 +error(0.01267141414585852902) D23 L0 ^ D25 +error(0.0003049970504562500117) D23 L0 ^ D33 +error(0.003474384044873775768) D25 D33 ^ D23 L0 +error(0.01760690989830183267) D24 +error(0.01761034888769726428) D24 D27 +error(0.01677373156352225669) D24 D27 ^ D26 +error(0.02147827847675571472) D24 D32 +error(0.003106327090157647713) D24 D32 ^ D34 +error(0.003234697932083938163) D24 D35 +error(0.003373490407387488149) D24 D35 ^ D26 +error(0.004108975948125093147) D24 D35 ^ D34 +error(0.001733457623872466154) D24 D35 ^ D34 ^ D26 +error(0.007592331923338608603) D25 +error(0.006958356509377302233) D25 D26 +error(0.0006072550393666976314) D25 D26 ^ D15 L0 +error(0.01199870467680090938) D25 D26 ^ D23 L0 +error(0.0007883610290700396794) D25 D26 ^ D27 L0 +error(0.0006337473548558848454) D25 D26 ^ D27 L0 ^ D15 L0 +error(0.02643920077157271148) D25 D33 +error(8.570995328558527859e-05) D25 ^ D13 ^ D23 L0 +error(0.00100458663257940381) D25 ^ D23 L0 ^ D15 L0 +error(0.01138557969942347037) D26 +error(0.002566698707180307439) D26 D33 +error(0.002085090359685817536) D26 D33 ^ D23 L0 +error(0.0007137802092043168609) D26 D33 ^ D35 L0 +error(0.001038532334963673549) D26 D33 ^ D35 L0 ^ D23 L0 +error(0.01905055614029557351) D26 D34 +error(0.0008339187507327511456) D26 D34 ^ D23 L0 +error(0.001952103134337229446) D26 D34 ^ D35 L0 +error(0.000125594406637713306) D26 ^ D14 ^ D16 +error(0.0002542444322934897831) D26 ^ D14 ^ D24 +error(0.007176519871716447417) D26 ^ D27 L0 +error(0.001067669372781608573) D26 ^ D35 L0 +error(0.003363392958977172616) D27 D35 ^ D26 +error(0.0178590916355138192) D27 D35 +error(0.01442846781429796103) D27 L0 +error(0.01238060773132331101) D28 +error(0.01733638920184899304) D28 D31 +error(0.02007634700723412435) D28 D31 ^ D29 +error(0.01309757907203012821) D28 D36 +error(0.003221516506290710968) D28 D36 ^ D37 +error(0.006405944107513558174) D28 D39 +error(0.00817183242086269232) D28 D39 ^ D29 +error(0.003133073946867561896) D28 D39 ^ D37 +error(0.0006888883138486812238) D28 D39 ^ D37 ^ D29 +error(0.0009601017666707132312) D28 D40 +error(0.000854370735000143885) D28 D40 ^ D29 D37 +error(0.0004741246161638219261) D28 D40 ^ D37 +error(0.01207070266934146853) D28 ^ D29 +error(0.0007648512721493256304) D28 ^ D37 +error(0.003169824356772648656) D29 D37 ^ D28 +error(0.01565801448195945633) D29 +error(0.01172028158188173456) D29 D30 +error(7.046870587543194815e-05) D29 D30 ^ D28 +error(0.0002615934920829612528) D29 D30 ^ D31 D32 +error(0.01089052759554807667) D29 D30 ^ D32 +error(0.001848530690090685472) D29 D30 ^ D32 D40 +error(0.001856075324445966403) D29 D30 ^ D40 +error(0.0003137159041512685583) D29 D30 ^ D40 ^ D28 +error(0.01441046174696460243) D29 D34 +error(0.01032959589799900373) D29 D34 ^ D31 D32 +error(0.02279220200844257749) D29 D37 +error(0.001488961618448497943) D29 D37 ^ D39 D40 +error(0.001531352171358075229) D29 D37 ^ D40 +error(0.002979184944838254249) D29 D41 +error(0.001916893783627156679) D29 D41 ^ D31 D39 +error(0.0001869345823219428185) D29 D41 ^ D31 D40 +error(0.0002543596755888904493) D29 D41 ^ D39 D40 +error(0.001904820730676128537) D29 D42 +error(0.001976644388877274623) D29 D42 ^ D31 D32 +error(0.0006014269677141524748) D29 D42 ^ D31 D39 +error(0.001319379888311604477) D29 D42 ^ D31 D40 +error(0.0005257704059546327051) D29 D42 ^ D32 D40 +error(0.001845601675876747897) D29 D42 ^ D39 D40 +error(0.0006818254208268925915) D29 ^ D39 L0 +error(0.004301117587431575739) D31 D39 ^ D29 +error(0.01010252734854268086) D30 +error(0.002390306305552239788) D30 D37 +error(0.0006029620322041566232) D30 D37 ^ D28 +error(0.002407428788310306007) D30 D37 ^ D40 +error(0.0001889916903862594799) D30 D37 ^ D40 ^ D28 +error(0.02551108346343008634) D30 D38 +error(0.002303061456115196304) D30 D38 ^ D40 +error(0.00120025549782614132) D30 D42 +error(0.0002584297321567436139) D30 D42 ^ D31 D40 +error(0.001116941506213237761) D30 D42 ^ D32 D40 +error(0.01088400880819501149) D30 ^ D32 +error(0.0004940548234322715429) D30 ^ D40 +error(0.0009773629053240386749) D30 ^ D40 ^ D32 +error(0.009701150545301108485) D31 D32 +error(0.0001089099398904180008) D31 D32 ^ D21 +error(0.0003379851821271760356) D31 D32 ^ D29 +error(0.001028780097136624671) D31 D32 ^ D33 D34 +error(0.00228883398972040816) D31 D32 ^ D34 D42 +error(0.0002159475451978183126) D31 D32 ^ D42 +error(0.02979764026993177856) D31 D39 +error(0.004822726463618352312) D31 D39 ^ D41 D42 +error(0.002701888779290216071) D31 D40 +error(0.001136231318871422022) D31 D40 ^ D41 D42 +error(0.000972237476194364467) D31 D43 +error(0.001353805965267947413) D31 D43 ^ D34 D42 +error(4.60661558852525237e-05) D31 D43 ^ D42 +error(0.01200915566688168408) D31 L0 +error(0.01267141414585852902) D31 L0 ^ D33 +error(0.0003049970504562500117) D31 L0 ^ D41 +error(0.003474384044873775768) D33 D41 ^ D31 L0 +error(0.01760690989830183267) D32 +error(0.01761034888769726428) D32 D35 +error(0.01677373156352225669) D32 D35 ^ D34 +error(0.02147827847675571472) D32 D40 +error(0.003106327090157647713) D32 D40 ^ D42 +error(0.003234697932083938163) D32 D43 +error(0.003373490407387488149) D32 D43 ^ D34 +error(0.004108975948125093147) D32 D43 ^ D42 +error(0.001733457623872466154) D32 D43 ^ D42 ^ D34 +error(0.007592331923338608603) D33 +error(0.006958356509377302233) D33 D34 +error(0.0006072550393666976314) D33 D34 ^ D23 L0 +error(0.01199870467680090938) D33 D34 ^ D31 L0 +error(0.0007883610290700396794) D33 D34 ^ D35 L0 +error(0.0006337473548558848454) D33 D34 ^ D35 L0 ^ D23 L0 +error(0.02643920077157271148) D33 D41 +error(8.570995328558527859e-05) D33 ^ D21 ^ D31 L0 +error(0.00100458663257940381) D33 ^ D31 L0 ^ D23 L0 +error(0.01138557969942347037) D34 +error(0.002566698707180307439) D34 D41 +error(0.002085090359685817536) D34 D41 ^ D31 L0 +error(0.0007137802092043168609) D34 D41 ^ D43 L0 +error(0.001038532334963673549) D34 D41 ^ D43 L0 ^ D31 L0 +error(0.01905055614029557351) D34 D42 +error(0.0008339187507327511456) D34 D42 ^ D31 L0 +error(0.001952103134337229446) D34 D42 ^ D43 L0 +error(0.000125594406637713306) D34 ^ D22 ^ D24 +error(0.0002542444322934897831) D34 ^ D22 ^ D32 +error(0.007176519871716447417) D34 ^ D35 L0 +error(0.001067669372781608573) D34 ^ D43 L0 +error(0.003363392958977172616) D35 D43 ^ D34 +error(0.0178590916355138192) D35 D43 +error(0.01442846781429796103) D35 L0 +error(0.01238060773132331101) D36 +error(0.01733638920184899304) D36 D39 +error(0.02007634700723412435) D36 D39 ^ D37 +error(0.01309757907203012821) D36 D44 +error(0.003221516506290710968) D36 D44 ^ D45 +error(0.006405944107513558174) D36 D47 +error(0.00817183242086269232) D36 D47 ^ D37 +error(0.003133073946867561896) D36 D47 ^ D45 +error(0.0006888883138486812238) D36 D47 ^ D45 ^ D37 +error(0.0009601017666707132312) D36 D48 +error(0.000854370735000143885) D36 D48 ^ D37 D45 +error(0.0004741246161638219261) D36 D48 ^ D45 +error(0.01207070266934146853) D36 ^ D37 +error(0.0007648512721493256304) D36 ^ D45 +error(0.003169824356772648656) D37 D45 ^ D36 +error(0.01565801448195945633) D37 +error(0.01172028158188173456) D37 D38 +error(7.046870587543194815e-05) D37 D38 ^ D36 +error(0.0002615934920829612528) D37 D38 ^ D39 D40 +error(0.01089052759554807667) D37 D38 ^ D40 +error(0.001848530690090685472) D37 D38 ^ D40 D48 +error(0.001856075324445966403) D37 D38 ^ D48 +error(0.0003137159041512685583) D37 D38 ^ D48 ^ D36 +error(0.01441046174696460243) D37 D42 +error(0.01032959589799900373) D37 D42 ^ D39 D40 +error(0.02279220200844257749) D37 D45 +error(0.001488961618448497943) D37 D45 ^ D47 D48 +error(0.001531352171358075229) D37 D45 ^ D48 +error(0.002979184944838254249) D37 D49 +error(0.001916893783627156679) D37 D49 ^ D39 D47 +error(0.0001869345823219428185) D37 D49 ^ D39 D48 +error(0.0002543596755888904493) D37 D49 ^ D47 D48 +error(0.001904820730676128537) D37 D50 +error(0.001976644388877274623) D37 D50 ^ D39 D40 +error(0.0006014269677141524748) D37 D50 ^ D39 D47 +error(0.001319379888311604477) D37 D50 ^ D39 D48 +error(0.0005257704059546327051) D37 D50 ^ D40 D48 +error(0.001845601675876747897) D37 D50 ^ D47 D48 +error(0.0006818254208268925915) D37 ^ D47 L0 +error(0.004301117587431575739) D39 D47 ^ D37 +error(0.01010252734854268086) D38 +error(0.002390306305552239788) D38 D45 +error(0.0006029620322041566232) D38 D45 ^ D36 +error(0.002407428788310306007) D38 D45 ^ D48 +error(0.0001889916903862594799) D38 D45 ^ D48 ^ D36 +error(0.02551108346343008634) D38 D46 +error(0.002303061456115196304) D38 D46 ^ D48 +error(0.00120025549782614132) D38 D50 +error(0.0002584297321567436139) D38 D50 ^ D39 D48 +error(0.001116941506213237761) D38 D50 ^ D40 D48 +error(0.01088400880819501149) D38 ^ D40 +error(0.0004940548234322715429) D38 ^ D48 +error(0.0009773629053240386749) D38 ^ D48 ^ D40 +error(0.009701150545301108485) D39 D40 +error(0.0001089099398904180008) D39 D40 ^ D29 +error(0.0003379851821271760356) D39 D40 ^ D37 +error(0.001028780097136624671) D39 D40 ^ D41 D42 +error(0.00228883398972040816) D39 D40 ^ D42 D50 +error(0.0002159475451978183126) D39 D40 ^ D50 +error(0.02979764026993177856) D39 D47 +error(0.004822726463618352312) D39 D47 ^ D49 D50 +error(0.002701888779290216071) D39 D48 +error(0.001136231318871422022) D39 D48 ^ D49 D50 +error(0.000972237476194364467) D39 D51 +error(0.001353805965267947413) D39 D51 ^ D42 D50 +error(4.60661558852525237e-05) D39 D51 ^ D50 +error(0.01200915566688168408) D39 L0 +error(0.01267141414585852902) D39 L0 ^ D41 +error(0.0003049970504562500117) D39 L0 ^ D49 +error(0.003474384044873775768) D41 D49 ^ D39 L0 +error(0.01760690989830183267) D40 +error(0.01761034888769726428) D40 D43 +error(0.01677373156352225669) D40 D43 ^ D42 +error(0.02147827847675571472) D40 D48 +error(0.003106327090157647713) D40 D48 ^ D50 +error(0.003234697932083938163) D40 D51 +error(0.003373490407387488149) D40 D51 ^ D42 +error(0.004108975948125093147) D40 D51 ^ D50 +error(0.001733457623872466154) D40 D51 ^ D50 ^ D42 +error(0.007592331923338608603) D41 +error(0.006958356509377302233) D41 D42 +error(0.0006072550393666976314) D41 D42 ^ D31 L0 +error(0.01199870467680090938) D41 D42 ^ D39 L0 +error(0.0007883610290700396794) D41 D42 ^ D43 L0 +error(0.0006337473548558848454) D41 D42 ^ D43 L0 ^ D31 L0 +error(0.02643920077157271148) D41 D49 +error(8.570995328558527859e-05) D41 ^ D29 ^ D39 L0 +error(0.00100458663257940381) D41 ^ D39 L0 ^ D31 L0 +error(0.01138557969942347037) D42 +error(0.002566698707180307439) D42 D49 +error(0.002085090359685817536) D42 D49 ^ D39 L0 +error(0.0007137802092043168609) D42 D49 ^ D51 L0 +error(0.001038532334963673549) D42 D49 ^ D51 L0 ^ D39 L0 +error(0.01905055614029557351) D42 D50 +error(0.0008339187507327511456) D42 D50 ^ D39 L0 +error(0.001952103134337229446) D42 D50 ^ D51 L0 +error(0.000125594406637713306) D42 ^ D30 ^ D32 +error(0.0002542444322934897831) D42 ^ D30 ^ D40 +error(0.007176519871716447417) D42 ^ D43 L0 +error(0.001067669372781608573) D42 ^ D51 L0 +error(0.003363392958977172616) D43 D51 ^ D42 +error(0.0178590916355138192) D43 D51 +error(0.01442846781429796103) D43 L0 +error(0.01238060773132331101) D44 +error(0.01733638920184899304) D44 D47 +error(0.02007634700723412435) D44 D47 ^ D45 +error(0.01309757907203012821) D44 D52 +error(0.003221516506290710968) D44 D52 ^ D53 +error(0.006405944107513558174) D44 D55 +error(0.00817183242086269232) D44 D55 ^ D45 +error(0.003133073946867561896) D44 D55 ^ D53 +error(0.0006888883138486812238) D44 D55 ^ D53 ^ D45 +error(0.0009601017666707132312) D44 D56 +error(0.000854370735000143885) D44 D56 ^ D45 D53 +error(0.0004741246161638219261) D44 D56 ^ D53 +error(0.01207070266934146853) D44 ^ D45 +error(0.0007648512721493256304) D44 ^ D53 +error(0.003169824356772648656) D45 D53 ^ D44 +error(0.01565801448195945633) D45 +error(0.01172028158188173456) D45 D46 +error(7.046870587543194815e-05) D45 D46 ^ D44 +error(0.0002615934920829612528) D45 D46 ^ D47 D48 +error(0.01089052759554807667) D45 D46 ^ D48 +error(0.001848530690090685472) D45 D46 ^ D48 D56 +error(0.001856075324445966403) D45 D46 ^ D56 +error(0.0003137159041512685583) D45 D46 ^ D56 ^ D44 +error(0.01441046174696460243) D45 D50 +error(0.01032959589799900373) D45 D50 ^ D47 D48 +error(0.02279220200844257749) D45 D53 +error(0.001488961618448497943) D45 D53 ^ D55 D56 +error(0.001531352171358075229) D45 D53 ^ D56 +error(0.002979184944838254249) D45 D57 +error(0.001916893783627156679) D45 D57 ^ D47 D55 +error(0.0001869345823219428185) D45 D57 ^ D47 D56 +error(0.0002543596755888904493) D45 D57 ^ D55 D56 +error(0.001904820730676128537) D45 D58 +error(0.001976644388877274623) D45 D58 ^ D47 D48 +error(0.0006014269677141524748) D45 D58 ^ D47 D55 +error(0.001319379888311604477) D45 D58 ^ D47 D56 +error(0.0005257704059546327051) D45 D58 ^ D48 D56 +error(0.001845601675876747897) D45 D58 ^ D55 D56 +error(0.0006818254208268925915) D45 ^ D55 L0 +error(0.004301117587431575739) D47 D55 ^ D45 +error(0.01010252734854268086) D46 +error(0.002390306305552239788) D46 D53 +error(0.0006029620322041566232) D46 D53 ^ D44 +error(0.002407428788310306007) D46 D53 ^ D56 +error(0.0001889916903862594799) D46 D53 ^ D56 ^ D44 +error(0.02551108346343008634) D46 D54 +error(0.002303061456115196304) D46 D54 ^ D56 +error(0.00120025549782614132) D46 D58 +error(0.0002584297321567436139) D46 D58 ^ D47 D56 +error(0.001116941506213237761) D46 D58 ^ D48 D56 +error(0.01088400880819501149) D46 ^ D48 +error(0.0004940548234322715429) D46 ^ D56 +error(0.0009773629053240386749) D46 ^ D56 ^ D48 +error(0.009701150545301108485) D47 D48 +error(0.0001089099398904180008) D47 D48 ^ D37 +error(0.0003379851821271760356) D47 D48 ^ D45 +error(0.001028780097136624671) D47 D48 ^ D49 D50 +error(0.00228883398972040816) D47 D48 ^ D50 D58 +error(0.0002159475451978183126) D47 D48 ^ D58 +error(0.02979764026993177856) D47 D55 +error(0.004822726463618352312) D47 D55 ^ D57 D58 +error(0.002701888779290216071) D47 D56 +error(0.001136231318871422022) D47 D56 ^ D57 D58 +error(0.000972237476194364467) D47 D59 +error(0.001353805965267947413) D47 D59 ^ D50 D58 +error(4.60661558852525237e-05) D47 D59 ^ D58 +error(0.01200915566688168408) D47 L0 +error(0.01267141414585852902) D47 L0 ^ D49 +error(0.0003049970504562500117) D47 L0 ^ D57 +error(0.003474384044873775768) D49 D57 ^ D47 L0 +error(0.01760690989830183267) D48 +error(0.01761034888769726428) D48 D51 +error(0.01677373156352225669) D48 D51 ^ D50 +error(0.02147827847675571472) D48 D56 +error(0.003106327090157647713) D48 D56 ^ D58 +error(0.003234697932083938163) D48 D59 +error(0.003373490407387488149) D48 D59 ^ D50 +error(0.004108975948125093147) D48 D59 ^ D58 +error(0.001733457623872466154) D48 D59 ^ D58 ^ D50 +error(0.007592331923338608603) D49 +error(0.006958356509377302233) D49 D50 +error(0.0006072550393666976314) D49 D50 ^ D39 L0 +error(0.01199870467680090938) D49 D50 ^ D47 L0 +error(0.0007883610290700396794) D49 D50 ^ D51 L0 +error(0.0006337473548558848454) D49 D50 ^ D51 L0 ^ D39 L0 +error(0.02643920077157271148) D49 D57 +error(8.570995328558527859e-05) D49 ^ D37 ^ D47 L0 +error(0.00100458663257940381) D49 ^ D47 L0 ^ D39 L0 +error(0.01138557969942347037) D50 +error(0.002566698707180307439) D50 D57 +error(0.002085090359685817536) D50 D57 ^ D47 L0 +error(0.0007137802092043168609) D50 D57 ^ D59 L0 +error(0.001038532334963673549) D50 D57 ^ D59 L0 ^ D47 L0 +error(0.01905055614029557351) D50 D58 +error(0.0008339187507327511456) D50 D58 ^ D47 L0 +error(0.001952103134337229446) D50 D58 ^ D59 L0 +error(0.000125594406637713306) D50 ^ D38 ^ D40 +error(0.0002542444322934897831) D50 ^ D38 ^ D48 +error(0.007176519871716447417) D50 ^ D51 L0 +error(0.001067669372781608573) D50 ^ D59 L0 +error(0.003363392958977172616) D51 D59 ^ D50 +error(0.0178590916355138192) D51 D59 +error(0.01442846781429796103) D51 L0 +error(0.01238060773132331101) D52 +error(0.01733638920184899304) D52 D55 +error(0.02007634700723412435) D52 D55 ^ D53 +error(0.01309757907203012821) D52 D60 +error(0.003221516506290710968) D52 D60 ^ D61 +error(0.006405944107513558174) D52 D63 +error(0.00817183242086269232) D52 D63 ^ D53 +error(0.003133073946867561896) D52 D63 ^ D61 +error(0.0006888883138486812238) D52 D63 ^ D61 ^ D53 +error(0.0009601017666707132312) D52 D64 +error(0.000854370735000143885) D52 D64 ^ D53 D61 +error(0.0004741246161638219261) D52 D64 ^ D61 +error(0.01207070266934146853) D52 ^ D53 +error(0.0007648512721493256304) D52 ^ D61 +error(0.003169824356772648656) D53 D61 ^ D52 +error(0.01565801448195945633) D53 +error(0.01172028158188173456) D53 D54 +error(7.046870587543194815e-05) D53 D54 ^ D52 +error(0.0002615934920829612528) D53 D54 ^ D55 D56 +error(0.01089052759554807667) D53 D54 ^ D56 +error(0.001848530690090685472) D53 D54 ^ D56 D64 +error(0.001856075324445966403) D53 D54 ^ D64 +error(0.0003137159041512685583) D53 D54 ^ D64 ^ D52 +error(0.01441046174696460243) D53 D58 +error(0.01032959589799900373) D53 D58 ^ D55 D56 +error(0.02279220200844257749) D53 D61 +error(0.001488961618448497943) D53 D61 ^ D63 D64 +error(0.001531352171358075229) D53 D61 ^ D64 +error(0.002979184944838254249) D53 D65 +error(0.001916893783627156679) D53 D65 ^ D55 D63 +error(0.0001869345823219428185) D53 D65 ^ D55 D64 +error(0.0002543596755888904493) D53 D65 ^ D63 D64 +error(0.001904820730676128537) D53 D66 +error(0.001976644388877274623) D53 D66 ^ D55 D56 +error(0.0006014269677141524748) D53 D66 ^ D55 D63 +error(0.001319379888311604477) D53 D66 ^ D55 D64 +error(0.0005257704059546327051) D53 D66 ^ D56 D64 +error(0.001845601675876747897) D53 D66 ^ D63 D64 +error(0.0006818254208268925915) D53 ^ D63 L0 +error(0.004301117587431575739) D55 D63 ^ D53 +error(0.01010252734854268086) D54 +error(0.002390306305552239788) D54 D61 +error(0.0006029620322041566232) D54 D61 ^ D52 +error(0.002407428788310306007) D54 D61 ^ D64 +error(0.0001889916903862594799) D54 D61 ^ D64 ^ D52 +error(0.02551108346343008634) D54 D62 +error(0.002303061456115196304) D54 D62 ^ D64 +error(0.00120025549782614132) D54 D66 +error(0.0002584297321567436139) D54 D66 ^ D55 D64 +error(0.001116941506213237761) D54 D66 ^ D56 D64 +error(0.01088400880819501149) D54 ^ D56 +error(0.0004940548234322715429) D54 ^ D64 +error(0.0009773629053240386749) D54 ^ D64 ^ D56 +error(0.009701150545301108485) D55 D56 +error(0.0001089099398904180008) D55 D56 ^ D45 +error(0.0003379851821271760356) D55 D56 ^ D53 +error(0.001028780097136624671) D55 D56 ^ D57 D58 +error(0.00228883398972040816) D55 D56 ^ D58 D66 +error(0.0002159475451978183126) D55 D56 ^ D66 +error(0.02979764026993177856) D55 D63 +error(0.004822726463618352312) D55 D63 ^ D65 D66 +error(0.002701888779290216071) D55 D64 +error(0.001136231318871422022) D55 D64 ^ D65 D66 +error(0.000972237476194364467) D55 D67 +error(0.001353805965267947413) D55 D67 ^ D58 D66 +error(4.60661558852525237e-05) D55 D67 ^ D66 +error(0.01200915566688168408) D55 L0 +error(0.01267141414585852902) D55 L0 ^ D57 +error(0.0003049970504562500117) D55 L0 ^ D65 +error(0.003474384044873775768) D57 D65 ^ D55 L0 +error(0.01760690989830183267) D56 +error(0.01761034888769726428) D56 D59 +error(0.01677373156352225669) D56 D59 ^ D58 +error(0.02147827847675571472) D56 D64 +error(0.003106327090157647713) D56 D64 ^ D66 +error(0.003234697932083938163) D56 D67 +error(0.003373490407387488149) D56 D67 ^ D58 +error(0.004108975948125093147) D56 D67 ^ D66 +error(0.001733457623872466154) D56 D67 ^ D66 ^ D58 +error(0.007592331923338608603) D57 +error(0.006958356509377302233) D57 D58 +error(0.0006072550393666976314) D57 D58 ^ D47 L0 +error(0.01199870467680090938) D57 D58 ^ D55 L0 +error(0.0007883610290700396794) D57 D58 ^ D59 L0 +error(0.0006337473548558848454) D57 D58 ^ D59 L0 ^ D47 L0 +error(0.02643920077157271148) D57 D65 +error(8.570995328558527859e-05) D57 ^ D45 ^ D55 L0 +error(0.00100458663257940381) D57 ^ D55 L0 ^ D47 L0 +error(0.01138557969942347037) D58 +error(0.002566698707180307439) D58 D65 +error(0.002085090359685817536) D58 D65 ^ D55 L0 +error(0.0007137802092043168609) D58 D65 ^ D67 L0 +error(0.001038532334963673549) D58 D65 ^ D67 L0 ^ D55 L0 +error(0.01905055614029557351) D58 D66 +error(0.0008339187507327511456) D58 D66 ^ D55 L0 +error(0.001952103134337229446) D58 D66 ^ D67 L0 +error(0.000125594406637713306) D58 ^ D46 ^ D48 +error(0.0002542444322934897831) D58 ^ D46 ^ D56 +error(0.007176519871716447417) D58 ^ D59 L0 +error(0.001067669372781608573) D58 ^ D67 L0 +error(0.003363392958977172616) D59 D67 ^ D58 +error(0.0178590916355138192) D59 D67 +error(0.01442846781429796103) D59 L0 +error(0.01345248728910399157) D60 +error(0.01882166522782919779) D60 D63 +error(0.01854792276734500145) D60 D63 ^ D61 +error(0.01648315234940495033) D60 D68 +error(0.01007879424158190061) D60 D69 +error(0.00830807156291218929) D60 D69 ^ D61 +error(0.001511044255528746832) D60 D70 +error(0.0006218521489624843782) D60 D70 ^ D61 +error(0.01560336281941558483) D60 ^ D61 +error(0.0002029315100892712493) D60 ^ D62 +error(0.04128120413111031201) D61 +error(0.01022053368908669262) D61 D62 +error(0.01056596263858442138) D61 D62 ^ D64 +error(0.002597348474854662293) D61 D62 ^ D64 D70 +error(0.001474996243934519405) D61 D62 ^ D70 +error(0.0138756600117021494) D61 D66 +error(0.00968835880322500495) D61 D66 ^ D63 D64 +error(0.0007036788925707222015) D61 ^ D60 ^ D62 +error(0.0006705389311994457147) D61 ^ D63 L0 +error(0.001160745875873206564) D61 ^ D69 L0 +error(0.005774273397071816305) D63 D69 ^ D61 +error(0.001908652379975875899) D61 ^ D70 +error(0.000419217170982119137) D61 ^ D70 ^ D60 ^ D62 +error(0.03663269349308410222) D62 +error(0.01251347126814495413) D62 ^ D64 +error(0.005161055838836031348) D62 ^ D70 +error(0.003091052617810464628) D64 D70 ^ D62 +error(0.006403280225691093328) D63 D64 +error(0.0001089099398904180008) D63 D64 ^ D53 +error(0.001087168964617422949) D63 D64 ^ D61 +error(0.0008971292328655107104) D63 D64 ^ D62 +error(0.0005792780737786086759) D63 D64 ^ D62 ^ D61 +error(0.004561330715357028547) D63 D64 ^ D66 +error(0.0349168558067340859) D63 D69 +error(0.002764835140004104873) D63 D70 +error(0.0008019519723799891026) D63 D70 ^ D61 +error(0.0009322533495864944843) D63 D70 ^ D62 +error(0.001041907208211227892) D63 D71 +error(0.002179183167117189346) D63 D71 ^ D66 +error(0.0135846140562406667) D63 L0 +error(0.01834942197067787606) D63 L0 ^ D65 +error(0.02304061350558099866) D64 +error(0.01661196147829684805) D64 D67 +error(0.0166043375008063411) D64 D67 ^ D66 +error(0.02013677496755272162) D64 D70 +error(0.001091723305004561927) D64 D70 ^ D61 +error(0.007636808979365261769) D64 D71 +error(0.002708782275456408407) D64 D71 ^ D66 +error(0.03575638419780165222) D65 +error(0.005576014082652112382) D65 D66 +error(0.0006072550393666976314) D65 D66 ^ D55 L0 +error(0.01125146517578896194) D65 D66 ^ D63 L0 +error(0.001279967611630104763) D65 D66 ^ D67 L0 +error(0.0006337473548558848454) D65 D66 ^ D67 L0 ^ D55 L0 +error(8.570995328558527859e-05) D65 ^ D53 ^ D63 L0 +error(0.00100458663257940381) D65 ^ D63 L0 ^ D55 L0 +error(0.03567040778160103509) D66 +error(0.000125594406637713306) D66 ^ D54 ^ D56 +error(0.0002542444322934897831) D66 ^ D54 ^ D64 +error(0.007525930707797243678) D66 ^ D67 L0 +error(0.006885975512507964795) D66 ^ D71 L0 +error(0.004386602732619691337) D67 D71 ^ D66 +error(0.01960394767567931809) D67 D71 +error(0.008813218108055843186) D67 L0 +error(0.01906140021747862456) D68 +error(0.01501216600007199142) D68 D69 +error(0.01438246392604512758) D69 D70 +error(0.002642563519328653548) D69 D70 ^ D61 +error(0.02932977517479359517) D69 L0 +error(0.03971141081691922925) D70 +error(0.01861137559407682884) D70 D71 +error(0.0001911570318256310922) D70 ^ D60 ^ D62 +error(0.01483730597773957015) D71 L0 +detector(5, 4, 0) D0 +detector(7, 4, 0) D1 +detector(7, 6, 0) D2 +detector(9, 6, 0) D3 +detector(5, 4, 1) D4 +detector(6, 5, 1) D5 +detector(6, 7, 1) D6 +detector(7, 4, 1) D7 +detector(7, 6, 1) D8 +detector(8, 3, 1) D9 +detector(8, 5, 1) D10 +detector(9, 6, 1) D11 +detector(5, 4, 2) D12 +detector(6, 5, 2) D13 +detector(6, 7, 2) D14 +detector(7, 4, 2) D15 +detector(7, 6, 2) D16 +detector(8, 3, 2) D17 +detector(8, 5, 2) D18 +detector(9, 6, 2) D19 +detector(5, 4, 3) D20 +detector(6, 5, 3) D21 +detector(6, 7, 3) D22 +detector(7, 4, 3) D23 +detector(7, 6, 3) D24 +detector(8, 3, 3) D25 +detector(8, 5, 3) D26 +detector(9, 6, 3) D27 +detector(5, 4, 4) D28 +detector(6, 5, 4) D29 +detector(6, 7, 4) D30 +detector(7, 4, 4) D31 +detector(7, 6, 4) D32 +detector(8, 3, 4) D33 +detector(8, 5, 4) D34 +detector(9, 6, 4) D35 +detector(5, 4, 5) D36 +detector(6, 5, 5) D37 +detector(6, 7, 5) D38 +detector(7, 4, 5) D39 +detector(7, 6, 5) D40 +detector(8, 3, 5) D41 +detector(8, 5, 5) D42 +detector(9, 6, 5) D43 +detector(5, 4, 6) D44 +detector(6, 5, 6) D45 +detector(6, 7, 6) D46 +detector(7, 4, 6) D47 +detector(7, 6, 6) D48 +detector(8, 3, 6) D49 +detector(8, 5, 6) D50 +detector(9, 6, 6) D51 +detector(5, 4, 7) D52 +detector(6, 5, 7) D53 +detector(6, 7, 7) D54 +detector(7, 4, 7) D55 +detector(7, 6, 7) D56 +detector(8, 3, 7) D57 +detector(8, 5, 7) D58 +detector(9, 6, 7) D59 +detector(5, 4, 8) D60 +detector(6, 5, 8) D61 +detector(6, 7, 8) D62 +detector(7, 4, 8) D63 +detector(7, 6, 8) D64 +detector(8, 3, 8) D65 +detector(8, 5, 8) D66 +detector(9, 6, 8) D67 +detector(5, 4, 9) D68 +detector(7, 4, 9) D69 +detector(7, 6, 9) D70 +detector(9, 6, 9) D71 diff --git a/shared/package-files/01/013741ad7ee9f74e18d335d06b378b612c510f44fd75434b06e4453900d7c87e/blob b/shared/package-files/01/013741ad7ee9f74e18d335d06b378b612c510f44fd75434b06e4453900d7c87e/blob new file mode 100644 index 0000000000000000000000000000000000000000..835aadfc9715a4291ed2539a8d977e9fb10301bf --- /dev/null +++ b/shared/package-files/01/013741ad7ee9f74e18d335d06b378b612c510f44fd75434b06e4453900d7c87e/blob @@ -0,0 +1,140 @@ +"""GLUT Input hook for interactive use with prompt_toolkit +""" + + +# GLUT is quite an old library and it is difficult to ensure proper +# integration within IPython since original GLUT does not allow to handle +# events one by one. Instead, it requires for the mainloop to be entered +# and never returned (there is not even a function to exit he +# mainloop). Fortunately, there are alternatives such as freeglut +# (available for linux and windows) and the OSX implementation gives +# access to a glutCheckLoop() function that blocks itself until a new +# event is received. This means we have to setup the idle callback to +# ensure we got at least one event that will unblock the function. +# +# Furthermore, it is not possible to install these handlers without a window +# being first created. We choose to make this window invisible. This means that +# display mode options are set at this level and user won't be able to change +# them later without modifying the code. This should probably be made available +# via IPython options system. + +import sys +import time +import signal +import OpenGL.GLUT as glut +import OpenGL.platform as platform +from timeit import default_timer as clock + +# Frame per second : 60 +# Should probably be an IPython option +glut_fps = 60 + +# Display mode : double buffeed + rgba + depth +# Should probably be an IPython option +glut_display_mode = (glut.GLUT_DOUBLE | + glut.GLUT_RGBA | + glut.GLUT_DEPTH) + +glutMainLoopEvent = None +if sys.platform == 'darwin': + try: + glutCheckLoop = platform.createBaseFunction( + 'glutCheckLoop', dll=platform.GLUT, resultType=None, + argTypes=[], + doc='glutCheckLoop( ) -> None', + argNames=(), + ) + except AttributeError as e: + raise RuntimeError( + '''Your glut implementation does not allow interactive sessions. ''' + '''Consider installing freeglut.''') from e + glutMainLoopEvent = glutCheckLoop +elif glut.HAVE_FREEGLUT: + glutMainLoopEvent = glut.glutMainLoopEvent +else: + raise RuntimeError( + '''Your glut implementation does not allow interactive sessions. ''' + '''Consider installing freeglut.''') + + +def glut_display(): + # Dummy display function + pass + +def glut_idle(): + # Dummy idle function + pass + +def glut_close(): + # Close function only hides the current window + glut.glutHideWindow() + glutMainLoopEvent() + +def glut_int_handler(signum, frame): + # Catch sigint and print the defaultipyt message + signal.signal(signal.SIGINT, signal.default_int_handler) + print('\nKeyboardInterrupt') + # Need to reprint the prompt at this stage + +# Initialisation code +glut.glutInit( sys.argv ) +glut.glutInitDisplayMode( glut_display_mode ) +# This is specific to freeglut +if bool(glut.glutSetOption): + glut.glutSetOption( glut.GLUT_ACTION_ON_WINDOW_CLOSE, + glut.GLUT_ACTION_GLUTMAINLOOP_RETURNS ) +glut.glutCreateWindow( b'ipython' ) +glut.glutReshapeWindow( 1, 1 ) +glut.glutHideWindow( ) +glut.glutWMCloseFunc( glut_close ) +glut.glutDisplayFunc( glut_display ) +glut.glutIdleFunc( glut_idle ) + + +def inputhook(context): + """Run the pyglet event loop by processing pending events only. + + This keeps processing pending events until stdin is ready. After + processing all pending events, a call to time.sleep is inserted. This is + needed, otherwise, CPU usage is at 100%. This sleep time should be tuned + though for best performance. + """ + # We need to protect against a user pressing Control-C when IPython is + # idle and this is running. We trap KeyboardInterrupt and pass. + + signal.signal(signal.SIGINT, glut_int_handler) + + try: + t = clock() + + # Make sure the default window is set after a window has been closed + if glut.glutGetWindow() == 0: + glut.glutSetWindow( 1 ) + glutMainLoopEvent() + return 0 + + while not context.input_is_ready(): + glutMainLoopEvent() + # We need to sleep at this point to keep the idle CPU load + # low. However, if sleep to long, GUI response is poor. As + # a compromise, we watch how often GUI events are being processed + # and switch between a short and long sleep time. Here are some + # stats useful in helping to tune this. + # time CPU load + # 0.001 13% + # 0.005 3% + # 0.01 1.5% + # 0.05 0.5% + used_time = clock() - t + if used_time > 10.0: + # print 'Sleep for 1 s' # dbg + time.sleep(1.0) + elif used_time > 0.1: + # Few GUI events coming in, so we can sleep longer + # print 'Sleep for 0.05 s' # dbg + time.sleep(0.05) + else: + # Many GUI events coming in, so sleep only very little + time.sleep(0.001) + except KeyboardInterrupt: + pass diff --git a/shared/package-files/01/0137a4e4033b74208f788be830e408b79c85345ccaac56f52a7a3c078334ae7e/blob b/shared/package-files/01/0137a4e4033b74208f788be830e408b79c85345ccaac56f52a7a3c078334ae7e/blob new file mode 100644 index 0000000000000000000000000000000000000000..a15d6475a9509e5324543c6119e44d143f829397 --- /dev/null +++ b/shared/package-files/01/0137a4e4033b74208f788be830e408b79c85345ccaac56f52a7a3c078334ae7e/blob @@ -0,0 +1,107 @@ +import platform +import pytest +import numpy as np + +from numpy import array +from . import util + + +class TestReturnReal(util.F2PyTest): + def check_function(self, t, tname): + if tname in ["t0", "t4", "s0", "s4"]: + err = 1e-5 + else: + err = 0.0 + assert abs(t(234) - 234.0) <= err + assert abs(t(234.6) - 234.6) <= err + assert abs(t("234") - 234) <= err + assert abs(t("234.6") - 234.6) <= err + assert abs(t(-234) + 234) <= err + assert abs(t([234]) - 234) <= err + assert abs(t((234, )) - 234.0) <= err + assert abs(t(array(234)) - 234.0) <= err + assert abs(t(array(234).astype("b")) + 22) <= err + assert abs(t(array(234, "h")) - 234.0) <= err + assert abs(t(array(234, "i")) - 234.0) <= err + assert abs(t(array(234, "l")) - 234.0) <= err + assert abs(t(array(234, "B")) - 234.0) <= err + assert abs(t(array(234, "f")) - 234.0) <= err + assert abs(t(array(234, "d")) - 234.0) <= err + if tname in ["t0", "t4", "s0", "s4"]: + assert t(1e200) == t(1e300) # inf + + # pytest.raises(ValueError, t, array([234], 'S1')) + pytest.raises(ValueError, t, "abc") + + pytest.raises(IndexError, t, []) + pytest.raises(IndexError, t, ()) + + pytest.raises(Exception, t, t) + pytest.raises(Exception, t, {}) + + try: + r = t(10**400) + assert repr(r) in ["inf", "Infinity"] + except OverflowError: + pass + + +@pytest.mark.skipif( + platform.system() == "Darwin", + reason="Prone to error when run with numpy/f2py/tests on mac os, " + "but not when run in isolation", +) +@pytest.mark.skipif( + np.dtype(np.intp).itemsize < 8, + reason="32-bit builds are buggy" +) +class TestCReturnReal(TestReturnReal): + suffix = ".pyf" + module_name = "c_ext_return_real" + code = """ +python module c_ext_return_real +usercode \'\'\' +float t4(float value) { return value; } +void s4(float *t4, float value) { *t4 = value; } +double t8(double value) { return value; } +void s8(double *t8, double value) { *t8 = value; } +\'\'\' +interface + function t4(value) + real*4 intent(c) :: t4,value + end + function t8(value) + real*8 intent(c) :: t8,value + end + subroutine s4(t4,value) + intent(c) s4 + real*4 intent(out) :: t4 + real*4 intent(c) :: value + end + subroutine s8(t8,value) + intent(c) s8 + real*8 intent(out) :: t8 + real*8 intent(c) :: value + end +end interface +end python module c_ext_return_real + """ + + @pytest.mark.parametrize("name", "t4,t8,s4,s8".split(",")) + def test_all(self, name): + self.check_function(getattr(self.module, name), name) + + +class TestFReturnReal(TestReturnReal): + sources = [ + util.getpath("tests", "src", "return_real", "foo77.f"), + util.getpath("tests", "src", "return_real", "foo90.f90"), + ] + + @pytest.mark.parametrize("name", "t0,t4,t8,td,s0,s4,s8,sd".split(",")) + def test_all_f77(self, name): + self.check_function(getattr(self.module, name), name) + + @pytest.mark.parametrize("name", "t0,t4,t8,td,s0,s4,s8,sd".split(",")) + def test_all_f90(self, name): + self.check_function(getattr(self.module.f90_return_real, name), name) diff --git a/shared/package-files/01/01383d06dd69c05f2a9cdb88d3ce9fa6b3380944ddad9764fe0d875c4d527fa0/blob b/shared/package-files/01/01383d06dd69c05f2a9cdb88d3ce9fa6b3380944ddad9764fe0d875c4d527fa0/blob new file mode 100644 index 0000000000000000000000000000000000000000..6c8a4f1e88e493ee08d24e668639c8d495fd49b1 --- /dev/null +++ b/shared/package-files/01/01383d06dd69c05f2a9cdb88d3ce9fa6b3380944ddad9764fe0d875c4d527fa0/blob @@ -0,0 +1,2 @@ +#include "detail/common.h" +#warning "Including 'common.h' is deprecated. It will be removed in v3.0. Use 'pybind11.h'." diff --git a/shared/package-files/01/01391cb523c0bce8bdb186b9b477ebdebb0e97b08ca24b8d390bcb7c5dc7b0a1/blob b/shared/package-files/01/01391cb523c0bce8bdb186b9b477ebdebb0e97b08ca24b8d390bcb7c5dc7b0a1/blob new file mode 100644 index 0000000000000000000000000000000000000000..3aa45802c9e6dad3c7611df2d44375fcd4f37a31 --- /dev/null +++ b/shared/package-files/01/01391cb523c0bce8bdb186b9b477ebdebb0e97b08ca24b8d390bcb7c5dc7b0a1/blob @@ -0,0 +1,28 @@ +#pragma once +// @generated by torchgen/gen.py from DispatchKeyFunction.h + +// NB: The implementing C++ file is RegisterDispatchKey.cpp + +// The only #includes we need are for custom classes that have defaults in the C++ API +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { + +namespace compositeexplicitautograd { + +TORCH_API at::Tensor constant_pad_nd(const at::Tensor & self, at::IntArrayRef pad, const at::Scalar & value=0); +TORCH_API at::Tensor constant_pad_nd_symint(const at::Tensor & self, c10::SymIntArrayRef pad, const at::Scalar & value=0); +TORCH_API at::Tensor & constant_pad_nd_out(at::Tensor & out, const at::Tensor & self, at::IntArrayRef pad, const at::Scalar & value=0); +TORCH_API at::Tensor & constant_pad_nd_outf(const at::Tensor & self, at::IntArrayRef pad, const at::Scalar & value, at::Tensor & out); +TORCH_API at::Tensor & constant_pad_nd_symint_out(at::Tensor & out, const at::Tensor & self, c10::SymIntArrayRef pad, const at::Scalar & value=0); +TORCH_API at::Tensor & constant_pad_nd_symint_outf(const at::Tensor & self, c10::SymIntArrayRef pad, const at::Scalar & value, at::Tensor & out); + +} // namespace compositeexplicitautograd +} // namespace at diff --git a/shared/package-files/01/0139f491334211ad9e0211931643173df0cb976f447b9710bc03dddc471d4166/blob b/shared/package-files/01/0139f491334211ad9e0211931643173df0cb976f447b9710bc03dddc471d4166/blob new file mode 100644 index 0000000000000000000000000000000000000000..11995260dd0beb3325fb6e95847d6cf630bf9e79 --- /dev/null +++ b/shared/package-files/01/0139f491334211ad9e0211931643173df0cb976f447b9710bc03dddc471d4166/blob @@ -0,0 +1,169 @@ +import numpy as np +import pytest + +import pandas as pd +from pandas import ( + DataFrame, + Index, + MultiIndex, + Series, + date_range, +) +import pandas._testing as tm + + +def test_unstack_preserves_object(): + mi = MultiIndex.from_product([["bar", "foo"], ["one", "two"]]) + + ser = Series(np.arange(4.0), index=mi, dtype=object) + + res1 = ser.unstack() + assert (res1.dtypes == object).all() + + res2 = ser.unstack(level=0) + assert (res2.dtypes == object).all() + + +def test_unstack(): + index = MultiIndex( + levels=[["bar", "foo"], ["one", "three", "two"]], + codes=[[1, 1, 0, 0], [0, 1, 0, 2]], + ) + + s = Series(np.arange(4.0), index=index) + unstacked = s.unstack() + + expected = DataFrame( + [[2.0, np.nan, 3.0], [0.0, 1.0, np.nan]], + index=["bar", "foo"], + columns=["one", "three", "two"], + ) + + tm.assert_frame_equal(unstacked, expected) + + unstacked = s.unstack(level=0) + tm.assert_frame_equal(unstacked, expected.T) + + index = MultiIndex( + levels=[["bar"], ["one", "two", "three"], [0, 1]], + codes=[[0, 0, 0, 0, 0, 0], [0, 1, 2, 0, 1, 2], [0, 1, 0, 1, 0, 1]], + ) + s = Series(np.random.default_rng(2).standard_normal(6), index=index) + exp_index = MultiIndex( + levels=[["one", "two", "three"], [0, 1]], + codes=[[0, 1, 2, 0, 1, 2], [0, 1, 0, 1, 0, 1]], + ) + expected = DataFrame({"bar": s.values}, index=exp_index).sort_index(level=0) + unstacked = s.unstack(0).sort_index() + tm.assert_frame_equal(unstacked, expected) + + # GH5873 + idx = MultiIndex.from_arrays([[101, 102], [3.5, np.nan]]) + ts = Series([1, 2], index=idx) + left = ts.unstack() + right = DataFrame( + [[np.nan, 1], [2, np.nan]], index=[101, 102], columns=[np.nan, 3.5] + ) + tm.assert_frame_equal(left, right) + + idx = MultiIndex.from_arrays( + [ + ["cat", "cat", "cat", "dog", "dog"], + ["a", "a", "b", "a", "b"], + [1, 2, 1, 1, np.nan], + ] + ) + ts = Series([1.0, 1.1, 1.2, 1.3, 1.4], index=idx) + right = DataFrame( + [[1.0, 1.3], [1.1, np.nan], [np.nan, 1.4], [1.2, np.nan]], + columns=["cat", "dog"], + ) + tpls = [("a", 1), ("a", 2), ("b", np.nan), ("b", 1)] + right.index = MultiIndex.from_tuples(tpls) + tm.assert_frame_equal(ts.unstack(level=0), right) + + +def test_unstack_tuplename_in_multiindex(): + # GH 19966 + idx = MultiIndex.from_product( + [["a", "b", "c"], [1, 2, 3]], names=[("A", "a"), ("B", "b")] + ) + ser = Series(1, index=idx) + result = ser.unstack(("A", "a")) + + expected = DataFrame( + [[1, 1, 1], [1, 1, 1], [1, 1, 1]], + columns=MultiIndex.from_tuples([("a",), ("b",), ("c",)], names=[("A", "a")]), + index=Index([1, 2, 3], name=("B", "b")), + ) + tm.assert_frame_equal(result, expected) + + +@pytest.mark.parametrize( + "unstack_idx, expected_values, expected_index, expected_columns", + [ + ( + ("A", "a"), + [[1, 1], [1, 1], [1, 1], [1, 1]], + MultiIndex.from_tuples([(1, 3), (1, 4), (2, 3), (2, 4)], names=["B", "C"]), + MultiIndex.from_tuples([("a",), ("b",)], names=[("A", "a")]), + ), + ( + (("A", "a"), "B"), + [[1, 1, 1, 1], [1, 1, 1, 1]], + Index([3, 4], name="C"), + MultiIndex.from_tuples( + [("a", 1), ("a", 2), ("b", 1), ("b", 2)], names=[("A", "a"), "B"] + ), + ), + ], +) +def test_unstack_mixed_type_name_in_multiindex( + unstack_idx, expected_values, expected_index, expected_columns +): + # GH 19966 + idx = MultiIndex.from_product( + [["a", "b"], [1, 2], [3, 4]], names=[("A", "a"), "B", "C"] + ) + ser = Series(1, index=idx) + result = ser.unstack(unstack_idx) + + expected = DataFrame( + expected_values, columns=expected_columns, index=expected_index + ) + tm.assert_frame_equal(result, expected) + + +def test_unstack_multi_index_categorical_values(): + df = DataFrame( + np.random.default_rng(2).standard_normal((10, 4)), + columns=Index(list("ABCD")), + index=date_range("2000-01-01", periods=10, freq="B"), + ) + mi = df.stack(future_stack=True).index.rename(["major", "minor"]) + ser = Series(["foo"] * len(mi), index=mi, name="category", dtype="category") + + result = ser.unstack() + + dti = ser.index.levels[0] + c = pd.Categorical(["foo"] * len(dti)) + expected = DataFrame( + {"A": c.copy(), "B": c.copy(), "C": c.copy(), "D": c.copy()}, + columns=Index(list("ABCD"), name="minor"), + index=dti.rename("major"), + ) + tm.assert_frame_equal(result, expected) + + +def test_unstack_mixed_level_names(): + # GH#48763 + arrays = [["a", "a"], [1, 2], ["red", "blue"]] + idx = MultiIndex.from_arrays(arrays, names=("x", 0, "y")) + ser = Series([1, 2], index=idx) + result = ser.unstack("x") + expected = DataFrame( + [[1], [2]], + columns=Index(["a"], name="x"), + index=MultiIndex.from_tuples([(1, "red"), (2, "blue")], names=[0, "y"]), + ) + tm.assert_frame_equal(result, expected) diff --git a/shared/package-files/01/013b3b2911c66bc1ca54e510814af4954c310da10737f9b2a2474d714be2ab39/blob b/shared/package-files/01/013b3b2911c66bc1ca54e510814af4954c310da10737f9b2a2474d714be2ab39/blob new file mode 100644 index 0000000000000000000000000000000000000000..a46112f145825b7aea946481ed9a039e81ed6e1b --- /dev/null +++ b/shared/package-files/01/013b3b2911c66bc1ca54e510814af4954c310da10737f9b2a2474d714be2ab39/blob @@ -0,0 +1,20 @@ +# Encoding file: iso8859-7, single-byte +S +003F 0 1 +00 +0000000100020003000400050006000700080009000A000B000C000D000E000F +0010001100120013001400150016001700180019001A001B001C001D001E001F +0020002100220023002400250026002700280029002A002B002C002D002E002F +0030003100320033003400350036003700380039003A003B003C003D003E003F +0040004100420043004400450046004700480049004A004B004C004D004E004F +0050005100520053005400550056005700580059005A005B005C005D005E005F +0060006100620063006400650066006700680069006A006B006C006D006E006F +0070007100720073007400750076007700780079007A007B007C007D007E007F +0080008100820083008400850086008700880089008A008B008C008D008E008F +0090009100920093009400950096009700980099009A009B009C009D009E009F +00A02018201900A320AC20AF00A600A700A800A9037A00AB00AC00AD00002015 +00B000B100B200B303840385038600B703880389038A00BB038C00BD038E038F +0390039103920393039403950396039703980399039A039B039C039D039E039F +03A003A1000003A303A403A503A603A703A803A903AA03AB03AC03AD03AE03AF +03B003B103B203B303B403B503B603B703B803B903BA03BB03BC03BD03BE03BF +03C003C103C203C303C403C503C603C703C803C903CA03CB03CC03CD03CE0000 diff --git a/shared/package-files/01/013beb8a44ed5facd6f0529b8e957b3bb22f00a4820412d0487d4928547d47b4/blob b/shared/package-files/01/013beb8a44ed5facd6f0529b8e957b3bb22f00a4820412d0487d4928547d47b4/blob new file mode 100644 index 0000000000000000000000000000000000000000..c87492ce9e77dc2f11b3138f9294e421621a8292 --- /dev/null +++ b/shared/package-files/01/013beb8a44ed5facd6f0529b8e957b3bb22f00a4820412d0487d4928547d47b4/blob @@ -0,0 +1,795 @@ +import builtins +from warnings import catch_warnings, simplefilter +import numpy as np +from operator import index +from collections import namedtuple + +__all__ = ['binned_statistic', + 'binned_statistic_2d', + 'binned_statistic_dd'] + + +BinnedStatisticResult = namedtuple('BinnedStatisticResult', + ('statistic', 'bin_edges', 'binnumber')) + + +def binned_statistic(x, values, statistic='mean', + bins=10, range=None): + """ + Compute a binned statistic for one or more sets of data. + + This is a generalization of a histogram function. A histogram divides + the space into bins, and returns the count of the number of points in + each bin. This function allows the computation of the sum, mean, median, + or other statistic of the values (or set of values) within each bin. + + Parameters + ---------- + x : (N,) array_like + A sequence of values to be binned. + values : (N,) array_like or list of (N,) array_like + The data on which the statistic will be computed. This must be + the same shape as `x`, or a set of sequences - each the same shape as + `x`. If `values` is a set of sequences, the statistic will be computed + on each independently. + statistic : string or callable, optional + The statistic to compute (default is 'mean'). + The following statistics are available: + + * 'mean' : compute the mean of values for points within each bin. + Empty bins will be represented by NaN. + * 'std' : compute the standard deviation within each bin. This + is implicitly calculated with ddof=0. + * 'median' : compute the median of values for points within each + bin. Empty bins will be represented by NaN. + * 'count' : compute the count of points within each bin. This is + identical to an unweighted histogram. `values` array is not + referenced. + * 'sum' : compute the sum of values for points within each bin. + This is identical to a weighted histogram. + * 'min' : compute the minimum of values for points within each bin. + Empty bins will be represented by NaN. + * 'max' : compute the maximum of values for point within each bin. + Empty bins will be represented by NaN. + * function : a user-defined function which takes a 1D array of + values, and outputs a single numerical statistic. This function + will be called on the values in each bin. Empty bins will be + represented by function([]), or NaN if this returns an error. + + bins : int or sequence of scalars, optional + If `bins` is an int, it defines the number of equal-width bins in the + given range (10 by default). If `bins` is a sequence, it defines the + bin edges, including the rightmost edge, allowing for non-uniform bin + widths. Values in `x` that are smaller than lowest bin edge are + assigned to bin number 0, values beyond the highest bin are assigned to + ``bins[-1]``. If the bin edges are specified, the number of bins will + be, (nx = len(bins)-1). + range : (float, float) or [(float, float)], optional + The lower and upper range of the bins. If not provided, range + is simply ``(x.min(), x.max())``. Values outside the range are + ignored. + + Returns + ------- + statistic : array + The values of the selected statistic in each bin. + bin_edges : array of dtype float + Return the bin edges ``(length(statistic)+1)``. + binnumber: 1-D ndarray of ints + Indices of the bins (corresponding to `bin_edges`) in which each value + of `x` belongs. Same length as `values`. A binnumber of `i` means the + corresponding value is between (bin_edges[i-1], bin_edges[i]). + + See Also + -------- + numpy.digitize, numpy.histogram, binned_statistic_2d, binned_statistic_dd + + Notes + ----- + All but the last (righthand-most) bin is half-open. In other words, if + `bins` is ``[1, 2, 3, 4]``, then the first bin is ``[1, 2)`` (including 1, + but excluding 2) and the second ``[2, 3)``. The last bin, however, is + ``[3, 4]``, which *includes* 4. + + .. versionadded:: 0.11.0 + + Examples + -------- + >>> import numpy as np + >>> from scipy import stats + >>> import matplotlib.pyplot as plt + + First some basic examples: + + Create two evenly spaced bins in the range of the given sample, and sum the + corresponding values in each of those bins: + + >>> values = [1.0, 1.0, 2.0, 1.5, 3.0] + >>> stats.binned_statistic([1, 1, 2, 5, 7], values, 'sum', bins=2) + BinnedStatisticResult(statistic=array([4. , 4.5]), + bin_edges=array([1., 4., 7.]), binnumber=array([1, 1, 1, 2, 2])) + + Multiple arrays of values can also be passed. The statistic is calculated + on each set independently: + + >>> values = [[1.0, 1.0, 2.0, 1.5, 3.0], [2.0, 2.0, 4.0, 3.0, 6.0]] + >>> stats.binned_statistic([1, 1, 2, 5, 7], values, 'sum', bins=2) + BinnedStatisticResult(statistic=array([[4. , 4.5], + [8. , 9. ]]), bin_edges=array([1., 4., 7.]), + binnumber=array([1, 1, 1, 2, 2])) + + >>> stats.binned_statistic([1, 2, 1, 2, 4], np.arange(5), statistic='mean', + ... bins=3) + BinnedStatisticResult(statistic=array([1., 2., 4.]), + bin_edges=array([1., 2., 3., 4.]), + binnumber=array([1, 2, 1, 2, 3])) + + As a second example, we now generate some random data of sailing boat speed + as a function of wind speed, and then determine how fast our boat is for + certain wind speeds: + + >>> rng = np.random.default_rng() + >>> windspeed = 8 * rng.random(500) + >>> boatspeed = .3 * windspeed**.5 + .2 * rng.random(500) + >>> bin_means, bin_edges, binnumber = stats.binned_statistic(windspeed, + ... boatspeed, statistic='median', bins=[1,2,3,4,5,6,7]) + >>> plt.figure() + >>> plt.plot(windspeed, boatspeed, 'b.', label='raw data') + >>> plt.hlines(bin_means, bin_edges[:-1], bin_edges[1:], colors='g', lw=5, + ... label='binned statistic of data') + >>> plt.legend() + + Now we can use ``binnumber`` to select all datapoints with a windspeed + below 1: + + >>> low_boatspeed = boatspeed[binnumber == 0] + + As a final example, we will use ``bin_edges`` and ``binnumber`` to make a + plot of a distribution that shows the mean and distribution around that + mean per bin, on top of a regular histogram and the probability + distribution function: + + >>> x = np.linspace(0, 5, num=500) + >>> x_pdf = stats.maxwell.pdf(x) + >>> samples = stats.maxwell.rvs(size=10000) + + >>> bin_means, bin_edges, binnumber = stats.binned_statistic(x, x_pdf, + ... statistic='mean', bins=25) + >>> bin_width = (bin_edges[1] - bin_edges[0]) + >>> bin_centers = bin_edges[1:] - bin_width/2 + + >>> plt.figure() + >>> plt.hist(samples, bins=50, density=True, histtype='stepfilled', + ... alpha=0.2, label='histogram of data') + >>> plt.plot(x, x_pdf, 'r-', label='analytical pdf') + >>> plt.hlines(bin_means, bin_edges[:-1], bin_edges[1:], colors='g', lw=2, + ... label='binned statistic of data') + >>> plt.plot((binnumber - 0.5) * bin_width, x_pdf, 'g.', alpha=0.5) + >>> plt.legend(fontsize=10) + >>> plt.show() + + """ + try: + N = len(bins) + except TypeError: + N = 1 + + if N != 1: + bins = [np.asarray(bins, float)] + + if range is not None: + if len(range) == 2: + range = [range] + + medians, edges, binnumbers = binned_statistic_dd( + [x], values, statistic, bins, range) + + return BinnedStatisticResult(medians, edges[0], binnumbers) + + +BinnedStatistic2dResult = namedtuple('BinnedStatistic2dResult', + ('statistic', 'x_edge', 'y_edge', + 'binnumber')) + + +def binned_statistic_2d(x, y, values, statistic='mean', + bins=10, range=None, expand_binnumbers=False): + """ + Compute a bidimensional binned statistic for one or more sets of data. + + This is a generalization of a histogram2d function. A histogram divides + the space into bins, and returns the count of the number of points in + each bin. This function allows the computation of the sum, mean, median, + or other statistic of the values (or set of values) within each bin. + + Parameters + ---------- + x : (N,) array_like + A sequence of values to be binned along the first dimension. + y : (N,) array_like + A sequence of values to be binned along the second dimension. + values : (N,) array_like or list of (N,) array_like + The data on which the statistic will be computed. This must be + the same shape as `x`, or a list of sequences - each with the same + shape as `x`. If `values` is such a list, the statistic will be + computed on each independently. + statistic : string or callable, optional + The statistic to compute (default is 'mean'). + The following statistics are available: + + * 'mean' : compute the mean of values for points within each bin. + Empty bins will be represented by NaN. + * 'std' : compute the standard deviation within each bin. This + is implicitly calculated with ddof=0. + * 'median' : compute the median of values for points within each + bin. Empty bins will be represented by NaN. + * 'count' : compute the count of points within each bin. This is + identical to an unweighted histogram. `values` array is not + referenced. + * 'sum' : compute the sum of values for points within each bin. + This is identical to a weighted histogram. + * 'min' : compute the minimum of values for points within each bin. + Empty bins will be represented by NaN. + * 'max' : compute the maximum of values for point within each bin. + Empty bins will be represented by NaN. + * function : a user-defined function which takes a 1D array of + values, and outputs a single numerical statistic. This function + will be called on the values in each bin. Empty bins will be + represented by function([]), or NaN if this returns an error. + + bins : int or [int, int] or array_like or [array, array], optional + The bin specification: + + * the number of bins for the two dimensions (nx = ny = bins), + * the number of bins in each dimension (nx, ny = bins), + * the bin edges for the two dimensions (x_edge = y_edge = bins), + * the bin edges in each dimension (x_edge, y_edge = bins). + + If the bin edges are specified, the number of bins will be, + (nx = len(x_edge)-1, ny = len(y_edge)-1). + + range : (2,2) array_like, optional + The leftmost and rightmost edges of the bins along each dimension + (if not specified explicitly in the `bins` parameters): + [[xmin, xmax], [ymin, ymax]]. All values outside of this range will be + considered outliers and not tallied in the histogram. + expand_binnumbers : bool, optional + 'False' (default): the returned `binnumber` is a shape (N,) array of + linearized bin indices. + 'True': the returned `binnumber` is 'unraveled' into a shape (2,N) + ndarray, where each row gives the bin numbers in the corresponding + dimension. + See the `binnumber` returned value, and the `Examples` section. + + .. versionadded:: 0.17.0 + + Returns + ------- + statistic : (nx, ny) ndarray + The values of the selected statistic in each two-dimensional bin. + x_edge : (nx + 1) ndarray + The bin edges along the first dimension. + y_edge : (ny + 1) ndarray + The bin edges along the second dimension. + binnumber : (N,) array of ints or (2,N) ndarray of ints + This assigns to each element of `sample` an integer that represents the + bin in which this observation falls. The representation depends on the + `expand_binnumbers` argument. See `Notes` for details. + + + See Also + -------- + numpy.digitize, numpy.histogram2d, binned_statistic, binned_statistic_dd + + Notes + ----- + Binedges: + All but the last (righthand-most) bin is half-open. In other words, if + `bins` is ``[1, 2, 3, 4]``, then the first bin is ``[1, 2)`` (including 1, + but excluding 2) and the second ``[2, 3)``. The last bin, however, is + ``[3, 4]``, which *includes* 4. + + `binnumber`: + This returned argument assigns to each element of `sample` an integer that + represents the bin in which it belongs. The representation depends on the + `expand_binnumbers` argument. If 'False' (default): The returned + `binnumber` is a shape (N,) array of linearized indices mapping each + element of `sample` to its corresponding bin (using row-major ordering). + Note that the returned linearized bin indices are used for an array with + extra bins on the outer binedges to capture values outside of the defined + bin bounds. + If 'True': The returned `binnumber` is a shape (2,N) ndarray where + each row indicates bin placements for each dimension respectively. In each + dimension, a binnumber of `i` means the corresponding value is between + (D_edge[i-1], D_edge[i]), where 'D' is either 'x' or 'y'. + + .. versionadded:: 0.11.0 + + Examples + -------- + >>> from scipy import stats + + Calculate the counts with explicit bin-edges: + + >>> x = [0.1, 0.1, 0.1, 0.6] + >>> y = [2.1, 2.6, 2.1, 2.1] + >>> binx = [0.0, 0.5, 1.0] + >>> biny = [2.0, 2.5, 3.0] + >>> ret = stats.binned_statistic_2d(x, y, None, 'count', bins=[binx, biny]) + >>> ret.statistic + array([[2., 1.], + [1., 0.]]) + + The bin in which each sample is placed is given by the `binnumber` + returned parameter. By default, these are the linearized bin indices: + + >>> ret.binnumber + array([5, 6, 5, 9]) + + The bin indices can also be expanded into separate entries for each + dimension using the `expand_binnumbers` parameter: + + >>> ret = stats.binned_statistic_2d(x, y, None, 'count', bins=[binx, biny], + ... expand_binnumbers=True) + >>> ret.binnumber + array([[1, 1, 1, 2], + [1, 2, 1, 1]]) + + Which shows that the first three elements belong in the xbin 1, and the + fourth into xbin 2; and so on for y. + + """ + + # This code is based on np.histogram2d + try: + N = len(bins) + except TypeError: + N = 1 + + if N != 1 and N != 2: + xedges = yedges = np.asarray(bins, float) + bins = [xedges, yedges] + + medians, edges, binnumbers = binned_statistic_dd( + [x, y], values, statistic, bins, range, + expand_binnumbers=expand_binnumbers) + + return BinnedStatistic2dResult(medians, edges[0], edges[1], binnumbers) + + +BinnedStatisticddResult = namedtuple('BinnedStatisticddResult', + ('statistic', 'bin_edges', + 'binnumber')) + + +def _bincount(x, weights): + if np.iscomplexobj(weights): + a = np.bincount(x, np.real(weights)) + b = np.bincount(x, np.imag(weights)) + z = a + b*1j + + else: + z = np.bincount(x, weights) + return z + + +def binned_statistic_dd(sample, values, statistic='mean', + bins=10, range=None, expand_binnumbers=False, + binned_statistic_result=None): + """ + Compute a multidimensional binned statistic for a set of data. + + This is a generalization of a histogramdd function. A histogram divides + the space into bins, and returns the count of the number of points in + each bin. This function allows the computation of the sum, mean, median, + or other statistic of the values within each bin. + + Parameters + ---------- + sample : array_like + Data to histogram passed as a sequence of N arrays of length D, or + as an (N,D) array. + values : (N,) array_like or list of (N,) array_like + The data on which the statistic will be computed. This must be + the same shape as `sample`, or a list of sequences - each with the + same shape as `sample`. If `values` is such a list, the statistic + will be computed on each independently. + statistic : string or callable, optional + The statistic to compute (default is 'mean'). + The following statistics are available: + + * 'mean' : compute the mean of values for points within each bin. + Empty bins will be represented by NaN. + * 'median' : compute the median of values for points within each + bin. Empty bins will be represented by NaN. + * 'count' : compute the count of points within each bin. This is + identical to an unweighted histogram. `values` array is not + referenced. + * 'sum' : compute the sum of values for points within each bin. + This is identical to a weighted histogram. + * 'std' : compute the standard deviation within each bin. This + is implicitly calculated with ddof=0. If the number of values + within a given bin is 0 or 1, the computed standard deviation value + will be 0 for the bin. + * 'min' : compute the minimum of values for points within each bin. + Empty bins will be represented by NaN. + * 'max' : compute the maximum of values for point within each bin. + Empty bins will be represented by NaN. + * function : a user-defined function which takes a 1D array of + values, and outputs a single numerical statistic. This function + will be called on the values in each bin. Empty bins will be + represented by function([]), or NaN if this returns an error. + + bins : sequence or positive int, optional + The bin specification must be in one of the following forms: + + * A sequence of arrays describing the bin edges along each dimension. + * The number of bins for each dimension (nx, ny, ... = bins). + * The number of bins for all dimensions (nx = ny = ... = bins). + range : sequence, optional + A sequence of lower and upper bin edges to be used if the edges are + not given explicitly in `bins`. Defaults to the minimum and maximum + values along each dimension. + expand_binnumbers : bool, optional + 'False' (default): the returned `binnumber` is a shape (N,) array of + linearized bin indices. + 'True': the returned `binnumber` is 'unraveled' into a shape (D,N) + ndarray, where each row gives the bin numbers in the corresponding + dimension. + See the `binnumber` returned value, and the `Examples` section of + `binned_statistic_2d`. + binned_statistic_result : binnedStatisticddResult + Result of a previous call to the function in order to reuse bin edges + and bin numbers with new values and/or a different statistic. + To reuse bin numbers, `expand_binnumbers` must have been set to False + (the default) + + .. versionadded:: 0.17.0 + + Returns + ------- + statistic : ndarray, shape(nx1, nx2, nx3,...) + The values of the selected statistic in each two-dimensional bin. + bin_edges : list of ndarrays + A list of D arrays describing the (nxi + 1) bin edges for each + dimension. + binnumber : (N,) array of ints or (D,N) ndarray of ints + This assigns to each element of `sample` an integer that represents the + bin in which this observation falls. The representation depends on the + `expand_binnumbers` argument. See `Notes` for details. + + + See Also + -------- + numpy.digitize, numpy.histogramdd, binned_statistic, binned_statistic_2d + + Notes + ----- + Binedges: + All but the last (righthand-most) bin is half-open in each dimension. In + other words, if `bins` is ``[1, 2, 3, 4]``, then the first bin is + ``[1, 2)`` (including 1, but excluding 2) and the second ``[2, 3)``. The + last bin, however, is ``[3, 4]``, which *includes* 4. + + `binnumber`: + This returned argument assigns to each element of `sample` an integer that + represents the bin in which it belongs. The representation depends on the + `expand_binnumbers` argument. If 'False' (default): The returned + `binnumber` is a shape (N,) array of linearized indices mapping each + element of `sample` to its corresponding bin (using row-major ordering). + If 'True': The returned `binnumber` is a shape (D,N) ndarray where + each row indicates bin placements for each dimension respectively. In each + dimension, a binnumber of `i` means the corresponding value is between + (bin_edges[D][i-1], bin_edges[D][i]), for each dimension 'D'. + + .. versionadded:: 0.11.0 + + Examples + -------- + >>> import numpy as np + >>> from scipy import stats + >>> import matplotlib.pyplot as plt + >>> from mpl_toolkits.mplot3d import Axes3D + + Take an array of 600 (x, y) coordinates as an example. + `binned_statistic_dd` can handle arrays of higher dimension `D`. But a plot + of dimension `D+1` is required. + + >>> mu = np.array([0., 1.]) + >>> sigma = np.array([[1., -0.5],[-0.5, 1.5]]) + >>> multinormal = stats.multivariate_normal(mu, sigma) + >>> data = multinormal.rvs(size=600, random_state=235412) + >>> data.shape + (600, 2) + + Create bins and count how many arrays fall in each bin: + + >>> N = 60 + >>> x = np.linspace(-3, 3, N) + >>> y = np.linspace(-3, 4, N) + >>> ret = stats.binned_statistic_dd(data, np.arange(600), bins=[x, y], + ... statistic='count') + >>> bincounts = ret.statistic + + Set the volume and the location of bars: + + >>> dx = x[1] - x[0] + >>> dy = y[1] - y[0] + >>> x, y = np.meshgrid(x[:-1]+dx/2, y[:-1]+dy/2) + >>> z = 0 + + >>> bincounts = bincounts.ravel() + >>> x = x.ravel() + >>> y = y.ravel() + + >>> fig = plt.figure() + >>> ax = fig.add_subplot(111, projection='3d') + >>> with np.errstate(divide='ignore'): # silence random axes3d warning + ... ax.bar3d(x, y, z, dx, dy, bincounts) + + Reuse bin numbers and bin edges with new values: + + >>> ret2 = stats.binned_statistic_dd(data, -np.arange(600), + ... binned_statistic_result=ret, + ... statistic='mean') + """ + known_stats = ['mean', 'median', 'count', 'sum', 'std', 'min', 'max'] + if not callable(statistic) and statistic not in known_stats: + raise ValueError(f'invalid statistic {statistic!r}') + + try: + bins = index(bins) + except TypeError: + # bins is not an integer + pass + # If bins was an integer-like object, now it is an actual Python int. + + # NOTE: for _bin_edges(), see e.g. gh-11365 + if isinstance(bins, int) and not np.isfinite(sample).all(): + raise ValueError(f'{sample!r} contains non-finite values.') + + # `Ndim` is the number of dimensions (e.g. `2` for `binned_statistic_2d`) + # `Dlen` is the length of elements along each dimension. + # This code is based on np.histogramdd + try: + # `sample` is an ND-array. + Dlen, Ndim = sample.shape + except (AttributeError, ValueError): + # `sample` is a sequence of 1D arrays. + sample = np.atleast_2d(sample).T + Dlen, Ndim = sample.shape + + # Store initial shape of `values` to preserve it in the output + values = np.asarray(values) + input_shape = list(values.shape) + # Make sure that `values` is 2D to iterate over rows + values = np.atleast_2d(values) + Vdim, Vlen = values.shape + + # Make sure `values` match `sample` + if statistic != 'count' and Vlen != Dlen: + raise AttributeError('The number of `values` elements must match the ' + 'length of each `sample` dimension.') + + try: + M = len(bins) + if M != Ndim: + raise AttributeError('The dimension of bins must be equal ' + 'to the dimension of the sample x.') + except TypeError: + bins = Ndim * [bins] + + if binned_statistic_result is None: + nbin, edges, dedges = _bin_edges(sample, bins, range) + binnumbers = _bin_numbers(sample, nbin, edges, dedges) + else: + edges = binned_statistic_result.bin_edges + nbin = np.array([len(edges[i]) + 1 for i in builtins.range(Ndim)]) + # +1 for outlier bins + dedges = [np.diff(edges[i]) for i in builtins.range(Ndim)] + binnumbers = binned_statistic_result.binnumber + + # Avoid overflow with double precision. Complex `values` -> `complex128`. + result_type = np.result_type(values, np.float64) + result = np.empty([Vdim, nbin.prod()], dtype=result_type) + + if statistic in {'mean', np.mean}: + result.fill(np.nan) + flatcount = _bincount(binnumbers, None) + a = flatcount.nonzero() + for vv in builtins.range(Vdim): + flatsum = _bincount(binnumbers, values[vv]) + result[vv, a] = flatsum[a] / flatcount[a] + elif statistic in {'std', np.std}: + result.fill(np.nan) + flatcount = _bincount(binnumbers, None) + a = flatcount.nonzero() + for vv in builtins.range(Vdim): + flatsum = _bincount(binnumbers, values[vv]) + delta = values[vv] - flatsum[binnumbers] / flatcount[binnumbers] + std = np.sqrt( + _bincount(binnumbers, delta*np.conj(delta))[a] / flatcount[a] + ) + result[vv, a] = std + result = np.real(result) + elif statistic == 'count': + result = np.empty([Vdim, nbin.prod()], dtype=np.float64) + result.fill(0) + flatcount = _bincount(binnumbers, None) + a = np.arange(len(flatcount)) + result[:, a] = flatcount[np.newaxis, :] + elif statistic in {'sum', np.sum}: + result.fill(0) + for vv in builtins.range(Vdim): + flatsum = _bincount(binnumbers, values[vv]) + a = np.arange(len(flatsum)) + result[vv, a] = flatsum + elif statistic in {'median', np.median}: + result.fill(np.nan) + for vv in builtins.range(Vdim): + i = np.lexsort((values[vv], binnumbers)) + _, j, counts = np.unique(binnumbers[i], + return_index=True, return_counts=True) + mid = j + (counts - 1) / 2 + mid_a = values[vv, i][np.floor(mid).astype(int)] + mid_b = values[vv, i][np.ceil(mid).astype(int)] + medians = (mid_a + mid_b) / 2 + result[vv, binnumbers[i][j]] = medians + elif statistic in {'min', np.min}: + result.fill(np.nan) + for vv in builtins.range(Vdim): + i = np.argsort(values[vv])[::-1] # Reversed so the min is last + result[vv, binnumbers[i]] = values[vv, i] + elif statistic in {'max', np.max}: + result.fill(np.nan) + for vv in builtins.range(Vdim): + i = np.argsort(values[vv]) + result[vv, binnumbers[i]] = values[vv, i] + elif callable(statistic): + with np.errstate(invalid='ignore'), catch_warnings(): + simplefilter("ignore", RuntimeWarning) + try: + null = statistic([]) + except Exception: + null = np.nan + if np.iscomplexobj(null): + result = result.astype(np.complex128) + result.fill(null) + try: + _calc_binned_statistic( + Vdim, binnumbers, result, values, statistic + ) + except ValueError: + result = result.astype(np.complex128) + _calc_binned_statistic( + Vdim, binnumbers, result, values, statistic + ) + + # Shape into a proper matrix + result = result.reshape(np.append(Vdim, nbin)) + + # Remove outliers (indices 0 and -1 for each bin-dimension). + core = tuple([slice(None)] + Ndim * [slice(1, -1)]) + result = result[core] + + # Unravel binnumbers into an ndarray, each row the bins for each dimension + if expand_binnumbers and Ndim > 1: + binnumbers = np.asarray(np.unravel_index(binnumbers, nbin)) + + if np.any(result.shape[1:] != nbin - 2): + raise RuntimeError('Internal Shape Error') + + # Reshape to have output (`result`) match input (`values`) shape + result = result.reshape(input_shape[:-1] + list(nbin-2)) + + return BinnedStatisticddResult(result, edges, binnumbers) + + +def _calc_binned_statistic(Vdim, bin_numbers, result, values, stat_func): + unique_bin_numbers = np.unique(bin_numbers) + for vv in builtins.range(Vdim): + bin_map = _create_binned_data(bin_numbers, unique_bin_numbers, + values, vv) + for i in unique_bin_numbers: + stat = stat_func(np.array(bin_map[i])) + if np.iscomplexobj(stat) and not np.iscomplexobj(result): + raise ValueError("The statistic function returns complex ") + result[vv, i] = stat + + +def _create_binned_data(bin_numbers, unique_bin_numbers, values, vv): + """ Create hashmap of bin ids to values in bins + key: bin number + value: list of binned data + """ + bin_map = dict() + for i in unique_bin_numbers: + bin_map[i] = [] + for i in builtins.range(len(bin_numbers)): + bin_map[bin_numbers[i]].append(values[vv, i]) + return bin_map + + +def _bin_edges(sample, bins=None, range=None): + """ Create edge arrays + """ + Dlen, Ndim = sample.shape + + nbin = np.empty(Ndim, int) # Number of bins in each dimension + edges = Ndim * [None] # Bin edges for each dim (will be 2D array) + dedges = Ndim * [None] # Spacing between edges (will be 2D array) + + # Select range for each dimension + # Used only if number of bins is given. + if range is None: + smin = np.atleast_1d(np.array(sample.min(axis=0), float)) + smax = np.atleast_1d(np.array(sample.max(axis=0), float)) + else: + if len(range) != Ndim: + raise ValueError( + f"range given for {len(range)} dimensions; {Ndim} required") + smin = np.empty(Ndim) + smax = np.empty(Ndim) + for i in builtins.range(Ndim): + if range[i][1] < range[i][0]: + raise ValueError( + f"In {f'dimension {i + 1} of ' if Ndim > 1 else ''}range," + " start must be <= stop") + smin[i], smax[i] = range[i] + + # Make sure the bins have a finite width. + for i in builtins.range(len(smin)): + if smin[i] == smax[i]: + smin[i] = smin[i] - .5 + smax[i] = smax[i] + .5 + + # Preserve sample floating point precision in bin edges + edges_dtype = (sample.dtype if np.issubdtype(sample.dtype, np.floating) + else float) + + # Create edge arrays + for i in builtins.range(Ndim): + if np.isscalar(bins[i]): + nbin[i] = bins[i] + 2 # +2 for outlier bins + edges[i] = np.linspace(smin[i], smax[i], nbin[i] - 1, + dtype=edges_dtype) + else: + edges[i] = np.asarray(bins[i], edges_dtype) + nbin[i] = len(edges[i]) + 1 # +1 for outlier bins + dedges[i] = np.diff(edges[i]) + + nbin = np.asarray(nbin) + + return nbin, edges, dedges + + +def _bin_numbers(sample, nbin, edges, dedges): + """Compute the bin number each sample falls into, in each dimension + """ + Dlen, Ndim = sample.shape + + sampBin = [ + np.digitize(sample[:, i], edges[i]) + for i in range(Ndim) + ] + + # Using `digitize`, values that fall on an edge are put in the right bin. + # For the rightmost bin, we want values equal to the right + # edge to be counted in the last bin, and not as an outlier. + for i in range(Ndim): + # Find the rounding precision + dedges_min = dedges[i].min() + if dedges_min == 0: + raise ValueError('The smallest edge difference is numerically 0.') + decimal = int(-np.log10(dedges_min)) + 6 + # Find which points are on the rightmost edge. + on_edge = np.where((sample[:, i] >= edges[i][-1]) & + (np.around(sample[:, i], decimal) == + np.around(edges[i][-1], decimal)))[0] + # Shift these points one bin to the left. + sampBin[i][on_edge] -= 1 + + # Compute the sample indices in the flattened statistic matrix. + binnumbers = np.ravel_multi_index(sampBin, nbin) + + return binnumbers diff --git a/shared/package-files/01/013d19dd6372c55207c0211987464b129de04c09e345b806c269e9f2bfc627b0/blob b/shared/package-files/01/013d19dd6372c55207c0211987464b129de04c09e345b806c269e9f2bfc627b0/blob new file mode 100644 index 0000000000000000000000000000000000000000..b80eb5f1577e96b78cf5d9996c57c794f5f0f4b8 --- /dev/null +++ b/shared/package-files/01/013d19dd6372c55207c0211987464b129de04c09e345b806c269e9f2bfc627b0/blob @@ -0,0 +1,31 @@ +#pragma once + +// @generated by torchgen/gen.py from NativeFunction.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace at { +namespace native { +struct TORCH_API structured_pow_Tensor_Tensor_out : public at::meta::structured_pow_Tensor_Tensor { +void impl(const at::Tensor & self, const at::Tensor & exponent, const at::Tensor & out); +}; +struct TORCH_API structured_pow_Scalar_out : public at::meta::structured_pow_Scalar { +void impl(const at::Scalar & self, const at::Tensor & exponent, const at::Tensor & out); +}; +struct TORCH_API structured_pow_Tensor_Scalar_out : public at::meta::structured_pow_Tensor_Scalar { +void impl(const at::Tensor & self, const at::Scalar & exponent, const at::Tensor & out); +}; +TORCH_API at::Tensor pow_sparse_scalar(const at::Tensor & self, const at::Scalar & exponent); +TORCH_API at::Tensor & pow_out_sparse_scalar(const at::Tensor & self, const at::Scalar & exponent, at::Tensor & out); +} // namespace native +} // namespace at diff --git a/shared/package-files/01/014174bc06d320431d0e24ee7c976e4dd8571e7ecf2cb8f5d93932b5cc3d5488/blob b/shared/package-files/01/014174bc06d320431d0e24ee7c976e4dd8571e7ecf2cb8f5d93932b5cc3d5488/blob new file mode 100644 index 0000000000000000000000000000000000000000..4132ea8c0d6058d8be5c29c899c0a6200db7f773 --- /dev/null +++ b/shared/package-files/01/014174bc06d320431d0e24ee7c976e4dd8571e7ecf2cb8f5d93932b5cc3d5488/blob @@ -0,0 +1,39 @@ +#pragma once + +// @generated by torchgen/gen.py from Function.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + + +#include + +namespace at { + + +// aten::_indices_copy(Tensor self) -> Tensor +inline at::Tensor _indices_copy(const at::Tensor & self) { + return at::_ops::_indices_copy::call(self); +} + +// aten::_indices_copy.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!) +inline at::Tensor & _indices_copy_out(at::Tensor & out, const at::Tensor & self) { + return at::_ops::_indices_copy_out::call(self, out); +} +// aten::_indices_copy.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!) +inline at::Tensor & _indices_copy_outf(const at::Tensor & self, at::Tensor & out) { + return at::_ops::_indices_copy_out::call(self, out); +} + +} diff --git a/shared/package-files/01/0141f3fce4f41d2ea45ecfbd7b9f467e50423f74dbe63cbc8e5f45c41839ac3b/blob b/shared/package-files/01/0141f3fce4f41d2ea45ecfbd7b9f467e50423f74dbe63cbc8e5f45c41839ac3b/blob new file mode 100644 index 0000000000000000000000000000000000000000..f847a06d8ea8d7fa75aac1de9025a5bd29bedf37 --- /dev/null +++ b/shared/package-files/01/0141f3fce4f41d2ea45ecfbd7b9f467e50423f74dbe63cbc8e5f45c41839ac3b/blob @@ -0,0 +1,39 @@ +import warnings + +import pytest + +from pandas.util._exceptions import rewrite_warning + +import pandas._testing as tm + + +@pytest.mark.parametrize( + "target_category, target_message, hit", + [ + (FutureWarning, "Target message", True), + (FutureWarning, "Target", True), + (FutureWarning, "get mess", True), + (FutureWarning, "Missed message", False), + (DeprecationWarning, "Target message", False), + ], +) +@pytest.mark.parametrize( + "new_category", + [ + None, + DeprecationWarning, + ], +) +def test_rewrite_warning(target_category, target_message, hit, new_category): + new_message = "Rewritten message" + if hit: + expected_category = new_category if new_category else target_category + expected_message = new_message + else: + expected_category = FutureWarning + expected_message = "Target message" + with tm.assert_produces_warning(expected_category, match=expected_message): + with rewrite_warning( + target_message, target_category, new_message, new_category + ): + warnings.warn(message="Target message", category=FutureWarning) diff --git a/shared/package-files/01/01426caff60c5ea5e5305550bed7b8a134b2d3613d16d38f3b32b57edb278bfa/blob b/shared/package-files/01/01426caff60c5ea5e5305550bed7b8a134b2d3613d16d38f3b32b57edb278bfa/blob new file mode 100644 index 0000000000000000000000000000000000000000..7fe8da7c2ce69387920bb81cc50c6449e8ed232d Binary files /dev/null and b/shared/package-files/01/01426caff60c5ea5e5305550bed7b8a134b2d3613d16d38f3b32b57edb278bfa/blob differ diff --git a/shared/package-files/01/0143237dd20046d086ab23200c324119afc49dc3f98a862b133c99a9738b4715/blob b/shared/package-files/01/0143237dd20046d086ab23200c324119afc49dc3f98a862b133c99a9738b4715/blob new file mode 100644 index 0000000000000000000000000000000000000000..21d35e4b6568ca12880d5325422a6c01d17a39d9 --- /dev/null +++ b/shared/package-files/01/0143237dd20046d086ab23200c324119afc49dc3f98a862b133c99a9738b4715/blob @@ -0,0 +1,75 @@ +''' Byteorder utilities for system - numpy byteorder encoding + +Converts a variety of string codes for little endian, big endian, +native byte order and swapped byte order to explicit NumPy endian +codes - one of '<' (little endian) or '>' (big endian) + +''' +import sys + +__all__ = [ + 'aliases', 'native_code', 'swapped_code', + 'sys_is_le', 'to_numpy_code' +] + +sys_is_le = sys.byteorder == 'little' +native_code = sys_is_le and '<' or '>' +swapped_code = sys_is_le and '>' or '<' + +aliases = {'little': ('little', '<', 'l', 'le'), + 'big': ('big', '>', 'b', 'be'), + 'native': ('native', '='), + 'swapped': ('swapped', 'S')} + + +def to_numpy_code(code): + """ + Convert various order codings to NumPy format. + + Parameters + ---------- + code : str + The code to convert. It is converted to lower case before parsing. + Legal values are: + 'little', 'big', 'l', 'b', 'le', 'be', '<', '>', 'native', '=', + 'swapped', 's'. + + Returns + ------- + out_code : {'<', '>'} + Here '<' is the numpy dtype code for little endian, + and '>' is the code for big endian. + + Examples + -------- + >>> import sys + >>> from scipy.io.matlab._byteordercodes import to_numpy_code + >>> sys_is_le = (sys.byteorder == 'little') + >>> sys_is_le + True + >>> to_numpy_code('big') + '>' + >>> to_numpy_code('little') + '<' + >>> nc = to_numpy_code('native') + >>> nc == '<' if sys_is_le else nc == '>' + True + >>> sc = to_numpy_code('swapped') + >>> sc == '>' if sys_is_le else sc == '<' + True + + """ + code = code.lower() + if code is None: + return native_code + if code in aliases['little']: + return '<' + elif code in aliases['big']: + return '>' + elif code in aliases['native']: + return native_code + elif code in aliases['swapped']: + return swapped_code + else: + raise ValueError( + f'We cannot handle byte order {code}') diff --git a/shared/package-files/01/0143830586d09d702ca3eeaa8f86698e5fd18af69fd28147e71a1a77600d356a/blob b/shared/package-files/01/0143830586d09d702ca3eeaa8f86698e5fd18af69fd28147e71a1a77600d356a/blob new file mode 100644 index 0000000000000000000000000000000000000000..f6039690374ab26d383bc8e0309438c051d0d405 --- /dev/null +++ b/shared/package-files/01/0143830586d09d702ca3eeaa8f86698e5fd18af69fd28147e71a1a77600d356a/blob @@ -0,0 +1,30 @@ +"""Fixer for sys.exc_{type, value, traceback} + +sys.exc_type -> sys.exc_info()[0] +sys.exc_value -> sys.exc_info()[1] +sys.exc_traceback -> sys.exc_info()[2] +""" + +# By Jeff Balogh and Benjamin Peterson + +# Local imports +from .. import fixer_base +from ..fixer_util import Attr, Call, Name, Number, Subscript, Node, syms + +class FixSysExc(fixer_base.BaseFix): + # This order matches the ordering of sys.exc_info(). + exc_info = ["exc_type", "exc_value", "exc_traceback"] + BM_compatible = True + PATTERN = """ + power< 'sys' trailer< dot='.' attribute=(%s) > > + """ % '|'.join("'%s'" % e for e in exc_info) + + def transform(self, node, results): + sys_attr = results["attribute"][0] + index = Number(self.exc_info.index(sys_attr.value)) + + call = Call(Name("exc_info"), prefix=sys_attr.prefix) + attr = Attr(Name("sys"), call) + attr[1].children[0].prefix = results["dot"].prefix + attr.append(Subscript(index)) + return Node(syms.power, attr, prefix=node.prefix) diff --git a/shared/package-files/01/014665ed64785f14b2cc831a872a44e3f7da3970a1e98a225c1c98d6e3992b15/blob b/shared/package-files/01/014665ed64785f14b2cc831a872a44e3f7da3970a1e98a225c1c98d6e3992b15/blob new file mode 100644 index 0000000000000000000000000000000000000000..81ad207306844a4b8e0b57efe72a6079d4a74e26 --- /dev/null +++ b/shared/package-files/01/014665ed64785f14b2cc831a872a44e3f7da3970a1e98a225c1c98d6e3992b15/blob @@ -0,0 +1,67 @@ +#pragma once + +#include +#include +#include + +template +class TORCH_PYTHON_API THPPointer { + public: + THPPointer() : ptr(nullptr){}; + explicit THPPointer(T* ptr) noexcept : ptr(ptr){}; + THPPointer(THPPointer&& p) noexcept : ptr(std::exchange(p.ptr, nullptr)) {} + + ~THPPointer() { + free(); + }; + T* get() { + return ptr; + } + const T* get() const { + return ptr; + } + T* release() { + T* tmp = ptr; + ptr = nullptr; + return tmp; + } + operator T*() { + return ptr; + } + THPPointer& operator=(T* new_ptr) noexcept { + free(); + ptr = new_ptr; + return *this; + } + THPPointer& operator=(THPPointer&& p) noexcept { + free(); + ptr = p.ptr; + p.ptr = nullptr; + return *this; + } + T* operator->() { + return ptr; + } + explicit operator bool() const { + return ptr != nullptr; + } + + private: + void free(); + T* ptr = nullptr; +}; + +/** + * An RAII-style, owning pointer to a PyObject. You must protect + * destruction of this object with the GIL. + * + * WARNING: Think twice before putting this as a field in a C++ + * struct. This class does NOT take out the GIL on destruction, + * so if you will need to ensure that the destructor of your struct + * is either (a) always invoked when the GIL is taken or (b) takes + * out the GIL itself. Easiest way to avoid this problem is to + * not use THPPointer in this situation. + */ +using THPObjectPtr = THPPointer; +using THPCodeObjectPtr = THPPointer; +using THPFrameObjectPtr = THPPointer; diff --git a/shared/package-files/01/0147fc417da1ef1923bfe39b762abdb515a7d5ecae5ff24342e8f43f09f3c30b/blob b/shared/package-files/01/0147fc417da1ef1923bfe39b762abdb515a7d5ecae5ff24342e8f43f09f3c30b/blob new file mode 100644 index 0000000000000000000000000000000000000000..41c2a281a701afbf8c6f4f6c8f92f7cb6c8862ae --- /dev/null +++ b/shared/package-files/01/0147fc417da1ef1923bfe39b762abdb515a7d5ecae5ff24342e8f43f09f3c30b/blob @@ -0,0 +1,30 @@ +#pragma once +// @generated by torchgen/gen.py from DispatchKeyFunction.h + +// NB: The implementing C++ file is RegisterDispatchKey.cpp + +// The only #includes we need are for custom classes that have defaults in the C++ API +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { + +namespace compositeimplicitautograd { + +TORCH_API at::Tensor & randn_out(at::Tensor & out, at::IntArrayRef size); +TORCH_API at::Tensor & randn_outf(at::IntArrayRef size, at::Tensor & out); +TORCH_API at::Tensor & randn_symint_out(at::Tensor & out, c10::SymIntArrayRef size); +TORCH_API at::Tensor & randn_symint_outf(c10::SymIntArrayRef size, at::Tensor & out); +TORCH_API at::Tensor & randn_out(at::Tensor & out, at::IntArrayRef size, c10::optional generator); +TORCH_API at::Tensor & randn_outf(at::IntArrayRef size, c10::optional generator, at::Tensor & out); +TORCH_API at::Tensor & randn_symint_out(at::Tensor & out, c10::SymIntArrayRef size, c10::optional generator); +TORCH_API at::Tensor & randn_symint_outf(c10::SymIntArrayRef size, c10::optional generator, at::Tensor & out); + +} // namespace compositeimplicitautograd +} // namespace at diff --git a/shared/package-files/01/014806b589b3d262285668ca54c01ae59ce50b5a796a7c64f8de12cbba5e3cda/blob b/shared/package-files/01/014806b589b3d262285668ca54c01ae59ce50b5a796a7c64f8de12cbba5e3cda/blob new file mode 100644 index 0000000000000000000000000000000000000000..98fb6bc54a3a78e142365094311c89ca6533528f --- /dev/null +++ b/shared/package-files/01/014806b589b3d262285668ca54c01ae59ce50b5a796a7c64f8de12cbba5e3cda/blob @@ -0,0 +1,84 @@ +import os +USE_SYMENGINE = os.getenv('USE_SYMENGINE', '0') +USE_SYMENGINE = USE_SYMENGINE.lower() in ('1', 't', 'true') # type: ignore + +if USE_SYMENGINE: + from symengine import (Symbol, Integer, sympify, S, + SympifyError, exp, log, gamma, sqrt, I, E, pi, Matrix, + sin, cos, tan, cot, csc, sec, asin, acos, atan, acot, acsc, asec, + sinh, cosh, tanh, coth, asinh, acosh, atanh, acoth, + lambdify, symarray, diff, zeros, eye, diag, ones, + expand, Function, symbols, var, Add, Mul, Derivative, + ImmutableMatrix, MatrixBase, Rational, Basic) + from symengine.lib.symengine_wrapper import gcd as igcd + from symengine import AppliedUndef +else: + from sympy.core.add import Add + from sympy.core.basic import Basic + from sympy.core.function import (diff, Function, AppliedUndef, + expand, Derivative) + from sympy.core.mul import Mul + from sympy.core.numbers import igcd, pi, I, Integer, Rational, E + from sympy.core.singleton import S + from sympy.core.symbol import Symbol, var, symbols + from sympy.core.sympify import SympifyError, sympify + from sympy.functions.elementary.exponential import log, exp + from sympy.functions.elementary.hyperbolic import (coth, sinh, + acosh, acoth, tanh, asinh, atanh, cosh) + from sympy.functions.elementary.miscellaneous import sqrt + from sympy.functions.elementary.trigonometric import (csc, + asec, cos, atan, sec, acot, asin, tan, sin, cot, acsc, acos) + from sympy.functions.special.gamma_functions import gamma + from sympy.matrices.dense import (eye, zeros, diag, Matrix, + ones, symarray) + from sympy.matrices.immutable import ImmutableMatrix + from sympy.matrices.matrices import MatrixBase + from sympy.utilities.lambdify import lambdify + + +# +# XXX: Handling of immutable and mutable matrices in SymEngine is inconsistent +# with SymPy's matrix classes in at least SymEngine version 0.7.0. Until that +# is fixed the function below is needed for consistent behaviour when +# attempting to simplify a matrix. +# +# Expected behaviour of a SymPy mutable/immutable matrix .simplify() method: +# +# Matrix.simplify() : works in place, returns None +# ImmutableMatrix.simplify() : returns a simplified copy +# +# In SymEngine both mutable and immutable matrices simplify in place and return +# None. This is inconsistent with the matrix being "immutable" and also the +# returned None leads to problems in the mechanics module. +# +# The simplify function should not be used because simplify(M) sympifies the +# matrix M and the SymEngine matrices all sympify to SymPy matrices. If we want +# to work with SymEngine matrices then we need to use their .simplify() method +# but that method does not work correctly with immutable matrices. +# +# The _simplify_matrix function can be removed when the SymEngine bug is fixed. +# Since this should be a temporary problem we do not make this function part of +# the public API. +# +# SymEngine issue: https://github.com/symengine/symengine.py/issues/363 +# + +def _simplify_matrix(M): + """Return a simplified copy of the matrix M""" + assert isinstance(M, (Matrix, ImmutableMatrix)) + Mnew = M.as_mutable() # makes a copy if mutable + Mnew.simplify() + if isinstance(M, ImmutableMatrix): + Mnew = Mnew.as_immutable() + return Mnew + + +__all__ = [ + 'Symbol', 'Integer', 'sympify', 'S', 'SympifyError', 'exp', 'log', + 'gamma', 'sqrt', 'I', 'E', 'pi', 'Matrix', 'sin', 'cos', 'tan', 'cot', + 'csc', 'sec', 'asin', 'acos', 'atan', 'acot', 'acsc', 'asec', 'sinh', + 'cosh', 'tanh', 'coth', 'asinh', 'acosh', 'atanh', 'acoth', 'lambdify', + 'symarray', 'diff', 'zeros', 'eye', 'diag', 'ones', 'expand', 'Function', + 'symbols', 'var', 'Add', 'Mul', 'Derivative', 'ImmutableMatrix', + 'MatrixBase', 'Rational', 'Basic', 'igcd', 'AppliedUndef', +] diff --git a/shared/package-files/01/0149b473bfed9d94fc2d4636cb491e549880a9128f7c926e1170c1ca1616d558/blob b/shared/package-files/01/0149b473bfed9d94fc2d4636cb491e549880a9128f7c926e1170c1ca1616d558/blob new file mode 100644 index 0000000000000000000000000000000000000000..0c3163a4ff9fd5eb0c470e199be0f7aec2fb4f50 --- /dev/null +++ b/shared/package-files/01/0149b473bfed9d94fc2d4636cb491e549880a9128f7c926e1170c1ca1616d558/blob @@ -0,0 +1,24 @@ +#pragma once +// @generated by torchgen/gen.py from DispatchKeyFunction.h + +// NB: The implementing C++ file is RegisterDispatchKey.cpp + +// The only #includes we need are for custom classes that have defaults in the C++ API +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { + +namespace compositeexplicitautogradnonfunctional { + +TORCH_API at::Tensor log2(const at::Tensor & self); +TORCH_API at::Tensor & log2_(at::Tensor & self); + +} // namespace compositeexplicitautogradnonfunctional +} // namespace at diff --git a/shared/package-files/01/014b8a2c1154101d5ad19860f7882e3910eb06ddda0bf0a6cbb7b5c4cf37ffa0/blob b/shared/package-files/01/014b8a2c1154101d5ad19860f7882e3910eb06ddda0bf0a6cbb7b5c4cf37ffa0/blob new file mode 100644 index 0000000000000000000000000000000000000000..0eebfdbab373ff676f78cebd322af811c45de5f9 --- /dev/null +++ b/shared/package-files/01/014b8a2c1154101d5ad19860f7882e3910eb06ddda0bf0a6cbb7b5c4cf37ffa0/blob @@ -0,0 +1,22 @@ +#pragma once + +// @generated by torchgen/gen.py from NativeFunction.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + +namespace at { +namespace native { +TORCH_API ::std::tuple miopen_batch_norm_out(const at::Tensor & input, const at::Tensor & weight, const c10::optional & bias, const c10::optional & running_mean, const c10::optional & running_var, bool training, double exponential_average_factor, double epsilon, at::Tensor & out0, at::Tensor & out1, at::Tensor & out2); +TORCH_API ::std::tuple miopen_batch_norm(const at::Tensor & input, const at::Tensor & weight, const c10::optional & bias, const c10::optional & running_mean, const c10::optional & running_var, bool training, double exponential_average_factor, double epsilon); +} // namespace native +} // namespace at diff --git a/shared/package-files/01/014bb1b7242f316ad304d6ce21a2fab8a701fc336935bd185f6f0922e4c7c3f6/blob b/shared/package-files/01/014bb1b7242f316ad304d6ce21a2fab8a701fc336935bd185f6f0922e4c7c3f6/blob new file mode 100644 index 0000000000000000000000000000000000000000..32662fc6a257e9bb3da60b259756d8f9f7fa7919 --- /dev/null +++ b/shared/package-files/01/014bb1b7242f316ad304d6ce21a2fab8a701fc336935bd185f6f0922e4c7c3f6/blob @@ -0,0 +1,19 @@ +from fontTools import ttLib + +superclass = ttLib.getTableClass("hmtx") + + +class table__v_m_t_x(superclass): + """Vertical Metrics table + + The ``vmtx`` table contains per-glyph metrics for the glyphs in a + ``glyf``, ``CFF ``, or ``CFF2`` table, as needed for vertical text + layout. + + See also https://learn.microsoft.com/en-us/typography/opentype/spec/vmtx + """ + + headerTag = "vhea" + advanceName = "height" + sideBearingName = "tsb" + numberOfMetricsName = "numberOfVMetrics" diff --git a/shared/package-files/01/014d855008345a085fbe73c35ba961301d64a4d75fbf7728091f1b95c44d049f/blob b/shared/package-files/01/014d855008345a085fbe73c35ba961301d64a4d75fbf7728091f1b95c44d049f/blob new file mode 100644 index 0000000000000000000000000000000000000000..35ae8121364d4fb3292c11f2a72333f456fa9c0a --- /dev/null +++ b/shared/package-files/01/014d855008345a085fbe73c35ba961301d64a4d75fbf7728091f1b95c44d049f/blob @@ -0,0 +1,42 @@ +0 0 1 +1 1 1 +1 0 0 +1 0 0 +1 1 1 +0 0 1 +0 0 0 +1 1 1 +0 0 0 +0 1 1 +0 1 0 +1 1 0 +0 0 0 +0 0 0 +0 0 0 +0 1 1 +1 1 1 +1 1 0 +0 1 0 +1 1 1 +0 1 0 +1 0 0 +0 1 0 +0 0 1 +0 1 0 +0 1 0 +0 1 0 +1 1 1 +1 1 1 +1 1 1 +1 1 0 +0 1 0 +0 1 1 +1 0 1 +0 1 0 +1 0 1 +0 0 1 +0 1 0 +1 0 0 +1 1 0 +1 1 1 +0 1 1 diff --git a/shared/package-files/01/0151cec08c4cfadf7fc3e163545efd46bcde0b9c1873983ded63d4a7b6c81e50/blob b/shared/package-files/01/0151cec08c4cfadf7fc3e163545efd46bcde0b9c1873983ded63d4a7b6c81e50/blob new file mode 100644 index 0000000000000000000000000000000000000000..3c9117ee57d3534e3e72329d740632c02e936200 --- /dev/null +++ b/shared/package-files/01/0151cec08c4cfadf7fc3e163545efd46bcde0b9c1873983ded63d4a7b6c81e50/blob @@ -0,0 +1,86 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING +if TYPE_CHECKING: + import torch + array = torch.Tensor + from typing import Union, Sequence, Literal + +from torch.fft import * # noqa: F403 +import torch.fft + +# Several torch fft functions do not map axes to dim + +def fftn( + x: array, + /, + *, + s: Sequence[int] = None, + axes: Sequence[int] = None, + norm: Literal["backward", "ortho", "forward"] = "backward", + **kwargs, +) -> array: + return torch.fft.fftn(x, s=s, dim=axes, norm=norm, **kwargs) + +def ifftn( + x: array, + /, + *, + s: Sequence[int] = None, + axes: Sequence[int] = None, + norm: Literal["backward", "ortho", "forward"] = "backward", + **kwargs, +) -> array: + return torch.fft.ifftn(x, s=s, dim=axes, norm=norm, **kwargs) + +def rfftn( + x: array, + /, + *, + s: Sequence[int] = None, + axes: Sequence[int] = None, + norm: Literal["backward", "ortho", "forward"] = "backward", + **kwargs, +) -> array: + return torch.fft.rfftn(x, s=s, dim=axes, norm=norm, **kwargs) + +def irfftn( + x: array, + /, + *, + s: Sequence[int] = None, + axes: Sequence[int] = None, + norm: Literal["backward", "ortho", "forward"] = "backward", + **kwargs, +) -> array: + return torch.fft.irfftn(x, s=s, dim=axes, norm=norm, **kwargs) + +def fftshift( + x: array, + /, + *, + axes: Union[int, Sequence[int]] = None, + **kwargs, +) -> array: + return torch.fft.fftshift(x, dim=axes, **kwargs) + +def ifftshift( + x: array, + /, + *, + axes: Union[int, Sequence[int]] = None, + **kwargs, +) -> array: + return torch.fft.ifftshift(x, dim=axes, **kwargs) + + +__all__ = torch.fft.__all__ + [ + "fftn", + "ifftn", + "rfftn", + "irfftn", + "fftshift", + "ifftshift", +] + +_all_ignore = ['torch'] diff --git a/shared/package-files/01/01550377a240cb58c294861e4033dc57e3bbc467dbef1edfa2337b85bec03475/blob b/shared/package-files/01/01550377a240cb58c294861e4033dc57e3bbc467dbef1edfa2337b85bec03475/blob new file mode 100644 index 0000000000000000000000000000000000000000..aeb9cad2d4c663cbc7e88246f6e35dc4c0c423e3 --- /dev/null +++ b/shared/package-files/01/01550377a240cb58c294861e4033dc57e3bbc467dbef1edfa2337b85bec03475/blob @@ -0,0 +1,333 @@ +""" + pygments.lexers.kuin + ~~~~~~~~~~~~~~~~~~~~ + + Lexers for the Kuin language. + + :copyright: Copyright 2006-2023 by the Pygments team, see AUTHORS. + :license: BSD, see LICENSE for details. +""" + +from pygments.lexer import RegexLexer, include, using, this, bygroups, words +from pygments.token import Text, Comment, Operator, Keyword, Name, String, \ + Number, Punctuation, Whitespace + +__all__ = ['KuinLexer'] + + +class KuinLexer(RegexLexer): + """ + For Kuin source code. + + .. versionadded:: 2.9 + """ + name = 'Kuin' + url = 'https://github.com/kuina/Kuin' + aliases = ['kuin'] + filenames = ['*.kn'] + + tokens = { + 'root': [ + include('statement'), + ], + 'statement': [ + # Whitespace / Comment + include('whitespace'), + + # Block-statement + (r'(\+?)([ \t]*)(\*?)([ \t]*)(\bfunc)([ \t]+(?:\n\s*\|)*[ \t]*)([a-zA-Z_][0-9a-zA-Z_]*)', + bygroups(Keyword,Whitespace, Keyword, Whitespace, Keyword, + using(this), Name.Function), 'func_'), + (r'\b(class)([ \t]+(?:\n\s*\|)*[ \t]*)([a-zA-Z_][0-9a-zA-Z_]*)', + bygroups(Keyword, using(this), Name.Class), 'class_'), + (r'\b(enum)([ \t]+(?:\n\s*\|)*[ \t]*)([a-zA-Z_][0-9a-zA-Z_]*)', + bygroups(Keyword, using(this), Name.Constant), 'enum_'), + (r'\b(block)\b(?:([ \t]+(?:\n\s*\|)*[ \t]*)([a-zA-Z_][0-9a-zA-Z_]*))?', + bygroups(Keyword, using(this), Name.Other), 'block_'), + (r'\b(ifdef)\b(?:([ \t]+(?:\n\s*\|)*[ \t]*)([a-zA-Z_][0-9a-zA-Z_]*))?', + bygroups(Keyword, using(this), Name.Other), 'ifdef_'), + (r'\b(if)\b(?:([ \t]+(?:\n\s*\|)*[ \t]*)([a-zA-Z_][0-9a-zA-Z_]*))?', + bygroups(Keyword, using(this), Name.Other), 'if_'), + (r'\b(switch)\b(?:([ \t]+(?:\n\s*\|)*[ \t]*)([a-zA-Z_][0-9a-zA-Z_]*))?', + bygroups(Keyword, using(this), Name.Other), 'switch_'), + (r'\b(while)\b(?:([ \t]+(?:\n\s*\|)*[ \t]*)([a-zA-Z_][0-9a-zA-Z_]*))?', + bygroups(Keyword, using(this), Name.Other), 'while_'), + (r'\b(for)\b(?:([ \t]+(?:\n\s*\|)*[ \t]*)([a-zA-Z_][0-9a-zA-Z_]*))?', + bygroups(Keyword, using(this), Name.Other), 'for_'), + (r'\b(foreach)\b(?:([ \t]+(?:\n\s*\|)*[ \t]*)([a-zA-Z_][0-9a-zA-Z_]*))?', + bygroups(Keyword, using(this), Name.Other), 'foreach_'), + (r'\b(try)\b(?:([ \t]+(?:\n\s*\|)*[ \t]*)([a-zA-Z_][0-9a-zA-Z_]*))?', + bygroups(Keyword, using(this), Name.Other), 'try_'), + + # Line-statement + (r'\b(do)\b', Keyword, 'do'), + (r'(\+?[ \t]*\bvar)\b', Keyword, 'var'), + (r'\b(const)\b', Keyword, 'const'), + (r'\b(ret)\b', Keyword, 'ret'), + (r'\b(throw)\b', Keyword, 'throw'), + (r'\b(alias)\b', Keyword, 'alias'), + (r'\b(assert)\b', Keyword, 'assert'), + (r'\|', Text, 'continued_line'), + (r'[ \t]*\n', Whitespace), + ], + + # Whitespace / Comment + 'whitespace': [ + (r'^([ \t]*)(;.*)', bygroups(Comment.Single, Whitespace)), + (r'[ \t]+(?![; \t])', Whitespace), + (r'\{', Comment.Multiline, 'multiline_comment'), + ], + 'multiline_comment': [ + (r'\{', Comment.Multiline, 'multiline_comment'), + (r'(?:\s*;.*|[^{}\n]+)', Comment.Multiline), + (r'\n', Comment.Multiline), + (r'\}', Comment.Multiline, '#pop'), + ], + + # Block-statement + 'func_': [ + include('expr'), + (r'\n', Whitespace, 'func'), + ], + 'func': [ + (r'\b(end)([ \t]+(?:\n\s*\|)*[ \t]*)(func)\b', + bygroups(Keyword, using(this), Keyword), '#pop:2'), + include('statement'), + ], + 'class_': [ + include('expr'), + (r'\n', Whitespace, 'class'), + ], + 'class': [ + (r'\b(end)([ \t]+(?:\n\s*\|)*[ \t]*)(class)\b', + bygroups(Keyword, using(this), Keyword), '#pop:2'), + include('statement'), + ], + 'enum_': [ + include('expr'), + (r'\n', Whitespace, 'enum'), + ], + 'enum': [ + (r'\b(end)([ \t]+(?:\n\s*\|)*[ \t]*)(enum)\b', + bygroups(Keyword, using(this), Keyword), '#pop:2'), + include('expr'), + (r'\n', Whitespace), + ], + 'block_': [ + include('expr'), + (r'\n', Whitespace, 'block'), + ], + 'block': [ + (r'\b(end)([ \t]+(?:\n\s*\|)*[ \t]*)(block)\b', + bygroups(Keyword, using(this), Keyword), '#pop:2'), + include('statement'), + include('break'), + include('skip'), + ], + 'ifdef_': [ + include('expr'), + (r'\n', Whitespace, 'ifdef'), + ], + 'ifdef': [ + (r'\b(end)([ \t]+(?:\n\s*\|)*[ \t]*)(ifdef)\b', + bygroups(Keyword, using(this), Keyword), '#pop:2'), + (words(('rls', 'dbg'), prefix=r'\b', suffix=r'\b'), + Keyword.Constant, 'ifdef_sp'), + include('statement'), + include('break'), + include('skip'), + ], + 'ifdef_sp': [ + include('expr'), + (r'\n', Whitespace, '#pop'), + ], + 'if_': [ + include('expr'), + (r'\n', Whitespace, 'if'), + ], + 'if': [ + (r'\b(end)([ \t]+(?:\n\s*\|)*[ \t]*)(if)\b', + bygroups(Keyword, using(this), Keyword), '#pop:2'), + (words(('elif', 'else'), prefix=r'\b', suffix=r'\b'), Keyword, 'if_sp'), + include('statement'), + include('break'), + include('skip'), + ], + 'if_sp': [ + include('expr'), + (r'\n', Whitespace, '#pop'), + ], + 'switch_': [ + include('expr'), + (r'\n', Whitespace, 'switch'), + ], + 'switch': [ + (r'\b(end)([ \t]+(?:\n\s*\|)*[ \t]*)(switch)\b', + bygroups(Keyword, using(this), Keyword), '#pop:2'), + (words(('case', 'default', 'to'), prefix=r'\b', suffix=r'\b'), + Keyword, 'switch_sp'), + include('statement'), + include('break'), + include('skip'), + ], + 'switch_sp': [ + include('expr'), + (r'\n', Whitespace, '#pop'), + ], + 'while_': [ + include('expr'), + (r'\n', Whitespace, 'while'), + ], + 'while': [ + (r'\b(end)([ \t]+(?:\n\s*\|)*[ \t]*)(while)\b', + bygroups(Keyword, using(this), Keyword), '#pop:2'), + include('statement'), + include('break'), + include('skip'), + ], + 'for_': [ + include('expr'), + (r'\n', Whitespace, 'for'), + ], + 'for': [ + (r'\b(end)([ \t]+(?:\n\s*\|)*[ \t]*)(for)\b', + bygroups(Keyword, using(this), Keyword), '#pop:2'), + include('statement'), + include('break'), + include('skip'), + ], + 'foreach_': [ + include('expr'), + (r'\n', Whitespace, 'foreach'), + ], + 'foreach': [ + (r'\b(end)([ \t]+(?:\n\s*\|)*[ \t]*)(foreach)\b', + bygroups(Keyword, using(this), Keyword), '#pop:2'), + include('statement'), + include('break'), + include('skip'), + ], + 'try_': [ + include('expr'), + (r'\n', Whitespace, 'try'), + ], + 'try': [ + (r'\b(end)([ \t]+(?:\n\s*\|)*[ \t]*)(try)\b', + bygroups(Keyword, using(this), Keyword), '#pop:2'), + (words(('catch', 'finally', 'to'), prefix=r'\b', suffix=r'\b'), + Keyword, 'try_sp'), + include('statement'), + include('break'), + include('skip'), + ], + 'try_sp': [ + include('expr'), + (r'\n', Whitespace, '#pop'), + ], + + # Line-statement + 'break': [ + (r'\b(break)\b([ \t]+)([a-zA-Z_][0-9a-zA-Z_]*)', + bygroups(Keyword, using(this), Name.Other)), + ], + 'skip': [ + (r'\b(skip)\b([ \t]+)([a-zA-Z_][0-9a-zA-Z_]*)', + bygroups(Keyword, using(this), Name.Other)), + ], + 'alias': [ + include('expr'), + (r'\n', Whitespace, '#pop'), + ], + 'assert': [ + include('expr'), + (r'\n', Whitespace, '#pop'), + ], + 'const': [ + include('expr'), + (r'\n', Whitespace, '#pop'), + ], + 'do': [ + include('expr'), + (r'\n', Whitespace, '#pop'), + ], + 'ret': [ + include('expr'), + (r'\n', Whitespace, '#pop'), + ], + 'throw': [ + include('expr'), + (r'\n', Whitespace, '#pop'), + ], + 'var': [ + include('expr'), + (r'\n', Whitespace, '#pop'), + ], + 'continued_line': [ + include('expr'), + (r'\n', Whitespace, '#pop'), + ], + + 'expr': [ + # Whitespace / Comment + include('whitespace'), + + # Punctuation + (r'\(', Punctuation,), + (r'\)', Punctuation,), + (r'\[', Punctuation,), + (r'\]', Punctuation,), + (r',', Punctuation), + + # Keyword + (words(( + 'true', 'false', 'null', 'inf' + ), prefix=r'\b', suffix=r'\b'), Keyword.Constant), + (words(( + 'me' + ), prefix=r'\b', suffix=r'\b'), Keyword), + (words(( + 'bit16', 'bit32', 'bit64', 'bit8', 'bool', + 'char', 'class', 'dict', 'enum', 'float', 'func', + 'int', 'list', 'queue', 'stack' + ), prefix=r'\b', suffix=r'\b'), Keyword.Type), + + # Number + (r'\b[0-9]\.[0-9]+(?!\.)(:?e[\+-][0-9]+)?\b', Number.Float), + (r'\b2#[01]+(?:b(?:8|16|32|64))?\b', Number.Bin), + (r'\b8#[0-7]+(?:b(?:8|16|32|64))?\b', Number.Oct), + (r'\b16#[0-9A-F]+(?:b(?:8|16|32|64))?\b', Number.Hex), + (r'\b[0-9]+(?:b(?:8|16|32|64))?\b', Number.Decimal), + + # String / Char + (r'"', String.Double, 'string'), + (r"'(?:\\.|.)+?'", String.Char), + + # Operator + (r'(?:\.|\$(?:>|<)?)', Operator), + (r'(?:\^)', Operator), + (r'(?:\+|-|!|##?)', Operator), + (r'(?:\*|/|%)', Operator), + (r'(?:~)', Operator), + (r'(?:(?:=|<>)(?:&|\$)?|<=?|>=?)', Operator), + (r'(?:&)', Operator), + (r'(?:\|)', Operator), + (r'(?:\?)', Operator), + (r'(?::(?::|\+|-|\*|/|%|\^|~)?)', Operator), + + # Identifier + (r"\b([a-zA-Z_][0-9a-zA-Z_]*)(?=@)\b", Name), + (r"(@)?\b([a-zA-Z_][0-9a-zA-Z_]*)\b", + bygroups(Name.Other, Name.Variable)), + ], + + # String + 'string': [ + (r'(?:\\[^{\n]|[^"\\])+', String.Double), + (r'\\\{', String.Double, 'toStrInString'), + (r'"', String.Double, '#pop'), + ], + 'toStrInString': [ + include('expr'), + (r'\}', String.Double, '#pop'), + ], + } diff --git a/shared/package-files/01/01591da6acf866c2de323a823a14d6ac5a9df942beb524378f3e9bb631f2e1cd/blob b/shared/package-files/01/01591da6acf866c2de323a823a14d6ac5a9df942beb524378f3e9bb631f2e1cd/blob new file mode 100644 index 0000000000000000000000000000000000000000..cc58e57bece89518dfa33950e3b14af2ec2fba0f --- /dev/null +++ b/shared/package-files/01/01591da6acf866c2de323a823a14d6ac5a9df942beb524378f3e9bb631f2e1cd/blob @@ -0,0 +1,216 @@ +error(0.009136552019934714511) D0 D2 +error(0.005464158925819233119) D0 D2 ^ D8 +error(0.005469859982010771837) D0 D3 +error(0.01761282241141449642) D0 D5 +error(0.002611938713844778274) D0 D5 ^ D7 D8 +error(0.001602991583532169641) D0 D5 ^ D8 +error(0.002281248792138410465) D0 D9 +error(0.0005702249272605554829) D0 D9 ^ D7 ^ D8 +error(0.002530008616832118192) D0 D10 +error(0.000756745747051372551) D0 D10 ^ D7 +error(0.001283472329134390227) D0 D10 ^ D7 D8 +error(0.003324822230312300328) D0 D10 ^ D8 +error(0.01410489125600283486) D0 L0 +error(0.008568718654201168405) D1 D3 +error(0.0200481630821856549) D1 D9 +error(0.005264374988297878047) D1 L0 +error(0.006622372643868884058) D2 +error(0.003653866618063004394) D2 D5 +error(0.002485682746826064441) D2 D5 ^ D8 +error(0.02670503232731233703) D2 D6 +error(0.004570299400977834159) D2 D6 ^ D8 +error(0.002810415699097040376) D2 D10 +error(0.002403831291505435612) D2 D10 ^ D8 +error(0.01238254091439352535) D3 +error(0.007074156531718671544) D3 D9 +error(0.0002615251970199665584) D3 D9 ^ D11 +error(0.02027395729299179272) D3 D10 +error(0.002565179960495663804) D3 D10 ^ D11 +error(0.007973152927160819317) D3 ^ D11 +error(0.02220659339750094899) D4 +error(0.01664835297211754786) D4 D7 +error(0.01708604558985005184) D4 D7 ^ D5 L0 +error(0.02237782062136002906) D4 D12 +error(0.004958116026045455982) D4 D12 ^ D13 L0 +error(0.005671323707155184052) D4 D15 +error(0.005506739356515328622) D4 D15 ^ D5 L0 +error(0.002644092168590221007) D4 D15 ^ D13 L0 +error(0.00093713256373133822) D4 D15 ^ D13 L0 ^ D5 L0 +error(0.0004744378536785873722) D4 D16 +error(0.001602231123625079759) D4 D16 ^ D5 D13 +error(0.0004654842048517412057) D4 D16 ^ D5 L0 +error(0.001257937987288801915) D4 D16 ^ D13 L0 +error(0.01817669479454275816) D4 ^ D5 L0 +error(0.004030619585409432777) D4 ^ D13 L0 +error(0.003178905849325630757) D5 D13 ^ D4 +error(0.008218595114538372257) D5 D6 +error(0.00089126178304638952) D5 D6 ^ D7 D16 +error(0.01334359251748560432) D5 D6 ^ D8 +error(0.004992139712583541257) D5 D6 ^ D8 D16 +error(0.0006482356022819127546) D5 D6 ^ D16 +error(0.001129435381317993488) D5 D6 ^ D16 ^ D4 +error(0.01575040590102892712) D5 D10 +error(0.01240968086796731366) D5 D10 ^ D7 D8 +error(0.01974470874319861693) D5 D13 +error(0.003172171860549861944) D5 D13 ^ D15 D16 +error(0.001044527312480149133) D5 D13 ^ D16 +error(0.002052249842967903727) D5 D17 +error(0.001160132296402382156) D5 D17 ^ D7 D15 +error(0.0006400549448208862771) D5 D17 ^ D7 D16 +error(0.0008241901707396004449) D5 D17 ^ D15 D16 +error(0.002163302208770687129) D5 D18 +error(0.002370589293255967022) D5 D18 ^ D7 D8 +error(0.001894079183581589935) D5 D18 ^ D7 D15 +error(0.001690123083343877562) D5 D18 ^ D7 D16 +error(0.003140466016737530376) D5 D18 ^ D15 D16 +error(0.01708547273643822723) D5 L0 +error(0.00282697018054000682) D7 D15 ^ D5 L0 +error(0.01642151620515877944) D6 +error(0.00180049872861907565) D6 D13 +error(0.00230853537296296478) D6 D13 ^ D16 +error(0.0003315128782695162023) D6 D13 ^ D16 ^ D4 +error(0.02406242506829752575) D6 D14 +error(0.004798197613096914088) D6 D14 ^ D16 +error(0.001757148080226241926) D6 D18 +error(0.0001913106593206013529) D6 D18 ^ D7 D8 +error(0.002140357000763331522) D6 D18 ^ D8 D16 +error(0.01523651903674870176) D6 ^ D8 +error(0.002352084697850920225) D6 ^ D16 ^ D8 +error(0.04195027679820911848) D7 +error(0.008040283102684174163) D7 D8 +error(0.001658107396684114837) D7 D8 ^ D10 D18 +error(0.01758107915734586496) D7 D15 +error(0.002138132726853613375) D7 D15 ^ D17 D18 +error(0.002984923855903891601) D7 D16 +error(0.0003612008314327335855) D7 D16 ^ D17 D18 +error(0.00237049356334604255) D7 D19 +error(0.0009415103370609101104) D7 D19 ^ D10 D18 +error(0.006241712534591854246) D7 ^ D0 L0 +error(0.0002169117478775997717) D7 ^ D5 L0 ^ D0 L0 +error(4.751059682527249584e-05) D7 ^ D8 ^ D0 L0 +error(0.01752651221686958929) D7 ^ D9 L0 +error(0.0002212162959289544007) D7 ^ D17 L0 +error(0.00239618700588853286) D9 D17 ^ D7 +error(0.03635038692751065004) D8 +error(0.018885140070960902) D8 D11 +error(0.01674584141695360795) D8 D11 ^ D10 +error(0.02245245230547847706) D8 D16 +error(0.003145413563016110411) D8 D16 ^ D18 +error(0.004405631949257069781) D8 D19 +error(0.002436259210597685639) D8 D19 ^ D10 +error(0.004664575900788009953) D8 D19 ^ D18 +error(0.0002486000126863092225) D8 D19 ^ D18 ^ D10 +error(0.001615328193195137482) D8 ^ D2 +error(0.002100729871540173762) D8 ^ D5 L0 +error(0.005693570554997882081) D8 ^ D10 +error(0.01052446318941231869) D9 D10 +error(0.01198153713490193208) D9 D10 ^ D7 +error(0.0008627097420875190622) D9 D10 ^ D7 ^ D8 +error(0.0002953419431381387847) D9 D10 ^ D8 +error(0.001004245850407009533) D9 D10 ^ D11 +error(0.01697383439923016296) D9 D17 +error(0.01968805833075008838) D9 L0 +error(0.02138546260676981586) D10 +error(0.006446353012199087379) D10 D17 +error(0.005190807972418269578) D10 D17 ^ D7 +error(0.0003512713244731430207) D10 D17 ^ D19 ^ D7 +error(0.02004767873589806751) D10 D18 +error(0.0002855832632238128159) D10 D18 ^ D7 +error(0.0009504042423179361867) D10 D18 ^ D19 +error(0.01405918236149469695) D10 ^ D11 +error(0.004291452065454295917) D10 ^ D19 +error(0.001281128318831409058) D11 D19 ^ D10 +error(0.03675554149602312803) D11 +error(0.02583097056613577538) D11 D19 +error(0.03013244766557492474) D12 +error(0.01886140351546503058) D12 D15 +error(0.01724036873822792915) D12 D15 ^ D13 L0 +error(0.01991574418275797453) D12 ^ D13 L0 +error(0.008667549432345093841) D12 ^ D20 L0 +error(0.005533941392691923804) D13 D20 ^ D12 +error(0.008341735507328154609) D13 D14 +error(0.0006498387015873938882) D13 D14 ^ D12 +error(0.01853998449442305352) D13 D14 ^ D16 +error(0.01231742548448962714) D13 D18 +error(0.01141942705380553924) D13 D18 ^ D15 D16 +error(0.02407598103302110298) D13 D20 +error(0.001612792009364578168) D13 D21 +error(0.001755520466182331884) D13 D21 ^ D15 +error(0.004769647005033404372) D13 D23 +error(0.004458647137099017513) D13 D23 ^ D15 +error(0.001092535256505172301) D13 D23 ^ D15 D16 +error(0.0005409754010685546323) D13 D23 ^ D16 +error(0.01000000000000000021) D13 L0 +error(0.01901632035765671302) D14 +error(0.003892233284482571332) D14 D20 +error(0.0005576072802830362579) D14 D20 ^ D12 +error(0.0327418805299789506) D14 D22 +error(0.002658430632104577702) D14 D23 +error(0.0006214505726791042873) D14 D23 ^ D15 +error(0.002272480947071183529) D14 D23 ^ D16 +error(0.01287980276692320125) D14 ^ D16 +error(0.03615703589192576645) D15 +error(0.0089646628767767432) D15 D16 +error(0.0004695341436693858711) D15 D16 ^ D5 L0 +error(0.0001466862929750814624) D15 D16 ^ D17 D18 +error(0.00116699376698910489) D15 D16 ^ D18 D23 +error(0.001099688958728371789) D15 ^ D16 ^ D23 +error(0.01514948179627582936) D15 ^ D17 L0 +error(0.00449897853184385698) D17 D21 ^ D15 +error(0.0002030389319659737168) D15 ^ D23 +error(0.00395647038893058231) D18 D23 ^ D15 +error(0.03851158625866567264) D16 +error(0.01693864137092335881) D16 D19 +error(0.01886300820286869462) D16 D19 ^ D18 +error(0.002853802791706025726) D16 ^ D18 +error(0.007929309772862245392) D16 ^ D23 +error(0.001412214974195339593) D16 ^ D23 ^ D18 +error(0.009898603679615149489) D17 D18 +error(0.001433094620702996588) D17 D18 ^ D7 +error(0.01234881507326082359) D17 D18 ^ D15 +error(0.0003162869202887969781) D17 D18 ^ D19 +error(0.0008773000388939430991) D17 D18 ^ D19 ^ D7 +error(0.02198290391349307094) D17 D21 +error(0.01711492459188631438) D17 L0 +error(0.000452607020332834644) D17 L0 ^ D15 ^ D7 +error(0.02736278443498239496) D18 +error(0.002916639017556591548) D18 D21 +error(0.005882416638128336317) D18 D21 ^ D15 +error(0.01898001588781324245) D18 D23 +error(0.0006639320211282793548) D18 ^ D6 ^ D8 +error(0.0007591947836394729015) D18 ^ D6 ^ D16 +error(0.00173940441292912769) D18 ^ D8 +error(0.01449896533919865088) D18 ^ D19 +error(0.02720617756495216644) D19 +error(0.02172967141509596356) D20 D22 +error(0.0156893119833464989) D20 D23 +error(0.02823841843042903393) D20 L0 +error(0.01540914428095823026) D21 D23 +error(0.004375204237091523223) D21 D23 ^ D15 +error(0.02436422234116262381) D21 L0 +error(0.01171423663884488264) D22 +error(0.02726237357467104633) D23 +detector(4, 7, 0) D0 +detector(6, 5, 0) D1 +detector(4, 9, 0) D2 +detector(6, 7, 0) D3 +detector(3, 6, 1) D4 +detector(4, 7, 1) D5 +detector(4, 9, 1) D6 +detector(5, 6, 1) D7 +detector(5, 8, 1) D8 +detector(6, 5, 1) D9 +detector(6, 7, 1) D10 +detector(7, 8, 1) D11 +detector(3, 6, 2) D12 +detector(4, 7, 2) D13 +detector(4, 9, 2) D14 +detector(5, 6, 2) D15 +detector(5, 8, 2) D16 +detector(6, 5, 2) D17 +detector(6, 7, 2) D18 +detector(7, 8, 2) D19 +detector(4, 7, 3) D20 +detector(6, 5, 3) D21 +detector(4, 9, 3) D22 +detector(6, 7, 3) D23 diff --git a/shared/package-files/01/01596b27e6f4a150ce2ceeb5f893ddcf9f2874d217e192b35a040fa1d176a92e/blob b/shared/package-files/01/01596b27e6f4a150ce2ceeb5f893ddcf9f2874d217e192b35a040fa1d176a92e/blob new file mode 100644 index 0000000000000000000000000000000000000000..2ff8d13758541e24bdf0ace84b14ff89d51d54e0 --- /dev/null +++ b/shared/package-files/01/01596b27e6f4a150ce2ceeb5f893ddcf9f2874d217e192b35a040fa1d176a92e/blob @@ -0,0 +1,11 @@ +#pragma once + +#include +#include + +namespace torch { +namespace jit { + +TORCH_API const std::vector& getAllBuiltinFunctionsFor(Symbol name); +} // namespace jit +} // namespace torch diff --git a/shared/package-files/01/015adba0f54b13e9499ae1ecfa0bc8864e46d64ea3a060cd0a47467425943007/blob b/shared/package-files/01/015adba0f54b13e9499ae1ecfa0bc8864e46d64ea3a060cd0a47467425943007/blob new file mode 100644 index 0000000000000000000000000000000000000000..e295354a912a657134c12919acbfb5182cef684c --- /dev/null +++ b/shared/package-files/01/015adba0f54b13e9499ae1ecfa0bc8864e46d64ea3a060cd0a47467425943007/blob @@ -0,0 +1,403 @@ +import abc +import io +from dataclasses import dataclass +from enum import auto, Enum +from functools import reduce +from typing import Any, List, Optional, Tuple, Union + +import torch + +from .metadata import ( + ChunkStorageMetadata, + Metadata, + MetadataIndex, + STATE_DICT_TYPE, + TensorProperties, +) + + +__all__ = [ + "WriteItemType", + "LoadItemType", + "TensorWriteData", + "WriteItem", + "ReadItem", + "SavePlan", + "LoadPlan", + "SavePlanner", + "LoadPlanner", +] + + +class WriteItemType(Enum): + TENSOR = auto() + SHARD = auto() + BYTE_IO = auto() + + +class LoadItemType(Enum): + TENSOR = auto() + BYTE_IO = auto() + + +@dataclass(frozen=True) +class TensorWriteData: + chunk: ChunkStorageMetadata + properties: TensorProperties + size: torch.Size + + +@dataclass(frozen=True) +class WriteItem: + """Dataclass which holds information about what needs to be written to storage.""" + + index: MetadataIndex + type: WriteItemType + + # Value present if it's a tensor write + tensor_data: Optional[TensorWriteData] = None + + def tensor_storage_size(self) -> Optional[int]: + """ + Calculates the storage size of the underlying tensor, or None if this is not a tensor write. + + Returns: + Optional[int] storage size, in bytes of underlying tensor if any. + """ + if self.tensor_data is None: + return None + + numels = reduce(lambda x, y: x * y, self.tensor_data.size, 1) + dtype_size = torch._utils._element_size(self.tensor_data.properties.dtype) + return numels * dtype_size + + +@dataclass(frozen=True) +class ReadItem: + # Read Item + type: LoadItemType + + # Index into the state_dict + dest_index: MetadataIndex + # Offsets into destination tensor + dest_offsets: torch.Size + + # Index into the checkpoint + storage_index: MetadataIndex + # Offset into the checkpoint data + storage_offsets: torch.Size + + # Size of the hypercube to copy + lengths: torch.Size + + +@dataclass(frozen=True) +class SavePlan: + items: List[WriteItem] + storage_data: Any = None + planner_data: Any = None + + +@dataclass +class LoadPlan: + items: List[ReadItem] + storage_data: Any = None + planner_data: Any = None + + +class SavePlanner(abc.ABC): + """ + Abstract class defining the protocol used by save_state_dict to plan the save process. + + SavePlanners are stateful objects that can be used to customize the whole save process. + + SavePlanner acts as an access proxy to the state_dict, so any transformation done to it + will be visible to the whole process. + + A planner subclass can expect the following sequence of calls during save_state_dict: + + 1) set_up_planner - called on all ranks. + Signals the start of a checkpoint save. + + 2) create_local_plan - called on all ranks. + Process the state_dict and produces a `SavePlan` that will be sent for global planning. + + 3) create_global_plan - called on the coordinator rank only. + Takes the SavePlan from all ranks and make any global decision. + + 4) finish_plan - called on all ranks. + This gives each rank a chance to adjust to global planning decisions. + + 5) resolve_data - called multiple times on each rank + Lookups a value on the `state_dict` for the storage layer to write. + + Users are recommended to extend DefaultSavePlanner instead of this interface directly as + most changes can be expressed by changes in a single method. + + There are 3 usual patterns of extension: + + Rewriting state_dict. This is the simplest way to extend the save process as it + doesn't requite understanding the intrincacies of how SavePlan works: + + >>> # xdoctest: +SKIP("undefined vars") + >>> class RenamePlanner(DefaultSavePlanner): + >>> def set_up_planner(self, state_dict, is_coordinator): + >>> # prefix all keys with `foo_`` + >>> super().set_up_planner({"foo_" + k: v for k, v in state_dict.items()}, is_coordinator) + + Modifying local plan and lookup in tandem. This is useful when fine control of how data is persisted + + >>> # xdoctest: +SKIP("undefined vars") + >>> class FP16Planner(DefaultSavePlanner): + >>> def create_local_plan(self): + >>> plan = super().create_local_plan() + >>> for p in plan: + >>> if p.tensor_data is not None: + >>> p.tensor_data.properties.dtype = torch.float16 + >>> return plan + >>> + >>> def resolve_data(self, write_item): + >>> item = super().resolve_data(write_item) + >>> return item if write_item.type == WriteItemType.BYTE_IO else item.to(torch.float16) + + Using the global planning step to make central decisions that can't be made individually by each rank + + >>> # xdoctest: +SKIP("undefined vars") + >>> from itertools import islice + >>> from dataclasses import replace + >>> class DDPLoadBalancingPlanner(DefaultSavePlanner): + >>> # This uses the default local plan behavior of having all non-sharded writes in rank 0 + >>> # This sample doesn't handle ShardedTensors + >>> def create_global_plan(self, all_plans): + >>> def chunk(it, size): + >>> it = iter(it) + >>> return list(iter(lambda: tuple(islice(it, size)), ())) + >>> all_plans = [ + >>> replace(plan, items=items) for plan, items in + >>> zip(all_plans, chunk(all_plans[0].items, len(all_plans))) + >>> ] + >>> return super().create_global_plan(all_plans) + + Finally, some planners need to save additional metadata in the checkpoint, this is + accomplished by having each rank contribute their data items in the local plan and + the global planner aggregate them: + + >>> # xdoctest: +SKIP("undefined vars") + >>> class SaveExtraDataPlanner(DefaultSavePlanner): + >>> def create_local_plan(self) -> SavePlan: + >>> plan = super().create_local_plan() + >>> return replace(plan, planner_data="per-rank-data") + >>> + >>> def create_global_plan(self, all_plans: List[SavePlan]) -> Tuple[List[SavePlan], Metadata]: + >>> global_plan, metadata = super().create_global_plan(all_plans) + >>> merged_data = [p.planner_data for p in global_plan] + >>> metadata = replace(metadata, planner_data=merged_data) + >>> return global_plan, metadata + """ + + @abc.abstractmethod + def set_up_planner(self, state_dict: STATE_DICT_TYPE, is_coordinator: bool) -> None: + """ + Initialize this planner to save ``state_dict``. + + Implementations should save those values as they won't be provided lated in the save process. + + This is called on all ranks. + """ + pass + + @abc.abstractmethod + def create_local_plan(self) -> SavePlan: + """ + Compute the save plan for the current rank. + + This will be aggregated and passed to create_global_plan. + Planner specific data can be passed through SavePlan::planner_data. + + This is called on all ranks. + """ + pass + + @abc.abstractmethod + def create_global_plan( + self, all_plans: List[SavePlan] + ) -> Tuple[List[SavePlan], Metadata]: + """ + Compute the global checkpoint plan and return the local plan of each rank. + + This is called on the coordinator rank only. + """ + pass + + @abc.abstractmethod + def finish_plan(self, new_plan: SavePlan) -> SavePlan: + """ + Merge the plan created by `create_local_plan` and the result of `create_global_plan`. + + This is called on all ranks. + """ + pass + + @abc.abstractmethod + def resolve_data(self, write_item: WriteItem) -> Union[torch.Tensor, io.BytesIO]: + """ + Transform and prepare ``write_item`` from ``state_dict`` for storage, ensuring idempotency and thread-safety. + + Lookup the object associated with ``write_item`` in ``state_dict`` and apply any + transformation (such as serialization) prior to the storage layer consuming it. + + Called on each rank multiple times, at least once per WriteItem in the final SavePlan. + + This method should be idempotent and thread-save. StorageWriter implementations + are free to call it as frequently as they need. + + Any transformation that allocates memory should be lazily done when his method + is called in order to reduce peak memory required by checkpointing. + + When returning tensors, they can be on any device or format, they can be views too. + It's the storage layer responsibility to figure out how to save them. + """ + pass + + +class LoadPlanner: + """ + Abstract class defining the protocol used by load_state_dict to plan the load process. + + LoadPlanner are stateful objects that can be used to customize the whole load process. + + LoadPlanner acts as an access proxy to the state_dict, so any transformation done to it + will be visible to the whole process. + + A planner subclass can expect the following sequence of calls during load_state_dict: + + 1) set_up_planner - called on all ranks. + Signals the start of loading a checkpoint. + + 2) create_local_plan - called on all ranks. + Process the state_dict and produces a `LoadPlan` that will be sent for global planning. + + 3) create_global_plan - called on the coordinator rank only. + Takes the LoadPlan from all ranks and make any global decision. + + 4) load_bytes - called multiple times on each rank + This is called once per non-tensor value in state_dict. + + 5) resolve_tensor and commit_tensor - called multiple times on each rank + They are called in pair for each Tensor value in state_dict. + + Users are recommended to extend DefaultLoadPlanner instead of this interface directly as + most changes can be expressed by changes in a single method. + + There are two usual patterns of extension: + + Rewriting state_dict. This is the simplest way to extend the load process as it + doesn't requite understanding the intrincacies of how LoadPlan works. We need + to keep a reference to the original state_dict as load happens in place so + we need to be able to perform it in place + + >>> # xdoctest: +SKIP("undefined vars") + >>> class RenamePlanner(DefaultLoadPlanner): + >>> def set_up_planner(self, state_dict, metadata, is_coordinator): + >>> self.original_state_dict = state_dict + >>> state_dict = {"foo_" + k: v for k, v in state_dict.items()} + >>> + >>> if self.flatten_sharded_tensors: + >>> state_dict = _flatten_sharded_tensors(state_dict) + >>> + >>> if self.flatten_state_dict: + >>> state_dict, self.mappings = flatten_state_dict(state_dict) + >>> + >>> self.state_dict = state_dict + >>> self.metadata = metadata + >>> self.is_coordinator = is_coordinator + >>> + >>> def load_bytes(self, read_item, value): + >>> # Remove the "foo_" prefix + >>> self.original_state_dict[read_item.dest_index.fqn[4:]] = torch.load(value) + + + Modifying resolve_tensor and commit_tensor to handle load time transformation. + + >>> # xdoctest: +SKIP("undefined vars") + >>> class MetaModelMaterialize(DefaultSavePlanner): + >>> def resolve_tensor(self, read_item): + >>> tensor = super().resolve_tensor(read_item) + >>> return torch.empty_like(tensor, device="cpu") + >>> + >>> def commit_tensor(self, read_item, tensor): + >>> self.state_dict[read_item.dest_index.fqn] = tensor + """ + + @abc.abstractmethod + def set_up_planner( + self, + state_dict: STATE_DICT_TYPE, + metadata: Metadata, + is_coordinator: bool, + ) -> None: + """ + Initialize this instance to load data into ``state_dict``. + + . N.B. This is called on every rank. + """ + pass + + @abc.abstractmethod + def create_local_plan(self) -> LoadPlan: + """ + Create a LoadPlan based on state_dict and metadata provided by set_up_planner. + + . N.B. This is called on every rank. + """ + pass + + @abc.abstractmethod + def create_global_plan(self, global_plan: List[LoadPlan]) -> List[LoadPlan]: + """ + Compute the global load plan and return plans for each rank. + + . N.B. This is called on the coordinator rank only + """ + pass + + @abc.abstractmethod + def finish_plan(self, central_plan: LoadPlan) -> LoadPlan: + """Accept the plan from coordinator and return final LoadPlan.""" + pass + + @abc.abstractmethod + def load_bytes(self, read_item: ReadItem, value: io.BytesIO) -> None: + """ + Load the item described by ``read_item``and ``value``. + + This method is expected to modify in-place the underlying state_dict. + + The contents of ``value`` are defined by the SavePlanner used to produce + the checkpoint being loaded. + """ + pass + + @abc.abstractmethod + def resolve_tensor(self, read_item: ReadItem) -> torch.Tensor: + """ + Return the tensor described by ``read_item`` to be used by the StorageReader to load `read_item`. + + The tensor should alias with one on the underlying state_dict as StorageReader will replace its contents. + If, for any reason, that's not possible, the planner can use the ``commit_tensor`` method to copy the data + back to the one in state_dict. + """ + pass + + @abc.abstractmethod + def commit_tensor(self, read_item: ReadItem, tensor: torch.Tensor) -> None: + """ + Call once the StorageReader finished loading data into ``tensor``. + + The provided tensor is the same one returned by the call to ``resolve_tensor``. + This method is only needed if this LoadPlanner needs to post process ``tensor`` prior to + copying it back to the one in the state_dict. + + The contents of tensor will follow its device synchronization model. + """ + pass diff --git a/shared/package-files/01/015b34abea9ffb5d20b35b645617c02dd79b268e2e3ee555057ed84fdd6b8905/blob b/shared/package-files/01/015b34abea9ffb5d20b35b645617c02dd79b268e2e3ee555057ed84fdd6b8905/blob new file mode 100644 index 0000000000000000000000000000000000000000..4693a5a5f347f037d85017449901e9229dacbf8e --- /dev/null +++ b/shared/package-files/01/015b34abea9ffb5d20b35b645617c02dd79b268e2e3ee555057ed84fdd6b8905/blob @@ -0,0 +1 @@ +sortedcontainers diff --git a/shared/package-files/01/015b5a0cf6d2e0f1d295c8ff52008db6fcbc0cac2521a801e46a9ae1d9eeda12/blob b/shared/package-files/01/015b5a0cf6d2e0f1d295c8ff52008db6fcbc0cac2521a801e46a9ae1d9eeda12/blob new file mode 100644 index 0000000000000000000000000000000000000000..ff334d4c8d48ceeb4fa83fdbcd2e678a3e2d887d --- /dev/null +++ b/shared/package-files/01/015b5a0cf6d2e0f1d295c8ff52008db6fcbc0cac2521a801e46a9ae1d9eeda12/blob @@ -0,0 +1,335 @@ +#pragma once + +#ifdef USE_XNNPACK +#include + +#include +#include + +using xnnpack_operator = at::native::xnnpack::Operator; + +namespace at { +namespace native { +namespace xnnp_utils { + +/* + * Return shape in the same order as the memory format + * e.g. channels_last will return NHWC instead of NCHW + */ +std::vector get_mem_format_aware_shape(const at::Tensor& in); + +/* + * Input is always int8_t, output can be [int8_t, uint8_t]. + * input + offset = output + * int8_t + 128 = uint8_t + * int8_t + 0 = int8_t + */ +template +void q8_copy_int8_weight_and_add_offset(const at::Tensor& in, at::Tensor& out); + +template +Tensor convert_conv_weights_to_channel_last_tensor( + const at::Tensor& src, + int groups, + bool transpose); + +/* + * Series of create wrapper functions to call xnn_create_[de]conv* functions. + */ +C10_ALWAYS_INLINE +enum xnn_status xnnp_create_convolution2d_nhwc( + uint32_t pad_top, + uint32_t pad_right, + uint32_t pad_bottom, + uint32_t pad_left, + uint32_t kernel_h, + uint32_t kernel_w, + uint32_t stride_h, + uint32_t stride_w, + uint32_t dilation_h, + uint32_t dilation_w, + uint32_t groups, + size_t group_input_channels, + size_t group_output_channels, + size_t ip_chan_stride, + size_t op_chan_stride, + int8_t izp, + float ip_scale, + int8_t kzp, + const float* k_scales, + const int8_t* kernel, + const int32_t* bias, + int8_t ozp, + float op_scale, + int8_t op_min, + int8_t op_max, + uint32_t flags, + xnn_operator_t* op, + bool per_channel, + bool transpose) { + /* Symmetric quantization forces kzp = 0 */ + TORCH_CHECK(!kzp, "XNNPACK Q[SC]8 conv kernels expects kernel zero point to be zero." + "But got: ", kzp); + + if (transpose) { + TORCH_CHECK(!per_channel, "XNNPACK Q[SC]8 does not have a per channel deconvolution!"); + return xnn_create_deconvolution2d_nhwc_qs8( + pad_top, /* uint32_t output_padding_top */ + pad_right, /* uint32_t output_padding_right */ + pad_bottom, /* uint32_t output_padding_bottom */ + pad_left, /* uint32_t output_padding_left */ + kernel_h, /* uint32_t kernel_height */ + kernel_w, /* uint32_t kernel_width */ + stride_h, /* uint32_t stride_height */ + stride_w, /* uint32_t stride_width */ + dilation_h, /* uint32_t dilation_height */ + dilation_w, /* uint32_t dilation_width */ + groups, /* uint32_t groups */ + group_input_channels, /* size_t group_input_channels */ + group_output_channels, /* size_t group_output_channels */ + ip_chan_stride, /* size_t input_pixel_stride */ + op_chan_stride, /* size_t output_pixel_stride */ + izp, /* int8_t input_zero_point */ + ip_scale, /* float input_scale */ + k_scales[0], /* float kernel_scale */ + kernel, /* const int8_t* kernel */ + bias, /* const int32_t* bias */ + ozp, /* int8_t output_zero_point */ + op_scale, /* float output_scale */ + op_min, /* int8_t output_min */ + op_max, /* int8_t output_max */ + flags, /* uint32_t flags */ + nullptr, /* xnn_caches_t caches */ + nullptr, /* xnn_weights_cache_t weights_cache */ + op); /* xnn_operator_t* deconvolution_op_out */ + + } + + if (!per_channel) { + return xnn_create_convolution2d_nhwc_qs8( + pad_top, /* uint32_t input_padding_top */ + pad_right, /* uint32_t input_padding_right */ + pad_bottom, /* uint32_t input_padding_bottom */ + pad_left, /* uint32_t input_padding_left */ + kernel_h, /* uint32_t kernel_height */ + kernel_w, /* uint32_t kernel_width */ + stride_h, /* uint32_t subsampling_height */ + stride_w, /* uint32_t subsampling_width */ + dilation_h, /* uint32_t dilation_height */ + dilation_w, /* uint32_t dilation_width */ + groups, /* uint32_t groups */ + group_input_channels, /* size_t group_input_channels */ + group_output_channels, /* size_t group_output_channels*/ + ip_chan_stride, /* size_t input_channel_stride */ + op_chan_stride, /* size_t output_channel_stride */ + izp, /* int8_t input_zero_point */ + ip_scale, /* float input_scale */ + k_scales[0], /* float kernel_scale */ + kernel, /* const int8_t* kernel */ + bias, /* const int32_t* bias */ + ozp, /* int8_t output_zero_point */ + op_scale, /* float output_scale */ + op_min, /* int8_t output_min */ + op_max, /* int8_t output_max */ + flags, /* uint32_t flags */ + nullptr, /* xnn_caches_t caches */ + nullptr, /* xnn_weights_cache_t weights_cache */ + op); /* xnn_operator_t* convolution_op_out */ + } else { /* per_channel */ + return xnn_create_convolution2d_nhwc_qs8_qc8w( + pad_top, /* uint32_t input_padding_top */ + pad_right, /* uint32_t input_padding_right */ + pad_bottom, /* uint32_t input_padding_bottom */ + pad_left, /* uint32_t input_padding_left */ + kernel_h, /* uint32_t kernel_height */ + kernel_w, /* uint32_t kernel_width */ + stride_h, /* uint32_t subsampling_height */ + stride_w, /* uint32_t subsampling_width */ + dilation_h, /* uint32_t dilation_height */ + dilation_w, /* uint32_t dilation_width */ + groups, /* uint32_t groups */ + group_input_channels, /* size_t group_input_channels */ + group_output_channels, /* size_t group_output_channels*/ + ip_chan_stride, /* size_t input_channel_stride */ + op_chan_stride, /* size_t output_channel_stride */ + izp, /* int8_t input_zero_point */ + ip_scale, /* float input_scale */ + k_scales, /* const float* kernel_scale */ + kernel, /* const int8_t* kernel */ + bias, /* const int32_t* bias */ + ozp, /* int8_t output_zero_point */ + op_scale, /* float output_scale */ + op_min, /* int8_t output_min */ + op_max, /* int8_t output_max */ + flags, /* uint32_t flags */ + nullptr, /* xnn_caches_t caches */ + nullptr, /* xnn_weights_cache_t weights_cache */ + op); /* xnn_operator_t* convolution_op_out */ + } +} + +/* + * Series of reshape wrapper functions to call xnn_reshape_[de]conv* functions. + */ +C10_ALWAYS_INLINE +enum xnn_status xnnp_reshape_convolution2d_nhwc( + xnn_operator_t op, + size_t batch, + size_t in_h, + size_t in_w, + pthreadpool_t pt_pool, + bool per_channel = false, + bool transpose = false, + uint32_t adj_h = 0, + uint32_t adj_w = 0) { + if(transpose) { + TORCH_CHECK(!per_channel, "XNNPACK Q[SC]8 does not have a per channel deconvolution!"); + return xnn_reshape_deconvolution2d_nhwc_qs8( + op, /* xnn_operator_t deconvolution_op */ + batch, /* size_t batch_size */ + in_h, /* size_t input_height */ + in_w, /* size_t input_width */ + adj_h, /* uint32_t adjustment_height */ + adj_w, /* uint32_t adjustment_width */ + nullptr, /* size_t* output_height_out */ + nullptr, /* size_t* output_width_out */ + pt_pool); /* pthreadpool_t threadpool */ + } + + size_t workspace_size = SIZE_MAX; + size_t workspace_alignment = SIZE_MAX; + + if (!per_channel) { + return xnn_reshape_convolution2d_nhwc_qs8( + op, /* xnn_operator_t convolution_op */ + batch, /* size_t batch_size */ + in_h, /* size_t input_height */ + in_w, /* size_t input_width */ + &workspace_size, /* size_t* workspace_size */ + &workspace_alignment, /* size_t* workspace_alignment */ + nullptr, /* size_t* output_height_out */ + nullptr, /* size_t* output_width_out */ + pt_pool); /* pthreadpool_t threadpool */ + } else { /* per_channel */ + return xnn_reshape_convolution2d_nhwc_qs8_qc8w( + op, /* xnn_operator_t convolution_op */ + batch, /* size_t batch_size */ + in_h, /* size_t input_height */ + in_w, /* size_t input_width */ + &workspace_size, /* size_t* workspace_size */ + &workspace_alignment, /* size_t* workspace_alignment */ + nullptr, /* size_t* output_height_out */ + nullptr, /* size_t* output_width_out */ + pt_pool); /* pthreadpool_t threadpool */ + } +} + + +/* + * Series of setup wrapper functions to call xnn_setup_[de]conv* functions. + */ +C10_ALWAYS_INLINE +enum xnn_status xnnp_setup_convolution2d_nhwc( + xnn_operator_t op, + const int8_t* inp, + int8_t* outp, + bool per_channel = false, + bool transpose = false) { + if(transpose) { + TORCH_CHECK(!per_channel, "XNNPACK Q[SC]8 does not have a per channel deconvolution!"); + + return xnn_setup_deconvolution2d_nhwc_qs8( + op, /* xnn_operator_t deconvolution_op */ + inp, /* const int8_t* input */ + outp); /* int8_t* output */ + } + + if (!per_channel) { + return xnn_setup_convolution2d_nhwc_qs8( + op, /* xnn_operator_t deconvolution_op */ + nullptr, /* void workspace */ + inp, /* const int8_t* input */ + outp); /* int8_t* output */ + } else { /* per_channel */ + return xnn_setup_convolution2d_nhwc_qs8_qc8w( + op, /* xnn_operator_t deconvolution_op */ + nullptr, /* void workspace */ + inp, /* const int8_t* input */ + outp); /* int8_t* output */ + } +} + + +/* + * Series of wrapper functions to call xnn_create* and xnn_setup* + * functions for linear + */ +C10_ALWAYS_INLINE +enum xnn_status xnnp_create_fully_connected_nc( + size_t input_channels, + size_t output_channels, + size_t input_stride, + size_t output_stride, + int8_t input_zero_point, + float input_scale, + int8_t kernel_zero_point, + float kernel_scale, + const int8_t* kernel, + const int32_t* bias, + int8_t output_zero_point, + float output_scale, + int8_t output_min, + int8_t output_max, + uint32_t flags, + xnn_operator_t* fully_connected_op_out) { + /* Symmetric quantization forces kzp = 0 */ + TORCH_CHECK(!kernel_zero_point, "XNNPACK QS8 linear kernel expects kernel zero point to be zero." + "But got: ", kernel_zero_point); + return xnn_create_fully_connected_nc_qs8( + input_channels, /* size_t input_channels */ + output_channels, /* size_t output_channels */ + input_stride, /* size_t input_stride */ + output_stride, /* size_t output_stride */ + input_zero_point, /* int8_t input_zero_point */ + input_scale, /* float input_scale */ + kernel_scale, /* float kernel_scale */ + kernel, /* const int8_t* kernel */ + bias, /* const int32_t* bias */ + output_zero_point, /* int8_t output_zero_point */ + output_scale, /* float output_scale */ + output_min, /* int8_t output_min */ + output_max, /* int8_t output_max */ + flags, /* uint32_t flags */ + nullptr, /* xnn_caches_t caches */ + nullptr, /* xnn_weights_cache_t */ + fully_connected_op_out); /* xnn_operator_t* fully_connected_op_out */ +} + +C10_ALWAYS_INLINE +enum xnn_status xnnp_reshape_fully_connected_nc( + xnn_operator_t fully_connected_op, + size_t batch_size, + pthreadpool_t threadpool) { + return xnn_reshape_fully_connected_nc_qs8( + fully_connected_op, /* xnn_operator_t fully_connected_op */ + batch_size, /* size_t batch_size */ + threadpool); /* pthreadpool_t threadpool */ +} + +C10_ALWAYS_INLINE +enum xnn_status xnnp_setup_fully_connected_nc( + xnn_operator_t fully_connected_op, + const int8_t* input, + int8_t* output) { + return xnn_setup_fully_connected_nc_qs8( + fully_connected_op, /* xnn_operator_t fully_connected_op */ + input, /* const int8_t* input */ + output /* int8_t* output */ + ); +} + +} // namespace xnnp_utils +} // namespace native +} // namespace at + +#endif // USE_XNNPACK diff --git a/shared/package-files/01/015e0c11a7025522f37d0bb595d73130ce5e81f4b705841e21466e15ec340a36/blob b/shared/package-files/01/015e0c11a7025522f37d0bb595d73130ce5e81f4b705841e21466e15ec340a36/blob new file mode 100644 index 0000000000000000000000000000000000000000..6f48e0026d2d98cecad0619f24824c73cf049cf1 --- /dev/null +++ b/shared/package-files/01/015e0c11a7025522f37d0bb595d73130ce5e81f4b705841e21466e15ec340a36/blob @@ -0,0 +1,1562 @@ +""" +This is a modified version of the cloudpickle module. +Patches: +- https://github.com/numba/numba/pull/7388 + Avoid resetting class state of dynamic classes. + +Original module docstring: + +Pickler class to extend the standard pickle.Pickler functionality + +The main objective is to make it natural to perform distributed computing on +clusters (such as PySpark, Dask, Ray...) with interactively defined code +(functions, classes, ...) written in notebooks or console. + +In particular this pickler adds the following features: +- serialize interactively-defined or locally-defined functions, classes, + enums, typevars, lambdas and nested functions to compiled byte code; +- deal with some other non-serializable objects in an ad-hoc manner where + applicable. + +This pickler is therefore meant to be used for the communication between short +lived Python processes running the same version of Python and libraries. In +particular, it is not meant to be used for long term storage of Python objects. + +It does not include an unpickler, as standard Python unpickling suffices. + +This module was extracted from the `cloud` package, developed by `PiCloud, Inc. +`_. + +Copyright (c) 2012-now, CloudPickle developers and contributors. +Copyright (c) 2012, Regents of the University of California. +Copyright (c) 2009 `PiCloud, Inc. `_. +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions +are met: + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + * Neither the name of the University of California, Berkeley 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. +""" + +import _collections_abc +from collections import ChainMap, OrderedDict +import abc +import builtins +import copyreg +import dataclasses +import dis +from enum import Enum +import io +import itertools +import logging +import opcode +import pickle +from pickle import _getattribute as _pickle_getattribute +import platform +import struct +import sys +import threading +import types +import typing +import uuid +import warnings +import weakref + +# The following import is required to be imported in the cloudpickle +# namespace to be able to load pickle files generated with older versions of +# cloudpickle. See: tests/test_backward_compat.py +from types import CellType # noqa: F401 + + +# cloudpickle is meant for inter process communication: we expect all +# communicating processes to run the same Python version hence we favor +# communication speed over compatibility: +DEFAULT_PROTOCOL = pickle.HIGHEST_PROTOCOL + +# Names of modules whose resources should be treated as dynamic. +_PICKLE_BY_VALUE_MODULES = set() + +# Track the provenance of reconstructed dynamic classes to make it possible to +# reconstruct instances from the matching singleton class definition when +# appropriate and preserve the usual "isinstance" semantics of Python objects. +_DYNAMIC_CLASS_TRACKER_BY_CLASS = weakref.WeakKeyDictionary() +_DYNAMIC_CLASS_TRACKER_BY_ID = weakref.WeakValueDictionary() +_DYNAMIC_CLASS_TRACKER_LOCK = threading.Lock() +_DYNAMIC_CLASS_TRACKER_REUSING = weakref.WeakSet() + +PYPY = platform.python_implementation() == "PyPy" + +builtin_code_type = None +if PYPY: + # builtin-code objects only exist in pypy + builtin_code_type = type(float.__new__.__code__) + +_extract_code_globals_cache = weakref.WeakKeyDictionary() + + +def _get_or_create_tracker_id(class_def): + with _DYNAMIC_CLASS_TRACKER_LOCK: + class_tracker_id = _DYNAMIC_CLASS_TRACKER_BY_CLASS.get(class_def) + if class_tracker_id is None: + class_tracker_id = uuid.uuid4().hex + _DYNAMIC_CLASS_TRACKER_BY_CLASS[class_def] = class_tracker_id + _DYNAMIC_CLASS_TRACKER_BY_ID[class_tracker_id] = class_def + return class_tracker_id + + +def _lookup_class_or_track(class_tracker_id, class_def): + if class_tracker_id is not None: + with _DYNAMIC_CLASS_TRACKER_LOCK: + orig_class_def = class_def + class_def = _DYNAMIC_CLASS_TRACKER_BY_ID.setdefault( + class_tracker_id, class_def + ) + _DYNAMIC_CLASS_TRACKER_BY_CLASS[class_def] = class_tracker_id + # Check if we are reusing a previous class_def + if orig_class_def is not class_def: + # Remember the class_def is being reused + _DYNAMIC_CLASS_TRACKER_REUSING.add(class_def) + return class_def + + +def register_pickle_by_value(module): + """Register a module to make its functions and classes picklable by value. + + By default, functions and classes that are attributes of an importable + module are to be pickled by reference, that is relying on re-importing + the attribute from the module at load time. + + If `register_pickle_by_value(module)` is called, all its functions and + classes are subsequently to be pickled by value, meaning that they can + be loaded in Python processes where the module is not importable. + + This is especially useful when developing a module in a distributed + execution environment: restarting the client Python process with the new + source code is enough: there is no need to re-install the new version + of the module on all the worker nodes nor to restart the workers. + + Note: this feature is considered experimental. See the cloudpickle + README.md file for more details and limitations. + """ + if not isinstance(module, types.ModuleType): + raise ValueError(f"Input should be a module object, got {str(module)} instead") + # In the future, cloudpickle may need a way to access any module registered + # for pickling by value in order to introspect relative imports inside + # functions pickled by value. (see + # https://github.com/cloudpipe/cloudpickle/pull/417#issuecomment-873684633). + # This access can be ensured by checking that module is present in + # sys.modules at registering time and assuming that it will still be in + # there when accessed during pickling. Another alternative would be to + # store a weakref to the module. Even though cloudpickle does not implement + # this introspection yet, in order to avoid a possible breaking change + # later, we still enforce the presence of module inside sys.modules. + if module.__name__ not in sys.modules: + raise ValueError( + f"{module} was not imported correctly, have you used an " + "`import` statement to access it?" + ) + _PICKLE_BY_VALUE_MODULES.add(module.__name__) + + +def unregister_pickle_by_value(module): + """Unregister that the input module should be pickled by value.""" + if not isinstance(module, types.ModuleType): + raise ValueError(f"Input should be a module object, got {str(module)} instead") + if module.__name__ not in _PICKLE_BY_VALUE_MODULES: + raise ValueError(f"{module} is not registered for pickle by value") + else: + _PICKLE_BY_VALUE_MODULES.remove(module.__name__) + + +def list_registry_pickle_by_value(): + return _PICKLE_BY_VALUE_MODULES.copy() + + +def _is_registered_pickle_by_value(module): + module_name = module.__name__ + if module_name in _PICKLE_BY_VALUE_MODULES: + return True + while True: + parent_name = module_name.rsplit(".", 1)[0] + if parent_name == module_name: + break + if parent_name in _PICKLE_BY_VALUE_MODULES: + return True + module_name = parent_name + return False + + +if sys.version_info >= (3, 14): + def _getattribute(obj, name): + return _pickle_getattribute(obj, name.split('.')) +else: + def _getattribute(obj, name): + return _pickle_getattribute(obj, name)[0] + + +def _whichmodule(obj, name): + """Find the module an object belongs to. + + This function differs from ``pickle.whichmodule`` in two ways: + - it does not mangle the cases where obj's module is __main__ and obj was + not found in any module. + - Errors arising during module introspection are ignored, as those errors + are considered unwanted side effects. + """ + module_name = getattr(obj, "__module__", None) + + if module_name is not None: + return module_name + # Protect the iteration by using a copy of sys.modules against dynamic + # modules that trigger imports of other modules upon calls to getattr or + # other threads importing at the same time. + for module_name, module in sys.modules.copy().items(): + # Some modules such as coverage can inject non-module objects inside + # sys.modules + if ( + module_name == "__main__" + or module_name == "__mp_main__" + or module is None + or not isinstance(module, types.ModuleType) + ): + continue + try: + if _getattribute(module, name) is obj: + return module_name + except Exception: + pass + return None + + +def _should_pickle_by_reference(obj, name=None): + """Test whether an function or a class should be pickled by reference + + Pickling by reference means by that the object (typically a function or a + class) is an attribute of a module that is assumed to be importable in the + target Python environment. Loading will therefore rely on importing the + module and then calling `getattr` on it to access the function or class. + + Pickling by reference is the only option to pickle functions and classes + in the standard library. In cloudpickle the alternative option is to + pickle by value (for instance for interactively or locally defined + functions and classes or for attributes of modules that have been + explicitly registered to be pickled by value. + """ + if isinstance(obj, types.FunctionType) or issubclass(type(obj), type): + module_and_name = _lookup_module_and_qualname(obj, name=name) + if module_and_name is None: + return False + module, name = module_and_name + return not _is_registered_pickle_by_value(module) + + elif isinstance(obj, types.ModuleType): + # We assume that sys.modules is primarily used as a cache mechanism for + # the Python import machinery. Checking if a module has been added in + # is sys.modules therefore a cheap and simple heuristic to tell us + # whether we can assume that a given module could be imported by name + # in another Python process. + if _is_registered_pickle_by_value(obj): + return False + return obj.__name__ in sys.modules + else: + raise TypeError( + "cannot check importability of {} instances".format(type(obj).__name__) + ) + + +def _lookup_module_and_qualname(obj, name=None): + if name is None: + name = getattr(obj, "__qualname__", None) + if name is None: # pragma: no cover + # This used to be needed for Python 2.7 support but is probably not + # needed anymore. However we keep the __name__ introspection in case + # users of cloudpickle rely on this old behavior for unknown reasons. + name = getattr(obj, "__name__", None) + + module_name = _whichmodule(obj, name) + + if module_name is None: + # In this case, obj.__module__ is None AND obj was not found in any + # imported module. obj is thus treated as dynamic. + return None + + if module_name == "__main__": + return None + + # Note: if module_name is in sys.modules, the corresponding module is + # assumed importable at unpickling time. See #357 + module = sys.modules.get(module_name, None) + if module is None: + # The main reason why obj's module would not be imported is that this + # module has been dynamically created, using for example + # types.ModuleType. The other possibility is that module was removed + # from sys.modules after obj was created/imported. But this case is not + # supported, as the standard pickle does not support it either. + return None + + try: + obj2 = _getattribute(module, name) + except AttributeError: + # obj was not found inside the module it points to + return None + if obj2 is not obj: + return None + return module, name + + +def _extract_code_globals(co): + """Find all globals names read or written to by codeblock co.""" + out_names = _extract_code_globals_cache.get(co) + if out_names is None: + # We use a dict with None values instead of a set to get a + # deterministic order and avoid introducing non-deterministic pickle + # bytes as a results. + out_names = {name: None for name in _walk_global_ops(co)} + + # Declaring a function inside another one using the "def ..." syntax + # generates a constant code object corresponding to the one of the + # nested function's As the nested function may itself need global + # variables, we need to introspect its code, extract its globals, (look + # for code object in it's co_consts attribute..) and add the result to + # code_globals + if co.co_consts: + for const in co.co_consts: + if isinstance(const, types.CodeType): + out_names.update(_extract_code_globals(const)) + + _extract_code_globals_cache[co] = out_names + + return out_names + + +def _find_imported_submodules(code, top_level_dependencies): + """Find currently imported submodules used by a function. + + Submodules used by a function need to be detected and referenced for the + function to work correctly at depickling time. Because submodules can be + referenced as attribute of their parent package (``package.submodule``), we + need a special introspection technique that does not rely on GLOBAL-related + opcodes to find references of them in a code object. + + Example: + ``` + import concurrent.futures + import cloudpickle + def func(): + x = concurrent.futures.ThreadPoolExecutor + if __name__ == '__main__': + cloudpickle.dumps(func) + ``` + The globals extracted by cloudpickle in the function's state include the + concurrent package, but not its submodule (here, concurrent.futures), which + is the module used by func. Find_imported_submodules will detect the usage + of concurrent.futures. Saving this module alongside with func will ensure + that calling func once depickled does not fail due to concurrent.futures + not being imported + """ + + subimports = [] + # check if any known dependency is an imported package + for x in top_level_dependencies: + if ( + isinstance(x, types.ModuleType) + and hasattr(x, "__package__") + and x.__package__ + ): + # check if the package has any currently loaded sub-imports + prefix = x.__name__ + "." + # A concurrent thread could mutate sys.modules, + # make sure we iterate over a copy to avoid exceptions + for name in list(sys.modules): + # Older versions of pytest will add a "None" module to + # sys.modules. + if name is not None and name.startswith(prefix): + # check whether the function can address the sub-module + tokens = set(name[len(prefix) :].split(".")) + if not tokens - set(code.co_names): + subimports.append(sys.modules[name]) + return subimports + + +# relevant opcodes +STORE_GLOBAL = opcode.opmap["STORE_GLOBAL"] +DELETE_GLOBAL = opcode.opmap["DELETE_GLOBAL"] +LOAD_GLOBAL = opcode.opmap["LOAD_GLOBAL"] +GLOBAL_OPS = (STORE_GLOBAL, DELETE_GLOBAL, LOAD_GLOBAL) +HAVE_ARGUMENT = dis.HAVE_ARGUMENT +EXTENDED_ARG = dis.EXTENDED_ARG + + +_BUILTIN_TYPE_NAMES = {} +for k, v in types.__dict__.items(): + if type(v) is type: + _BUILTIN_TYPE_NAMES[v] = k + + +def _builtin_type(name): + if name == "ClassType": # pragma: no cover + # Backward compat to load pickle files generated with cloudpickle + # < 1.3 even if loading pickle files from older versions is not + # officially supported. + return type + return getattr(types, name) + + +def _walk_global_ops(code): + """Yield referenced name for global-referencing instructions in code.""" + for instr in dis.get_instructions(code): + op = instr.opcode + if op in GLOBAL_OPS: + yield instr.argval + + +def _extract_class_dict(cls): + """Retrieve a copy of the dict of a class without the inherited method.""" + # Hack to circumvent non-predictable memoization caused by string interning. + # See the inline comment in _class_setstate for details. + clsdict = {"".join(k): cls.__dict__[k] for k in sorted(cls.__dict__)} + + if len(cls.__bases__) == 1: + inherited_dict = cls.__bases__[0].__dict__ + else: + inherited_dict = {} + for base in reversed(cls.__bases__): + inherited_dict.update(base.__dict__) + to_remove = [] + for name, value in clsdict.items(): + try: + base_value = inherited_dict[name] + if value is base_value: + to_remove.append(name) + except KeyError: + pass + for name in to_remove: + clsdict.pop(name) + return clsdict + + +def is_tornado_coroutine(func): + """Return whether `func` is a Tornado coroutine function. + + Running coroutines are not supported. + """ + warnings.warn( + "is_tornado_coroutine is deprecated in cloudpickle 3.0 and will be " + "removed in cloudpickle 4.0. Use tornado.gen.is_coroutine_function " + "directly instead.", + category=DeprecationWarning, + ) + if "tornado.gen" not in sys.modules: + return False + gen = sys.modules["tornado.gen"] + if not hasattr(gen, "is_coroutine_function"): + # Tornado version is too old + return False + return gen.is_coroutine_function(func) + + +def subimport(name): + # We cannot do simply: `return __import__(name)`: Indeed, if ``name`` is + # the name of a submodule, __import__ will return the top-level root module + # of this submodule. For instance, __import__('os.path') returns the `os` + # module. + __import__(name) + return sys.modules[name] + + +def dynamic_subimport(name, vars): + mod = types.ModuleType(name) + mod.__dict__.update(vars) + mod.__dict__["__builtins__"] = builtins.__dict__ + return mod + + +def _get_cell_contents(cell): + try: + return cell.cell_contents + except ValueError: + # Handle empty cells explicitly with a sentinel value. + return _empty_cell_value + + +def instance(cls): + """Create a new instance of a class. + + Parameters + ---------- + cls : type + The class to create an instance of. + + Returns + ------- + instance : cls + A new instance of ``cls``. + """ + return cls() + + +@instance +class _empty_cell_value: + """Sentinel for empty closures.""" + + @classmethod + def __reduce__(cls): + return cls.__name__ + + +def _make_function(code, globals, name, argdefs, closure): + # Setting __builtins__ in globals is needed for nogil CPython. + globals["__builtins__"] = __builtins__ + return types.FunctionType(code, globals, name, argdefs, closure) + + +def _make_empty_cell(): + if False: + # trick the compiler into creating an empty cell in our lambda + cell = None + raise AssertionError("this route should not be executed") + + return (lambda: cell).__closure__[0] + + +def _make_cell(value=_empty_cell_value): + cell = _make_empty_cell() + if value is not _empty_cell_value: + cell.cell_contents = value + return cell + + +def _make_skeleton_class( + type_constructor, name, bases, type_kwargs, class_tracker_id, extra +): + """Build dynamic class with an empty __dict__ to be filled once memoized + + If class_tracker_id is not None, try to lookup an existing class definition + matching that id. If none is found, track a newly reconstructed class + definition under that id so that other instances stemming from the same + class id will also reuse this class definition. + + The "extra" variable is meant to be a dict (or None) that can be used for + forward compatibility shall the need arise. + """ + # We need to intern the keys of the type_kwargs dict to avoid having + # different pickles for the same dynamic class depending on whether it was + # dynamically created or reconstructed from a pickled stream. + type_kwargs = {sys.intern(k): v for k, v in type_kwargs.items()} + + skeleton_class = types.new_class( + name, bases, {"metaclass": type_constructor}, lambda ns: ns.update(type_kwargs) + ) + + return _lookup_class_or_track(class_tracker_id, skeleton_class) + + +def _make_skeleton_enum( + bases, name, qualname, members, module, class_tracker_id, extra +): + """Build dynamic enum with an empty __dict__ to be filled once memoized + + The creation of the enum class is inspired by the code of + EnumMeta._create_. + + If class_tracker_id is not None, try to lookup an existing enum definition + matching that id. If none is found, track a newly reconstructed enum + definition under that id so that other instances stemming from the same + class id will also reuse this enum definition. + + The "extra" variable is meant to be a dict (or None) that can be used for + forward compatibility shall the need arise. + """ + # enums always inherit from their base Enum class at the last position in + # the list of base classes: + enum_base = bases[-1] + metacls = enum_base.__class__ + classdict = metacls.__prepare__(name, bases) + + for member_name, member_value in members.items(): + classdict[member_name] = member_value + enum_class = metacls.__new__(metacls, name, bases, classdict) + enum_class.__module__ = module + enum_class.__qualname__ = qualname + + return _lookup_class_or_track(class_tracker_id, enum_class) + + +def _make_typevar(name, bound, constraints, covariant, contravariant, class_tracker_id): + tv = typing.TypeVar( + name, + *constraints, + bound=bound, + covariant=covariant, + contravariant=contravariant, + ) + return _lookup_class_or_track(class_tracker_id, tv) + + +def _decompose_typevar(obj): + return ( + obj.__name__, + obj.__bound__, + obj.__constraints__, + obj.__covariant__, + obj.__contravariant__, + _get_or_create_tracker_id(obj), + ) + + +def _typevar_reduce(obj): + # TypeVar instances require the module information hence why we + # are not using the _should_pickle_by_reference directly + module_and_name = _lookup_module_and_qualname(obj, name=obj.__name__) + + if module_and_name is None: + return (_make_typevar, _decompose_typevar(obj)) + elif _is_registered_pickle_by_value(module_and_name[0]): + return (_make_typevar, _decompose_typevar(obj)) + + return (getattr, module_and_name) + + +def _get_bases(typ): + if "__orig_bases__" in getattr(typ, "__dict__", {}): + # For generic types (see PEP 560) + # Note that simply checking `hasattr(typ, '__orig_bases__')` is not + # correct. Subclasses of a fully-parameterized generic class does not + # have `__orig_bases__` defined, but `hasattr(typ, '__orig_bases__')` + # will return True because it's defined in the base class. + bases_attr = "__orig_bases__" + else: + # For regular class objects + bases_attr = "__bases__" + return getattr(typ, bases_attr) + + +def _make_dict_keys(obj, is_ordered=False): + if is_ordered: + return OrderedDict.fromkeys(obj).keys() + else: + return dict.fromkeys(obj).keys() + + +def _make_dict_values(obj, is_ordered=False): + if is_ordered: + return OrderedDict((i, _) for i, _ in enumerate(obj)).values() + else: + return {i: _ for i, _ in enumerate(obj)}.values() + + +def _make_dict_items(obj, is_ordered=False): + if is_ordered: + return OrderedDict(obj).items() + else: + return obj.items() + + +# COLLECTION OF OBJECTS __getnewargs__-LIKE METHODS +# ------------------------------------------------- + + +def _class_getnewargs(obj): + type_kwargs = {} + if "__module__" in obj.__dict__: + type_kwargs["__module__"] = obj.__module__ + + __dict__ = obj.__dict__.get("__dict__", None) + if isinstance(__dict__, property): + type_kwargs["__dict__"] = __dict__ + + return ( + type(obj), + obj.__name__, + _get_bases(obj), + type_kwargs, + _get_or_create_tracker_id(obj), + None, + ) + + +def _enum_getnewargs(obj): + members = {e.name: e.value for e in obj} + return ( + obj.__bases__, + obj.__name__, + obj.__qualname__, + members, + obj.__module__, + _get_or_create_tracker_id(obj), + None, + ) + + +# COLLECTION OF OBJECTS RECONSTRUCTORS +# ------------------------------------ +def _file_reconstructor(retval): + return retval + + +# COLLECTION OF OBJECTS STATE GETTERS +# ----------------------------------- + + +def _function_getstate(func): + # - Put func's dynamic attributes (stored in func.__dict__) in state. These + # attributes will be restored at unpickling time using + # f.__dict__.update(state) + # - Put func's members into slotstate. Such attributes will be restored at + # unpickling time by iterating over slotstate and calling setattr(func, + # slotname, slotvalue) + slotstate = { + # Hack to circumvent non-predictable memoization caused by string interning. + # See the inline comment in _class_setstate for details. + "__name__": "".join(func.__name__), + "__qualname__": "".join(func.__qualname__), + "__annotations__": func.__annotations__, + "__kwdefaults__": func.__kwdefaults__, + "__defaults__": func.__defaults__, + "__module__": func.__module__, + "__doc__": func.__doc__, + "__closure__": func.__closure__, + } + + f_globals_ref = _extract_code_globals(func.__code__) + f_globals = {k: func.__globals__[k] for k in f_globals_ref if k in func.__globals__} + + if func.__closure__ is not None: + closure_values = list(map(_get_cell_contents, func.__closure__)) + else: + closure_values = () + + # Extract currently-imported submodules used by func. Storing these modules + # in a smoke _cloudpickle_subimports attribute of the object's state will + # trigger the side effect of importing these modules at unpickling time + # (which is necessary for func to work correctly once depickled) + slotstate["_cloudpickle_submodules"] = _find_imported_submodules( + func.__code__, itertools.chain(f_globals.values(), closure_values) + ) + slotstate["__globals__"] = f_globals + + # Hack to circumvent non-predictable memoization caused by string interning. + # See the inline comment in _class_setstate for details. + state = {"".join(k): v for k, v in func.__dict__.items()} + return state, slotstate + + +def _class_getstate(obj): + clsdict = _extract_class_dict(obj) + clsdict.pop("__weakref__", None) + + if issubclass(type(obj), abc.ABCMeta): + # If obj is an instance of an ABCMeta subclass, don't pickle the + # cache/negative caches populated during isinstance/issubclass + # checks, but pickle the list of registered subclasses of obj. + clsdict.pop("_abc_cache", None) + clsdict.pop("_abc_negative_cache", None) + clsdict.pop("_abc_negative_cache_version", None) + registry = clsdict.pop("_abc_registry", None) + if registry is None: + # The abc caches and registered subclasses of a + # class are bundled into the single _abc_impl attribute + clsdict.pop("_abc_impl", None) + (registry, _, _, _) = abc._get_dump(obj) + + clsdict["_abc_impl"] = [subclass_weakref() for subclass_weakref in registry] + else: + # In the above if clause, registry is a set of weakrefs -- in + # this case, registry is a WeakSet + clsdict["_abc_impl"] = [type_ for type_ in registry] + + if "__slots__" in clsdict: + # pickle string length optimization: member descriptors of obj are + # created automatically from obj's __slots__ attribute, no need to + # save them in obj's state + if isinstance(obj.__slots__, str): + clsdict.pop(obj.__slots__) + else: + for k in obj.__slots__: + clsdict.pop(k, None) + + clsdict.pop("__dict__", None) # unpicklable property object + + return (clsdict, {}) + + +def _enum_getstate(obj): + clsdict, slotstate = _class_getstate(obj) + + members = {e.name: e.value for e in obj} + # Cleanup the clsdict that will be passed to _make_skeleton_enum: + # Those attributes are already handled by the metaclass. + for attrname in [ + "_generate_next_value_", + "_member_names_", + "_member_map_", + "_member_type_", + "_value2member_map_", + ]: + clsdict.pop(attrname, None) + for member in members: + clsdict.pop(member) + # Special handling of Enum subclasses + return clsdict, slotstate + + +# COLLECTIONS OF OBJECTS REDUCERS +# ------------------------------- +# A reducer is a function taking a single argument (obj), and that returns a +# tuple with all the necessary data to re-construct obj. Apart from a few +# exceptions (list, dict, bytes, int, etc.), a reducer is necessary to +# correctly pickle an object. +# While many built-in objects (Exceptions objects, instances of the "object" +# class, etc), are shipped with their own built-in reducer (invoked using +# obj.__reduce__), some do not. The following methods were created to "fill +# these holes". + + +def _code_reduce(obj): + """code object reducer.""" + # If you are not sure about the order of arguments, take a look at help + # of the specific type from types, for example: + # >>> from types import CodeType + # >>> help(CodeType) + + # Hack to circumvent non-predictable memoization caused by string interning. + # See the inline comment in _class_setstate for details. + co_name = "".join(obj.co_name) + + # Create shallow copies of these tuple to make cloudpickle payload deterministic. + # When creating a code object during load, copies of these four tuples are + # created, while in the main process, these tuples can be shared. + # By always creating copies, we make sure the resulting payload is deterministic. + co_names = tuple(name for name in obj.co_names) + co_varnames = tuple(name for name in obj.co_varnames) + co_freevars = tuple(name for name in obj.co_freevars) + co_cellvars = tuple(name for name in obj.co_cellvars) + if hasattr(obj, "co_exceptiontable"): + # Python 3.11 and later: there are some new attributes + # related to the enhanced exceptions. + args = ( + obj.co_argcount, + obj.co_posonlyargcount, + obj.co_kwonlyargcount, + obj.co_nlocals, + obj.co_stacksize, + obj.co_flags, + obj.co_code, + obj.co_consts, + co_names, + co_varnames, + obj.co_filename, + co_name, + obj.co_qualname, + obj.co_firstlineno, + obj.co_linetable, + obj.co_exceptiontable, + co_freevars, + co_cellvars, + ) + elif hasattr(obj, "co_linetable"): + # Python 3.10 and later: obj.co_lnotab is deprecated and constructor + # expects obj.co_linetable instead. + args = ( + obj.co_argcount, + obj.co_posonlyargcount, + obj.co_kwonlyargcount, + obj.co_nlocals, + obj.co_stacksize, + obj.co_flags, + obj.co_code, + obj.co_consts, + co_names, + co_varnames, + obj.co_filename, + co_name, + obj.co_firstlineno, + obj.co_linetable, + co_freevars, + co_cellvars, + ) + elif hasattr(obj, "co_nmeta"): # pragma: no cover + # "nogil" Python: modified attributes from 3.9 + args = ( + obj.co_argcount, + obj.co_posonlyargcount, + obj.co_kwonlyargcount, + obj.co_nlocals, + obj.co_framesize, + obj.co_ndefaultargs, + obj.co_nmeta, + obj.co_flags, + obj.co_code, + obj.co_consts, + co_varnames, + obj.co_filename, + co_name, + obj.co_firstlineno, + obj.co_lnotab, + obj.co_exc_handlers, + obj.co_jump_table, + co_freevars, + co_cellvars, + obj.co_free2reg, + obj.co_cell2reg, + ) + else: + # Backward compat for 3.8 and 3.9 + args = ( + obj.co_argcount, + obj.co_posonlyargcount, + obj.co_kwonlyargcount, + obj.co_nlocals, + obj.co_stacksize, + obj.co_flags, + obj.co_code, + obj.co_consts, + co_names, + co_varnames, + obj.co_filename, + co_name, + obj.co_firstlineno, + obj.co_lnotab, + co_freevars, + co_cellvars, + ) + return types.CodeType, args + + +def _cell_reduce(obj): + """Cell (containing values of a function's free variables) reducer.""" + try: + obj.cell_contents + except ValueError: # cell is empty + return _make_empty_cell, () + else: + return _make_cell, (obj.cell_contents,) + + +def _classmethod_reduce(obj): + orig_func = obj.__func__ + return type(obj), (orig_func,) + + +def _file_reduce(obj): + """Save a file.""" + import io + + if not hasattr(obj, "name") or not hasattr(obj, "mode"): + raise pickle.PicklingError( + "Cannot pickle files that do not map to an actual file" + ) + if obj is sys.stdout: + return getattr, (sys, "stdout") + if obj is sys.stderr: + return getattr, (sys, "stderr") + if obj is sys.stdin: + raise pickle.PicklingError("Cannot pickle standard input") + if obj.closed: + raise pickle.PicklingError("Cannot pickle closed files") + if hasattr(obj, "isatty") and obj.isatty(): + raise pickle.PicklingError("Cannot pickle files that map to tty objects") + if "r" not in obj.mode and "+" not in obj.mode: + raise pickle.PicklingError( + "Cannot pickle files that are not opened for reading: %s" % obj.mode + ) + + name = obj.name + + retval = io.StringIO() + + try: + # Read the whole file + curloc = obj.tell() + obj.seek(0) + contents = obj.read() + obj.seek(curloc) + except OSError as e: + raise pickle.PicklingError( + "Cannot pickle file %s as it cannot be read" % name + ) from e + retval.write(contents) + retval.seek(curloc) + + retval.name = name + return _file_reconstructor, (retval,) + + +def _getset_descriptor_reduce(obj): + return getattr, (obj.__objclass__, obj.__name__) + + +def _mappingproxy_reduce(obj): + return types.MappingProxyType, (dict(obj),) + + +def _memoryview_reduce(obj): + return bytes, (obj.tobytes(),) + + +def _module_reduce(obj): + if _should_pickle_by_reference(obj): + return subimport, (obj.__name__,) + else: + # Some external libraries can populate the "__builtins__" entry of a + # module's `__dict__` with unpicklable objects (see #316). For that + # reason, we do not attempt to pickle the "__builtins__" entry, and + # restore a default value for it at unpickling time. + state = obj.__dict__.copy() + state.pop("__builtins__", None) + return dynamic_subimport, (obj.__name__, state) + + +def _method_reduce(obj): + return (types.MethodType, (obj.__func__, obj.__self__)) + + +def _logger_reduce(obj): + return logging.getLogger, (obj.name,) + + +def _root_logger_reduce(obj): + return logging.getLogger, () + + +def _property_reduce(obj): + return property, (obj.fget, obj.fset, obj.fdel, obj.__doc__) + + +def _weakset_reduce(obj): + return weakref.WeakSet, (list(obj),) + + +def _dynamic_class_reduce(obj): + """Save a class that can't be referenced as a module attribute. + + This method is used to serialize classes that are defined inside + functions, or that otherwise can't be serialized as attribute lookups + from importable modules. + """ + if Enum is not None and issubclass(obj, Enum): + return ( + _make_skeleton_enum, + _enum_getnewargs(obj), + _enum_getstate(obj), + None, + None, + _class_setstate, + ) + else: + return ( + _make_skeleton_class, + _class_getnewargs(obj), + _class_getstate(obj), + None, + None, + _class_setstate, + ) + + +def _class_reduce(obj): + """Select the reducer depending on the dynamic nature of the class obj.""" + if obj is type(None): # noqa + return type, (None,) + elif obj is type(Ellipsis): + return type, (Ellipsis,) + elif obj is type(NotImplemented): + return type, (NotImplemented,) + elif obj in _BUILTIN_TYPE_NAMES: + return _builtin_type, (_BUILTIN_TYPE_NAMES[obj],) + elif not _should_pickle_by_reference(obj): + return _dynamic_class_reduce(obj) + return NotImplemented + + +def _dict_keys_reduce(obj): + # Safer not to ship the full dict as sending the rest might + # be unintended and could potentially cause leaking of + # sensitive information + return _make_dict_keys, (list(obj),) + + +def _dict_values_reduce(obj): + # Safer not to ship the full dict as sending the rest might + # be unintended and could potentially cause leaking of + # sensitive information + return _make_dict_values, (list(obj),) + + +def _dict_items_reduce(obj): + return _make_dict_items, (dict(obj),) + + +def _odict_keys_reduce(obj): + # Safer not to ship the full dict as sending the rest might + # be unintended and could potentially cause leaking of + # sensitive information + return _make_dict_keys, (list(obj), True) + + +def _odict_values_reduce(obj): + # Safer not to ship the full dict as sending the rest might + # be unintended and could potentially cause leaking of + # sensitive information + return _make_dict_values, (list(obj), True) + + +def _odict_items_reduce(obj): + return _make_dict_items, (dict(obj), True) + + +def _dataclass_field_base_reduce(obj): + return _get_dataclass_field_type_sentinel, (obj.name,) + + +# COLLECTIONS OF OBJECTS STATE SETTERS +# ------------------------------------ +# state setters are called at unpickling time, once the object is created and +# it has to be updated to how it was at unpickling time. + + +def _function_setstate(obj, state): + """Update the state of a dynamic function. + + As __closure__ and __globals__ are readonly attributes of a function, we + cannot rely on the native setstate routine of pickle.load_build, that calls + setattr on items of the slotstate. Instead, we have to modify them inplace. + """ + state, slotstate = state + obj.__dict__.update(state) + + obj_globals = slotstate.pop("__globals__") + obj_closure = slotstate.pop("__closure__") + # _cloudpickle_subimports is a set of submodules that must be loaded for + # the pickled function to work correctly at unpickling time. Now that these + # submodules are depickled (hence imported), they can be removed from the + # object's state (the object state only served as a reference holder to + # these submodules) + slotstate.pop("_cloudpickle_submodules") + + obj.__globals__.update(obj_globals) + obj.__globals__["__builtins__"] = __builtins__ + + if obj_closure is not None: + for i, cell in enumerate(obj_closure): + try: + value = cell.cell_contents + except ValueError: # cell is empty + continue + obj.__closure__[i].cell_contents = value + + for k, v in slotstate.items(): + setattr(obj, k, v) + + +def _class_setstate(obj, state): + # Check if class is being reused and needs bypass setstate logic. + if obj in _DYNAMIC_CLASS_TRACKER_REUSING: + return obj + state, slotstate = state + registry = None + for attrname, attr in state.items(): + if attrname == "_abc_impl": + registry = attr + else: + # Note: setting attribute names on a class automatically triggers their + # interning in CPython: + # https://github.com/python/cpython/blob/v3.12.0/Objects/object.c#L957 + # + # This means that to get deterministic pickling for a dynamic class that + # was initially defined in a different Python process, the pickler + # needs to ensure that dynamic class and function attribute names are + # systematically copied into a non-interned version to avoid + # unpredictable pickle payloads. + # + # Indeed the Pickler's memoizer relies on physical object identity to break + # cycles in the reference graph of the object being serialized. + setattr(obj, attrname, attr) + + if sys.version_info >= (3, 13) and "__firstlineno__" in state: + # Set the Python 3.13+ only __firstlineno__ attribute one more time, as it + # will be automatically deleted by the `setattr(obj, attrname, attr)` call + # above when `attrname` is "__firstlineno__". We assume that preserving this + # information might be important for some users and that it not stale in the + # context of cloudpickle usage, hence legitimate to propagate. Furthermore it + # is necessary to do so to keep deterministic chained pickling as tested in + # test_deterministic_str_interning_for_chained_dynamic_class_pickling. + obj.__firstlineno__ = state["__firstlineno__"] + + if registry is not None: + for subclass in registry: + obj.register(subclass) + + return obj + + +# COLLECTION OF DATACLASS UTILITIES +# --------------------------------- +# There are some internal sentinel values whose identity must be preserved when +# unpickling dataclass fields. Each sentinel value has a unique name that we can +# use to retrieve its identity at unpickling time. + + +_DATACLASSE_FIELD_TYPE_SENTINELS = { + dataclasses._FIELD.name: dataclasses._FIELD, + dataclasses._FIELD_CLASSVAR.name: dataclasses._FIELD_CLASSVAR, + dataclasses._FIELD_INITVAR.name: dataclasses._FIELD_INITVAR, +} + + +def _get_dataclass_field_type_sentinel(name): + return _DATACLASSE_FIELD_TYPE_SENTINELS[name] + + +class Pickler(pickle.Pickler): + # set of reducers defined and used by cloudpickle (private) + _dispatch_table = {} + _dispatch_table[classmethod] = _classmethod_reduce + _dispatch_table[io.TextIOWrapper] = _file_reduce + _dispatch_table[logging.Logger] = _logger_reduce + _dispatch_table[logging.RootLogger] = _root_logger_reduce + _dispatch_table[memoryview] = _memoryview_reduce + _dispatch_table[property] = _property_reduce + _dispatch_table[staticmethod] = _classmethod_reduce + _dispatch_table[CellType] = _cell_reduce + _dispatch_table[types.CodeType] = _code_reduce + _dispatch_table[types.GetSetDescriptorType] = _getset_descriptor_reduce + _dispatch_table[types.ModuleType] = _module_reduce + _dispatch_table[types.MethodType] = _method_reduce + _dispatch_table[types.MappingProxyType] = _mappingproxy_reduce + _dispatch_table[weakref.WeakSet] = _weakset_reduce + _dispatch_table[typing.TypeVar] = _typevar_reduce + _dispatch_table[_collections_abc.dict_keys] = _dict_keys_reduce + _dispatch_table[_collections_abc.dict_values] = _dict_values_reduce + _dispatch_table[_collections_abc.dict_items] = _dict_items_reduce + _dispatch_table[type(OrderedDict().keys())] = _odict_keys_reduce + _dispatch_table[type(OrderedDict().values())] = _odict_values_reduce + _dispatch_table[type(OrderedDict().items())] = _odict_items_reduce + _dispatch_table[abc.abstractmethod] = _classmethod_reduce + _dispatch_table[abc.abstractclassmethod] = _classmethod_reduce + _dispatch_table[abc.abstractstaticmethod] = _classmethod_reduce + _dispatch_table[abc.abstractproperty] = _property_reduce + _dispatch_table[dataclasses._FIELD_BASE] = _dataclass_field_base_reduce + + dispatch_table = ChainMap(_dispatch_table, copyreg.dispatch_table) + + # function reducers are defined as instance methods of cloudpickle.Pickler + # objects, as they rely on a cloudpickle.Pickler attribute (globals_ref) + def _dynamic_function_reduce(self, func): + """Reduce a function that is not pickleable via attribute lookup.""" + newargs = self._function_getnewargs(func) + state = _function_getstate(func) + return (_make_function, newargs, state, None, None, _function_setstate) + + def _function_reduce(self, obj): + """Reducer for function objects. + + If obj is a top-level attribute of a file-backed module, this reducer + returns NotImplemented, making the cloudpickle.Pickler fall back to + traditional pickle.Pickler routines to save obj. Otherwise, it reduces + obj using a custom cloudpickle reducer designed specifically to handle + dynamic functions. + """ + if _should_pickle_by_reference(obj): + return NotImplemented + else: + return self._dynamic_function_reduce(obj) + + def _function_getnewargs(self, func): + code = func.__code__ + + # base_globals represents the future global namespace of func at + # unpickling time. Looking it up and storing it in + # cloudpickle.Pickler.globals_ref allow functions sharing the same + # globals at pickling time to also share them once unpickled, at one + # condition: since globals_ref is an attribute of a cloudpickle.Pickler + # instance, and that a new cloudpickle.Pickler is created each time + # cloudpickle.dump or cloudpickle.dumps is called, functions also need + # to be saved within the same invocation of + # cloudpickle.dump/cloudpickle.dumps (for example: + # cloudpickle.dumps([f1, f2])). There is no such limitation when using + # cloudpickle.Pickler.dump, as long as the multiple invocations are + # bound to the same cloudpickle.Pickler instance. + base_globals = self.globals_ref.setdefault(id(func.__globals__), {}) + + if base_globals == {}: + # Add module attributes used to resolve relative imports + # instructions inside func. + for k in ["__package__", "__name__", "__path__", "__file__"]: + if k in func.__globals__: + base_globals[k] = func.__globals__[k] + + # Do not bind the free variables before the function is created to + # avoid infinite recursion. + if func.__closure__ is None: + closure = None + else: + closure = tuple(_make_empty_cell() for _ in range(len(code.co_freevars))) + + return code, base_globals, None, None, closure + + def dump(self, obj): + try: + return super().dump(obj) + except RuntimeError as e: + if len(e.args) > 0 and "recursion" in e.args[0]: + msg = "Could not pickle object as excessively deep recursion required." + raise pickle.PicklingError(msg) from e + else: + raise + + def __init__(self, file, protocol=None, buffer_callback=None): + if protocol is None: + protocol = DEFAULT_PROTOCOL + super().__init__(file, protocol=protocol, buffer_callback=buffer_callback) + # map functions __globals__ attribute ids, to ensure that functions + # sharing the same global namespace at pickling time also share + # their global namespace at unpickling time. + self.globals_ref = {} + self.proto = int(protocol) + + if not PYPY: + # pickle.Pickler is the C implementation of the CPython pickler and + # therefore we rely on reduce_override method to customize the pickler + # behavior. + + # `cloudpickle.Pickler.dispatch` is only left for backward + # compatibility - note that when using protocol 5, + # `cloudpickle.Pickler.dispatch` is not an extension of + # `pickle._Pickler.dispatch` dictionary, because `cloudpickle.Pickler` + # subclasses the C-implemented `pickle.Pickler`, which does not expose + # a `dispatch` attribute. Earlier versions of `cloudpickle.Pickler` + # used `cloudpickle.Pickler.dispatch` as a class-level attribute + # storing all reducers implemented by cloudpickle, but the attribute + # name was not a great choice given because it would collide with a + # similarly named attribute in the pure-Python `pickle._Pickler` + # implementation in the standard library. + dispatch = dispatch_table + + # Implementation of the reducer_override callback, in order to + # efficiently serialize dynamic functions and classes by subclassing + # the C-implemented `pickle.Pickler`. + # TODO: decorrelate reducer_override (which is tied to CPython's + # implementation - would it make sense to backport it to pypy? - and + # pickle's protocol 5 which is implementation agnostic. Currently, the + # availability of both notions coincide on CPython's pickle, but it may + # not be the case anymore when pypy implements protocol 5. + + def reducer_override(self, obj): + """Type-agnostic reducing callback for function and classes. + + For performance reasons, subclasses of the C `pickle.Pickler` class + cannot register custom reducers for functions and classes in the + dispatch_table attribute. Reducers for such types must instead + implemented via the special `reducer_override` method. + + Note that this method will be called for any object except a few + builtin-types (int, lists, dicts etc.), which differs from reducers + in the Pickler's dispatch_table, each of them being invoked for + objects of a specific type only. + + This property comes in handy for classes: although most classes are + instances of the ``type`` metaclass, some of them can be instances + of other custom metaclasses (such as enum.EnumMeta for example). In + particular, the metaclass will likely not be known in advance, and + thus cannot be special-cased using an entry in the dispatch_table. + reducer_override, among other things, allows us to register a + reducer that will be called for any class, independently of its + type. + + Notes: + + * reducer_override has the priority over dispatch_table-registered + reducers. + * reducer_override can be used to fix other limitations of + cloudpickle for other types that suffered from type-specific + reducers, such as Exceptions. See + https://github.com/cloudpipe/cloudpickle/issues/248 + """ + t = type(obj) + try: + is_anyclass = issubclass(t, type) + except TypeError: # t is not a class (old Boost; see SF #502085) + is_anyclass = False + + if is_anyclass: + return _class_reduce(obj) + elif isinstance(obj, types.FunctionType): + return self._function_reduce(obj) + else: + # fallback to save_global, including the Pickler's + # dispatch_table + return NotImplemented + + else: + # When reducer_override is not available, hack the pure-Python + # Pickler's types.FunctionType and type savers. Note: the type saver + # must override Pickler.save_global, because pickle.py contains a + # hard-coded call to save_global when pickling meta-classes. + dispatch = pickle.Pickler.dispatch.copy() + + def _save_reduce_pickle5( + self, + func, + args, + state=None, + listitems=None, + dictitems=None, + state_setter=None, + obj=None, + ): + save = self.save + write = self.write + self.save_reduce( + func, + args, + state=None, + listitems=listitems, + dictitems=dictitems, + obj=obj, + ) + # backport of the Python 3.8 state_setter pickle operations + save(state_setter) + save(obj) # simple BINGET opcode as obj is already memoized. + save(state) + write(pickle.TUPLE2) + # Trigger a state_setter(obj, state) function call. + write(pickle.REDUCE) + # The purpose of state_setter is to carry-out an + # inplace modification of obj. We do not care about what the + # method might return, so its output is eventually removed from + # the stack. + write(pickle.POP) + + def save_global(self, obj, name=None, pack=struct.pack): + """Main dispatch method. + + The name of this method is somewhat misleading: all types get + dispatched here. + """ + if obj is type(None): # noqa + return self.save_reduce(type, (None,), obj=obj) + elif obj is type(Ellipsis): + return self.save_reduce(type, (Ellipsis,), obj=obj) + elif obj is type(NotImplemented): + return self.save_reduce(type, (NotImplemented,), obj=obj) + elif obj in _BUILTIN_TYPE_NAMES: + return self.save_reduce( + _builtin_type, (_BUILTIN_TYPE_NAMES[obj],), obj=obj + ) + + if name is not None: + super().save_global(obj, name=name) + elif not _should_pickle_by_reference(obj, name=name): + self._save_reduce_pickle5(*_dynamic_class_reduce(obj), obj=obj) + else: + super().save_global(obj, name=name) + + dispatch[type] = save_global + + def save_function(self, obj, name=None): + """Registered with the dispatch to handle all function types. + + Determines what kind of function obj is (e.g. lambda, defined at + interactive prompt, etc) and handles the pickling appropriately. + """ + if _should_pickle_by_reference(obj, name=name): + return super().save_global(obj, name=name) + elif PYPY and isinstance(obj.__code__, builtin_code_type): + return self.save_pypy_builtin_func(obj) + else: + return self._save_reduce_pickle5( + *self._dynamic_function_reduce(obj), obj=obj + ) + + def save_pypy_builtin_func(self, obj): + """Save pypy equivalent of builtin functions. + + PyPy does not have the concept of builtin-functions. Instead, + builtin-functions are simple function instances, but with a + builtin-code attribute. + Most of the time, builtin functions should be pickled by attribute. + But PyPy has flaky support for __qualname__, so some builtin + functions such as float.__new__ will be classified as dynamic. For + this reason only, we created this special routine. Because + builtin-functions are not expected to have closure or globals, + there is no additional hack (compared the one already implemented + in pickle) to protect ourselves from reference cycles. A simple + (reconstructor, newargs, obj.__dict__) tuple is save_reduced. Note + also that PyPy improved their support for __qualname__ in v3.6, so + this routing should be removed when cloudpickle supports only PyPy + 3.6 and later. + """ + rv = ( + types.FunctionType, + (obj.__code__, {}, obj.__name__, obj.__defaults__, obj.__closure__), + obj.__dict__, + ) + self.save_reduce(*rv, obj=obj) + + dispatch[types.FunctionType] = save_function + + +# Shorthands similar to pickle.dump/pickle.dumps + + +def dump(obj, file, protocol=None, buffer_callback=None): + """Serialize obj as bytes streamed into file + + protocol defaults to cloudpickle.DEFAULT_PROTOCOL which is an alias to + pickle.HIGHEST_PROTOCOL. This setting favors maximum communication + speed between processes running the same Python version. + + Set protocol=pickle.DEFAULT_PROTOCOL instead if you need to ensure + compatibility with older versions of Python (although this is not always + guaranteed to work because cloudpickle relies on some internal + implementation details that can change from one Python version to the + next). + """ + Pickler(file, protocol=protocol, buffer_callback=buffer_callback).dump(obj) + + +def dumps(obj, protocol=None, buffer_callback=None): + """Serialize obj as a string of bytes allocated in memory + + protocol defaults to cloudpickle.DEFAULT_PROTOCOL which is an alias to + pickle.HIGHEST_PROTOCOL. This setting favors maximum communication + speed between processes running the same Python version. + + Set protocol=pickle.DEFAULT_PROTOCOL instead if you need to ensure + compatibility with older versions of Python (although this is not always + guaranteed to work because cloudpickle relies on some internal + implementation details that can change from one Python version to the + next). + """ + with io.BytesIO() as file: + cp = Pickler(file, protocol=protocol, buffer_callback=buffer_callback) + cp.dump(obj) + return file.getvalue() + + +# Include pickles unloading functions in this namespace for convenience. +load, loads = pickle.load, pickle.loads + +# Backward compat alias. +CloudPickler = Pickler diff --git a/shared/package-files/01/015e860b7da0df1e7e77d39e022bf8d8e24fbf2fa9005a2738ca9fc67a16e641/blob b/shared/package-files/01/015e860b7da0df1e7e77d39e022bf8d8e24fbf2fa9005a2738ca9fc67a16e641/blob new file mode 100644 index 0000000000000000000000000000000000000000..85d0af33c105a80a75a89cbc8986dd81e98f4bc2 Binary files /dev/null and b/shared/package-files/01/015e860b7da0df1e7e77d39e022bf8d8e24fbf2fa9005a2738ca9fc67a16e641/blob differ diff --git a/shared/package-files/01/01612b0f9f9455c284cf29a547e380d332800dbec62a9fcadf3c59a26e958f3c/blob b/shared/package-files/01/01612b0f9f9455c284cf29a547e380d332800dbec62a9fcadf3c59a26e958f3c/blob new file mode 100644 index 0000000000000000000000000000000000000000..51c83f1b07faf194616e92efdf3fc717b85ffc84 --- /dev/null +++ b/shared/package-files/01/01612b0f9f9455c284cf29a547e380d332800dbec62a9fcadf3c59a26e958f3c/blob @@ -0,0 +1,23 @@ +#pragma once + +// @generated by torchgen/gen.py from NativeFunction.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + +namespace at { +namespace native { +TORCH_API at::Tensor & slow_conv_dilated3d_out_symint(const at::Tensor & self, const at::Tensor & weight, c10::SymIntArrayRef kernel_size, const c10::optional & bias, c10::SymIntArrayRef stride, c10::SymIntArrayRef padding, c10::SymIntArrayRef dilation, at::Tensor & out); +TORCH_API at::Tensor slow_conv_dilated3d_cpu(const at::Tensor & self, const at::Tensor & weight, at::IntArrayRef kernel_size, const c10::optional & bias={}, at::IntArrayRef stride=1, at::IntArrayRef padding=0, at::IntArrayRef dilation=1); +TORCH_API at::Tensor slow_conv_dilated3d_cuda(const at::Tensor & self, const at::Tensor & weight, at::IntArrayRef kernel_size, const c10::optional & bias={}, at::IntArrayRef stride=1, at::IntArrayRef padding=0, at::IntArrayRef dilation=1); +} // namespace native +} // namespace at diff --git a/shared/package-files/01/0162e39bab3968223942753de896c7e98e5467132b9a9636dbbc8b0ead237fbf/blob b/shared/package-files/01/0162e39bab3968223942753de896c7e98e5467132b9a9636dbbc8b0ead237fbf/blob new file mode 100644 index 0000000000000000000000000000000000000000..a9f9a047b6912dda446394129407d36028a07910 --- /dev/null +++ b/shared/package-files/01/0162e39bab3968223942753de896c7e98e5467132b9a9636dbbc8b0ead237fbf/blob @@ -0,0 +1,19 @@ +from typing import Any, Callable, TypeVar + +from django.middleware.csrf import CsrfViewMiddleware + +csrf_protect: Any + +class _EnsureCsrfToken(CsrfViewMiddleware): ... + +requires_csrf_token: Any + +class _EnsureCsrfCookie(CsrfViewMiddleware): + get_response: None + def process_view(self, request: Any, callback: Any, callback_args: Any, callback_kwargs: Any): ... + +ensure_csrf_cookie: Any + +_F = TypeVar("_F", bound=Callable[..., Any]) + +def csrf_exempt(view_func: _F) -> _F: ... diff --git a/shared/package-files/01/01676409d253988f26fe3506bfb30086ec0a072486cd5c1fd063f86f7aa1efeb/blob b/shared/package-files/01/01676409d253988f26fe3506bfb30086ec0a072486cd5c1fd063f86f7aa1efeb/blob new file mode 100644 index 0000000000000000000000000000000000000000..3a3ae5f506505c9c03b2ac8be33d301d60074681 --- /dev/null +++ b/shared/package-files/01/01676409d253988f26fe3506bfb30086ec0a072486cd5c1fd063f86f7aa1efeb/blob @@ -0,0 +1,518 @@ +from scipy._lib._array_api import array_namespace, xp_size + +from functools import cached_property + + +class Rule: + """ + Base class for numerical integration algorithms (cubatures). + + Finds an estimate for the integral of ``f`` over the region described by two arrays + ``a`` and ``b`` via `estimate`, and find an estimate for the error of this + approximation via `estimate_error`. + + If a subclass does not implement its own `estimate_error`, then it will use a + default error estimate based on the difference between the estimate over the whole + region and the sum of estimates over that region divided into ``2^ndim`` subregions. + + See Also + -------- + FixedRule + + Examples + -------- + In the following, a custom rule is created which uses 3D Genz-Malik cubature for + the estimate of the integral, and the difference between this estimate and a less + accurate estimate using 5-node Gauss-Legendre quadrature as an estimate for the + error. + + >>> import numpy as np + >>> from scipy.integrate import cubature + >>> from scipy.integrate._rules import ( + ... Rule, ProductNestedFixed, GenzMalikCubature, GaussLegendreQuadrature + ... ) + >>> def f(x, r, alphas): + ... # f(x) = cos(2*pi*r + alpha @ x) + ... # Need to allow r and alphas to be arbitrary shape + ... npoints, ndim = x.shape[0], x.shape[-1] + ... alphas_reshaped = alphas[np.newaxis, :] + ... x_reshaped = x.reshape(npoints, *([1]*(len(alphas.shape) - 1)), ndim) + ... return np.cos(2*np.pi*r + np.sum(alphas_reshaped * x_reshaped, axis=-1)) + >>> genz = GenzMalikCubature(ndim=3) + >>> gauss = GaussKronrodQuadrature(npoints=21) + >>> # Gauss-Kronrod is 1D, so we find the 3D product rule: + >>> gauss_3d = ProductNestedFixed([gauss, gauss, gauss]) + >>> class CustomRule(Rule): + ... def estimate(self, f, a, b, args=()): + ... return genz.estimate(f, a, b, args) + ... def estimate_error(self, f, a, b, args=()): + ... return np.abs( + ... genz.estimate(f, a, b, args) + ... - gauss_3d.estimate(f, a, b, args) + ... ) + >>> rng = np.random.default_rng() + >>> res = cubature( + ... f=f, + ... a=np.array([0, 0, 0]), + ... b=np.array([1, 1, 1]), + ... rule=CustomRule(), + ... args=(rng.random((2,)), rng.random((3, 2, 3))) + ... ) + >>> res.estimate + array([[-0.95179502, 0.12444608], + [-0.96247411, 0.60866385], + [-0.97360014, 0.25515587]]) + """ + + def estimate(self, f, a, b, args=()): + r""" + Calculate estimate of integral of `f` in rectangular region described by + corners `a` and ``b``. + + Parameters + ---------- + f : callable + Function to integrate. `f` must have the signature:: + f(x : ndarray, \*args) -> ndarray + + `f` should accept arrays ``x`` of shape:: + (npoints, ndim) + + and output arrays of shape:: + (npoints, output_dim_1, ..., output_dim_n) + + In this case, `estimate` will return arrays of shape:: + (output_dim_1, ..., output_dim_n) + a, b : ndarray + Lower and upper limits of integration as rank-1 arrays specifying the left + and right endpoints of the intervals being integrated over. Infinite limits + are currently not supported. + args : tuple, optional + Additional positional args passed to ``f``, if any. + + Returns + ------- + est : ndarray + Result of estimation. If `f` returns arrays of shape ``(npoints, + output_dim_1, ..., output_dim_n)``, then `est` will be of shape + ``(output_dim_1, ..., output_dim_n)``. + """ + raise NotImplementedError + + def estimate_error(self, f, a, b, args=()): + r""" + Estimate the error of the approximation for the integral of `f` in rectangular + region described by corners `a` and `b`. + + If a subclass does not override this method, then a default error estimator is + used. This estimates the error as ``|est - refined_est|`` where ``est`` is + ``estimate(f, a, b)`` and ``refined_est`` is the sum of + ``estimate(f, a_k, b_k)`` where ``a_k, b_k`` are the coordinates of each + subregion of the region described by ``a`` and ``b``. In the 1D case, this + is equivalent to comparing the integral over an entire interval ``[a, b]`` to + the sum of the integrals over the left and right subintervals, ``[a, (a+b)/2]`` + and ``[(a+b)/2, b]``. + + Parameters + ---------- + f : callable + Function to estimate error for. `f` must have the signature:: + f(x : ndarray, \*args) -> ndarray + + `f` should accept arrays `x` of shape:: + (npoints, ndim) + + and output arrays of shape:: + (npoints, output_dim_1, ..., output_dim_n) + + In this case, `estimate` will return arrays of shape:: + (output_dim_1, ..., output_dim_n) + a, b : ndarray + Lower and upper limits of integration as rank-1 arrays specifying the left + and right endpoints of the intervals being integrated over. Infinite limits + are currently not supported. + args : tuple, optional + Additional positional args passed to `f`, if any. + + Returns + ------- + err_est : ndarray + Result of error estimation. If `f` returns arrays of shape + ``(npoints, output_dim_1, ..., output_dim_n)``, then `est` will be + of shape ``(output_dim_1, ..., output_dim_n)``. + """ + + est = self.estimate(f, a, b, args) + refined_est = 0 + + for a_k, b_k in _split_subregion(a, b): + refined_est += self.estimate(f, a_k, b_k, args) + + return self.xp.abs(est - refined_est) + + +class FixedRule(Rule): + """ + A rule implemented as the weighted sum of function evaluations at fixed nodes. + + Attributes + ---------- + nodes_and_weights : (ndarray, ndarray) + A tuple ``(nodes, weights)`` of nodes at which to evaluate ``f`` and the + corresponding weights. ``nodes`` should be of shape ``(num_nodes,)`` for 1D + cubature rules (quadratures) and more generally for N-D cubature rules, it + should be of shape ``(num_nodes, ndim)``. ``weights`` should be of shape + ``(num_nodes,)``. The nodes and weights should be for integrals over + :math:`[-1, 1]^n`. + + See Also + -------- + GaussLegendreQuadrature, GaussKronrodQuadrature, GenzMalikCubature + + Examples + -------- + + Implementing Simpson's 1/3 rule: + + >>> import numpy as np + >>> from scipy.integrate._rules import FixedRule + >>> class SimpsonsQuad(FixedRule): + ... @property + ... def nodes_and_weights(self): + ... nodes = np.array([-1, 0, 1]) + ... weights = np.array([1/3, 4/3, 1/3]) + ... return (nodes, weights) + >>> rule = SimpsonsQuad() + >>> rule.estimate( + ... f=lambda x: x**2, + ... a=np.array([0]), + ... b=np.array([1]), + ... ) + [0.3333333] + """ + + def __init__(self): + self.xp = None + + @property + def nodes_and_weights(self): + raise NotImplementedError + + def estimate(self, f, a, b, args=()): + r""" + Calculate estimate of integral of `f` in rectangular region described by + corners `a` and `b` as ``sum(weights * f(nodes))``. + + Nodes and weights will automatically be adjusted from calculating integrals over + :math:`[-1, 1]^n` to :math:`[a, b]^n`. + + Parameters + ---------- + f : callable + Function to integrate. `f` must have the signature:: + f(x : ndarray, \*args) -> ndarray + + `f` should accept arrays `x` of shape:: + (npoints, ndim) + + and output arrays of shape:: + (npoints, output_dim_1, ..., output_dim_n) + + In this case, `estimate` will return arrays of shape:: + (output_dim_1, ..., output_dim_n) + a, b : ndarray + Lower and upper limits of integration as rank-1 arrays specifying the left + and right endpoints of the intervals being integrated over. Infinite limits + are currently not supported. + args : tuple, optional + Additional positional args passed to `f`, if any. + + Returns + ------- + est : ndarray + Result of estimation. If `f` returns arrays of shape ``(npoints, + output_dim_1, ..., output_dim_n)``, then `est` will be of shape + ``(output_dim_1, ..., output_dim_n)``. + """ + nodes, weights = self.nodes_and_weights + + if self.xp is None: + self.xp = array_namespace(nodes) + + return _apply_fixed_rule(f, a, b, nodes, weights, args, self.xp) + + +class NestedFixedRule(FixedRule): + r""" + A cubature rule with error estimate given by the difference between two underlying + fixed rules. + + If constructed as ``NestedFixedRule(higher, lower)``, this will use:: + + estimate(f, a, b) := higher.estimate(f, a, b) + estimate_error(f, a, b) := \|higher.estimate(f, a, b) - lower.estimate(f, a, b)| + + (where the absolute value is taken elementwise). + + Attributes + ---------- + higher : Rule + Higher accuracy rule. + + lower : Rule + Lower accuracy rule. + + See Also + -------- + GaussKronrodQuadrature + + Examples + -------- + + >>> from scipy.integrate import cubature + >>> from scipy.integrate._rules import ( + ... GaussLegendreQuadrature, NestedFixedRule, ProductNestedFixed + ... ) + >>> higher = GaussLegendreQuadrature(10) + >>> lower = GaussLegendreQuadrature(5) + >>> rule = NestedFixedRule( + ... higher, + ... lower + ... ) + >>> rule_2d = ProductNestedFixed([rule, rule]) + """ + + def __init__(self, higher, lower): + self.higher = higher + self.lower = lower + self.xp = None + + @property + def nodes_and_weights(self): + if self.higher is not None: + return self.higher.nodes_and_weights + else: + raise NotImplementedError + + @property + def lower_nodes_and_weights(self): + if self.lower is not None: + return self.lower.nodes_and_weights + else: + raise NotImplementedError + + def estimate_error(self, f, a, b, args=()): + r""" + Estimate the error of the approximation for the integral of `f` in rectangular + region described by corners `a` and `b`. + + Parameters + ---------- + f : callable + Function to estimate error for. `f` must have the signature:: + f(x : ndarray, \*args) -> ndarray + + `f` should accept arrays `x` of shape:: + (npoints, ndim) + + and output arrays of shape:: + (npoints, output_dim_1, ..., output_dim_n) + + In this case, `estimate` will return arrays of shape:: + (output_dim_1, ..., output_dim_n) + a, b : ndarray + Lower and upper limits of integration as rank-1 arrays specifying the left + and right endpoints of the intervals being integrated over. Infinite limits + are currently not supported. + args : tuple, optional + Additional positional args passed to `f`, if any. + + Returns + ------- + err_est : ndarray + Result of error estimation. If `f` returns arrays of shape + ``(npoints, output_dim_1, ..., output_dim_n)``, then `est` will be + of shape ``(output_dim_1, ..., output_dim_n)``. + """ + + nodes, weights = self.nodes_and_weights + lower_nodes, lower_weights = self.lower_nodes_and_weights + + if self.xp is None: + self.xp = array_namespace(nodes) + + error_nodes = self.xp.concat([nodes, lower_nodes], axis=0) + error_weights = self.xp.concat([weights, -lower_weights], axis=0) + + return self.xp.abs( + _apply_fixed_rule(f, a, b, error_nodes, error_weights, args, self.xp) + ) + + +class ProductNestedFixed(NestedFixedRule): + """ + Find the n-dimensional cubature rule constructed from the Cartesian product of 1-D + `NestedFixedRule` quadrature rules. + + Given a list of N 1-dimensional quadrature rules which support error estimation + using NestedFixedRule, this will find the N-dimensional cubature rule obtained by + taking the Cartesian product of their nodes, and estimating the error by taking the + difference with a lower-accuracy N-dimensional cubature rule obtained using the + ``.lower_nodes_and_weights`` rule in each of the base 1-dimensional rules. + + Parameters + ---------- + base_rules : list of NestedFixedRule + List of base 1-dimensional `NestedFixedRule` quadrature rules. + + Attributes + ---------- + base_rules : list of NestedFixedRule + List of base 1-dimensional `NestedFixedRule` qudarature rules. + + Examples + -------- + + Evaluate a 2D integral by taking the product of two 1D rules: + + >>> import numpy as np + >>> from scipy.integrate import cubature + >>> from scipy.integrate._rules import ( + ... ProductNestedFixed, GaussKronrodQuadrature + ... ) + >>> def f(x): + ... # f(x) = cos(x_1) + cos(x_2) + ... return np.sum(np.cos(x), axis=-1) + >>> rule = ProductNestedFixed( + ... [GaussKronrodQuadrature(15), GaussKronrodQuadrature(15)] + ... ) # Use 15-point Gauss-Kronrod, which implements NestedFixedRule + >>> a, b = np.array([0, 0]), np.array([1, 1]) + >>> rule.estimate(f, a, b) # True value 2*sin(1), approximately 1.6829 + np.float64(1.682941969615793) + >>> rule.estimate_error(f, a, b) + np.float64(2.220446049250313e-16) + """ + + def __init__(self, base_rules): + for rule in base_rules: + if not isinstance(rule, NestedFixedRule): + raise ValueError("base rules for product need to be instance of" + "NestedFixedRule") + + self.base_rules = base_rules + self.xp = None + + @cached_property + def nodes_and_weights(self): + nodes = _cartesian_product( + [rule.nodes_and_weights[0] for rule in self.base_rules] + ) + + if self.xp is None: + self.xp = array_namespace(nodes) + + weights = self.xp.prod( + _cartesian_product( + [rule.nodes_and_weights[1] for rule in self.base_rules] + ), + axis=-1, + ) + + return nodes, weights + + @cached_property + def lower_nodes_and_weights(self): + nodes = _cartesian_product( + [cubature.lower_nodes_and_weights[0] for cubature in self.base_rules] + ) + + if self.xp is None: + self.xp = array_namespace(nodes) + + weights = self.xp.prod( + _cartesian_product( + [cubature.lower_nodes_and_weights[1] for cubature in self.base_rules] + ), + axis=-1, + ) + + return nodes, weights + + +def _cartesian_product(arrays): + xp = array_namespace(*arrays) + + arrays_ix = xp.meshgrid(*arrays, indexing='ij') + result = xp.reshape(xp.stack(arrays_ix, axis=-1), (-1, len(arrays))) + + return result + + +def _split_subregion(a, b, xp, split_at=None): + """ + Given the coordinates of a region like a=[0, 0] and b=[1, 1], yield the coordinates + of all subregions, which in this case would be:: + + ([0, 0], [1/2, 1/2]), + ([0, 1/2], [1/2, 1]), + ([1/2, 0], [1, 1/2]), + ([1/2, 1/2], [1, 1]) + """ + xp = array_namespace(a, b) + + if split_at is None: + split_at = (a + b) / 2 + + left = [xp.asarray([a[i], split_at[i]]) for i in range(a.shape[0])] + right = [xp.asarray([split_at[i], b[i]]) for i in range(b.shape[0])] + + a_sub = _cartesian_product(left) + b_sub = _cartesian_product(right) + + for i in range(a_sub.shape[0]): + yield a_sub[i, ...], b_sub[i, ...] + + +def _apply_fixed_rule(f, a, b, orig_nodes, orig_weights, args, xp): + # Downcast nodes and weights to common dtype of a and b + result_dtype = a.dtype + orig_nodes = xp.astype(orig_nodes, result_dtype) + orig_weights = xp.astype(orig_weights, result_dtype) + + # Ensure orig_nodes are at least 2D, since 1D cubature methods can return arrays of + # shape (npoints,) rather than (npoints, 1) + if orig_nodes.ndim == 1: + orig_nodes = orig_nodes[:, None] + + rule_ndim = orig_nodes.shape[-1] + + a_ndim = xp_size(a) + b_ndim = xp_size(b) + + if rule_ndim != a_ndim or rule_ndim != b_ndim: + raise ValueError(f"rule and function are of incompatible dimension, nodes have" + f"ndim {rule_ndim}, while limit of integration has ndim" + f"a_ndim={a_ndim}, b_ndim={b_ndim}") + + lengths = b - a + + # The underlying rule is for the hypercube [-1, 1]^n. + # + # To handle arbitrary regions of integration, it's necessary to apply a linear + # change of coordinates to map each interval [a[i], b[i]] to [-1, 1]. + nodes = (orig_nodes + 1) * (lengths * 0.5) + a + + # Also need to multiply the weights by a scale factor equal to the determinant + # of the Jacobian for this coordinate change. + weight_scale_factor = xp.prod(lengths, dtype=result_dtype) / 2**rule_ndim + weights = orig_weights * weight_scale_factor + + f_nodes = f(nodes, *args) + weights_reshaped = xp.reshape(weights, (-1, *([1] * (f_nodes.ndim - 1)))) + + # f(nodes) will have shape (num_nodes, output_dim_1, ..., output_dim_n) + # Summing along the first axis means estimate will shape (output_dim_1, ..., + # output_dim_n) + est = xp.sum(weights_reshaped * f_nodes, axis=0, dtype=result_dtype) + + return est diff --git a/shared/package-files/01/0168ac959da10dbb34a31fea396444ba0b1b4bcffc9692f8f0b3cc478d2aa62d/blob b/shared/package-files/01/0168ac959da10dbb34a31fea396444ba0b1b4bcffc9692f8f0b3cc478d2aa62d/blob new file mode 100644 index 0000000000000000000000000000000000000000..419c319a2573a5e18827715df01719dd3f701f7d --- /dev/null +++ b/shared/package-files/01/0168ac959da10dbb34a31fea396444ba0b1b4bcffc9692f8f0b3cc478d2aa62d/blob @@ -0,0 +1,410 @@ +StartFontMetrics 2.0 +Comment Copyright (c) 1985, 1987, 1989, 1992 Adobe Systems Incorporated. All Rights Reserved. +Comment Creation Date: Tue Jan 21 16:12:06 1992 +Comment UniqueID 37830 +Comment VMusage 33139 40031 +FontName Bookman-LightItalic +FullName ITC Bookman Light Italic +FamilyName ITC Bookman +Weight Light +ItalicAngle -10 +IsFixedPitch false +FontBBox -228 -250 1269 883 +UnderlinePosition -100 +UnderlineThickness 50 +Version 001.004 +Notice Copyright (c) 1985, 1987, 1989, 1992 Adobe Systems Incorporated. All Rights Reserved.ITC Bookman is a registered trademark of International Typeface Corporation. +EncodingScheme AdobeStandardEncoding +CapHeight 681 +XHeight 494 +Ascender 717 +Descender -212 +StartCharMetrics 228 +C 32 ; WX 300 ; N space ; B 0 0 0 0 ; +C 33 ; WX 320 ; N exclam ; B 103 -8 342 698 ; +C 34 ; WX 360 ; N quotedbl ; B 107 468 402 698 ; +C 35 ; WX 620 ; N numbersign ; B 107 0 598 681 ; +C 36 ; WX 620 ; N dollar ; B 78 -85 619 762 ; +C 37 ; WX 800 ; N percent ; B 56 -8 811 691 ; +C 38 ; WX 820 ; N ampersand ; B 65 -18 848 698 ; +C 39 ; WX 280 ; N quoteright ; B 148 470 288 698 ; +C 40 ; WX 280 ; N parenleft ; B 96 -146 383 727 ; +C 41 ; WX 280 ; N parenright ; B -8 -146 279 727 ; +C 42 ; WX 440 ; N asterisk ; B 139 324 505 698 ; +C 43 ; WX 600 ; N plus ; B 91 43 595 548 ; +C 44 ; WX 300 ; N comma ; B 88 -115 227 112 ; +C 45 ; WX 320 ; N hyphen ; B 78 269 336 325 ; +C 46 ; WX 300 ; N period ; B 96 -8 231 127 ; +C 47 ; WX 600 ; N slash ; B 104 -149 562 717 ; +C 48 ; WX 620 ; N zero ; B 86 -17 646 698 ; +C 49 ; WX 620 ; N one ; B 154 0 500 681 ; +C 50 ; WX 620 ; N two ; B 66 0 636 698 ; +C 51 ; WX 620 ; N three ; B 55 -17 622 698 ; +C 52 ; WX 620 ; N four ; B 69 0 634 681 ; +C 53 ; WX 620 ; N five ; B 70 -17 614 681 ; +C 54 ; WX 620 ; N six ; B 89 -17 657 698 ; +C 55 ; WX 620 ; N seven ; B 143 0 672 681 ; +C 56 ; WX 620 ; N eight ; B 61 -17 655 698 ; +C 57 ; WX 620 ; N nine ; B 77 -17 649 698 ; +C 58 ; WX 300 ; N colon ; B 96 -8 292 494 ; +C 59 ; WX 300 ; N semicolon ; B 88 -114 292 494 ; +C 60 ; WX 600 ; N less ; B 79 33 588 561 ; +C 61 ; WX 600 ; N equal ; B 91 161 595 433 ; +C 62 ; WX 600 ; N greater ; B 93 33 602 561 ; +C 63 ; WX 540 ; N question ; B 114 -8 604 698 ; +C 64 ; WX 780 ; N at ; B 102 -17 802 698 ; +C 65 ; WX 700 ; N A ; B -25 0 720 681 ; +C 66 ; WX 720 ; N B ; B 21 0 746 681 ; +C 67 ; WX 720 ; N C ; B 88 -17 746 698 ; +C 68 ; WX 740 ; N D ; B 21 0 782 681 ; +C 69 ; WX 680 ; N E ; B 21 0 736 681 ; +C 70 ; WX 620 ; N F ; B 21 0 743 681 ; +C 71 ; WX 760 ; N G ; B 88 -17 813 698 ; +C 72 ; WX 800 ; N H ; B 21 0 888 681 ; +C 73 ; WX 320 ; N I ; B 21 0 412 681 ; +C 74 ; WX 560 ; N J ; B -2 -17 666 681 ; +C 75 ; WX 720 ; N K ; B 21 0 804 681 ; +C 76 ; WX 580 ; N L ; B 21 0 656 681 ; +C 77 ; WX 860 ; N M ; B 18 0 956 681 ; +C 78 ; WX 720 ; N N ; B 18 0 823 681 ; +C 79 ; WX 760 ; N O ; B 88 -17 799 698 ; +C 80 ; WX 600 ; N P ; B 21 0 681 681 ; +C 81 ; WX 780 ; N Q ; B 61 -191 812 698 ; +C 82 ; WX 700 ; N R ; B 21 0 736 681 ; +C 83 ; WX 640 ; N S ; B 61 -17 668 698 ; +C 84 ; WX 600 ; N T ; B 50 0 725 681 ; +C 85 ; WX 720 ; N U ; B 118 -17 842 681 ; +C 86 ; WX 680 ; N V ; B 87 0 815 681 ; +C 87 ; WX 960 ; N W ; B 87 0 1095 681 ; +C 88 ; WX 700 ; N X ; B -25 0 815 681 ; +C 89 ; WX 660 ; N Y ; B 87 0 809 681 ; +C 90 ; WX 580 ; N Z ; B 8 0 695 681 ; +C 91 ; WX 260 ; N bracketleft ; B 56 -136 351 717 ; +C 92 ; WX 600 ; N backslash ; B 84 0 542 717 ; +C 93 ; WX 260 ; N bracketright ; B 15 -136 309 717 ; +C 94 ; WX 600 ; N asciicircum ; B 97 276 599 681 ; +C 95 ; WX 500 ; N underscore ; B 0 -125 500 -75 ; +C 96 ; WX 280 ; N quoteleft ; B 191 470 330 698 ; +C 97 ; WX 620 ; N a ; B 71 -8 686 494 ; +C 98 ; WX 600 ; N b ; B 88 -8 621 717 ; +C 99 ; WX 480 ; N c ; B 65 -8 522 494 ; +C 100 ; WX 640 ; N d ; B 65 -8 695 717 ; +C 101 ; WX 540 ; N e ; B 65 -8 575 494 ; +C 102 ; WX 340 ; N f ; B -160 -218 557 725 ; L i fi ; L l fl ; +C 103 ; WX 560 ; N g ; B 4 -221 581 494 ; +C 104 ; WX 620 ; N h ; B 88 -8 689 717 ; +C 105 ; WX 280 ; N i ; B 88 -8 351 663 ; +C 106 ; WX 280 ; N j ; B -200 -221 308 663 ; +C 107 ; WX 600 ; N k ; B 88 -8 657 717 ; +C 108 ; WX 280 ; N l ; B 100 -8 342 717 ; +C 109 ; WX 880 ; N m ; B 88 -8 952 494 ; +C 110 ; WX 620 ; N n ; B 88 -8 673 494 ; +C 111 ; WX 540 ; N o ; B 65 -8 572 494 ; +C 112 ; WX 600 ; N p ; B -24 -212 620 494 ; +C 113 ; WX 560 ; N q ; B 65 -212 584 494 ; +C 114 ; WX 400 ; N r ; B 88 0 481 494 ; +C 115 ; WX 540 ; N s ; B 65 -8 547 494 ; +C 116 ; WX 340 ; N t ; B 88 -8 411 664 ; +C 117 ; WX 620 ; N u ; B 88 -8 686 484 ; +C 118 ; WX 540 ; N v ; B 88 -8 562 494 ; +C 119 ; WX 880 ; N w ; B 88 -8 893 494 ; +C 120 ; WX 540 ; N x ; B 9 -8 626 494 ; +C 121 ; WX 600 ; N y ; B 60 -221 609 484 ; +C 122 ; WX 520 ; N z ; B 38 -8 561 494 ; +C 123 ; WX 360 ; N braceleft ; B 122 -191 442 717 ; +C 124 ; WX 600 ; N bar ; B 294 -250 372 750 ; +C 125 ; WX 380 ; N braceright ; B 13 -191 333 717 ; +C 126 ; WX 600 ; N asciitilde ; B 91 207 595 386 ; +C 161 ; WX 320 ; N exclamdown ; B 73 -213 301 494 ; +C 162 ; WX 620 ; N cent ; B 148 -29 596 715 ; +C 163 ; WX 620 ; N sterling ; B 4 -17 702 698 ; +C 164 ; WX 20 ; N fraction ; B -228 0 323 681 ; +C 165 ; WX 620 ; N yen ; B 71 0 735 681 ; +C 166 ; WX 620 ; N florin ; B -26 -218 692 725 ; +C 167 ; WX 620 ; N section ; B 38 -178 638 698 ; +C 168 ; WX 620 ; N currency ; B 100 89 605 591 ; +C 169 ; WX 200 ; N quotesingle ; B 99 473 247 698 ; +C 170 ; WX 440 ; N quotedblleft ; B 191 470 493 698 ; +C 171 ; WX 300 ; N guillemotleft ; B 70 129 313 434 ; +C 172 ; WX 180 ; N guilsinglleft ; B 75 129 208 434 ; +C 173 ; WX 180 ; N guilsinglright ; B 70 129 203 434 ; +C 174 ; WX 640 ; N fi ; B -159 -222 709 725 ; +C 175 ; WX 660 ; N fl ; B -159 -218 713 725 ; +C 177 ; WX 500 ; N endash ; B 33 269 561 325 ; +C 178 ; WX 620 ; N dagger ; B 192 -130 570 698 ; +C 179 ; WX 620 ; N daggerdbl ; B 144 -122 566 698 ; +C 180 ; WX 300 ; N periodcentered ; B 137 229 272 364 ; +C 182 ; WX 620 ; N paragraph ; B 112 0 718 681 ; +C 183 ; WX 460 ; N bullet ; B 100 170 444 511 ; +C 184 ; WX 320 ; N quotesinglbase ; B 87 -114 226 113 ; +C 185 ; WX 480 ; N quotedblbase ; B 87 -114 390 113 ; +C 186 ; WX 440 ; N quotedblright ; B 148 470 451 698 ; +C 187 ; WX 300 ; N guillemotright ; B 60 129 303 434 ; +C 188 ; WX 1000 ; N ellipsis ; B 99 -8 900 127 ; +C 189 ; WX 1180 ; N perthousand ; B 56 -8 1199 691 ; +C 191 ; WX 540 ; N questiondown ; B 18 -212 508 494 ; +C 193 ; WX 340 ; N grave ; B 182 551 377 706 ; +C 194 ; WX 320 ; N acute ; B 178 551 373 706 ; +C 195 ; WX 440 ; N circumflex ; B 176 571 479 685 ; +C 196 ; WX 440 ; N tilde ; B 180 586 488 671 ; +C 197 ; WX 440 ; N macron ; B 178 599 484 658 ; +C 198 ; WX 440 ; N breve ; B 191 577 500 680 ; +C 199 ; WX 260 ; N dotaccent ; B 169 543 290 664 ; +C 200 ; WX 420 ; N dieresis ; B 185 569 467 688 ; +C 202 ; WX 300 ; N ring ; B 178 551 334 706 ; +C 203 ; WX 320 ; N cedilla ; B 45 -178 240 0 ; +C 205 ; WX 340 ; N hungarumlaut ; B 167 547 402 738 ; +C 206 ; WX 260 ; N ogonek ; B 51 -173 184 0 ; +C 207 ; WX 440 ; N caron ; B 178 571 481 684 ; +C 208 ; WX 1000 ; N emdash ; B 33 269 1061 325 ; +C 225 ; WX 1220 ; N AE ; B -45 0 1269 681 ; +C 227 ; WX 440 ; N ordfeminine ; B 130 396 513 698 ; +C 232 ; WX 580 ; N Lslash ; B 21 0 656 681 ; +C 233 ; WX 760 ; N Oslash ; B 88 -95 799 777 ; +C 234 ; WX 1180 ; N OE ; B 88 -17 1237 698 ; +C 235 ; WX 400 ; N ordmasculine ; B 139 396 455 698 ; +C 241 ; WX 880 ; N ae ; B 71 -8 918 494 ; +C 245 ; WX 280 ; N dotlessi ; B 88 -8 351 484 ; +C 248 ; WX 340 ; N lslash ; B 50 -8 398 717 ; +C 249 ; WX 540 ; N oslash ; B 65 -49 571 532 ; +C 250 ; WX 900 ; N oe ; B 65 -8 948 494 ; +C 251 ; WX 620 ; N germandbls ; B -121 -111 653 698 ; +C -1 ; WX 540 ; N ecircumflex ; B 65 -8 575 685 ; +C -1 ; WX 540 ; N edieresis ; B 65 -8 575 688 ; +C -1 ; WX 620 ; N aacute ; B 71 -8 686 706 ; +C -1 ; WX 740 ; N registered ; B 84 -17 784 698 ; +C -1 ; WX 280 ; N icircumflex ; B 76 -8 379 685 ; +C -1 ; WX 620 ; N udieresis ; B 88 -8 686 688 ; +C -1 ; WX 540 ; N ograve ; B 65 -8 572 706 ; +C -1 ; WX 620 ; N uacute ; B 88 -8 686 706 ; +C -1 ; WX 620 ; N ucircumflex ; B 88 -8 686 685 ; +C -1 ; WX 700 ; N Aacute ; B -25 0 720 883 ; +C -1 ; WX 280 ; N igrave ; B 88 -8 351 706 ; +C -1 ; WX 320 ; N Icircumflex ; B 21 0 449 862 ; +C -1 ; WX 480 ; N ccedilla ; B 65 -178 522 494 ; +C -1 ; WX 620 ; N adieresis ; B 71 -8 686 688 ; +C -1 ; WX 680 ; N Ecircumflex ; B 21 0 736 862 ; +C -1 ; WX 540 ; N scaron ; B 65 -8 547 684 ; +C -1 ; WX 600 ; N thorn ; B -24 -212 620 717 ; +C -1 ; WX 980 ; N trademark ; B 69 277 965 681 ; +C -1 ; WX 540 ; N egrave ; B 65 -8 575 706 ; +C -1 ; WX 372 ; N threesuperior ; B 70 269 439 698 ; +C -1 ; WX 520 ; N zcaron ; B 38 -8 561 684 ; +C -1 ; WX 620 ; N atilde ; B 71 -8 686 671 ; +C -1 ; WX 620 ; N aring ; B 71 -8 686 706 ; +C -1 ; WX 540 ; N ocircumflex ; B 65 -8 572 685 ; +C -1 ; WX 680 ; N Edieresis ; B 21 0 736 865 ; +C -1 ; WX 930 ; N threequarters ; B 99 0 913 691 ; +C -1 ; WX 600 ; N ydieresis ; B 60 -221 609 688 ; +C -1 ; WX 600 ; N yacute ; B 60 -221 609 706 ; +C -1 ; WX 280 ; N iacute ; B 88 -8 351 706 ; +C -1 ; WX 700 ; N Acircumflex ; B -25 0 720 862 ; +C -1 ; WX 720 ; N Uacute ; B 118 -17 842 883 ; +C -1 ; WX 540 ; N eacute ; B 65 -8 575 706 ; +C -1 ; WX 760 ; N Ograve ; B 88 -17 799 883 ; +C -1 ; WX 620 ; N agrave ; B 71 -8 686 706 ; +C -1 ; WX 720 ; N Udieresis ; B 118 -17 842 865 ; +C -1 ; WX 620 ; N acircumflex ; B 71 -8 686 685 ; +C -1 ; WX 320 ; N Igrave ; B 21 0 412 883 ; +C -1 ; WX 372 ; N twosuperior ; B 68 279 439 698 ; +C -1 ; WX 720 ; N Ugrave ; B 118 -17 842 883 ; +C -1 ; WX 930 ; N onequarter ; B 91 0 913 681 ; +C -1 ; WX 720 ; N Ucircumflex ; B 118 -17 842 862 ; +C -1 ; WX 640 ; N Scaron ; B 61 -17 668 861 ; +C -1 ; WX 320 ; N Idieresis ; B 21 0 447 865 ; +C -1 ; WX 280 ; N idieresis ; B 88 -8 377 688 ; +C -1 ; WX 680 ; N Egrave ; B 21 0 736 883 ; +C -1 ; WX 760 ; N Oacute ; B 88 -17 799 883 ; +C -1 ; WX 600 ; N divide ; B 91 46 595 548 ; +C -1 ; WX 700 ; N Atilde ; B -25 0 720 848 ; +C -1 ; WX 700 ; N Aring ; B -25 0 720 883 ; +C -1 ; WX 760 ; N Odieresis ; B 88 -17 799 865 ; +C -1 ; WX 700 ; N Adieresis ; B -25 0 720 865 ; +C -1 ; WX 720 ; N Ntilde ; B 18 0 823 848 ; +C -1 ; WX 580 ; N Zcaron ; B 8 0 695 861 ; +C -1 ; WX 600 ; N Thorn ; B 21 0 656 681 ; +C -1 ; WX 320 ; N Iacute ; B 21 0 412 883 ; +C -1 ; WX 600 ; N plusminus ; B 91 0 595 548 ; +C -1 ; WX 600 ; N multiply ; B 91 44 595 548 ; +C -1 ; WX 680 ; N Eacute ; B 21 0 736 883 ; +C -1 ; WX 660 ; N Ydieresis ; B 87 0 809 865 ; +C -1 ; WX 372 ; N onesuperior ; B 114 279 339 688 ; +C -1 ; WX 620 ; N ugrave ; B 88 -8 686 706 ; +C -1 ; WX 600 ; N logicalnot ; B 91 163 595 433 ; +C -1 ; WX 620 ; N ntilde ; B 88 -8 673 671 ; +C -1 ; WX 760 ; N Otilde ; B 88 -17 799 848 ; +C -1 ; WX 540 ; N otilde ; B 65 -8 572 671 ; +C -1 ; WX 720 ; N Ccedilla ; B 88 -178 746 698 ; +C -1 ; WX 700 ; N Agrave ; B -25 0 720 883 ; +C -1 ; WX 930 ; N onehalf ; B 91 0 925 681 ; +C -1 ; WX 740 ; N Eth ; B 21 0 782 681 ; +C -1 ; WX 400 ; N degree ; B 120 398 420 698 ; +C -1 ; WX 660 ; N Yacute ; B 87 0 809 883 ; +C -1 ; WX 760 ; N Ocircumflex ; B 88 -17 799 862 ; +C -1 ; WX 540 ; N oacute ; B 65 -8 572 706 ; +C -1 ; WX 620 ; N mu ; B 53 -221 686 484 ; +C -1 ; WX 600 ; N minus ; B 91 259 595 335 ; +C -1 ; WX 540 ; N eth ; B 65 -8 642 725 ; +C -1 ; WX 540 ; N odieresis ; B 65 -8 572 688 ; +C -1 ; WX 740 ; N copyright ; B 84 -17 784 698 ; +C -1 ; WX 600 ; N brokenbar ; B 294 -175 372 675 ; +EndCharMetrics +StartKernData +StartKernPairs 85 + +KPX A Y -62 +KPX A W -73 +KPX A V -78 +KPX A T -5 + +KPX F period -97 +KPX F comma -98 +KPX F A -16 + +KPX L y 20 +KPX L Y 7 +KPX L W 9 +KPX L V 4 + +KPX P period -105 +KPX P comma -106 +KPX P A -30 + +KPX R Y 11 +KPX R W 2 +KPX R V 2 +KPX R T 65 + +KPX T semicolon 48 +KPX T s -7 +KPX T r 67 +KPX T period -78 +KPX T o 14 +KPX T i 71 +KPX T hyphen 20 +KPX T e 10 +KPX T comma -79 +KPX T colon 48 +KPX T c 16 +KPX T a 9 +KPX T A -14 + +KPX V y -14 +KPX V u -10 +KPX V semicolon -44 +KPX V r -20 +KPX V period -100 +KPX V o -70 +KPX V i 3 +KPX V hyphen 20 +KPX V e -70 +KPX V comma -109 +KPX V colon -35 +KPX V a -70 +KPX V A -70 + +KPX W y -14 +KPX W u -20 +KPX W semicolon -42 +KPX W r -30 +KPX W period -100 +KPX W o -60 +KPX W i 3 +KPX W hyphen 20 +KPX W e -60 +KPX W comma -109 +KPX W colon -35 +KPX W a -60 +KPX W A -60 + +KPX Y v -19 +KPX Y u -31 +KPX Y semicolon -40 +KPX Y q -72 +KPX Y period -100 +KPX Y p -37 +KPX Y o -75 +KPX Y i -11 +KPX Y hyphen 20 +KPX Y e -78 +KPX Y comma -109 +KPX Y colon -35 +KPX Y a -79 +KPX Y A -82 + +KPX f f -19 + +KPX r q -14 +KPX r period -134 +KPX r o -10 +KPX r n 38 +KPX r m 37 +KPX r hyphen 20 +KPX r h -20 +KPX r g -3 +KPX r f -9 +KPX r e -15 +KPX r d -9 +KPX r comma -143 +KPX r c -8 +EndKernPairs +EndKernData +StartComposites 56 +CC Aacute 2 ; PCC A 0 0 ; PCC acute 200 177 ; +CC Acircumflex 2 ; PCC A 0 0 ; PCC circumflex 130 177 ; +CC Adieresis 2 ; PCC A 0 0 ; PCC dieresis 140 177 ; +CC Agrave 2 ; PCC A 0 0 ; PCC grave 160 177 ; +CC Aring 2 ; PCC A 0 0 ; PCC ring 220 177 ; +CC Atilde 2 ; PCC A 0 0 ; PCC tilde 130 177 ; +CC Eacute 2 ; PCC E 0 0 ; PCC acute 210 177 ; +CC Ecircumflex 2 ; PCC E 0 0 ; PCC circumflex 140 177 ; +CC Edieresis 2 ; PCC E 0 0 ; PCC dieresis 150 177 ; +CC Egrave 2 ; PCC E 0 0 ; PCC grave 150 177 ; +CC Iacute 2 ; PCC I 0 0 ; PCC acute 30 177 ; +CC Icircumflex 2 ; PCC I 0 0 ; PCC circumflex -30 177 ; +CC Idieresis 2 ; PCC I 0 0 ; PCC dieresis -20 177 ; +CC Igrave 2 ; PCC I 0 0 ; PCC grave -30 177 ; +CC Ntilde 2 ; PCC N 0 0 ; PCC tilde 130 177 ; +CC Oacute 2 ; PCC O 0 0 ; PCC acute 250 177 ; +CC Ocircumflex 2 ; PCC O 0 0 ; PCC circumflex 190 177 ; +CC Odieresis 2 ; PCC O 0 0 ; PCC dieresis 200 177 ; +CC Ograve 2 ; PCC O 0 0 ; PCC grave 210 177 ; +CC Otilde 2 ; PCC O 0 0 ; PCC tilde 190 177 ; +CC Scaron 2 ; PCC S 0 0 ; PCC caron 100 177 ; +CC Uacute 2 ; PCC U 0 0 ; PCC acute 230 177 ; +CC Ucircumflex 2 ; PCC U 0 0 ; PCC circumflex 170 177 ; +CC Udieresis 2 ; PCC U 0 0 ; PCC dieresis 180 177 ; +CC Ugrave 2 ; PCC U 0 0 ; PCC grave 170 177 ; +CC Yacute 2 ; PCC Y 0 0 ; PCC acute 200 177 ; +CC Ydieresis 2 ; PCC Y 0 0 ; PCC dieresis 140 177 ; +CC Zcaron 2 ; PCC Z 0 0 ; PCC caron 70 177 ; +CC aacute 2 ; PCC a 0 0 ; PCC acute 120 0 ; +CC acircumflex 2 ; PCC a 0 0 ; PCC circumflex 70 0 ; +CC adieresis 2 ; PCC a 0 0 ; PCC dieresis 80 0 ; +CC agrave 2 ; PCC a 0 0 ; PCC grave 110 0 ; +CC aring 2 ; PCC a 0 0 ; PCC ring 140 0 ; +CC atilde 2 ; PCC a 0 0 ; PCC tilde 60 0 ; +CC eacute 2 ; PCC e 0 0 ; PCC acute 90 0 ; +CC ecircumflex 2 ; PCC e 0 0 ; PCC circumflex 30 0 ; +CC edieresis 2 ; PCC e 0 0 ; PCC dieresis 40 0 ; +CC egrave 2 ; PCC e 0 0 ; PCC grave 80 0 ; +CC iacute 2 ; PCC dotlessi 0 0 ; PCC acute -40 0 ; +CC icircumflex 2 ; PCC dotlessi 0 0 ; PCC circumflex -100 0 ; +CC idieresis 2 ; PCC dotlessi 0 0 ; PCC dieresis -90 0 ; +CC igrave 2 ; PCC dotlessi 0 0 ; PCC grave -60 0 ; +CC ntilde 2 ; PCC n 0 0 ; PCC tilde 60 0 ; +CC oacute 2 ; PCC o 0 0 ; PCC acute 80 0 ; +CC ocircumflex 2 ; PCC o 0 0 ; PCC circumflex 20 0 ; +CC odieresis 2 ; PCC o 0 0 ; PCC dieresis 40 0 ; +CC ograve 2 ; PCC o 0 0 ; PCC grave 80 0 ; +CC otilde 2 ; PCC o 0 0 ; PCC tilde 30 0 ; +CC scaron 2 ; PCC s 0 0 ; PCC caron 30 0 ; +CC uacute 2 ; PCC u 0 0 ; PCC acute 120 0 ; +CC ucircumflex 2 ; PCC u 0 0 ; PCC circumflex 60 0 ; +CC udieresis 2 ; PCC u 0 0 ; PCC dieresis 70 0 ; +CC ugrave 2 ; PCC u 0 0 ; PCC grave 110 0 ; +CC yacute 2 ; PCC y 0 0 ; PCC acute 140 0 ; +CC ydieresis 2 ; PCC y 0 0 ; PCC dieresis 70 0 ; +CC zcaron 2 ; PCC z 0 0 ; PCC caron 20 0 ; +EndComposites +EndFontMetrics diff --git a/shared/package-files/01/01693deed89d7c02f88e586661082939b32eb04b0d73c685017d2cc53dd71fa6/blob b/shared/package-files/01/01693deed89d7c02f88e586661082939b32eb04b0d73c685017d2cc53dd71fa6/blob new file mode 100644 index 0000000000000000000000000000000000000000..cfb13ac96271fa7b926cc703918984760e6ede15 --- /dev/null +++ b/shared/package-files/01/01693deed89d7c02f88e586661082939b32eb04b0d73c685017d2cc53dd71fa6/blob @@ -0,0 +1,15 @@ +# flake8: noqa: F401 +r""" +This file is in the process of migration to `torch/ao/quantization`, and +is kept here for compatibility while the migration process is ongoing. +If you are adding a new entry/functionality, please, add it to the +`torch/ao/quantization/fuser_method_mappings.py`, while adding an import statement +here. +""" +from torch.ao.quantization.fuser_method_mappings import ( + _DEFAULT_OP_LIST_TO_FUSER_METHOD, + fuse_conv_bn, + fuse_conv_bn_relu, + fuse_linear_bn, + get_fuser_method, +) diff --git a/shared/package-files/01/016a16230fd82667e714a610c3ab6020507de70179dfcf15dc01a5e053b80dfc/blob b/shared/package-files/01/016a16230fd82667e714a610c3ab6020507de70179dfcf15dc01a5e053b80dfc/blob new file mode 100644 index 0000000000000000000000000000000000000000..d36d0efae2d92d6276dd70b0dcd1d0dda4dfc3ce --- /dev/null +++ b/shared/package-files/01/016a16230fd82667e714a610c3ab6020507de70179dfcf15dc01a5e053b80dfc/blob @@ -0,0 +1,77 @@ +from enum import Enum +from typing import Optional, Tuple + +from torch import Tensor + +# Defined in torch/csrc/functorch/init.cpp + +def _set_dynamic_layer_keys_included(included: bool) -> None: ... +def get_unwrapped(tensor: Tensor) -> Tensor: ... +def is_batchedtensor(tensor: Tensor) -> bool: ... +def is_functionaltensor(tensor: Tensor) -> bool: ... +def is_functorch_wrapped_tensor(tensor: Tensor) -> bool: ... +def is_gradtrackingtensor(tensor: Tensor) -> bool: ... +def maybe_get_bdim(tensor: Tensor) -> int: ... +def maybe_get_level(tensor: Tensor) -> int: ... +def maybe_current_level() -> Optional[int]: ... +def unwrap_if_dead(tensor: Tensor) -> Tensor: ... +def _unwrap_for_grad(tensor: Tensor, level: int) -> Tensor: ... +def _wrap_for_grad(tensor: Tensor, level: int) -> Tensor: ... +def _unwrap_batched(tensor: Tensor, level: int) -> Tuple[Tensor, Optional[int]]: ... +def current_level() -> int: ... +def _add_batch_dim(tensor: Tensor, bdim: int, level: int) -> Tensor: ... +def set_single_level_autograd_function_allowed(allowed: bool) -> None: ... +def get_single_level_autograd_function_allowed() -> bool: ... +def _unwrap_functional_tensor(tensor: Tensor, reapply_views: bool) -> Tensor: ... +def _wrap_functional_tensor(tensor: Tensor, level: int) -> Tensor: ... +def _vmap_increment_nesting(batch_size: int, randomness: str) -> int: ... +def _vmap_decrement_nesting() -> int: ... +def _grad_increment_nesting() -> int: ... +def _grad_decrement_nesting() -> int: ... + +# Defined in aten/src/ATen/functorch/Interpreter.h +class TransformType(Enum): + Torch: TransformType = ... + Vmap: TransformType = ... + Grad: TransformType = ... + Jvp: TransformType = ... + Functionalize: TransformType = ... + +class RandomnessType(Enum): + Error: TransformType = ... + Same: TransformType = ... + Different: TransformType = ... + +class CInterpreter: + def key(self) -> TransformType: ... + def level(self) -> int: ... + +class CGradInterpreterPtr: + def __init__(self, interpreter: CInterpreter): ... + def lift(self, Tensor) -> Tensor: ... + def prevGradMode(self) -> bool: ... + +class CJvpInterpreterPtr: + def __init__(self, interpreter: CInterpreter): ... + def lift(self, Tensor) -> Tensor: ... + def prevFwdGradMode(self) -> bool: ... + +class CFunctionalizeInterpreterPtr: + def __init__(self, interpreter: CInterpreter): ... + def key(self) -> TransformType: ... + def level(self) -> int: ... + def functionalizeAddBackViews(self) -> bool: ... + +class CVmapInterpreterPtr: + def __init__(self, interpreter: CInterpreter): ... + def key(self) -> TransformType: ... + def level(self) -> int: ... + def batchSize(self) -> int: ... + def randomness(self) -> RandomnessType: ... + +class DynamicLayer: ... + +def get_interpreter_stack() -> list[CInterpreter]: ... +def peek_interpreter_stack() -> CInterpreter: ... +def pop_dynamic_layer_stack() -> DynamicLayer: ... +def push_dynamic_layer_stack(dl: DynamicLayer) -> int: ... diff --git a/shared/package-files/01/016e40ba478f466706375fd4b04177e38d9aa9288c75636ab9084475c51320d0/blob b/shared/package-files/01/016e40ba478f466706375fd4b04177e38d9aa9288c75636ab9084475c51320d0/blob new file mode 100644 index 0000000000000000000000000000000000000000..035a0c9c7956bcf29f5a8fe6c0a121a568a390de --- /dev/null +++ b/shared/package-files/01/016e40ba478f466706375fd4b04177e38d9aa9288c75636ab9084475c51320d0/blob @@ -0,0 +1,50 @@ +#pragma once + +// @generated by torchgen/gen.py from Operator.h + +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { +namespace _ops { + + +struct TORCH_API _foreach_zero_ { + using schema = void (at::TensorList); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::_foreach_zero_") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "_foreach_zero_(Tensor(a!)[] self) -> ()") + static void call(at::TensorList self); + static void redispatch(c10::DispatchKeySet dispatchKeySet, at::TensorList self); +}; + +struct TORCH_API _foreach_zero_out { + using schema = void (at::TensorList, at::TensorList); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::_foreach_zero") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "out") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "_foreach_zero.out(Tensor[] self, *, Tensor(a!)[] out) -> ()") + static void call(at::TensorList self, at::TensorList out); + static void redispatch(c10::DispatchKeySet dispatchKeySet, at::TensorList self, at::TensorList out); +}; + +struct TORCH_API _foreach_zero { + using schema = ::std::vector (at::TensorList); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::_foreach_zero") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "_foreach_zero(Tensor[] self) -> Tensor[] self_out") + static ::std::vector call(at::TensorList self); + static ::std::vector redispatch(c10::DispatchKeySet dispatchKeySet, at::TensorList self); +}; + +}} // namespace at::_ops diff --git a/shared/package-files/01/016f17f90d4020faacffa9dcf5a988e90a8b715d35102120867d7e4dcd979205/blob b/shared/package-files/01/016f17f90d4020faacffa9dcf5a988e90a8b715d35102120867d7e4dcd979205/blob new file mode 100644 index 0000000000000000000000000000000000000000..ddfa2bb973159841b07259c4880d351bc10fa076 --- /dev/null +++ b/shared/package-files/01/016f17f90d4020faacffa9dcf5a988e90a8b715d35102120867d7e4dcd979205/blob @@ -0,0 +1,425 @@ +#pragma once + +#include +#include +#include +#include +#include +#include +#include +#include + +namespace torch::autograd { + +using optional_variable_list = std::vector>; +using _jvp_fn_t = std::function; +using _view_as_self_fn_t = std::function; + +TORCH_API std::vector> _wrap_outputs( + const variable_list& input_vars, + const std::unordered_set& non_differentiable, + const std::unordered_set& dirty_inputs, + const at::ArrayRef> raw_outputs, + const std::shared_ptr& cdata, + const _jvp_fn_t& jvp_user_function, + const std::unordered_set& to_save_if_setup_context, + const _view_as_self_fn_t& view_as_self_fn); + +TORCH_API void check_variable_result( + const at::TensorBase& original, + const at::TensorBase& result, + const std::string& hook_name); + +// Get the return type of the forward function of the custom Function class X +template +using forward_t = decltype(X::forward(nullptr, std::declval()...)); + +/// To use custom autograd operations, implement a Function subclass with +/// static forward and backward functions: +/// +/// `forward` can take as many arguments as you want and should return either a +/// variable list or a Variable. Use of any direct Variable arguments will be +/// registered in the graph but no vectors/sets or any other data structures +/// will be traversed. You can use c10::optional as one of the arguments +/// and it will be registered as a variable in the graph if the argument has a +/// value. It should take a pointer to `torch::autograd::AutogradContext` as the +/// first argument. Variables can be saved in the `ctx` using +/// `ctx->save_for_backward` +/// (see `torch::autograd::AutogradContext::save_for_backward`) and other data +/// can be saved in the `ctx->saved_data` map +/// (see `torch::autograd::AutogradContext::saved_data`) +/// in the form of `` pairs. +/// +/// `backward` should take a pointer to `torch::autograd::AutogradContext` +/// and a variable list containing as many Variables as there were outputs from +/// `forward` as arguments. It should return as many Variables as there were +/// inputs with each of them containing the gradient w.r.t. its corresponding +/// input. Variables saved in `forward` can be accessed with +/// `ctx->get_saved_variables` (see +/// `torch::autograd::AutogradContext::get_saved_variables`) and other saved +/// data can be accessed from `ctx->saved_data`. +/// +/// For example: +/// ``` +/// class MyFunction : public Function { +/// public: +/// static variable_list forward(AutogradContext *ctx, int n, Variable var) { +/// // Save data for backward in context +/// ctx->saved_data["n"] = n; +/// var.mul_(2); +/// // Mark var as modified by inplace operation +/// ctx->mark_dirty({var}); +/// return {var}; +/// } +/// +/// static variable_list backward(AutogradContext *ctx, variable_list +/// grad_output) { +/// // Use data saved in forward +/// auto n = ctx->saved_data["n"].toInt(); +/// return {grad_output[0]*n}; +/// } +/// }; +/// ``` +/// +/// To use `MyFunction`: +/// ``` +/// Variable x; +/// auto y = MyFunction::apply(6, x); +/// // Example backward call +/// y[0].sum().backward(); +/// ``` +template +struct TORCH_API Function { + // We need to use a different template parameter than T here because T will + // inherit from Function, and when Function is instantiated, T::forward + // is not declared yet. + // The enable_if check is to ensure that the user doesn't explicitly provide + // the parameter X. + template + static auto apply(Args&&... args) + -> std::enable_if_t, forward_t>; +}; + +/// Context to save information during `forward` that can be accessed in +/// `backward` in custom autograd operations (see `torch::autograd::Function` +/// for details). +struct TORCH_API AutogradContext { + AutogradContext() = default; + AutogradContext(const AutogradContext& other) = delete; + AutogradContext& operator=(const AutogradContext& other) = delete; + + /// Can be used to save non-variable data for `backward`. + // NOLINTNEXTLINE(cppcoreguidelines-non-private-member-variables-in-classes) + ska::flat_hash_map saved_data; + + /// Saves the list of variables for a future call to `backward`. This + /// should be called at most once from inside of `forward`. + void save_for_backward(variable_list to_save); + /// Marks variables in the list as modified in an in-place operation. This + /// should be called at most once from inside of `forward` and all arguments + /// should be inputs. + void mark_dirty(const variable_list& inputs); + /// Marks outputs in the list as not requiring gradients. This should be + /// called at most once from inside of `forward` and all arguments should be + /// outputs. + void mark_non_differentiable(const variable_list& outputs); + // Sets whether undefined output grad tensors should be expanded to tensors + // full of zeros before calling backward function. Default value is true. + void set_materialize_grads(bool value); + + /// Get the list of variables that were saved in `forward` using + /// `save_for_backward()`. Before returning them to the user, a check is made + /// to ensure that they were not modified by any in-place operations. + variable_list get_saved_variables() const; + const std::unordered_set& get_and_bump_dirty() const; + const std::unordered_set& get_non_differentiable() const; + + /// Expose the Node's `task_should_compute_output` method to the cpp + /// custom autograd Function as `needs_input_grad`. + bool needs_input_grad(size_t output_edge_index) const; + bool needs_input_grad(std::initializer_list idxs) const; + + private: + std::unordered_set non_differentiable_; + std::unordered_set dirty_inputs_; + std::vector saved_variables_; + variable_list to_save_; + bool materialize_grads_{true}; + + // The CppNode in the autograd graph that owns this AutogradContext. We need a + // weak_ptr to avoid a refcycle. Since grad_fn_ owns this AutogradContext, it + // will always be alive when we want to use it. + std::weak_ptr grad_fn_; + bool has_freed_buffers_{false}; + + void save_variables(); + + template + friend struct CppNode; +}; + +// CppNode is the Node in the autograd graph that represents the user defined +// backward function for Function. Calls to CppNode::apply are forward to +// T::backward(). +template +struct CppNode : public Node { + variable_list apply(variable_list&& inputs) override; + AutogradContext ctx_; + std::vector is_variable_input_; + std::vector input_info_; + std::vector output_info_; + + void release_variables() override; + + void set_ctx_grad_fn(const std::shared_ptr& node); + void save_variables_to_ctx(); +}; + +struct ExtractVariables : IterArgs { + // NOLINTNEXTLINE(cppcoreguidelines-avoid-const-or-ref-data-members) + std::vector& is_var_; + // NOLINTNEXTLINE(cppcoreguidelines-avoid-const-or-ref-data-members) + variable_list& list_; + ExtractVariables(std::vector& is_var, variable_list& list) + : is_var_(is_var), list_(list) {} + void operator()(const c10::optional& x) { + // NOLINTNEXTLINE(bugprone-branch-clone) + if (x.has_value() && x.value().defined()) { + is_var_.push_back(true); + list_.emplace_back(x.value()); + } else { + is_var_.push_back(false); + } + } + void operator()(const at::Tensor& x) { + is_var_.push_back(true); + list_.emplace_back(x); + } + void operator()(const at::TensorList& list) { + for (const at::Tensor& x : list) { + is_var_.push_back(true); + list_.emplace_back(x); + } + } + template + void operator()(const T& x) { + is_var_.push_back(false); + } +}; + +template +inline void extract_vars( + std::vector& is_var, + variable_list& list, + Args&&... args) { + ExtractVariables(is_var, list).apply(std::forward(args)...); +} + +template +std::enable_if_t, T> to_output_type( + std::vector>& output_list) { + // NOLINTNEXTLINE(cppcoreguidelines-init-variables) + variable_list result; + std::transform( + output_list.begin(), + output_list.end(), + std::back_inserter(result), + [](const c10::optional& var) { return *var; }); + return result; +} + +template +std::enable_if_t, T> to_output_type( + std::vector>& output_list) { + return *output_list[0]; +} + +inline std::vector> to_optional(Variable& output) { + return std::vector>{output}; +} + +inline std::vector> to_optional(variable_list& output) { + // NOLINTNEXTLINE(cppcoreguidelines-init-variables) + std::vector> result; + std::transform( + output.begin(), + output.end(), + std::back_inserter(result), + [](const Variable& var) { return var; }); + return result; +} + +template +template +auto Function::apply(Args&&... args) + -> std::enable_if_t, forward_t> { + const auto& functorch_tls = at::functorch::functorchTLSAccessor(); + if (functorch_tls) { + // Function support for functorch is handled in Python. + // Here we are dealing with a (C++) Function, which is not supported. + // Let's raise an error instead of being silently incorrect. + functorch_tls->checkSupportsCppAutogradFunction(); + } + + std::shared_ptr> node(new CppNode(), deleteNode); + // NOLINTNEXTLINE(cppcoreguidelines-init-variables) + variable_list input_vars; + + const size_t num_inputs = sizeof...(Args); + input_vars.reserve(num_inputs); + node->is_variable_input_.reserve(num_inputs); + // TODO Add tracing here + extract_vars(node->is_variable_input_, input_vars, args...); + + // NOLINTNEXTLINE(cppcoreguidelines-init-variables) + bool is_executable = + GradMode::is_enabled() && any_variable_requires_grad(input_vars); + auto next_edges = + (is_executable ? collect_next_edges(input_vars) : edge_list()); + node->set_ctx_grad_fn(node); + node->set_next_edges(std::move(next_edges)); + node->clear_input_metadata(); + + node->input_info_.reserve(input_vars.size()); + for (auto& var : input_vars) { + node->input_info_.emplace_back(var); + } + + using forward_return_t = forward_t; + // NOLINTNEXTLINE(cppcoreguidelines-init-variables) + forward_return_t outputs; + { + AutoGradMode grad_mode(false); + outputs = T::forward(&node->ctx_, std::forward(args)...); + } + + _jvp_fn_t jvp_fn = [](const variable_list& inputs, + const variable_list& gI) -> variable_list { + TORCH_CHECK( + false, + "jvp is not implemented for the c++ API of custom Function yet.", + "Please open a feature request on GitHub if you need this."); + }; + + auto view_as_self_fn = [](const at::Tensor& x) -> at::Tensor { + return x.view_as(x); + }; + + auto wrapped_outputs = _wrap_outputs( + input_vars, + node->ctx_.get_non_differentiable(), + node->ctx_.get_and_bump_dirty(), + to_optional(outputs), + is_executable ? node : nullptr, + jvp_fn, + {}, + view_as_self_fn); + + node->output_info_.reserve(wrapped_outputs.size()); + for (auto& output : wrapped_outputs) { + if (is_executable && output.has_value()) { + node->output_info_.emplace_back(output.value()); + } else if (is_executable) { + node->output_info_.emplace_back(); + } + } + + if (is_executable) { + node->save_variables_to_ctx(); + } + + // wrapped_outputs will be a variable_list so, convert it to the correct + // return type. Only Variable and variable_list are accepted as return types. + return to_output_type(wrapped_outputs); +} + +// The logic here is the same as PyNode::apply, so changes to it should be done +// in both the places +template +// NOLINTNEXTLINE(cppcoreguidelines-rvalue-reference-param-not-moved) +variable_list CppNode::apply(variable_list&& inputs) { + at::OptionalDeviceGuard _device_guard; + + auto num_inputs = inputs.size(); + // NOLINTNEXTLINE(cppcoreguidelines-init-variables) + variable_list backward_inputs; + backward_inputs.reserve(num_inputs); + for (const auto i : c10::irange(num_inputs)) { + if (inputs[i].defined() || !ctx_.materialize_grads_) { + backward_inputs.emplace_back(std::move(inputs[i])); + } else { + backward_inputs.emplace_back(output_info_[i].zeros(_device_guard)); + } + } + + // Acquire lock to here protect thread safety on custom C++ Autograd Node + // This is needed for the custom Autograd Node since we don't know if the + // user defined Node will write to the shared data during backward. + // see Note [Thread Safety on Autograd Node] + std::lock_guard lock(mutex_); + + auto outputs = T::backward(&ctx_, backward_inputs); + + const auto num_forward_inputs = + static_cast(is_variable_input_.size()); + auto num_outputs = static_cast(outputs.size()); + // Returning too many results is ok, but only as long as they're all + // undefined. Truncate the result vector in that case. + if (num_outputs > num_forward_inputs) { + bool all_undef = true; + for (const auto i : c10::irange(num_forward_inputs, num_outputs)) { + all_undef &= (!outputs[i].defined()); + } + if (all_undef) { + outputs.resize(num_forward_inputs); + num_outputs = num_forward_inputs; + } + } + + if (num_outputs != num_forward_inputs) { + std::string msg("function "); + msg += name() + " returned an incorrect number of gradients (expected "; + msg += c10::to_string(num_forward_inputs) + ", got "; + msg += c10::to_string(num_outputs) + ")"; + throw std::runtime_error(msg); + } + + // NOLINTNEXTLINE(cppcoreguidelines-init-variables) + variable_list results; + results.reserve(num_outputs); + for (const auto i : c10::irange(num_outputs)) { + if (!is_variable_input_[i]) { + if (outputs[i].defined()) { + std::string msg("function "); + msg += name() + + " returned a gradient different that is defined at position "; + msg += c10::to_string(i + 1) + + ", but the corresponding forward input was not a Variable"; + throw std::runtime_error(msg); + } + continue; + } + results.emplace_back(outputs[i]); + } + return results; +} + +template +void CppNode::release_variables() { + // lock to ensure thread safety, see [Thread Safety on Autograd Node] + std::lock_guard lock(mutex_); + ctx_.saved_variables_.clear(); + ctx_.has_freed_buffers_ = true; +} + +template +void CppNode::save_variables_to_ctx() { + ctx_.save_variables(); +} + +template +void CppNode::set_ctx_grad_fn(const std::shared_ptr& node) { + ctx_.grad_fn_ = node; +} + +} // namespace torch::autograd diff --git a/shared/package-files/01/0171b93b163daf4dd90d216d578f325ec14f5d094c159b43d1c1dc788a70cc88/blob b/shared/package-files/01/0171b93b163daf4dd90d216d578f325ec14f5d094c159b43d1c1dc788a70cc88/blob new file mode 100644 index 0000000000000000000000000000000000000000..e6112637569a0e7c9b749aa076a3bc5598e9e08b --- /dev/null +++ b/shared/package-files/01/0171b93b163daf4dd90d216d578f325ec14f5d094c159b43d1c1dc788a70cc88/blob @@ -0,0 +1,17 @@ +from typing import Any + +http_method_funcs: Any + +class View: + methods: Any = ... + provide_automatic_options: Any = ... + decorators: Any = ... + def dispatch_request(self, *args: Any, **kwargs: Any) -> Any: ... + @classmethod + def as_view(cls, name: Any, *class_args: Any, **class_kwargs: Any): ... + +class MethodViewType(type): + def __init__(self, name: Any, bases: Any, d: Any) -> None: ... + +class MethodView(View, metaclass=MethodViewType): + def dispatch_request(self, *args: Any, **kwargs: Any) -> Any: ... diff --git a/shared/package-files/01/01748f726386dc66458a5795bfd21e5044b4c1be648c34d8cf3b32e5f0b28f81/blob b/shared/package-files/01/01748f726386dc66458a5795bfd21e5044b4c1be648c34d8cf3b32e5f0b28f81/blob new file mode 100644 index 0000000000000000000000000000000000000000..497c34293d95af01ea59a6afac438ffd082c8164 --- /dev/null +++ b/shared/package-files/01/01748f726386dc66458a5795bfd21e5044b4c1be648c34d8cf3b32e5f0b28f81/blob @@ -0,0 +1,10 @@ +import torch + +add_stat_value = torch.ops.prim.AddStatValue + +set_logger = torch._C._logging_set_logger +LockingLogger = torch._C.LockingLogger +AggregationType = torch._C.AggregationType +NoopLogger = torch._C.NoopLogger + +time_point = torch.ops.prim.TimePoint diff --git a/shared/package-files/01/01768756eaea12677400d33801cc9c23ffc32a8ea75a82e183f86e88d18f132d/blob b/shared/package-files/01/01768756eaea12677400d33801cc9c23ffc32a8ea75a82e183f86e88d18f132d/blob new file mode 100644 index 0000000000000000000000000000000000000000..5569125d92112482cfe113e9c796d1136f544305 --- /dev/null +++ b/shared/package-files/01/01768756eaea12677400d33801cc9c23ffc32a8ea75a82e183f86e88d18f132d/blob @@ -0,0 +1,41 @@ +click-8.1.7.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +click-8.1.7.dist-info/LICENSE.rst,sha256=morRBqOU6FO_4h9C9OctWSgZoigF2ZG18ydQKSkrZY0,1475 +click-8.1.7.dist-info/METADATA,sha256=qIMevCxGA9yEmJOM_4WHuUJCwWpsIEVbCPOhs45YPN4,3014 +click-8.1.7.dist-info/RECORD,, +click-8.1.7.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +click-8.1.7.dist-info/WHEEL,sha256=yQN5g4mg4AybRjkgi-9yy4iQEFibGQmlz78Pik5Or-A,92 +click-8.1.7.dist-info/direct_url.json,sha256=RqeFhTh3TqOYxlVpTaxwyzr_67O_sK6JQdepLifQ4uk,65 +click-8.1.7.dist-info/top_level.txt,sha256=J1ZQogalYS4pphY_lPECoNMfw0HzTSrZglC4Yfwo4xA,6 +click/__init__.py,sha256=YDDbjm406dTOA0V8bTtdGnhN7zj5j-_dFRewZF_pLvw,3138 +click/__pycache__/__init__.cpython-310.pyc,, +click/__pycache__/_compat.cpython-310.pyc,, +click/__pycache__/_termui_impl.cpython-310.pyc,, +click/__pycache__/_textwrap.cpython-310.pyc,, +click/__pycache__/_winconsole.cpython-310.pyc,, +click/__pycache__/core.cpython-310.pyc,, +click/__pycache__/decorators.cpython-310.pyc,, +click/__pycache__/exceptions.cpython-310.pyc,, +click/__pycache__/formatting.cpython-310.pyc,, +click/__pycache__/globals.cpython-310.pyc,, +click/__pycache__/parser.cpython-310.pyc,, +click/__pycache__/shell_completion.cpython-310.pyc,, +click/__pycache__/termui.cpython-310.pyc,, +click/__pycache__/testing.cpython-310.pyc,, +click/__pycache__/types.cpython-310.pyc,, +click/__pycache__/utils.cpython-310.pyc,, +click/_compat.py,sha256=5318agQpbt4kroKsbqDOYpTSWzL_YCZVUQiTT04yXmc,18744 +click/_termui_impl.py,sha256=3dFYv4445Nw-rFvZOTBMBPYwB1bxnmNk9Du6Dm_oBSU,24069 +click/_textwrap.py,sha256=10fQ64OcBUMuK7mFvh8363_uoOxPlRItZBmKzRJDgoY,1353 +click/_winconsole.py,sha256=5ju3jQkcZD0W27WEMGqmEP4y_crUVzPCqsX_FYb7BO0,7860 +click/core.py,sha256=j6oEWtGgGna8JarD6WxhXmNnxLnfRjwXglbBc-8jr7U,114086 +click/decorators.py,sha256=-ZlbGYgV-oI8jr_oH4RpuL1PFS-5QmeuEAsLDAYgxtw,18719 +click/exceptions.py,sha256=fyROO-47HWFDjt2qupo7A3J32VlpM-ovJnfowu92K3s,9273 +click/formatting.py,sha256=Frf0-5W33-loyY_i9qrwXR8-STnW3m5gvyxLVUdyxyk,9706 +click/globals.py,sha256=TP-qM88STzc7f127h35TD_v920FgfOD2EwzqA0oE8XU,1961 +click/parser.py,sha256=LKyYQE9ZLj5KgIDXkrcTHQRXIggfoivX14_UVIn56YA,19067 +click/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +click/shell_completion.py,sha256=Ty3VM_ts0sQhj6u7eFTiLwHPoTgcXTGEAUg2OpLqYKw,18460 +click/termui.py,sha256=H7Q8FpmPelhJ2ovOhfCRhjMtCpNyjFXryAMLZODqsdc,28324 +click/testing.py,sha256=1Qd4kS5bucn1hsNIRryd0WtTMuCpkA93grkWxT8POsU,16084 +click/types.py,sha256=TZvz3hKvBztf-Hpa2enOmP4eznSPLzijjig5b_0XMxE,36391 +click/utils.py,sha256=1476UduUNY6UePGU4m18uzVHLt1sKM2PP3yWsQhbItM,20298 diff --git a/shared/package-files/01/017692a97227c0158452beaa98a9d129f67d448623c3714c5e68ae1039fb0501/blob b/shared/package-files/01/017692a97227c0158452beaa98a9d129f67d448623c3714c5e68ae1039fb0501/blob new file mode 100644 index 0000000000000000000000000000000000000000..0bf822509ad9b5749788c0ffaed83433d6317188 --- /dev/null +++ b/shared/package-files/01/017692a97227c0158452beaa98a9d129f67d448623c3714c5e68ae1039fb0501/blob @@ -0,0 +1,23 @@ +#pragma once +// @generated by torchgen/gen.py from DispatchKeyFunction.h + +// NB: The implementing C++ file is RegisterDispatchKey.cpp + +// The only #includes we need are for custom classes that have defaults in the C++ API +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { + +namespace cuda { + +TORCH_API ::std::tuple _scaled_dot_product_cudnn_attention(const at::Tensor & query, const at::Tensor & key, const at::Tensor & value, double dropout_p=0.0, bool is_causal=false, bool return_debug_mask=false, c10::optional scale=c10::nullopt); + +} // namespace cuda +} // namespace at diff --git a/shared/package-files/01/01796244e030182fc57f6721914c6ac1d990c6cc1b436aea193fc00ac696a5f5/blob b/shared/package-files/01/01796244e030182fc57f6721914c6ac1d990c6cc1b436aea193fc00ac696a5f5/blob new file mode 100644 index 0000000000000000000000000000000000000000..306d6b305126a796e9f67c0b69d81ec0f22fad40 --- /dev/null +++ b/shared/package-files/01/01796244e030182fc57f6721914c6ac1d990c6cc1b436aea193fc00ac696a5f5/blob @@ -0,0 +1,35 @@ +# DO NOT EDIT! This file was generated by jschema_to_python version 0.0.1.dev29, +# with extension for dataclasses and type annotation. + +from __future__ import annotations + +import dataclasses +from typing import List, Optional + +from torch.onnx._internal.diagnostics.infra.sarif import ( + _edge, + _message, + _node, + _property_bag, +) + + +@dataclasses.dataclass +class Graph(object): + """A network of nodes and directed edges that describes some aspect of the structure of the code (for example, a call graph).""" + + description: Optional[_message.Message] = dataclasses.field( + default=None, metadata={"schema_property_name": "description"} + ) + edges: Optional[List[_edge.Edge]] = dataclasses.field( + default=None, metadata={"schema_property_name": "edges"} + ) + nodes: Optional[List[_node.Node]] = dataclasses.field( + default=None, metadata={"schema_property_name": "nodes"} + ) + properties: Optional[_property_bag.PropertyBag] = dataclasses.field( + default=None, metadata={"schema_property_name": "properties"} + ) + + +# flake8: noqa diff --git a/shared/package-files/01/017b4a764e0cda97e2ebf282826a640ee8db695b91d6c98d220a73ebff747c84/blob b/shared/package-files/01/017b4a764e0cda97e2ebf282826a640ee8db695b91d6c98d220a73ebff747c84/blob new file mode 100644 index 0000000000000000000000000000000000000000..336dd5c69c6965f4727df75fa096b09d26650ba3 --- /dev/null +++ b/shared/package-files/01/017b4a764e0cda97e2ebf282826a640ee8db695b91d6c98d220a73ebff747c84/blob @@ -0,0 +1,42 @@ +import sys +from typing import IO, Any, Callable, Dict, List, Optional, Sequence, Text, Tuple, Union + +_str = Union[str, Text] +_Timer = Callable[[], float] +_stmt = Union[_str, Callable[[], Any]] + +default_timer: _Timer + +class Timer: + if sys.version_info >= (3, 5): + def __init__( + self, stmt: _stmt = ..., setup: _stmt = ..., timer: _Timer = ..., globals: Optional[Dict[str, Any]] = ... + ) -> None: ... + else: + def __init__(self, stmt: _stmt = ..., setup: _stmt = ..., timer: _Timer = ...) -> None: ... + def print_exc(self, file: Optional[IO[str]] = ...) -> None: ... + def timeit(self, number: int = ...) -> float: ... + def repeat(self, repeat: int = ..., number: int = ...) -> List[float]: ... + if sys.version_info >= (3, 6): + def autorange(self, callback: Optional[Callable[[int, float], Any]] = ...) -> Tuple[int, float]: ... + +if sys.version_info >= (3, 5): + def timeit( + stmt: _stmt = ..., setup: _stmt = ..., timer: _Timer = ..., number: int = ..., globals: Optional[Dict[str, Any]] = ... + ) -> float: ... + def repeat( + stmt: _stmt = ..., + setup: _stmt = ..., + timer: _Timer = ..., + repeat: int = ..., + number: int = ..., + globals: Optional[Dict[str, Any]] = ..., + ) -> List[float]: ... + +else: + def timeit(stmt: _stmt = ..., setup: _stmt = ..., timer: _Timer = ..., number: int = ...) -> float: ... + def repeat( + stmt: _stmt = ..., setup: _stmt = ..., timer: _Timer = ..., repeat: int = ..., number: int = ... + ) -> List[float]: ... + +def main(args: Optional[Sequence[str]]) -> None: ... diff --git a/shared/package-files/01/017ca2ce51bb3436cc7a1332c325a64bc72247da7b5c68e5cc992cd205b7b4c0/blob b/shared/package-files/01/017ca2ce51bb3436cc7a1332c325a64bc72247da7b5c68e5cc992cd205b7b4c0/blob new file mode 100644 index 0000000000000000000000000000000000000000..569fb48625298a6cddb64fefb10bad827b540429 --- /dev/null +++ b/shared/package-files/01/017ca2ce51bb3436cc7a1332c325a64bc72247da7b5c68e5cc992cd205b7b4c0/blob @@ -0,0 +1,1757 @@ +import itertools +import functools +import sys +import operator +from collections import namedtuple + +import numpy as np + +import unittest +import warnings + +from numba import jit, typeof, njit, typed +from numba.core import errors, types, config +from numba.tests.support import (TestCase, tag, ignore_internal_warnings, + MemoryLeakMixin) +from numba.core.extending import (overload_method, box, register_jitable, + overload) + + +forceobj_flags = {'forceobj': True} + +no_pyobj_flags = {'nopython': True, '_nrt': False} + +nrt_no_pyobj_flags = {'nopython': True} + + +def abs_usecase(x): + return abs(x) + +def all_usecase(x, y): + if x == None and y == None: + return all([]) + elif x == None: + return all([y]) + elif y == None: + return all([x]) + else: + return all([x, y]) + +def any_usecase(x, y): + if x == None and y == None: + return any([]) + elif x == None: + return any([y]) + elif y == None: + return any([x]) + else: + return any([x, y]) + +def bool_usecase(x): + return bool(x) + +def complex_usecase(x, y): + return complex(x, y) + +def divmod_usecase(x, y): + return divmod(x, y) + +def enumerate_usecase(): + result = 0 + for i, j in enumerate((1., 2.5, 3.)): + result += i * j + return result + +def enumerate_start_usecase(): + result = 0 + for i, j in enumerate((1., 2.5, 3.), 42): + result += i * j + return result + +def enumerate_invalid_start_usecase(): + result = 0 + for i, j in enumerate((1., 2.5, 3.), 3.14159): + result += i * j + return result + +def filter_usecase(x, filter_func): + return filter(filter_func, x) + +def float_usecase(x): + return float(x) + +def float_inf_usecase(x): + d = { + 0: float('inf'), + 1: float('INF'), + 2: float('-inf'), + 3: float('-INF'), + 4: float('\r\nINF\r '), + 5: float(' \r\n\t-INF'), + 6: float('1234.45'), + 7: float('\n-123.4\r'), + } + return d.get(x) + +def format_usecase(x, y): + return x.format(y) + +def globals_usecase(): + return globals() + +# NOTE: hash() is tested in test_hashing + +def hex_usecase(x): + return hex(x) + +def str_usecase(x): + return str(x) + +def int_usecase(x, base): + return int(x, base=base) + +def iter_next_usecase(x): + it = iter(x) + return next(it), next(it) + +def locals_usecase(x): + y = 5 + return locals()['y'] + +def long_usecase(x, base): + return long(x, base=base) + +def map_usecase(x, map_func): + return map(map_func, x) + + +def max_usecase1(x, y): + return max(x, y) + +def max_usecase2(x, y): + return max([x, y]) + +def max_usecase3(x): + return max(x) + +def max_usecase4(): + return max(()) + + +def min_usecase1(x, y): + return min(x, y) + +def min_usecase2(x, y): + return min([x, y]) + +def min_usecase3(x): + return min(x) + +def min_usecase4(): + return min(()) + +def oct_usecase(x): + return oct(x) + +def reduce_usecase(reduce_func, x): + return functools.reduce(reduce_func, x) + +def round_usecase1(x): + return round(x) + +def round_usecase2(x, n): + return round(x, n) + +def sum_usecase(x): + return sum(x) + +def type_unary_usecase(a, b): + return type(a)(b) + +def truth_usecase(p): + return operator.truth(p) + +def unichr_usecase(x): + return unichr(x) + +def zip_usecase(): + result = 0 + for i, j in zip((1, 2, 3), (4.5, 6.7)): + result += i * j + return result + +def zip_0_usecase(): + result = 0 + for i in zip(): + result += 1 + return result + +def zip_1_usecase(): + result = 0 + for i, in zip((1, 2)): + result += i + return result + + +def zip_3_usecase(): + result = 0 + for i, j, k in zip((1, 2), (3, 4, 5), (6.7, 8.9)): + result += i * j * k + return result + + +def zip_first_exhausted(): + iterable = range(7) + n = 3 + it = iter(iterable) + # 1st iterator is shorter + front = list(zip(range(n), it)) + # Make sure that we didn't skip one in `it` + back = list(it) + return front, back + + +def pow_op_usecase(x, y): + return x ** y + + +def pow_usecase(x, y): + return pow(x, y) + + +def sum_usecase(x): + return sum(x) + + +def sum_kwarg_usecase(x, start=0): + ret = sum(x, start) + return sum(x, start=start), ret + + +def isinstance_usecase(a): + if isinstance(a, (int, float)): + if isinstance(a, int): + return a + 1, 'int' + if isinstance(a, float): + return a + 2.0, 'float' + elif isinstance(a, str): + return a + ", world!", 'str' + elif isinstance(a, complex): + return a.imag, 'complex' + elif isinstance(a, (tuple, list)): + if isinstance(a, tuple): + return 'tuple' + else: + return 'list' + elif isinstance(a, set): + return 'set' + elif isinstance(a, bytes): + return 'bytes' + return 'no match' + + +def isinstance_dict(): + a = {1: 2, 3: 4} + b = {'a': 10, 'b': np.zeros(3)} + if isinstance(a, dict) and isinstance(b, dict): + return 'dict' + else: + return 'not dict' + + +def isinstance_usecase_numba_types(a): + if isinstance(a, typed.List): + return 'typed list' + elif isinstance(a, (types.int32, types.int64)): + if isinstance(a, types.int32): + return 'int32' + else: + return 'int64' + elif isinstance(a, (types.float32, types.float64)): + if isinstance(a, types.float32): + return 'float32' + elif isinstance(a, types.float64): + return 'float64' + elif isinstance(a, typed.Dict): + return 'typed dict' + else: + return 'no match' + + +def isinstance_usecase_numba_types_2(): + # some types cannot be passed as argument to njit functions + a = b'hello' + b = range(1, 2) + c = dict() + c[2] = 3 + if isinstance(a, bytes) and \ + isinstance(b, range) and \ + isinstance(c, dict): + return True + return False + + +def invalid_isinstance_usecase(x): + if isinstance(x, ('foo',)): + return 'true branch' + else: + return 'false branch' + + +def isinstance_usecase_invalid_type(x): + # this should be a valid call when x := float + if isinstance(x, (float, 'not a type')): + return True + else: + return False + + +def invalid_isinstance_usecase_phi_nopropagate(x): + if x > 4: + z = 10 + else: + z = 'a' + if isinstance(z, int): + return True + else: + return False + + +def invalid_isinstance_usecase_phi_nopropagate2(a): + # Numba issue #9125 + x = 0 + if isinstance(a, int): + a = (a, a) + + for i in range(len(a)): + x += i + return x + + +def invalid_isinstance_optional_usecase(x): + if x > 4: + z = 10 + else: + z = None + if isinstance(z, int): + return True + else: + return False + +def invalid_isinstance_unsupported_type_usecase(): + ntpl = namedtuple('ntpl', ['a', 'b']) + inst = ntpl(1, 2) + def impl(x): + return isinstance(inst, ntpl) + return impl + +class TestBuiltins(TestCase): + + def run_nullary_func(self, pyfunc, flags): + cfunc = jit((), **flags)(pyfunc) + expected = pyfunc() + self.assertPreciseEqual(cfunc(), expected) + + def test_abs(self, flags=forceobj_flags): + pyfunc = abs_usecase + + cfunc = jit((types.int32,), **flags)(pyfunc) + for x in [-1, 0, 1]: + self.assertPreciseEqual(cfunc(x), pyfunc(x)) + + cfunc = jit((types.float32,), **flags)(pyfunc) + for x in [-1.1, 0.0, 1.1]: + self.assertPreciseEqual(cfunc(x), pyfunc(x), prec='single') + + complex_values = [-1.1 + 0.5j, 0.0 + 0j, 1.1 + 3j, + float('inf') + 1j * float('nan'), + float('nan') - 1j * float('inf')] + cfunc = jit((types.complex64,), **flags)(pyfunc) + for x in complex_values: + self.assertPreciseEqual(cfunc(x), pyfunc(x), prec='single') + cfunc = jit((types.complex128,), **flags)(pyfunc) + for x in complex_values: + self.assertPreciseEqual(cfunc(x), pyfunc(x)) + + for unsigned_type in types.unsigned_domain: + unsigned_values = [0, 10, 2, 2 ** unsigned_type.bitwidth - 1] + cfunc = jit((unsigned_type,), **flags)(pyfunc) + for x in unsigned_values: + self.assertPreciseEqual(cfunc(x), pyfunc(x)) + + def test_abs_npm(self): + self.test_abs(flags=no_pyobj_flags) + + def test_all(self, flags=forceobj_flags): + pyfunc = all_usecase + + cfunc = jit((types.int32,types.int32), **flags)(pyfunc) + x_operands = [-1, 0, 1, None] + y_operands = [-1, 0, 1, None] + for x, y in itertools.product(x_operands, y_operands): + self.assertPreciseEqual(cfunc(x, y), pyfunc(x, y)) + + def test_all_npm(self): + with self.assertTypingError(): + self.test_all(flags=no_pyobj_flags) + + def test_any(self, flags=forceobj_flags): + pyfunc = any_usecase + + cfunc = jit((types.int32,types.int32), **flags)(pyfunc) + x_operands = [-1, 0, 1, None] + y_operands = [-1, 0, 1, None] + for x, y in itertools.product(x_operands, y_operands): + self.assertPreciseEqual(cfunc(x, y), pyfunc(x, y)) + + def test_any_npm(self): + with self.assertTypingError(): + self.test_any(flags=no_pyobj_flags) + + def test_bool(self, flags=forceobj_flags): + pyfunc = bool_usecase + + cfunc = jit((types.int32,), **flags)(pyfunc) + for x in [-1, 0, 1]: + self.assertPreciseEqual(cfunc(x), pyfunc(x)) + cfunc = jit((types.float64,), **flags)(pyfunc) + for x in [0.0, -0.0, 1.5, float('inf'), float('nan')]: + self.assertPreciseEqual(cfunc(x), pyfunc(x)) + cfunc = jit((types.complex128,), **flags)(pyfunc) + for x in [complex(0, float('inf')), complex(0, float('nan'))]: + self.assertPreciseEqual(cfunc(x), pyfunc(x)) + + def test_bool_npm(self): + self.test_bool(flags=no_pyobj_flags) + + def test_bool_nonnumber(self, flags=forceobj_flags): + pyfunc = bool_usecase + + cfunc = jit((types.string,), **flags)(pyfunc) + for x in ['x', '']: + self.assertPreciseEqual(cfunc(x), pyfunc(x)) + + cfunc = jit((types.Dummy('list'),), **flags)(pyfunc) + for x in [[1], []]: + self.assertPreciseEqual(cfunc(x), pyfunc(x)) + + def test_bool_nonnumber_npm(self): + with self.assertTypingError(): + self.test_bool_nonnumber(flags=no_pyobj_flags) + + def test_complex(self, flags=forceobj_flags): + pyfunc = complex_usecase + + cfunc = jit((types.int32, types.int32), **flags)(pyfunc) + + x_operands = [-1, 0, 1] + y_operands = [-1, 0, 1] + for x, y in itertools.product(x_operands, y_operands): + self.assertPreciseEqual(cfunc(x, y), pyfunc(x, y)) + + def test_complex_npm(self): + self.test_complex(flags=no_pyobj_flags) + + def test_divmod_ints(self, flags=forceobj_flags): + pyfunc = divmod_usecase + + cfunc = jit((types.int64, types.int64), **flags)(pyfunc) + + def truncate_result(x, bits=64): + # Remove any extraneous bits (since Numba will return + # a 64-bit result by definition) + if x >= 0: + x &= (1 << (bits - 1)) - 1 + return x + + denominators = [1, 3, 7, 15, -1, -3, -7, -15, 2**63 - 1, -2**63] + numerators = denominators + [0] + for x, y, in itertools.product(numerators, denominators): + expected_quot, expected_rem = pyfunc(x, y) + quot, rem = cfunc(x, y) + f = truncate_result + self.assertPreciseEqual((f(quot), f(rem)), + (f(expected_quot), f(expected_rem))) + + for x in numerators: + with self.assertRaises(ZeroDivisionError): + cfunc(x, 0) + + def test_divmod_ints_npm(self): + self.test_divmod_ints(flags=no_pyobj_flags) + + def test_divmod_floats(self, flags=forceobj_flags): + pyfunc = divmod_usecase + + cfunc = jit((types.float64, types.float64), **flags)(pyfunc) + + denominators = [1., 3.5, 1e100, -2., -7.5, -1e101, + np.inf, -np.inf, np.nan] + numerators = denominators + [-0.0, 0.0] + for x, y, in itertools.product(numerators, denominators): + expected_quot, expected_rem = pyfunc(x, y) + quot, rem = cfunc(x, y) + self.assertPreciseEqual((quot, rem), (expected_quot, expected_rem)) + + for x in numerators: + with self.assertRaises(ZeroDivisionError): + cfunc(x, 0.0) + + def test_divmod_floats_npm(self): + self.test_divmod_floats(flags=no_pyobj_flags) + + def test_enumerate(self, flags=forceobj_flags): + self.run_nullary_func(enumerate_usecase, flags) + + def test_enumerate_npm(self): + self.test_enumerate(flags=no_pyobj_flags) + + def test_enumerate_start(self, flags=forceobj_flags): + self.run_nullary_func(enumerate_start_usecase, flags) + + def test_enumerate_start_npm(self): + self.test_enumerate_start(flags=no_pyobj_flags) + + def test_enumerate_start_invalid_start_type(self): + pyfunc = enumerate_invalid_start_usecase + + cfunc = jit((), **forceobj_flags)(pyfunc) + + with self.assertRaises(TypeError) as raises: + cfunc() + + msg = "'float' object cannot be interpreted as an integer" + self.assertIn(msg, str(raises.exception)) + + def test_enumerate_start_invalid_start_type_npm(self): + pyfunc = enumerate_invalid_start_usecase + with self.assertRaises(errors.TypingError) as raises: + jit((), **no_pyobj_flags)(pyfunc) + msg = "Only integers supported as start value in enumerate" + self.assertIn(msg, str(raises.exception)) + + def test_filter(self, flags=forceobj_flags): + pyfunc = filter_usecase + argtys = (types.Dummy('list'), types.Dummy('function_ptr')) + cfunc = jit(argtys, **flags)(pyfunc) + + filter_func = lambda x: x % 2 + x = [0, 1, 2, 3, 4] + self.assertSequenceEqual(list(cfunc(x, filter_func)), + list(pyfunc(x, filter_func))) + + def test_filter_npm(self): + with self.assertTypingError(): + self.test_filter(flags=no_pyobj_flags) + + def test_float(self, flags=forceobj_flags): + pyfunc = float_usecase + + cfunc = jit((types.int32,), **flags)(pyfunc) + for x in [-1, 0, 1]: + self.assertPreciseEqual(cfunc(x), pyfunc(x)) + + cfunc = jit((types.float32,), **flags)(pyfunc) + for x in [-1.1, 0.0, 1.1]: + self.assertPreciseEqual(cfunc(x), pyfunc(x), prec='single') + + cfunc = jit((types.string,), **flags)(pyfunc) + for x in ['-1.1', '0.0', '1.1', 'inf', '-inf', 'INF', '-INF']: + self.assertPreciseEqual(cfunc(x), pyfunc(x)) + + def test_float_npm(self): + with self.assertTypingError(): + self.test_float(flags=no_pyobj_flags) + + def test_float_string_literal(self): + pyfunc = float_inf_usecase + cfunc = njit(pyfunc) + for x in range(8): + self.assertPreciseEqual(cfunc(x), pyfunc(x)) + + def test_format(self, flags=forceobj_flags): + pyfunc = format_usecase + + cfunc = jit((types.string, types.int32,), **flags)(pyfunc) + x = '{0}' + for y in [-1, 0, 1]: + self.assertPreciseEqual(cfunc(x, y), pyfunc(x, y)) + + cfunc = jit((types.string, types.float32,), **flags)(pyfunc) + x = '{0}' + for y in [-1.1, 0.0, 1.1]: + self.assertPreciseEqual(cfunc(x, y), pyfunc(x, y)) + + cfunc = jit((types.string, types.string,), **flags)(pyfunc) + x = '{0}' + for y in ['a', 'b', 'c']: + self.assertPreciseEqual(cfunc(x, y), pyfunc(x, y)) + + def test_format_npm(self): + with self.assertTypingError(): + self.test_format(flags=no_pyobj_flags) + + def test_globals(self, flags=forceobj_flags): + pyfunc = globals_usecase + cfunc = jit((), **flags)(pyfunc) + g = cfunc() + self.assertIs(g, globals()) + + def test_globals_npm(self): + with self.assertTypingError(): + self.test_globals(flags=no_pyobj_flags) + + def test_globals_jit(self, flags=forceobj_flags): + # Issue #416: weird behaviour of globals() in combination with + # the @jit decorator. + pyfunc = globals_usecase + jitted = jit(**flags)(pyfunc) + self.assertIs(jitted(), globals()) + self.assertIs(jitted(), globals()) + + def test_globals_jit_npm(self): + with self.assertTypingError(): + self.test_globals_jit(nopython=True) + + def test_hex(self, flags=forceobj_flags): + pyfunc = hex_usecase + + cfunc = jit((types.int32,), **flags)(pyfunc) + for x in [-1, 0, 1]: + self.assertPreciseEqual(cfunc(x), pyfunc(x)) + + def test_hex_npm(self): + with self.assertTypingError(): + self.test_hex(flags=no_pyobj_flags) + + def test_int_str(self): + pyfunc = str_usecase + + small_inputs = [ + 1234, + 1, + 0, + 10, + 1000, + ] + + large_inputs = [ + 123456789, + 2222222, + 1000000, + ~0x0 + ] + + args = [*small_inputs, *large_inputs] + + typs = [ + types.int8, + types.int16, + types.int32, + types.int64, + types.uint, + types.uint8, + types.uint16, + types.uint32, + types.uint64, + ] + + for typ in typs: + cfunc = jit((typ,), **nrt_no_pyobj_flags)(pyfunc) + for v in args: + tp_info = np.iinfo(typ.key) + if not (tp_info.min <= v <= tp_info.max): + continue + self.assertPreciseEqual(cfunc(typ(v)), pyfunc(typ(v))) + + if typ.signed: + self.assertPreciseEqual(cfunc(typ(-v)), pyfunc(typ(-v))) + + def test_int(self, flags=forceobj_flags): + pyfunc = int_usecase + + cfunc = jit((types.string, types.int32,), **flags)(pyfunc) + + x_operands = ['-1', '0', '1', '10'] + y_operands = [2, 8, 10, 16] + for x, y in itertools.product(x_operands, y_operands): + self.assertPreciseEqual(cfunc(x, y), pyfunc(x, y)) + + def test_int_npm(self): + with self.assertTypingError(): + self.test_int(flags=no_pyobj_flags) + + def test_int_kws(self): + cfunc = njit(int_usecase) + with self.assertRaises(errors.TypingError): + cfunc('1234', base=10) + + def test_int_preserve_type_usecase(self): + def pyfunc(x): + return int(x) + + cfunc = njit(pyfunc) + + for typ in [types.int32, types.int64, types.uint32, types.uint64]: + v = typ(1234) + self.assertEqual(cfunc(v), pyfunc(v)) + + for i in range(len(cfunc.signatures)): + sig = cfunc.signatures[i] + ov = cfunc.overloads[sig] + + # Check that the return type is the same as the argument type, + # i.e. that int(x) does not widen the type of x. + self.assertIs(ov.signature.return_type, ov.signature.args[0]) + + def test_iter_next(self, flags=forceobj_flags): + pyfunc = iter_next_usecase + cfunc = jit((types.UniTuple(types.int32, 3),), **flags)(pyfunc) + self.assertPreciseEqual(cfunc((1, 42, 5)), (1, 42)) + + cfunc = jit((types.UniTuple(types.int32, 1),), **flags)(pyfunc) + with self.assertRaises(StopIteration): + cfunc((1,)) + + def test_iter_next_npm(self): + self.test_iter_next(flags=no_pyobj_flags) + + def test_locals(self, flags=forceobj_flags): + pyfunc = locals_usecase + with self.assertRaises(errors.ForbiddenConstruct): + jit((types.int64,), **flags)(pyfunc) + + def test_locals_forceobj(self): + self.test_locals(flags=forceobj_flags) + + def test_locals_npm(self): + with self.assertTypingError(): + self.test_locals(flags=no_pyobj_flags) + + def test_map(self, flags=forceobj_flags): + pyfunc = map_usecase + argtys = (types.Dummy('list'), types.Dummy('function_ptr')) + cfunc = jit(argtys, **flags)(pyfunc) + + map_func = lambda x: x * 2 + x = [0, 1, 2, 3, 4] + self.assertSequenceEqual(list(cfunc(x, map_func)), + list(pyfunc(x, map_func))) + + def test_map_npm(self): + with self.assertTypingError(): + self.test_map(flags=no_pyobj_flags) + + # + # min() and max() + # + + def check_minmax_1(self, pyfunc, flags): + cfunc = jit((types.int32, types.int32), **flags)(pyfunc) + + x_operands = [-1, 0, 1] + y_operands = [-1, 0, 1] + for x, y in itertools.product(x_operands, y_operands): + self.assertPreciseEqual(cfunc(x, y), pyfunc(x, y)) + + def test_max_1(self, flags=forceobj_flags): + """ + max(*args) + """ + self.check_minmax_1(max_usecase1, flags) + + def test_min_1(self, flags=forceobj_flags): + """ + min(*args) + """ + self.check_minmax_1(min_usecase1, flags) + + def test_max_npm_1(self): + self.test_max_1(flags=no_pyobj_flags) + + def test_min_npm_1(self): + self.test_min_1(flags=no_pyobj_flags) + + def check_minmax_2(self, pyfunc, flags): + cfunc = jit((types.int32, types.int32), **flags)(pyfunc) + + x_operands = [-1, 0, 1] + y_operands = [-1, 0, 1] + for x, y in itertools.product(x_operands, y_operands): + self.assertPreciseEqual(cfunc(x, y), pyfunc(x, y)) + + def test_max_2(self, flags=forceobj_flags): + """ + max(list) + """ + self.check_minmax_2(max_usecase2, flags) + + def test_min_2(self, flags=forceobj_flags): + """ + min(list) + """ + self.check_minmax_2(min_usecase2, flags) + + def test_max_npm_2(self): + with self.assertTypingError(): + self.test_max_2(flags=no_pyobj_flags) + + def test_min_npm_2(self): + with self.assertTypingError(): + self.test_min_2(flags=no_pyobj_flags) + + def check_minmax_3(self, pyfunc, flags): + def check(argty): + cfunc = jit((argty,), **flags)(pyfunc) + # Check that the algorithm matches Python's with a non-total order + tup = (1.5, float('nan'), 2.5) + for val in [tup, tup[::-1]]: + self.assertPreciseEqual(cfunc(val), pyfunc(val)) + + check(types.UniTuple(types.float64, 3)) + check(types.Tuple((types.float32, types.float64, types.float32))) + + def test_max_3(self, flags=forceobj_flags): + """ + max(tuple) + """ + self.check_minmax_3(max_usecase3, flags) + + def test_min_3(self, flags=forceobj_flags): + """ + min(tuple) + """ + self.check_minmax_3(min_usecase3, flags) + + def test_max_npm_3(self): + self.test_max_3(flags=no_pyobj_flags) + + def test_min_npm_3(self): + self.test_min_3(flags=no_pyobj_flags) + + def check_min_max_invalid_types(self, pyfunc, flags=forceobj_flags): + cfunc = jit((types.int32, types.Dummy('list'),), **flags)(pyfunc) + cfunc(1, [1]) + + def test_max_1_invalid_types(self): + with self.assertRaises(TypeError): + self.check_min_max_invalid_types(max_usecase1) + + def test_max_1_invalid_types_npm(self): + with self.assertTypingError(): + self.check_min_max_invalid_types(max_usecase1, flags=no_pyobj_flags) + + def test_min_1_invalid_types(self): + with self.assertRaises(TypeError): + self.check_min_max_invalid_types(min_usecase1) + + def test_min_1_invalid_types_npm(self): + with self.assertTypingError(): + self.check_min_max_invalid_types(min_usecase1, flags=no_pyobj_flags) + + def check_minmax_bool1(self, pyfunc, flags): + cfunc = jit((types.bool_, types.bool_), **flags)(pyfunc) + + operands = (False, True) + for x, y in itertools.product(operands, operands): + self.assertPreciseEqual(cfunc(x, y), pyfunc(x, y)) + + def test_max_bool1(self, flags=forceobj_flags): + # tests max() + self.check_minmax_bool1(max_usecase1, flags) + + def test_min_bool1(self, flags=forceobj_flags): + # tests min() + self.check_minmax_bool1(min_usecase1, flags) + + # Test that max(1) and min(1) fail + + def check_min_max_unary_non_iterable(self, pyfunc, flags=forceobj_flags): + cfunc = jit((types.int32,), **flags)(pyfunc) + cfunc(1) + + def test_max_unary_non_iterable(self): + with self.assertRaises(TypeError): + self.check_min_max_unary_non_iterable(max_usecase3) + + def test_max_unary_non_iterable_npm(self): + with self.assertTypingError(): + self.check_min_max_unary_non_iterable(max_usecase3) + + def test_min_unary_non_iterable(self): + with self.assertRaises(TypeError): + self.check_min_max_unary_non_iterable(min_usecase3) + + def test_min_unary_non_iterable_npm(self): + with self.assertTypingError(): + self.check_min_max_unary_non_iterable(min_usecase3) + + # Test that max(()) and min(()) fail + + def check_min_max_empty_tuple(self, pyfunc, func_name): + with self.assertTypingError() as raises: + jit((), **no_pyobj_flags)(pyfunc) + self.assertIn("%s() argument is an empty tuple" % func_name, + str(raises.exception)) + + def test_max_empty_tuple(self): + self.check_min_max_empty_tuple(max_usecase4, "max") + + def test_min_empty_tuple(self): + self.check_min_max_empty_tuple(min_usecase4, "min") + + def check_min_max_type_unification(self, pyfunc, func_name): + with self.assertTypingError() as raises: + njit(pyfunc)(np.bool_(True), np.datetime64('2020', 'Y')) + self.assertIn( + "Given types cannot be unified: [bool, datetime64[Y]]", + str(raises.exception) + ) + + def test_max_type_unification(self): + self.check_min_max_type_unification(max_usecase1, "max") + + def test_min_type_unification(self): + self.check_min_max_type_unification(min_usecase1, "min") + + def test_oct(self, flags=forceobj_flags): + pyfunc = oct_usecase + + cfunc = jit((types.int32,), **flags)(pyfunc) + for x in [-8, -1, 0, 1, 8]: + self.assertPreciseEqual(cfunc(x), pyfunc(x)) + + def test_oct_npm(self): + with self.assertTypingError(): + self.test_oct(flags=no_pyobj_flags) + + def test_reduce(self, flags=forceobj_flags): + pyfunc = reduce_usecase + argtys = (types.Dummy('function_ptr'), types.Dummy('list')) + cfunc = jit(argtys, **flags)(pyfunc) + + reduce_func = lambda x, y: x + y + + x = range(10) + self.assertPreciseEqual(cfunc(reduce_func, x), pyfunc(reduce_func, x)) + + x = [x + x/10.0 for x in range(10)] + self.assertPreciseEqual(cfunc(reduce_func, x), pyfunc(reduce_func, x)) + + x = [complex(x, x) for x in range(10)] + self.assertPreciseEqual(cfunc(reduce_func, x), pyfunc(reduce_func, x)) + + def test_reduce_npm(self): + with self.assertTypingError(): + self.test_reduce(flags=no_pyobj_flags) + + def test_round1(self, flags=forceobj_flags): + pyfunc = round_usecase1 + + for tp in (types.float64, types.float32): + cfunc = jit((tp,), **flags)(pyfunc) + values = [-1.6, -1.5, -1.4, -0.5, 0.0, 0.1, 0.5, 0.6, 1.4, 1.5, 5.0] + values += [-0.1, -0.0] + for x in values: + self.assertPreciseEqual(cfunc(x), pyfunc(x)) + + def test_round1_npm(self): + self.test_round1(flags=no_pyobj_flags) + + def test_round2(self, flags=forceobj_flags): + pyfunc = round_usecase2 + + for tp in (types.float64, types.float32): + prec = 'single' if tp is types.float32 else 'exact' + cfunc = jit((tp, types.int32), **flags)(pyfunc) + for x in [0.0, 0.1, 0.125, 0.25, 0.5, 0.75, 1.25, + 1.5, 1.75, 2.25, 2.5, 2.75, 12.5, 15.0, 22.5]: + for n in (-1, 0, 1, 2): + self.assertPreciseEqual(cfunc(x, n), pyfunc(x, n), + prec=prec) + expected = pyfunc(-x, n) + self.assertPreciseEqual(cfunc(-x, n), pyfunc(-x, n), + prec=prec) + + def test_round2_npm(self): + self.test_round2(flags=no_pyobj_flags) + + def test_sum_objmode(self, flags=forceobj_flags): + pyfunc = sum_usecase + + cfunc = jit((types.Dummy('list'),), **flags)(pyfunc) + + x = range(10) + self.assertPreciseEqual(cfunc(x), pyfunc(x)) + + x = [x + x/10.0 for x in range(10)] + self.assertPreciseEqual(cfunc(x), pyfunc(x)) + + x = [complex(x, x) for x in range(10)] + self.assertPreciseEqual(cfunc(x), pyfunc(x)) + + def test_sum(self): + # In Python 3.8+ "start" can be specified as a kwarg, so test that too + sum_default = njit(sum_usecase) + sum_kwarg = njit(sum_kwarg_usecase) + + @njit + def sum_range(sz, start=0): + tmp = range(sz) + ret = sum(tmp, start) + return sum(tmp, start=start), ret + + ntpl = namedtuple('ntpl', ['a', 'b']) + + # check call with default kwarg, start=0 + def args(): + yield [*range(10)] + yield [x + x/10.0 for x in range(10)] + yield [x * 1j for x in range(10)] + yield (1, 2, 3) + yield (1, 2, 3j) + # uints will likely end up as floats as `start` is signed, so just + # test mixed signed ints + yield (np.int64(32), np.int32(2), np.int8(3)) + tl = typed.List(range(5)) + yield tl + yield np.ones(5) + yield ntpl(100, 200) + yield ntpl(100, 200j) + + for x in args(): + self.assertPreciseEqual(sum_default(x), sum_default.py_func(x)) + + # Check the uint use case, as start is signed, NumPy will end up with + # a float result whereas Numba will end up with an int (see integer + # typing NBEP). + x = (np.uint64(32), np.uint32(2), np.uint8(3)) + self.assertEqual(sum_default(x), sum_default.py_func(x)) + + # check call with changing default kwarg, start + def args_kws(): + yield [*range(10)], 12 + yield [x + x/10.0 for x in range(10)], 19j + yield [x * 1j for x in range(10)], -2 + yield (1, 2, 3), 9 + yield (1, 2, 3j), -0 + # uints will likely end up as floats as `start` is signed, so just + # test mixed signed ints + yield (np.int64(32), np.int32(2), np.int8(3)), np.uint32(7) + tl = typed.List(range(5)) + yield tl, 100 + yield np.ones((5, 5)), 10 * np.ones((5,)) + yield ntpl(100, 200), -50 + yield ntpl(100, 200j), 9 + + for x, start in args_kws(): + self.assertPreciseEqual(sum_kwarg(x, start=start), + sum_kwarg.py_func(x, start=start)) + + # check call with range() + for start in range(-3, 4): + for sz in range(-3, 4): + self.assertPreciseEqual(sum_range(sz, start=start), + sum_range.py_func(sz, start=start)) + + def test_sum_exceptions(self): + sum_default = njit(sum_usecase) + sum_kwarg = njit(sum_kwarg_usecase) + + # check start as string/bytes/bytearray is error + msg = "sum() can't sum {}" + + with self.assertRaises(errors.TypingError) as raises: + sum_kwarg((1, 2, 3), 'a') + + self.assertIn(msg.format('strings'), str(raises.exception)) + + with self.assertRaises(errors.TypingError) as raises: + sum_kwarg((1, 2, 3), b'123') + + self.assertIn(msg.format('bytes'), str(raises.exception)) + + with self.assertRaises(errors.TypingError) as raises: + sum_kwarg((1, 2, 3), bytearray(b'123')) + + self.assertIn(msg.format('bytearray'), str(raises.exception)) + + # check invalid type has no impl + with self.assertRaises(errors.TypingError) as raises: + sum_default('abcd') + + self.assertIn('No implementation', str(raises.exception)) + + def test_truth(self): + pyfunc = truth_usecase + cfunc = jit(nopython=True)(pyfunc) + + self.assertEqual(pyfunc(True), cfunc(True)) + self.assertEqual(pyfunc(False), cfunc(False)) + + def test_type_unary(self): + # Test type(val) and type(val)(other_val) + pyfunc = type_unary_usecase + cfunc = jit(nopython=True)(pyfunc) + + def check(*args): + expected = pyfunc(*args) + self.assertPreciseEqual(cfunc(*args), expected) + + check(1.5, 2) + check(1, 2.5) + check(1.5j, 2) + check(True, 2) + check(2.5j, False) + + def test_zip(self, flags=forceobj_flags): + self.run_nullary_func(zip_usecase, flags) + + def test_zip_npm(self): + self.test_zip(flags=no_pyobj_flags) + + def test_zip_1(self, flags=forceobj_flags): + self.run_nullary_func(zip_1_usecase, flags) + + def test_zip_1_npm(self): + self.test_zip_1(flags=no_pyobj_flags) + + def test_zip_3(self, flags=forceobj_flags): + self.run_nullary_func(zip_3_usecase, flags) + + def test_zip_3_npm(self): + self.test_zip_3(flags=no_pyobj_flags) + + def test_zip_0(self, flags=forceobj_flags): + self.run_nullary_func(zip_0_usecase, flags) + + def test_zip_0_npm(self): + self.test_zip_0(flags=no_pyobj_flags) + + def test_zip_first_exhausted(self, flags=forceobj_flags): + """ + Test side effect to the input iterators when a left iterator has been + exhausted before the ones on the right. + """ + self.run_nullary_func(zip_first_exhausted, flags) + + def test_zip_first_exhausted_npm(self): + self.test_zip_first_exhausted(flags=nrt_no_pyobj_flags) + + def test_pow_op_usecase(self): + args = [ + (2, 3), + (2.0, 3), + (2, 3.0), + (2j, 3.0j), + ] + + for x, y in args: + argtys = (typeof(x), typeof(y)) + cfunc = jit(argtys, **no_pyobj_flags)(pow_op_usecase) + r = cfunc(x, y) + self.assertPreciseEqual(r, pow_op_usecase(x, y)) + + def test_pow_usecase(self): + args = [ + (2, 3), + (2.0, 3), + (2, 3.0), + (2j, 3.0j), + ] + + for x, y in args: + argtys = (typeof(x), typeof(y)) + cfunc = jit(argtys, **no_pyobj_flags)(pow_usecase) + r = cfunc(x, y) + self.assertPreciseEqual(r, pow_usecase(x, y)) + + def _check_min_max(self, pyfunc): + cfunc = njit()(pyfunc) + expected = pyfunc() + got = cfunc() + self.assertPreciseEqual(expected, got) + + def test_min_max_iterable_input(self): + + @njit + def frange(start, stop, step): + i = start + while i < stop: + yield i + i += step + + def sample_functions(op): + yield lambda: op(range(10)) + yield lambda: op(range(4, 12)) + yield lambda: op(range(-4, -15, -1)) + yield lambda: op([6.6, 5.5, 7.7]) + yield lambda: op([(3, 4), (1, 2)]) + yield lambda: op(frange(1.1, 3.3, 0.1)) + yield lambda: op([np.nan, -np.inf, np.inf, np.nan]) + yield lambda: op([(3,), (1,), (2,)]) + + for fn in sample_functions(op=min): + self._check_min_max(fn) + + for fn in sample_functions(op=max): + self._check_min_max(fn) + + +class TestOperatorMixedTypes(TestCase): + + def test_eq_ne(self): + for opstr in ('eq', 'ne'): + op = getattr(operator, opstr) + + @njit + def func(a, b): + return op(a, b) + + # all these things should evaluate to being equal or not, all should + # survive typing. + things = (1, 0, True, False, 1.0, 2.0, 1.1, 1j, None, "", "1") + for x, y in itertools.product(things, things): + self.assertPreciseEqual(func.py_func(x, y), func(x, y)) + + def test_eq_ne_returns_literal_on_none(self): + + def check(operator): + for (x, y) in ((None, None), (None, 1), (1, None)): + + def bar(result): + pass + + @overload(bar, prefer_literal=True) + def ol_bar(result): + # compile expected result + expect = types.literal(operator(x,y)) + # Assert that result has the correct literal_value + self.assertEqual(result, expect) + return lambda result: None + + @jit + def check_eq(x, y): + bar(operator(x, y)) + + check_eq(x, y) + + check(operator.ne) + check(operator.eq) + + def test_10414(self): + # test for https://github.com/numba/numba/issues/10414 + + @njit + def func(x): + a = None + if x: + a = 0 + return a == None, a != None + + self.assertEqual(func(True), func.py_func(True)) + self.assertEqual(func(False), func.py_func(False)) + + def test_cmp(self): + for opstr in ('gt', 'lt', 'ge', 'le', 'eq', 'ne'): + op = getattr(operator, opstr) + @njit + def func(a, b): + return op(a, b) + + # numerical things should all be comparable + things = (1, 0, True, False, 1.0, 0.0, 1.1) + for x, y in itertools.product(things, things): + expected = func.py_func(x, y) + got = func(x, y) + message = ("%s %s %s does not match between Python and Numba" + % (x, opstr, y)) + self.assertEqual(expected, got, message) + + +class TestIsinstanceBuiltin(TestCase): + def test_isinstance(self): + pyfunc = isinstance_usecase + cfunc = jit(nopython=True)(pyfunc) + + inputs = ( + 3, # int + 5.0, # float + "Hello", # string + b'world', # bytes + 1j, # complex + [1, 2, 3], # list + (1, 3, 3, 3), # UniTuple + set([1, 2]), # set + (1, 'nba', 2), # Heterogeneous Tuple + # {'hello': 2}, # dict - doesn't work as input + None, + ) + + for inpt in inputs: + expected = pyfunc(inpt) + got = cfunc(inpt) + self.assertEqual(expected, got) + + def test_isinstance_dict(self): + # Tests typed.Dict and LiteralStrKeyDict + pyfunc = isinstance_dict + cfunc = jit(nopython=True)(pyfunc) + self.assertEqual(pyfunc(), cfunc()) + + def test_isinstance_issue9125(self): + pyfunc = invalid_isinstance_usecase_phi_nopropagate2 + cfunc = jit(nopython=True)(pyfunc) + self.assertEqual(pyfunc(3), cfunc(3)) + + def test_isinstance_numba_types(self): + # This makes use of type aliasing between python scalars and NumPy + # scalars, see also test_numba_types() + pyfunc = isinstance_usecase_numba_types + cfunc = jit(nopython=True)(pyfunc) + + inputs = ( + (types.int32(1), 'int32'), + (types.int64(2), 'int64'), + (types.float32(3.0), 'float32'), + (types.float64(4.0), 'float64'), + (types.complex64(5j), 'no match'), + (typed.List([1, 2]), 'typed list'), + (typed.Dict.empty(types.int64, types.int64), 'typed dict') + ) + + for inpt, expected in inputs: + got = cfunc(inpt) + self.assertEqual(expected, got) + + def test_isinstance_numba_types_2(self): + pyfunc = isinstance_usecase_numba_types_2 + cfunc = jit(nopython=True)(pyfunc) + self.assertEqual(pyfunc(), cfunc()) + + def test_isinstance_invalid_type(self): + pyfunc = isinstance_usecase_invalid_type + cfunc = jit(nopython=True)(pyfunc) + + # valid type + self.assertTrue(cfunc(3.4)) + + # invalid type + msg = 'Cannot infer Numba type of Python type' + + with self.assertRaises(errors.TypingError) as raises: + cfunc(100) + + self.assertIn(msg, str(raises.exception)) + + def test_isinstance_exceptions(self): + fns = [ + (invalid_isinstance_usecase, + 'Cannot infer Numba type of Python type'), + (invalid_isinstance_usecase_phi_nopropagate, + ('isinstance() cannot determine the type of variable "z" due to a ' + 'branch.')), + (invalid_isinstance_optional_usecase, + ('isinstance() cannot determine the type of variable "z" due to a ' + 'branch.')), + (invalid_isinstance_unsupported_type_usecase(), + ('isinstance() does not support variables of type "ntpl(')), + ] + + for fn, msg in fns: + fn = njit(fn) + + with self.assertRaises(errors.TypingError) as raises: + fn(100) + + self.assertIn(msg, str(raises.exception)) + + def test_combinations(self): + # Combinatorically test common classes and instances + def gen_w_arg(clazz_type): + def impl(x): + return isinstance(x, clazz_type) + return impl + + clazz_types = (int, float, complex, str, list, tuple, bytes, set, range, + np.int8, np.float32,) + instances = (1, 2.3, 4j, '5', [6,], (7,), b'8', {9,}, None, + (10, 11, 12), (13, 'a', 14j), np.array([15, 16, 17]), + np.int8(18), np.float32(19), + typed.Dict.empty(types.unicode_type, types.float64), + typed.List.empty_list(types.complex128), np.ones(4)) + + for ct in clazz_types: + fn = njit(gen_w_arg(ct)) + for x in instances: + expected = fn.py_func(x) + got = fn(x) + self.assertEqual(got, expected) + + def test_numba_types(self): + # Check types which are Numba types, this would break without the jit + # decorator in all cases except numba.typed containers. + def gen_w_arg(clazz_type): + def impl(): + return isinstance(1, clazz_type) + return impl + + clazz_types = (types.Integer, types.Float, types.Array,) + + msg = "Numba type classes.*are not supported" + for ct in clazz_types: + fn = njit(gen_w_arg(ct)) + with self.assertRaises(errors.TypingError) as raises: + fn() + self.assertRegex(str(raises.exception), msg) + + def test_python_numpy_scalar_alias_problem(self): + # There's a problem due to Python and NumPy scalars being aliased in the + # type system. This is because e.g. int scalar values and NumPy np.intp + # type alias to types.intp. This test merely records this fact. + + @njit + def foo(): + return isinstance(np.intp(10), int) + + self.assertEqual(foo(), True) + self.assertEqual(foo.py_func(), False) + + @njit + def bar(): + return isinstance(1, np.intp) + + self.assertEqual(bar(), True) + self.assertEqual(bar.py_func(), False) + + def test_branch_prune(self): + # Check that isinstance branches are pruned allowing otherwise + # impossible type specific specialisation. + + @njit + def foo(x): + if isinstance(x, str): + return x + 'some_string' + elif isinstance(x, complex): + return np.imag(x) + elif isinstance(x, tuple): + return len(x) + else: + assert 0 + + for x in ('string', 1 + 2j, ('a', 3, 4j)): + expected = foo.py_func(x) + got = foo(x) + self.assertEqual(got, expected) + + def test_branch_prune_and_bind_to_sig(self): + # see issue 9795 + @register_jitable + def f(x, y): + return x + y + + @njit + def call_f(x): + if isinstance(x, tuple): + return f(*x) + else: + return f(x) + + # The issue is that without isinstance and branch pruning working + # correctly, an attempt will be made to bind the function `f` with + # argument `x`. If `x` is a Tuple type, this will fail on the `else` + # branch as `f` takes two arguments opposed to one. + x = (1, 2) + self.assertEqual(call_f(x), call_f.py_func(x)) + + + # This should raise as partial type inference and branch pruning will + # remove the `f(*x)` branch and just leave `f(x)`, which then won't + # bind because `f` takes two arguments and only one is supplied. + with self.assertRaises(errors.TypingError) as raises: + call_f(1) + + msg = str(raises.exception) + self.assertIn("Cannot bind", msg) + self.assertIn("TypeError: missing a required argument: 'y'", msg) + + def test_branch_prune_non_tuples_as_star_arg(self): + + # see issue 9795 + @register_jitable + def f(x, y): + return x + y + + @register_jitable + def g(x): + return x + + @njit + def call_f(x): + if isinstance(x, tuple): + return f(*x) + else: + return g(x) + + # The issue is that without isinstance and branch pruning working + # correctly, an attempt will be made to bind the function `f` with + # argument `x`. If `x` is a non-tuple type `*x` will not bind to the + # signature of `f`. + x = 1 + self.assertEqual(call_f(x), call_f.py_func(x)) + + def test_branch_prune_literal_as_star_arg(self): + + # see issue 9795 + @register_jitable + def f(x, y): + return x + y + + @register_jitable + def g(x): + return x + + one = 1 + @njit + def call_f(): + x = one + if isinstance(x, tuple): + return f(*x) + else: + return g(x) + + # The issue is that without isinstance and branch pruning working + # correctly, an attempt will be made to bind the function `f` with + # argument `x`. If `x` is a non-tuple const value type `*x` will not + # bind to the signature of `f`. + self.assertEqual(call_f(), call_f.py_func()) + + +class TestGetattrBuiltin(MemoryLeakMixin, TestCase): + # Tests the getattr() builtin + + def test_getattr_func_retty(self): + + @njit + def foo(x): + attr = getattr(x, '__hash__') + return attr() + + for x in (1, 2.34, (5, 6, 7)): + self.assertPreciseEqual(foo(x), foo.py_func(x)) + + def test_getattr_value_retty(self): + + @njit + def foo(x): + return getattr(x, 'ndim') + + for x in range(3): + tmp = np.empty((1, ) * x) + self.assertPreciseEqual(foo(tmp), foo.py_func(tmp)) + + def test_getattr_module_obj(self): + # Consts on modules work ok + + @njit + def foo(): + return getattr(np, 'pi') + + self.assertPreciseEqual(foo(), foo.py_func()) + + def test_getattr_module_obj_not_implemented(self): + # Functions on modules do not work at present + + @njit + def foo(): + return getattr(np, 'cos')(1) + + with self.assertRaises(errors.TypingError) as raises: + foo() + + msg = "Returning function objects is not implemented" + self.assertIn(msg, str(raises.exception)) + + def test_getattr_raises_attribute_error(self): + + invalid_attr = '__not_a_valid_attr__' + + @njit + def foo(x): + return getattr(x, invalid_attr) + + with self.assertRaises(AttributeError) as raises: + foo(1.23) + + self.assertIn(f"'float64' has no attribute '{invalid_attr}'", + str(raises.exception)) + + def test_getattr_with_default(self): + # Checks returning a default works + + @njit + def foo(x, default): + return getattr(x, '__not_a_valid_attr__', default) + + for x, y in zip((1, 2.34, (5, 6, 7),), (None, 20, 'some_string')): + self.assertPreciseEqual(foo(x, y), foo.py_func(x, y)) + + def test_getattr_non_literal_str(self): + + @njit + def foo(x, nonliteral_str): + return getattr(x, nonliteral_str) + + with self.assertRaises(errors.TypingError) as raises: + foo(1, '__hash__') + + msg = "argument 'name' must be a literal string" + self.assertIn(msg, str(raises.exception)) + + def test_getattr_no_optional_type_generated(self): + + @njit + def default_hash(): + return 12345 + + @njit + def foo(): + hash_func = getattr(np.ones(1), "__not_a_valid_attr__", + default_hash) + return hash_func() # Optionals have no call support + + self.assertPreciseEqual(foo(), foo.py_func()) + + +class TestHasattrBuiltin(MemoryLeakMixin, TestCase): + # Tests the hasattr() builtin + + def test_hasattr(self): + + @njit + def foo(x): + return hasattr(x, '__hash__'), hasattr(x, '__not_a_valid_attr__') + + ty = types.int64 + for x in (1, 2.34, (5, 6, 7), typed.Dict.empty(ty, ty), + typed.List.empty_list(ty), np.ones(4), 'ABC'): + self.assertPreciseEqual(foo(x), foo.py_func(x)) + + def test_hasattr_non_const_attr(self): + # This tests that an error is raised in the case that a hasattr() call + # is made on an attribute that cannot be resolved as a compile time + # constant (there's a phi in the way!). + + @njit + def foo(pred): + if pred > 3: + attr = "__hash__" + else: + attr = "__str__" + + hasattr(1, attr) + + with self.assertRaises(errors.NumbaTypeError) as raises: + foo(6) + + msg = ('hasattr() cannot determine the type of variable ' + '"attr" due to a branch.') + self.assertIn(msg, str(raises.exception)) + + +class TestStrAndReprBuiltin(MemoryLeakMixin, TestCase): + + def test_str_default(self): + + @njit + def foo(): + return str() + + self.assertEqual(foo(), foo.py_func()) + + def test_str_object_kwarg(self): + + @njit + def foo(x): + return str(object=x) + + value = "a string" + self.assertEqual(foo(value), foo.py_func(value)) + + def test_str_calls_dunder_str(self): + + @njit + def foo(x): + return str(x) + + Dummy, DummyType = self.make_dummy_type() + dummy = Dummy() + string_repr = "this is the dummy object str" + Dummy.__str__= lambda inst: string_repr + + @overload_method(DummyType, "__str__") + def ol_dummy_string(dummy): + def impl(dummy): + return string_repr + return impl + + @overload_method(DummyType, "__repr__") + def ol_dummy_repr(dummy): + def impl(dummy): + return "SHOULD NOT BE CALLED" + return impl + + self.assertEqual(foo(dummy), foo.py_func(dummy)) + + def test_str_falls_back_to_repr(self): + + @njit + def foo(x): + return str(x) + + Dummy, DummyType = self.make_dummy_type() + dummy = Dummy() + string_repr = "this is the dummy object repr" + Dummy.__repr__= lambda inst: string_repr + + @overload_method(DummyType, "__repr__") + def ol_dummy_repr(dummy): + def impl(dummy): + return string_repr + return impl + + self.assertEqual(foo(dummy), foo.py_func(dummy)) + + def test_repr(self): + @njit + def foo(x): + return repr(x), x + + for x in ("abc", False, 123): + self.assertEqual(foo(x), foo.py_func(x)) + + def test_repr_fallback(self): + # checks str/repr fallback, there's no overloaded __str__ or __repr__ + # for the dummy type so it has to use generic '' + # string for the `repr` call. + + Dummy, DummyType = self.make_dummy_type() + dummy = Dummy() + string_repr = f"" + Dummy.__repr__= lambda inst: string_repr + + @box(DummyType) + def box_dummy(typ, obj, c): + clazobj = c.pyapi.unserialize(c.pyapi.serialize_object(Dummy)) + return c.pyapi.call_function_objargs(clazobj, ()) + + @njit + def foo(x): + return str(x) + + self.assertEqual(foo(dummy), foo.py_func(dummy)) + + + +if __name__ == '__main__': + unittest.main() diff --git a/shared/package-files/01/017d7b1a287153ceee6ac408c4ea7bd1f2b8698237caa9aa181c8dbb305caea4/blob b/shared/package-files/01/017d7b1a287153ceee6ac408c4ea7bd1f2b8698237caa9aa181c8dbb305caea4/blob new file mode 100644 index 0000000000000000000000000000000000000000..dadb226324d23dd02ab0b03b26277215869c67dc Binary files /dev/null and b/shared/package-files/01/017d7b1a287153ceee6ac408c4ea7bd1f2b8698237caa9aa181c8dbb305caea4/blob differ diff --git a/shared/package-files/01/017e6affd6c3011b42d30ddb14d9a134a1aa7b75fb365a6b644bcc09b57fbccb/blob b/shared/package-files/01/017e6affd6c3011b42d30ddb14d9a134a1aa7b75fb365a6b644bcc09b57fbccb/blob new file mode 100644 index 0000000000000000000000000000000000000000..71c0c0f8070515ddf1b1584ec12213f4c2336d98 --- /dev/null +++ b/shared/package-files/01/017e6affd6c3011b42d30ddb14d9a134a1aa7b75fb365a6b644bcc09b57fbccb/blob @@ -0,0 +1,1080 @@ +from __future__ import annotations +import re +import typing +from itertools import product +from typing import Any, Callable + +import sympy +from sympy import Mul, Add, Pow, log, exp, sqrt, cos, sin, tan, asin, acos, acot, asec, acsc, sinh, cosh, tanh, asinh, \ + acosh, atanh, acoth, asech, acsch, expand, im, flatten, polylog, cancel, expand_trig, sign, simplify, \ + UnevaluatedExpr, S, atan, atan2, Mod, Max, Min, rf, Ei, Si, Ci, airyai, airyaiprime, airybi, primepi, prime, \ + isprime, cot, sec, csc, csch, sech, coth, Function, I, pi, Tuple, GreaterThan, StrictGreaterThan, StrictLessThan, \ + LessThan, Equality, Or, And, Lambda, Integer, Dummy, symbols +from sympy.core.sympify import sympify, _sympify +from sympy.functions.special.bessel import airybiprime +from sympy.functions.special.error_functions import li +from sympy.utilities.exceptions import sympy_deprecation_warning + + +def mathematica(s, additional_translations=None): + sympy_deprecation_warning( + """The ``mathematica`` function for the Mathematica parser is now +deprecated. Use ``parse_mathematica`` instead. +The parameter ``additional_translation`` can be replaced by SymPy's +.replace( ) or .subs( ) methods on the output expression instead.""", + deprecated_since_version="1.11", + active_deprecations_target="mathematica-parser-new", + ) + parser = MathematicaParser(additional_translations) + return sympify(parser._parse_old(s)) + + +def parse_mathematica(s): + """ + Translate a string containing a Wolfram Mathematica expression to a SymPy + expression. + + If the translator is unable to find a suitable SymPy expression, the + ``FullForm`` of the Mathematica expression will be output, using SymPy + ``Function`` objects as nodes of the syntax tree. + + Examples + ======== + + >>> from sympy.parsing.mathematica import parse_mathematica + >>> parse_mathematica("Sin[x]^2 Tan[y]") + sin(x)**2*tan(y) + >>> e = parse_mathematica("F[7,5,3]") + >>> e + F(7, 5, 3) + >>> from sympy import Function, Max, Min + >>> e.replace(Function("F"), lambda *x: Max(*x)*Min(*x)) + 21 + + Both standard input form and Mathematica full form are supported: + + >>> parse_mathematica("x*(a + b)") + x*(a + b) + >>> parse_mathematica("Times[x, Plus[a, b]]") + x*(a + b) + + To get a matrix from Wolfram's code: + + >>> m = parse_mathematica("{{a, b}, {c, d}}") + >>> m + ((a, b), (c, d)) + >>> from sympy import Matrix + >>> Matrix(m) + Matrix([ + [a, b], + [c, d]]) + + If the translation into equivalent SymPy expressions fails, an SymPy + expression equivalent to Wolfram Mathematica's "FullForm" will be created: + + >>> parse_mathematica("x_.") + Optional(Pattern(x, Blank())) + >>> parse_mathematica("Plus @@ {x, y, z}") + Apply(Plus, (x, y, z)) + >>> parse_mathematica("f[x_, 3] := x^3 /; x > 0") + SetDelayed(f(Pattern(x, Blank()), 3), Condition(x**3, x > 0)) + """ + parser = MathematicaParser() + return parser.parse(s) + + +def _parse_Function(*args): + if len(args) == 1: + arg = args[0] + Slot = Function("Slot") + slots = arg.atoms(Slot) + numbers = [a.args[0] for a in slots] + number_of_arguments = max(numbers) + if isinstance(number_of_arguments, Integer): + variables = symbols(f"dummy0:{number_of_arguments}", cls=Dummy) + return Lambda(variables, arg.xreplace({Slot(i+1): v for i, v in enumerate(variables)})) + return Lambda((), arg) + elif len(args) == 2: + variables = args[0] + body = args[1] + return Lambda(variables, body) + else: + raise SyntaxError("Function node expects 1 or 2 arguments") + + +def _deco(cls): + cls._initialize_class() + return cls + + +@_deco +class MathematicaParser: + """ + An instance of this class converts a string of a Wolfram Mathematica + expression to a SymPy expression. + + The main parser acts internally in three stages: + + 1. tokenizer: tokenizes the Mathematica expression and adds the missing * + operators. Handled by ``_from_mathematica_to_tokens(...)`` + 2. full form list: sort the list of strings output by the tokenizer into a + syntax tree of nested lists and strings, equivalent to Mathematica's + ``FullForm`` expression output. This is handled by the function + ``_from_tokens_to_fullformlist(...)``. + 3. SymPy expression: the syntax tree expressed as full form list is visited + and the nodes with equivalent classes in SymPy are replaced. Unknown + syntax tree nodes are cast to SymPy ``Function`` objects. This is + handled by ``_from_fullformlist_to_sympy(...)``. + + """ + + # left: Mathematica, right: SymPy + CORRESPONDENCES = { + 'Sqrt[x]': 'sqrt(x)', + 'Exp[x]': 'exp(x)', + 'Log[x]': 'log(x)', + 'Log[x,y]': 'log(y,x)', + 'Log2[x]': 'log(x,2)', + 'Log10[x]': 'log(x,10)', + 'Mod[x,y]': 'Mod(x,y)', + 'Max[*x]': 'Max(*x)', + 'Min[*x]': 'Min(*x)', + 'Pochhammer[x,y]':'rf(x,y)', + 'ArcTan[x,y]':'atan2(y,x)', + 'ExpIntegralEi[x]': 'Ei(x)', + 'SinIntegral[x]': 'Si(x)', + 'CosIntegral[x]': 'Ci(x)', + 'AiryAi[x]': 'airyai(x)', + 'AiryAiPrime[x]': 'airyaiprime(x)', + 'AiryBi[x]' :'airybi(x)', + 'AiryBiPrime[x]' :'airybiprime(x)', + 'LogIntegral[x]':' li(x)', + 'PrimePi[x]': 'primepi(x)', + 'Prime[x]': 'prime(x)', + 'PrimeQ[x]': 'isprime(x)' + } + + # trigonometric, e.t.c. + for arc, tri, h in product(('', 'Arc'), ( + 'Sin', 'Cos', 'Tan', 'Cot', 'Sec', 'Csc'), ('', 'h')): + fm = arc + tri + h + '[x]' + if arc: # arc func + fs = 'a' + tri.lower() + h + '(x)' + else: # non-arc func + fs = tri.lower() + h + '(x)' + CORRESPONDENCES.update({fm: fs}) + + REPLACEMENTS = { + ' ': '', + '^': '**', + '{': '[', + '}': ']', + } + + RULES = { + # a single whitespace to '*' + 'whitespace': ( + re.compile(r''' + (?:(?<=[a-zA-Z\d])|(?<=\d\.)) # a letter or a number + \s+ # any number of whitespaces + (?:(?=[a-zA-Z\d])|(?=\.\d)) # a letter or a number + ''', re.VERBOSE), + '*'), + + # add omitted '*' character + 'add*_1': ( + re.compile(r''' + (?:(?<=[])\d])|(?<=\d\.)) # ], ) or a number + # '' + (?=[(a-zA-Z]) # ( or a single letter + ''', re.VERBOSE), + '*'), + + # add omitted '*' character (variable letter preceding) + 'add*_2': ( + re.compile(r''' + (?<=[a-zA-Z]) # a letter + \( # ( as a character + (?=.) # any characters + ''', re.VERBOSE), + '*('), + + # convert 'Pi' to 'pi' + 'Pi': ( + re.compile(r''' + (?: + \A|(?<=[^a-zA-Z]) + ) + Pi # 'Pi' is 3.14159... in Mathematica + (?=[^a-zA-Z]) + ''', re.VERBOSE), + 'pi'), + } + + # Mathematica function name pattern + FM_PATTERN = re.compile(r''' + (?: + \A|(?<=[^a-zA-Z]) # at the top or a non-letter + ) + [A-Z][a-zA-Z\d]* # Function + (?=\[) # [ as a character + ''', re.VERBOSE) + + # list or matrix pattern (for future usage) + ARG_MTRX_PATTERN = re.compile(r''' + \{.*\} + ''', re.VERBOSE) + + # regex string for function argument pattern + ARGS_PATTERN_TEMPLATE = r''' + (?: + \A|(?<=[^a-zA-Z]) + ) + {arguments} # model argument like x, y,... + (?=[^a-zA-Z]) + ''' + + # will contain transformed CORRESPONDENCES dictionary + TRANSLATIONS: dict[tuple[str, int], dict[str, Any]] = {} + + # cache for a raw users' translation dictionary + cache_original: dict[tuple[str, int], dict[str, Any]] = {} + + # cache for a compiled users' translation dictionary + cache_compiled: dict[tuple[str, int], dict[str, Any]] = {} + + @classmethod + def _initialize_class(cls): + # get a transformed CORRESPONDENCES dictionary + d = cls._compile_dictionary(cls.CORRESPONDENCES) + cls.TRANSLATIONS.update(d) + + def __init__(self, additional_translations=None): + self.translations = {} + + # update with TRANSLATIONS (class constant) + self.translations.update(self.TRANSLATIONS) + + if additional_translations is None: + additional_translations = {} + + # check the latest added translations + if self.__class__.cache_original != additional_translations: + if not isinstance(additional_translations, dict): + raise ValueError('The argument must be dict type') + + # get a transformed additional_translations dictionary + d = self._compile_dictionary(additional_translations) + + # update cache + self.__class__.cache_original = additional_translations + self.__class__.cache_compiled = d + + # merge user's own translations + self.translations.update(self.__class__.cache_compiled) + + @classmethod + def _compile_dictionary(cls, dic): + # for return + d = {} + + for fm, fs in dic.items(): + # check function form + cls._check_input(fm) + cls._check_input(fs) + + # uncover '*' hiding behind a whitespace + fm = cls._apply_rules(fm, 'whitespace') + fs = cls._apply_rules(fs, 'whitespace') + + # remove whitespace(s) + fm = cls._replace(fm, ' ') + fs = cls._replace(fs, ' ') + + # search Mathematica function name + m = cls.FM_PATTERN.search(fm) + + # if no-hit + if m is None: + err = "'{f}' function form is invalid.".format(f=fm) + raise ValueError(err) + + # get Mathematica function name like 'Log' + fm_name = m.group() + + # get arguments of Mathematica function + args, end = cls._get_args(m) + + # function side check. (e.g.) '2*Func[x]' is invalid. + if m.start() != 0 or end != len(fm): + err = "'{f}' function form is invalid.".format(f=fm) + raise ValueError(err) + + # check the last argument's 1st character + if args[-1][0] == '*': + key_arg = '*' + else: + key_arg = len(args) + + key = (fm_name, key_arg) + + # convert '*x' to '\\*x' for regex + re_args = [x if x[0] != '*' else '\\' + x for x in args] + + # for regex. Example: (?:(x|y|z)) + xyz = '(?:(' + '|'.join(re_args) + '))' + + # string for regex compile + patStr = cls.ARGS_PATTERN_TEMPLATE.format(arguments=xyz) + + pat = re.compile(patStr, re.VERBOSE) + + # update dictionary + d[key] = {} + d[key]['fs'] = fs # SymPy function template + d[key]['args'] = args # args are ['x', 'y'] for example + d[key]['pat'] = pat + + return d + + def _convert_function(self, s): + '''Parse Mathematica function to SymPy one''' + + # compiled regex object + pat = self.FM_PATTERN + + scanned = '' # converted string + cur = 0 # position cursor + while True: + m = pat.search(s) + + if m is None: + # append the rest of string + scanned += s + break + + # get Mathematica function name + fm = m.group() + + # get arguments, and the end position of fm function + args, end = self._get_args(m) + + # the start position of fm function + bgn = m.start() + + # convert Mathematica function to SymPy one + s = self._convert_one_function(s, fm, args, bgn, end) + + # update cursor + cur = bgn + + # append converted part + scanned += s[:cur] + + # shrink s + s = s[cur:] + + return scanned + + def _convert_one_function(self, s, fm, args, bgn, end): + # no variable-length argument + if (fm, len(args)) in self.translations: + key = (fm, len(args)) + + # x, y,... model arguments + x_args = self.translations[key]['args'] + + # make CORRESPONDENCES between model arguments and actual ones + d = {k: v for k, v in zip(x_args, args)} + + # with variable-length argument + elif (fm, '*') in self.translations: + key = (fm, '*') + + # x, y,..*args (model arguments) + x_args = self.translations[key]['args'] + + # make CORRESPONDENCES between model arguments and actual ones + d = {} + for i, x in enumerate(x_args): + if x[0] == '*': + d[x] = ','.join(args[i:]) + break + d[x] = args[i] + + # out of self.translations + else: + err = "'{f}' is out of the whitelist.".format(f=fm) + raise ValueError(err) + + # template string of converted function + template = self.translations[key]['fs'] + + # regex pattern for x_args + pat = self.translations[key]['pat'] + + scanned = '' + cur = 0 + while True: + m = pat.search(template) + + if m is None: + scanned += template + break + + # get model argument + x = m.group() + + # get a start position of the model argument + xbgn = m.start() + + # add the corresponding actual argument + scanned += template[:xbgn] + d[x] + + # update cursor to the end of the model argument + cur = m.end() + + # shrink template + template = template[cur:] + + # update to swapped string + s = s[:bgn] + scanned + s[end:] + + return s + + @classmethod + def _get_args(cls, m): + '''Get arguments of a Mathematica function''' + + s = m.string # whole string + anc = m.end() + 1 # pointing the first letter of arguments + square, curly = [], [] # stack for brakets + args = [] + + # current cursor + cur = anc + for i, c in enumerate(s[anc:], anc): + # extract one argument + if c == ',' and (not square) and (not curly): + args.append(s[cur:i]) # add an argument + cur = i + 1 # move cursor + + # handle list or matrix (for future usage) + if c == '{': + curly.append(c) + elif c == '}': + curly.pop() + + # seek corresponding ']' with skipping irrevant ones + if c == '[': + square.append(c) + elif c == ']': + if square: + square.pop() + else: # empty stack + args.append(s[cur:i]) + break + + # the next position to ']' bracket (the function end) + func_end = i + 1 + + return args, func_end + + @classmethod + def _replace(cls, s, bef): + aft = cls.REPLACEMENTS[bef] + s = s.replace(bef, aft) + return s + + @classmethod + def _apply_rules(cls, s, bef): + pat, aft = cls.RULES[bef] + return pat.sub(aft, s) + + @classmethod + def _check_input(cls, s): + for bracket in (('[', ']'), ('{', '}'), ('(', ')')): + if s.count(bracket[0]) != s.count(bracket[1]): + err = "'{f}' function form is invalid.".format(f=s) + raise ValueError(err) + + if '{' in s: + err = "Currently list is not supported." + raise ValueError(err) + + def _parse_old(self, s): + # input check + self._check_input(s) + + # uncover '*' hiding behind a whitespace + s = self._apply_rules(s, 'whitespace') + + # remove whitespace(s) + s = self._replace(s, ' ') + + # add omitted '*' character + s = self._apply_rules(s, 'add*_1') + s = self._apply_rules(s, 'add*_2') + + # translate function + s = self._convert_function(s) + + # '^' to '**' + s = self._replace(s, '^') + + # 'Pi' to 'pi' + s = self._apply_rules(s, 'Pi') + + # '{', '}' to '[', ']', respectively +# s = cls._replace(s, '{') # currently list is not taken into account +# s = cls._replace(s, '}') + + return s + + def parse(self, s): + s2 = self._from_mathematica_to_tokens(s) + s3 = self._from_tokens_to_fullformlist(s2) + s4 = self._from_fullformlist_to_sympy(s3) + return s4 + + INFIX = "Infix" + PREFIX = "Prefix" + POSTFIX = "Postfix" + FLAT = "Flat" + RIGHT = "Right" + LEFT = "Left" + + _mathematica_op_precedence: list[tuple[str, str | None, dict[str, str | Callable]]] = [ + (POSTFIX, None, {";": lambda x: x + ["Null"] if isinstance(x, list) and x and x[0] == "CompoundExpression" else ["CompoundExpression", x, "Null"]}), + (INFIX, FLAT, {";": "CompoundExpression"}), + (INFIX, RIGHT, {"=": "Set", ":=": "SetDelayed", "+=": "AddTo", "-=": "SubtractFrom", "*=": "TimesBy", "/=": "DivideBy"}), + (INFIX, LEFT, {"//": lambda x, y: [x, y]}), + (POSTFIX, None, {"&": "Function"}), + (INFIX, LEFT, {"/.": "ReplaceAll"}), + (INFIX, RIGHT, {"->": "Rule", ":>": "RuleDelayed"}), + (INFIX, LEFT, {"/;": "Condition"}), + (INFIX, FLAT, {"|": "Alternatives"}), + (POSTFIX, None, {"..": "Repeated", "...": "RepeatedNull"}), + (INFIX, FLAT, {"||": "Or"}), + (INFIX, FLAT, {"&&": "And"}), + (PREFIX, None, {"!": "Not"}), + (INFIX, FLAT, {"===": "SameQ", "=!=": "UnsameQ"}), + (INFIX, FLAT, {"==": "Equal", "!=": "Unequal", "<=": "LessEqual", "<": "Less", ">=": "GreaterEqual", ">": "Greater"}), + (INFIX, None, {";;": "Span"}), + (INFIX, FLAT, {"+": "Plus", "-": "Plus"}), + (INFIX, FLAT, {"*": "Times", "/": "Times"}), + (INFIX, FLAT, {".": "Dot"}), + (PREFIX, None, {"-": lambda x: MathematicaParser._get_neg(x), + "+": lambda x: x}), + (INFIX, RIGHT, {"^": "Power"}), + (INFIX, RIGHT, {"@@": "Apply", "/@": "Map", "//@": "MapAll", "@@@": lambda x, y: ["Apply", x, y, ["List", "1"]]}), + (POSTFIX, None, {"'": "Derivative", "!": "Factorial", "!!": "Factorial2", "--": "Decrement"}), + (INFIX, None, {"[": lambda x, y: [x, *y], "[[": lambda x, y: ["Part", x, *y]}), + (PREFIX, None, {"{": lambda x: ["List", *x], "(": lambda x: x[0]}), + (INFIX, None, {"?": "PatternTest"}), + (POSTFIX, None, { + "_": lambda x: ["Pattern", x, ["Blank"]], + "_.": lambda x: ["Optional", ["Pattern", x, ["Blank"]]], + "__": lambda x: ["Pattern", x, ["BlankSequence"]], + "___": lambda x: ["Pattern", x, ["BlankNullSequence"]], + }), + (INFIX, None, {"_": lambda x, y: ["Pattern", x, ["Blank", y]]}), + (PREFIX, None, {"#": "Slot", "##": "SlotSequence"}), + ] + + _missing_arguments_default = { + "#": lambda: ["Slot", "1"], + "##": lambda: ["SlotSequence", "1"], + } + + _literal = r"[A-Za-z][A-Za-z0-9]*" + _number = r"(?:[0-9]+(?:\.[0-9]*)?|\.[0-9]+)" + + _enclosure_open = ["(", "[", "[[", "{"] + _enclosure_close = [")", "]", "]]", "}"] + + @classmethod + def _get_neg(cls, x): + return f"-{x}" if isinstance(x, str) and re.match(MathematicaParser._number, x) else ["Times", "-1", x] + + @classmethod + def _get_inv(cls, x): + return ["Power", x, "-1"] + + _regex_tokenizer = None + + def _get_tokenizer(self): + if self._regex_tokenizer is not None: + # Check if the regular expression has already been compiled: + return self._regex_tokenizer + tokens = [self._literal, self._number] + tokens_escape = self._enclosure_open[:] + self._enclosure_close[:] + for typ, strat, symdict in self._mathematica_op_precedence: + for k in symdict: + tokens_escape.append(k) + tokens_escape.sort(key=lambda x: -len(x)) + tokens.extend(map(re.escape, tokens_escape)) + tokens.append(",") + tokens.append("\n") + tokenizer = re.compile("(" + "|".join(tokens) + ")") + self._regex_tokenizer = tokenizer + return self._regex_tokenizer + + def _from_mathematica_to_tokens(self, code: str): + tokenizer = self._get_tokenizer() + + # Find strings: + code_splits: list[str | list] = [] + while True: + string_start = code.find("\"") + if string_start == -1: + if len(code) > 0: + code_splits.append(code) + break + match_end = re.search(r'(? 0: + code_splits.append(code[:string_start]) + code_splits.append(["_Str", code[string_start+1:string_end].replace('\\"', '"')]) + code = code[string_end+1:] + + # Remove comments: + for i, code_split in enumerate(code_splits): + if isinstance(code_split, list): + continue + while True: + pos_comment_start = code_split.find("(*") + if pos_comment_start == -1: + break + pos_comment_end = code_split.find("*)") + if pos_comment_end == -1 or pos_comment_end < pos_comment_start: + raise SyntaxError("mismatch in comment (* *) code") + code_split = code_split[:pos_comment_start] + code_split[pos_comment_end+2:] + code_splits[i] = code_split + + # Tokenize the input strings with a regular expression: + token_lists = [tokenizer.findall(i) if isinstance(i, str) and i.isascii() else [i] for i in code_splits] + tokens = [j for i in token_lists for j in i] + + # Remove newlines at the beginning + while tokens and tokens[0] == "\n": + tokens.pop(0) + # Remove newlines at the end + while tokens and tokens[-1] == "\n": + tokens.pop(-1) + + return tokens + + def _is_op(self, token: str | list) -> bool: + if isinstance(token, list): + return False + if re.match(self._literal, token): + return False + if re.match("-?" + self._number, token): + return False + return True + + def _is_valid_star1(self, token: str | list) -> bool: + if token in (")", "}"): + return True + return not self._is_op(token) + + def _is_valid_star2(self, token: str | list) -> bool: + if token in ("(", "{"): + return True + return not self._is_op(token) + + def _from_tokens_to_fullformlist(self, tokens: list): + stack: list[list] = [[]] + open_seq = [] + pointer: int = 0 + while pointer < len(tokens): + token = tokens[pointer] + if token in self._enclosure_open: + stack[-1].append(token) + open_seq.append(token) + stack.append([]) + elif token == ",": + if len(stack[-1]) == 0 and stack[-2][-1] == open_seq[-1]: + raise SyntaxError("%s cannot be followed by comma ," % open_seq[-1]) + stack[-1] = self._parse_after_braces(stack[-1]) + stack.append([]) + elif token in self._enclosure_close: + ind = self._enclosure_close.index(token) + if self._enclosure_open[ind] != open_seq[-1]: + unmatched_enclosure = SyntaxError("unmatched enclosure") + if token == "]]" and open_seq[-1] == "[": + if open_seq[-2] == "[": + # These two lines would be logically correct, but are + # unnecessary: + # token = "]" + # tokens[pointer] = "]" + tokens.insert(pointer+1, "]") + elif open_seq[-2] == "[[": + if tokens[pointer+1] == "]": + tokens[pointer+1] = "]]" + elif tokens[pointer+1] == "]]": + tokens[pointer+1] = "]]" + tokens.insert(pointer+2, "]") + else: + raise unmatched_enclosure + else: + raise unmatched_enclosure + if len(stack[-1]) == 0 and stack[-2][-1] == "(": + raise SyntaxError("( ) not valid syntax") + last_stack = self._parse_after_braces(stack[-1], True) + stack[-1] = last_stack + new_stack_element = [] + while stack[-1][-1] != open_seq[-1]: + new_stack_element.append(stack.pop()) + new_stack_element.reverse() + if open_seq[-1] == "(" and len(new_stack_element) != 1: + raise SyntaxError("( must be followed by one expression, %i detected" % len(new_stack_element)) + stack[-1].append(new_stack_element) + open_seq.pop(-1) + else: + stack[-1].append(token) + pointer += 1 + assert len(stack) == 1 + return self._parse_after_braces(stack[0]) + + def _util_remove_newlines(self, lines: list, tokens: list, inside_enclosure: bool): + pointer = 0 + size = len(tokens) + while pointer < size: + token = tokens[pointer] + if token == "\n": + if inside_enclosure: + # Ignore newlines inside enclosures + tokens.pop(pointer) + size -= 1 + continue + if pointer == 0: + tokens.pop(0) + size -= 1 + continue + if pointer > 1: + try: + prev_expr = self._parse_after_braces(tokens[:pointer], inside_enclosure) + except SyntaxError: + tokens.pop(pointer) + size -= 1 + continue + else: + prev_expr = tokens[0] + if len(prev_expr) > 0 and prev_expr[0] == "CompoundExpression": + lines.extend(prev_expr[1:]) + else: + lines.append(prev_expr) + for i in range(pointer): + tokens.pop(0) + size -= pointer + pointer = 0 + continue + pointer += 1 + + def _util_add_missing_asterisks(self, tokens: list): + size: int = len(tokens) + pointer: int = 0 + while pointer < size: + if (pointer > 0 and + self._is_valid_star1(tokens[pointer - 1]) and + self._is_valid_star2(tokens[pointer])): + # This is a trick to add missing * operators in the expression, + # `"*" in op_dict` makes sure the precedence level is the same as "*", + # while `not self._is_op( ... )` makes sure this and the previous + # expression are not operators. + if tokens[pointer] == "(": + # ( has already been processed by now, replace: + tokens[pointer] = "*" + tokens[pointer + 1] = tokens[pointer + 1][0] + else: + tokens.insert(pointer, "*") + pointer += 1 + size += 1 + pointer += 1 + + def _parse_after_braces(self, tokens: list, inside_enclosure: bool = False): + op_dict: dict + changed: bool = False + lines: list = [] + + self._util_remove_newlines(lines, tokens, inside_enclosure) + + for op_type, grouping_strat, op_dict in reversed(self._mathematica_op_precedence): + if "*" in op_dict: + self._util_add_missing_asterisks(tokens) + size: int = len(tokens) + pointer: int = 0 + while pointer < size: + token = tokens[pointer] + if isinstance(token, str) and token in op_dict: + op_name: str | Callable = op_dict[token] + node: list + first_index: int + if isinstance(op_name, str): + node = [op_name] + first_index = 1 + else: + node = [] + first_index = 0 + if token in ("+", "-") and op_type == self.PREFIX and pointer > 0 and not self._is_op(tokens[pointer - 1]): + # Make sure that PREFIX + - don't match expressions like a + b or a - b, + # the INFIX + - are supposed to match that expression: + pointer += 1 + continue + if op_type == self.INFIX: + if pointer == 0 or pointer == size - 1 or self._is_op(tokens[pointer - 1]) or self._is_op(tokens[pointer + 1]): + pointer += 1 + continue + changed = True + tokens[pointer] = node + if op_type == self.INFIX: + arg1 = tokens.pop(pointer-1) + arg2 = tokens.pop(pointer) + if token == "/": + arg2 = self._get_inv(arg2) + elif token == "-": + arg2 = self._get_neg(arg2) + pointer -= 1 + size -= 2 + node.append(arg1) + node_p = node + if grouping_strat == self.FLAT: + while pointer + 2 < size and self._check_op_compatible(tokens[pointer+1], token): + node_p.append(arg2) + other_op = tokens.pop(pointer+1) + arg2 = tokens.pop(pointer+1) + if other_op == "/": + arg2 = self._get_inv(arg2) + elif other_op == "-": + arg2 = self._get_neg(arg2) + size -= 2 + node_p.append(arg2) + elif grouping_strat == self.RIGHT: + while pointer + 2 < size and tokens[pointer+1] == token: + node_p.append([op_name, arg2]) + node_p = node_p[-1] + tokens.pop(pointer+1) + arg2 = tokens.pop(pointer+1) + size -= 2 + node_p.append(arg2) + elif grouping_strat == self.LEFT: + while pointer + 1 < size and tokens[pointer+1] == token: + if isinstance(op_name, str): + node_p[first_index] = [op_name, node_p[first_index], arg2] + else: + node_p[first_index] = op_name(node_p[first_index], arg2) + tokens.pop(pointer+1) + arg2 = tokens.pop(pointer+1) + size -= 2 + node_p.append(arg2) + else: + node.append(arg2) + elif op_type == self.PREFIX: + assert grouping_strat is None + if pointer == size - 1 or self._is_op(tokens[pointer + 1]): + tokens[pointer] = self._missing_arguments_default[token]() + else: + node.append(tokens.pop(pointer+1)) + size -= 1 + elif op_type == self.POSTFIX: + assert grouping_strat is None + if pointer == 0 or self._is_op(tokens[pointer - 1]): + tokens[pointer] = self._missing_arguments_default[token]() + else: + node.append(tokens.pop(pointer-1)) + pointer -= 1 + size -= 1 + if isinstance(op_name, Callable): # type: ignore + op_call: Callable = typing.cast(Callable, op_name) + new_node = op_call(*node) + node.clear() + if isinstance(new_node, list): + node.extend(new_node) + else: + tokens[pointer] = new_node + pointer += 1 + if len(tokens) > 1 or (len(lines) == 0 and len(tokens) == 0): + if changed: + # Trick to deal with cases in which an operator with lower + # precedence should be transformed before an operator of higher + # precedence. Such as in the case of `#&[x]` (that is + # equivalent to `Lambda(d_, d_)(x)` in SymPy). In this case the + # operator `&` has lower precedence than `[`, but needs to be + # evaluated first because otherwise `# (&[x])` is not a valid + # expression: + return self._parse_after_braces(tokens, inside_enclosure) + raise SyntaxError("unable to create a single AST for the expression") + if len(lines) > 0: + if tokens[0] and tokens[0][0] == "CompoundExpression": + tokens = tokens[0][1:] + compound_expression = ["CompoundExpression", *lines, *tokens] + return compound_expression + return tokens[0] + + def _check_op_compatible(self, op1: str, op2: str): + if op1 == op2: + return True + muldiv = {"*", "/"} + addsub = {"+", "-"} + if op1 in muldiv and op2 in muldiv: + return True + if op1 in addsub and op2 in addsub: + return True + return False + + def _from_fullform_to_fullformlist(self, wmexpr: str): + """ + Parses FullForm[Downvalues[]] generated by Mathematica + """ + out: list = [] + stack = [out] + generator = re.finditer(r'[\[\],]', wmexpr) + last_pos = 0 + for match in generator: + if match is None: + break + position = match.start() + last_expr = wmexpr[last_pos:position].replace(',', '').replace(']', '').replace('[', '').strip() + + if match.group() == ',': + if last_expr != '': + stack[-1].append(last_expr) + elif match.group() == ']': + if last_expr != '': + stack[-1].append(last_expr) + stack.pop() + elif match.group() == '[': + stack[-1].append([last_expr]) + stack.append(stack[-1][-1]) + last_pos = match.end() + return out[0] + + def _from_fullformlist_to_fullformsympy(self, pylist: list): + from sympy import Function, Symbol + + def converter(expr): + if isinstance(expr, list): + if len(expr) > 0: + head = expr[0] + args = [converter(arg) for arg in expr[1:]] + return Function(head)(*args) + else: + raise ValueError("Empty list of expressions") + elif isinstance(expr, str): + return Symbol(expr) + else: + return _sympify(expr) + + return converter(pylist) + + _node_conversions = { + "Times": Mul, + "Plus": Add, + "Power": Pow, + "Log": lambda *a: log(*reversed(a)), + "Log2": lambda x: log(x, 2), + "Log10": lambda x: log(x, 10), + "Exp": exp, + "Sqrt": sqrt, + + "Sin": sin, + "Cos": cos, + "Tan": tan, + "Cot": cot, + "Sec": sec, + "Csc": csc, + + "ArcSin": asin, + "ArcCos": acos, + "ArcTan": lambda *a: atan2(*reversed(a)) if len(a) == 2 else atan(*a), + "ArcCot": acot, + "ArcSec": asec, + "ArcCsc": acsc, + + "Sinh": sinh, + "Cosh": cosh, + "Tanh": tanh, + "Coth": coth, + "Sech": sech, + "Csch": csch, + + "ArcSinh": asinh, + "ArcCosh": acosh, + "ArcTanh": atanh, + "ArcCoth": acoth, + "ArcSech": asech, + "ArcCsch": acsch, + + "Expand": expand, + "Im": im, + "Re": sympy.re, + "Flatten": flatten, + "Polylog": polylog, + "Cancel": cancel, + # Gamma=gamma, + "TrigExpand": expand_trig, + "Sign": sign, + "Simplify": simplify, + "Defer": UnevaluatedExpr, + "Identity": S, + # Sum=Sum_doit, + # Module=With, + # Block=With, + "Null": lambda *a: S.Zero, + "Mod": Mod, + "Max": Max, + "Min": Min, + "Pochhammer": rf, + "ExpIntegralEi": Ei, + "SinIntegral": Si, + "CosIntegral": Ci, + "AiryAi": airyai, + "AiryAiPrime": airyaiprime, + "AiryBi": airybi, + "AiryBiPrime": airybiprime, + "LogIntegral": li, + "PrimePi": primepi, + "Prime": prime, + "PrimeQ": isprime, + + "List": Tuple, + "Greater": StrictGreaterThan, + "GreaterEqual": GreaterThan, + "Less": StrictLessThan, + "LessEqual": LessThan, + "Equal": Equality, + "Or": Or, + "And": And, + + "Function": _parse_Function, + } + + _atom_conversions = { + "I": I, + "Pi": pi, + } + + def _from_fullformlist_to_sympy(self, full_form_list): + + def recurse(expr): + if isinstance(expr, list): + if isinstance(expr[0], list): + head = recurse(expr[0]) + else: + head = self._node_conversions.get(expr[0], Function(expr[0])) + return head(*[recurse(arg) for arg in expr[1:]]) + else: + return self._atom_conversions.get(expr, sympify(expr)) + + return recurse(full_form_list) + + def _from_fullformsympy_to_sympy(self, mform): + + expr = mform + for mma_form, sympy_node in self._node_conversions.items(): + expr = expr.replace(Function(mma_form), sympy_node) + return expr diff --git a/shared/package-files/01/0180b950bf528f33e5d6c4bcf538fd90f31906264c32f215b5fa3b180a267b82/blob b/shared/package-files/01/0180b950bf528f33e5d6c4bcf538fd90f31906264c32f215b5fa3b180a267b82/blob new file mode 100644 index 0000000000000000000000000000000000000000..54bb94ca78f66c00ebc9fe0b8f535cf2b0cd8f98 --- /dev/null +++ b/shared/package-files/01/0180b950bf528f33e5d6c4bcf538fd90f31906264c32f215b5fa3b180a267b82/blob @@ -0,0 +1,223 @@ +import gc +import itertools + +import numpy as np + +import unittest +from numba import jit, njit +from numba.core import types +from numba.tests.support import TestCase +from numba.np import numpy_support + + +def identity(x): + return x + +def addition(x, y): + return x + y + +def equality(x, y): + return x == y + +def foobar(x, y, z): + return x + + +class TestConversion(TestCase): + """ + Testing Python to Native conversion + """ + + def test_complex_identity(self): + pyfunc = identity + cfunc = njit(types.complex64(types.complex64))(pyfunc) + + xs = [1.0j, (1+1j), (-1-1j), (1+0j)] + for x in xs: + self.assertEqual(cfunc(x), x) + for x in np.complex64(xs): + self.assertEqual(cfunc(x), x) + + cfunc = njit(types.complex128(types.complex128))(pyfunc) + + xs = [1.0j, (1+1j), (-1-1j), (1+0j)] + for x in xs: + self.assertEqual(cfunc(x), x) + for x in np.complex128(xs): + self.assertEqual(cfunc(x), x) + + def test_complex_addition(self): + pyfunc = addition + cfunc = njit(types.complex64(types.complex64, types.complex64))(pyfunc) + + xs = [1.0j, (1+1j), (-1-1j), (1+0j)] + for x in xs: + y = x + self.assertEqual(cfunc(x, y), x + y) + for x in np.complex64(xs): + y = x + self.assertEqual(cfunc(x, y), x + y) + + + cfunc = njit(types.complex128(types.complex128, + types.complex128))(pyfunc) + + xs = [1.0j, (1+1j), (-1-1j), (1+0j)] + for x in xs: + y = x + self.assertEqual(cfunc(x, y), x + y) + for x in np.complex128(xs): + y = x + self.assertEqual(cfunc(x, y), x + y) + + def test_boolean_as_int(self): + pyfunc = equality + cfunc = njit((types.boolean, types.intp))(pyfunc) + + xs = True, False + ys = -1, 0, 1 + + for xs, ys in itertools.product(xs, ys): + self.assertEqual(pyfunc(xs, ys), cfunc(xs, ys)) + + def test_boolean_as_float(self): + pyfunc = equality + cfunc = njit((types.boolean, types.float64))(pyfunc) + + xs = True, False + ys = -1, 0, 1 + + for xs, ys in itertools.product(xs, ys): + self.assertEqual(pyfunc(xs, ys), cfunc(xs, ys)) + + def test_boolean_eq_boolean(self): + pyfunc = equality + cfunc = njit((types.boolean, types.boolean))(pyfunc) + + xs = True, False + ys = True, False + + for xs, ys in itertools.product(xs, ys): + self.assertEqual(pyfunc(xs, ys), cfunc(xs, ys)) + + # test when a function parameters are jitted as unsigned types + # the function is called with negative parameters the Python error + # that it generates is correctly handled -- a Python error is returned to the user + # For more info, see the comment in Include/longobject.h for _PyArray_AsByteArray + # which PyLong_AsUnsignedLongLong calls + def test_negative_to_unsigned(self): + def f(x): + return x + with self.assertRaises(OverflowError): + jit('uintp(uintp)', nopython=True)(f)(-5) + + # test the switch logic in callwraper.py:build_wrapper() works for more than one argument + # and where the error occurs + def test_multiple_args_negative_to_unsigned(self): + pyfunc = foobar + cfunc = njit(types.uint64(types.uint64, types.uint64, + types.uint64),)(pyfunc) + + test_fail_args = ((-1, 0, 1), (0, -1, 1), (0, 1, -1)) + with self.assertRaises(OverflowError): + for a, b, c in test_fail_args: + cfunc(a, b, c) + + # test switch logic of callwraper.py:build_wrapper() with records as function parameters + def test_multiple_args_records(self): + pyfunc = foobar + + mystruct_dt = np.dtype([('p', np.float64), + ('row', np.float64), + ('col', np.float64)]) + mystruct = numpy_support.from_dtype(mystruct_dt) + + cfunc = njit(mystruct[:](mystruct[:], types.uint64, + types.uint64),)(pyfunc) + + st1 = np.recarray(3, dtype=mystruct_dt) + + st1.p = np.arange(st1.size) + 1 + st1.row = np.arange(st1.size) + 1 + st1.col = np.arange(st1.size) + 1 + + with self.assertRefCount(st1): + test_fail_args = ((st1, -1, 1), (st1, 1, -1)) + + for a, b, c in test_fail_args: + with self.assertRaises(OverflowError): + cfunc(a, b, c) + + del test_fail_args, a, b, c + gc.collect() + + # test switch logic of callwraper.py:build_wrapper() with no function parameters + def test_with_no_parameters(self): + def f(): + pass + self.assertEqual(f(), jit('()', nopython=True)(f)()) + + def check_argument_cleanup(self, typ, obj): + """ + Check that argument cleanup doesn't leak references. + """ + def f(x, y): + pass + + def _objects(obj): + objs = [obj] + if isinstance(obj, tuple): + for v in obj: + objs += _objects(v) + return objs + + objects = _objects(obj) + + cfunc = njit((typ, types.uint32))(f) + with self.assertRefCount(*objects): + cfunc(obj, 1) + with self.assertRefCount(*objects): + with self.assertRaises(OverflowError): + cfunc(obj, -1) + + cfunc = njit((types.uint32, typ))(f) + with self.assertRefCount(*objects): + cfunc(1, obj) + with self.assertRefCount(*objects): + with self.assertRaises(OverflowError): + cfunc(-1, obj) + + def test_cleanup_buffer(self): + mem = memoryview(bytearray(b"xyz")) + self.check_argument_cleanup(types.MemoryView(types.byte, 1, 'C'), mem) + + def test_cleanup_record(self): + dtype = np.dtype([('x', np.float64), ('y', np.float64)]) + recarr = np.zeros(1, dtype=dtype) + self.check_argument_cleanup(numpy_support.from_dtype(dtype), recarr[0]) + + def test_cleanup_tuple(self): + mem = memoryview(bytearray(b"xyz")) + tp = types.UniTuple(types.MemoryView(types.byte, 1, 'C'), 2) + self.check_argument_cleanup(tp, (mem, mem)) + + def test_cleanup_optional(self): + mem = memoryview(bytearray(b"xyz")) + tp = types.Optional(types.MemoryView(types.byte, 1, 'C')) + self.check_argument_cleanup(tp, mem) + + def test_stringliteral_to_unicode(self): + # See issue #6907, explicit signature on bar() takes a unicode_type but + # the call to bar() in foo() is with a StringLiteral + + @jit(types.void(types.unicode_type), nopython=True) + def bar(string): + pass + + @jit(types.void(), nopython=True) + def foo2(): + bar("literal string") + + +if __name__ == '__main__': + unittest.main() diff --git a/shared/package-files/01/0186b23768dfd43a79ad767b58f05d521b4f068fc93028bea43f685b9ce61642/blob b/shared/package-files/01/0186b23768dfd43a79ad767b58f05d521b4f068fc93028bea43f685b9ce61642/blob new file mode 100644 index 0000000000000000000000000000000000000000..15ab81d16d932e6c4b4351e54081c5e5301d38c1 --- /dev/null +++ b/shared/package-files/01/0186b23768dfd43a79ad767b58f05d521b4f068fc93028bea43f685b9ce61642/blob @@ -0,0 +1,7 @@ +import numpy as np + +e = np.e +inf = np.inf +nan = np.nan +pi = np.pi +newaxis = np.newaxis diff --git a/shared/package-files/01/018a252ef2e57059243d8321790eb046903ac1237a35e5bcd6698c21ba47216f/blob b/shared/package-files/01/018a252ef2e57059243d8321790eb046903ac1237a35e5bcd6698c21ba47216f/blob new file mode 100644 index 0000000000000000000000000000000000000000..afa8e142702362de4ef26a8c0484561a20ea2ade --- /dev/null +++ b/shared/package-files/01/018a252ef2e57059243d8321790eb046903ac1237a35e5bcd6698c21ba47216f/blob @@ -0,0 +1,23 @@ +#pragma once +// @generated by torchgen/gen.py from DispatchKeyFunction.h + +// NB: The implementing C++ file is RegisterDispatchKey.cpp + +// The only #includes we need are for custom classes that have defaults in the C++ API +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { + +namespace compositeexplicitautogradnonfunctional { + +TORCH_API at::Tensor pixel_unshuffle(const at::Tensor & self, int64_t downscale_factor); + +} // namespace compositeexplicitautogradnonfunctional +} // namespace at diff --git a/shared/package-files/01/018ad179ff5d005fa75becd64920054ff449e0682b68f81b9e4f49a5250845be/blob b/shared/package-files/01/018ad179ff5d005fa75becd64920054ff449e0682b68f81b9e4f49a5250845be/blob new file mode 100644 index 0000000000000000000000000000000000000000..a65e13fc5a6bf4e6fc605adc10c86e280c0b1dc5 --- /dev/null +++ b/shared/package-files/01/018ad179ff5d005fa75becd64920054ff449e0682b68f81b9e4f49a5250845be/blob @@ -0,0 +1,39 @@ +#pragma once + +// @generated by torchgen/gen.py from Operator.h + +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { +namespace _ops { + + +struct TORCH_API linalg_solve_ex { + using schema = ::std::tuple (const at::Tensor &, const at::Tensor &, bool, bool); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::linalg_solve_ex") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "linalg_solve_ex(Tensor A, Tensor B, *, bool left=True, bool check_errors=False) -> (Tensor result, Tensor info)") + static ::std::tuple call(const at::Tensor & A, const at::Tensor & B, bool left, bool check_errors); + static ::std::tuple redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & A, const at::Tensor & B, bool left, bool check_errors); +}; + +struct TORCH_API linalg_solve_ex_out { + using schema = ::std::tuple (const at::Tensor &, const at::Tensor &, bool, bool, at::Tensor &, at::Tensor &); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::linalg_solve_ex") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "out") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "linalg_solve_ex.out(Tensor A, Tensor B, *, bool left=True, bool check_errors=False, Tensor(a!) result, Tensor(b!) info) -> (Tensor(a!) result, Tensor(b!) info)") + static ::std::tuple call(const at::Tensor & A, const at::Tensor & B, bool left, bool check_errors, at::Tensor & result, at::Tensor & info); + static ::std::tuple redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & A, const at::Tensor & B, bool left, bool check_errors, at::Tensor & result, at::Tensor & info); +}; + +}} // namespace at::_ops diff --git a/shared/package-files/01/018b1a2c70e8ef537cc328d1026afdeca5839392ce47235a7b8d22e1b788cdc7/blob b/shared/package-files/01/018b1a2c70e8ef537cc328d1026afdeca5839392ce47235a7b8d22e1b788cdc7/blob new file mode 100644 index 0000000000000000000000000000000000000000..1d82b5006396cde400807e17eaf09fa342b01750 --- /dev/null +++ b/shared/package-files/01/018b1a2c70e8ef537cc328d1026afdeca5839392ce47235a7b8d22e1b788cdc7/blob @@ -0,0 +1,383 @@ +# +# Secret Labs' Regular Expression Engine +# +# re-compatible interface for the sre matching engine +# +# Copyright (c) 1998-2001 by Secret Labs AB. All rights reserved. +# +# This version of the SRE library can be redistributed under CNRI's +# Python 1.6 license. For any other use, please contact Secret Labs +# AB (info@pythonware.com). +# +# Portions of this engine have been developed in cooperation with +# CNRI. Hewlett-Packard provided funding for 1.6 integration and +# other compatibility work. +# + +r"""Support for regular expressions (RE). + +This module provides regular expression matching operations similar to +those found in Perl. It supports both 8-bit and Unicode strings; both +the pattern and the strings being processed can contain null bytes and +characters outside the US ASCII range. + +Regular expressions can contain both special and ordinary characters. +Most ordinary characters, like "A", "a", or "0", are the simplest +regular expressions; they simply match themselves. You can +concatenate ordinary characters, so last matches the string 'last'. + +The special characters are: + "." Matches any character except a newline. + "^" Matches the start of the string. + "$" Matches the end of the string or just before the newline at + the end of the string. + "*" Matches 0 or more (greedy) repetitions of the preceding RE. + Greedy means that it will match as many repetitions as possible. + "+" Matches 1 or more (greedy) repetitions of the preceding RE. + "?" Matches 0 or 1 (greedy) of the preceding RE. + *?,+?,?? Non-greedy versions of the previous three special characters. + {m,n} Matches from m to n repetitions of the preceding RE. + {m,n}? Non-greedy version of the above. + "\\" Either escapes special characters or signals a special sequence. + [] Indicates a set of characters. + A "^" as the first character indicates a complementing set. + "|" A|B, creates an RE that will match either A or B. + (...) Matches the RE inside the parentheses. + The contents can be retrieved or matched later in the string. + (?aiLmsux) The letters set the corresponding flags defined below. + (?:...) Non-grouping version of regular parentheses. + (?P...) The substring matched by the group is accessible by name. + (?P=name) Matches the text matched earlier by the group named name. + (?#...) A comment; ignored. + (?=...) Matches if ... matches next, but doesn't consume the string. + (?!...) Matches if ... doesn't match next. + (?<=...) Matches if preceded by ... (must be fixed length). + (? 1: + res = f'~({res})' + else: + res = f'~{res}' + return res + __str__ = object.__str__ +globals().update(RegexFlag.__members__) + +# sre exception +error = sre_compile.error + +# -------------------------------------------------------------------- +# public interface + +def match(pattern, string, flags=0): + """Try to apply the pattern at the start of the string, returning + a Match object, or None if no match was found.""" + return _compile(pattern, flags).match(string) + +def fullmatch(pattern, string, flags=0): + """Try to apply the pattern to all of the string, returning + a Match object, or None if no match was found.""" + return _compile(pattern, flags).fullmatch(string) + +def search(pattern, string, flags=0): + """Scan through string looking for a match to the pattern, returning + a Match object, or None if no match was found.""" + return _compile(pattern, flags).search(string) + +def sub(pattern, repl, string, count=0, flags=0): + """Return the string obtained by replacing the leftmost + non-overlapping occurrences of the pattern in string by the + replacement repl. repl can be either a string or a callable; + if a string, backslash escapes in it are processed. If it is + a callable, it's passed the Match object and must return + a replacement string to be used.""" + return _compile(pattern, flags).sub(repl, string, count) + +def subn(pattern, repl, string, count=0, flags=0): + """Return a 2-tuple containing (new_string, number). + new_string is the string obtained by replacing the leftmost + non-overlapping occurrences of the pattern in the source + string by the replacement repl. number is the number of + substitutions that were made. repl can be either a string or a + callable; if a string, backslash escapes in it are processed. + If it is a callable, it's passed the Match object and must + return a replacement string to be used.""" + return _compile(pattern, flags).subn(repl, string, count) + +def split(pattern, string, maxsplit=0, flags=0): + """Split the source string by the occurrences of the pattern, + returning a list containing the resulting substrings. If + capturing parentheses are used in pattern, then the text of all + groups in the pattern are also returned as part of the resulting + list. If maxsplit is nonzero, at most maxsplit splits occur, + and the remainder of the string is returned as the final element + of the list.""" + return _compile(pattern, flags).split(string, maxsplit) + +def findall(pattern, string, flags=0): + """Return a list of all non-overlapping matches in the string. + + If one or more capturing groups are present in the pattern, return + a list of groups; this will be a list of tuples if the pattern + has more than one group. + + Empty matches are included in the result.""" + return _compile(pattern, flags).findall(string) + +def finditer(pattern, string, flags=0): + """Return an iterator over all non-overlapping matches in the + string. For each match, the iterator returns a Match object. + + Empty matches are included in the result.""" + return _compile(pattern, flags).finditer(string) + +def compile(pattern, flags=0): + "Compile a regular expression pattern, returning a Pattern object." + return _compile(pattern, flags) + +def purge(): + "Clear the regular expression caches" + _cache.clear() + _compile_repl.cache_clear() + +def template(pattern, flags=0): + "Compile a template pattern, returning a Pattern object" + return _compile(pattern, flags|T) + +# SPECIAL_CHARS +# closing ')', '}' and ']' +# '-' (a range in character set) +# '&', '~', (extended character set operations) +# '#' (comment) and WHITESPACE (ignored) in verbose mode +_special_chars_map = {i: '\\' + chr(i) for i in b'()[]{}?*+-|^$\\.&~# \t\n\r\v\f'} + +def escape(pattern): + """ + Escape special characters in a string. + """ + if isinstance(pattern, str): + return pattern.translate(_special_chars_map) + else: + pattern = str(pattern, 'latin1') + return pattern.translate(_special_chars_map).encode('latin1') + +Pattern = type(sre_compile.compile('', 0)) +Match = type(sre_compile.compile('', 0).match('')) + +# -------------------------------------------------------------------- +# internals + +_cache = {} # ordered! + +_MAXCACHE = 512 +def _compile(pattern, flags): + # internal: compile pattern + if isinstance(flags, RegexFlag): + flags = flags.value + try: + return _cache[type(pattern), pattern, flags] + except KeyError: + pass + if isinstance(pattern, Pattern): + if flags: + raise ValueError( + "cannot process flags argument with a compiled pattern") + return pattern + if not sre_compile.isstring(pattern): + raise TypeError("first argument must be string or compiled pattern") + p = sre_compile.compile(pattern, flags) + if not (flags & DEBUG): + if len(_cache) >= _MAXCACHE: + # Drop the oldest item + try: + del _cache[next(iter(_cache))] + except (StopIteration, RuntimeError, KeyError): + pass + _cache[type(pattern), pattern, flags] = p + return p + +@functools.lru_cache(_MAXCACHE) +def _compile_repl(repl, pattern): + # internal: compile replacement pattern + return sre_parse.parse_template(repl, pattern) + +def _expand(pattern, match, template): + # internal: Match.expand implementation hook + template = sre_parse.parse_template(template, pattern) + return sre_parse.expand_template(template, match) + +def _subx(pattern, template): + # internal: Pattern.sub/subn implementation helper + template = _compile_repl(template, pattern) + if not template[0] and len(template[1]) == 1: + # literal replacement + return template[1][0] + def filter(match, template=template): + return sre_parse.expand_template(template, match) + return filter + +# register myself for pickling + +import copyreg + +def _pickle(p): + return _compile, (p.pattern, p.flags) + +copyreg.pickle(Pattern, _pickle, _compile) + +# -------------------------------------------------------------------- +# experimental stuff (see python-dev discussions for details) + +class Scanner: + def __init__(self, lexicon, flags=0): + from sre_constants import BRANCH, SUBPATTERN + if isinstance(flags, RegexFlag): + flags = flags.value + self.lexicon = lexicon + # combine phrases into a compound pattern + p = [] + s = sre_parse.State() + s.flags = flags + for phrase, action in lexicon: + gid = s.opengroup() + p.append(sre_parse.SubPattern(s, [ + (SUBPATTERN, (gid, 0, 0, sre_parse.parse(phrase, flags))), + ])) + s.closegroup(gid, p[-1]) + p = sre_parse.SubPattern(s, [(BRANCH, (None, p))]) + self.scanner = sre_compile.compile(p) + def scan(self, string): + result = [] + append = result.append + match = self.scanner.scanner(string).match + i = 0 + while True: + m = match() + if not m: + break + j = m.end() + if i == j: + break + action = self.lexicon[m.lastindex-1][1] + if callable(action): + self.match = m + action = action(self, m.group()) + if action is not None: + append(action) + i = j + return result, string[i:] diff --git a/shared/package-files/01/018b364b05796a7920c27bca23d4523b58d9724d75f27bb74b26789e0cd936ca/blob b/shared/package-files/01/018b364b05796a7920c27bca23d4523b58d9724d75f27bb74b26789e0cd936ca/blob new file mode 100644 index 0000000000000000000000000000000000000000..c00ed13d7f3076d53ec080a46fe7e13ff7dfb5a2 --- /dev/null +++ b/shared/package-files/01/018b364b05796a7920c27bca23d4523b58d9724d75f27bb74b26789e0cd936ca/blob @@ -0,0 +1,46 @@ +from operator import mul +from functools import reduce + +import numpy as np +from numpy.random import randint +from numpy.lib import Arrayterator +from numpy.testing import assert_ + + +def test(): + np.random.seed(np.arange(10)) + + # Create a random array + ndims = randint(5)+1 + shape = tuple(randint(10)+1 for dim in range(ndims)) + els = reduce(mul, shape) + a = np.arange(els) + a.shape = shape + + buf_size = randint(2*els) + b = Arrayterator(a, buf_size) + + # Check that each block has at most ``buf_size`` elements + for block in b: + assert_(len(block.flat) <= (buf_size or els)) + + # Check that all elements are iterated correctly + assert_(list(b.flat) == list(a.flat)) + + # Slice arrayterator + start = [randint(dim) for dim in shape] + stop = [randint(dim)+1 for dim in shape] + step = [randint(dim)+1 for dim in shape] + slice_ = tuple(slice(*t) for t in zip(start, stop, step)) + c = b[slice_] + d = a[slice_] + + # Check that each block has at most ``buf_size`` elements + for block in c: + assert_(len(block.flat) <= (buf_size or els)) + + # Check that the arrayterator is sliced correctly + assert_(np.all(c.__array__() == d)) + + # Check that all elements are iterated correctly + assert_(list(c.flat) == list(d.flat)) diff --git a/shared/package-files/01/018da6f2a981b5c4af7c740b5a7efda067d23e60dcce8ba7accf5e47a9d7e770/blob b/shared/package-files/01/018da6f2a981b5c4af7c740b5a7efda067d23e60dcce8ba7accf5e47a9d7e770/blob new file mode 100644 index 0000000000000000000000000000000000000000..b22fb1ae8faf3f65a1032c8d6fd2f81931d72cf2 --- /dev/null +++ b/shared/package-files/01/018da6f2a981b5c4af7c740b5a7efda067d23e60dcce8ba7accf5e47a9d7e770/blob @@ -0,0 +1,22 @@ +#pragma once + +#include + +namespace c10d { + +C10_EXPORT void set_thread_isolation_mode(bool enable); + +bool get_thread_isolation_mode(); + +C10_EXPORT void register_process_group( + const std::string& group_name, + c10::intrusive_ptr group); + +C10_EXPORT c10::intrusive_ptr resolve_process_group( + const std::string& group_name); + +C10_EXPORT void unregister_process_group(const std::string& group_name); + +C10_EXPORT void unregister_all_process_groups(); + +} // namespace c10d diff --git a/shared/package-files/01/018ecaf6222567f0169b3077b3c6d07acd40b7343e63427a8bca97d6c165cc2e/blob b/shared/package-files/01/018ecaf6222567f0169b3077b3c6d07acd40b7343e63427a8bca97d6c165cc2e/blob new file mode 100644 index 0000000000000000000000000000000000000000..b38bdb546022fd0aa72dd89cd460c2d9fdf6fab5 --- /dev/null +++ b/shared/package-files/01/018ecaf6222567f0169b3077b3c6d07acd40b7343e63427a8bca97d6c165cc2e/blob @@ -0,0 +1,26 @@ +#pragma once +// @generated by torchgen/gen.py from DispatchKeyFunction.h + +// NB: The implementing C++ file is RegisterDispatchKey.cpp + +// The only #includes we need are for custom classes that have defaults in the C++ API +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { + +namespace cuda { + +TORCH_API at::Tensor sin(const at::Tensor & self); +TORCH_API at::Tensor & sin_out(at::Tensor & out, const at::Tensor & self); +TORCH_API at::Tensor & sin_outf(const at::Tensor & self, at::Tensor & out); +TORCH_API at::Tensor & sin_(at::Tensor & self); + +} // namespace cuda +} // namespace at diff --git a/shared/package-files/01/019156dbff231c96de5e02b5047171d7087c7899164b07ddf2beb5588fc00547/blob b/shared/package-files/01/019156dbff231c96de5e02b5047171d7087c7899164b07ddf2beb5588fc00547/blob new file mode 100644 index 0000000000000000000000000000000000000000..101f3b6c12117dce459e9e3c98229ab23901cf48 --- /dev/null +++ b/shared/package-files/01/019156dbff231c96de5e02b5047171d7087c7899164b07ddf2beb5588fc00547/blob @@ -0,0 +1,615 @@ +../../../bin/pygmentize,sha256=hdLA986HHdRzuddY0HvB9ZjHqmYbxwtxGwRQdXlOT-0,498 +Pygments-2.15.1.dist-info/AUTHORS,sha256=TdJddtUy7LNm2wA_GLgRetvaopiRjjIIA5WOHzsI1WE,9974 +Pygments-2.15.1.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +Pygments-2.15.1.dist-info/LICENSE,sha256=qdZvHVJt8C4p3Oc0NtNOVuhjL0bCdbvf_HBWnogvnxc,1331 +Pygments-2.15.1.dist-info/METADATA,sha256=0vGsTBqE3q3Pi2-2JjCrSimfsh4ejRVGbddETm8IXv4,2451 +Pygments-2.15.1.dist-info/RECORD,, +Pygments-2.15.1.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +Pygments-2.15.1.dist-info/WHEEL,sha256=2wepM1nk4DS4eFpYrW1TTqPcoGNfHhhO_i5m4cOimbo,92 +Pygments-2.15.1.dist-info/direct_url.json,sha256=uw9pfVekoJtGBpF5PyByP3HIZ2mmibVdJaHGqhCJKnY,68 +Pygments-2.15.1.dist-info/entry_points.txt,sha256=uUXw-XhMKBEX4pWcCtpuTTnPhL3h7OEE2jWi51VQsa8,53 +Pygments-2.15.1.dist-info/top_level.txt,sha256=RjKKqrVIStoebLHdbs0yZ2Lk4rS7cxGguXsLCYvZ2Ak,9 +pygments/__init__.py,sha256=KXCoLMvtF-oa7UOyFz4JxCrZe0f_7BGHMs7xzz2LFP0,2959 +pygments/__main__.py,sha256=xVzk7wG94kskOfLT6ORXWRPRZZ0IAavOeRCtGXn2yEM,348 +pygments/__pycache__/__init__.cpython-310.pyc,, +pygments/__pycache__/__main__.cpython-310.pyc,, +pygments/__pycache__/cmdline.cpython-310.pyc,, +pygments/__pycache__/console.cpython-310.pyc,, +pygments/__pycache__/filter.cpython-310.pyc,, +pygments/__pycache__/formatter.cpython-310.pyc,, +pygments/__pycache__/lexer.cpython-310.pyc,, +pygments/__pycache__/modeline.cpython-310.pyc,, +pygments/__pycache__/plugin.cpython-310.pyc,, +pygments/__pycache__/regexopt.cpython-310.pyc,, +pygments/__pycache__/scanner.cpython-310.pyc,, +pygments/__pycache__/sphinxext.cpython-310.pyc,, +pygments/__pycache__/style.cpython-310.pyc,, +pygments/__pycache__/token.cpython-310.pyc,, +pygments/__pycache__/unistring.cpython-310.pyc,, +pygments/__pycache__/util.cpython-310.pyc,, +pygments/cmdline.py,sha256=5BDrKb_cOcvzp0Ps8rr4rFIO8kYb15JDlEiRKpoTwWE,23530 +pygments/console.py,sha256=2wZ5W-U6TudJD1_NLUwjclMpbomFM91lNv11_60sfGY,1697 +pygments/filter.py,sha256=j5aLM9a9wSx6eH1oy473oSkJ02hGWNptBlVo4s1g_30,1938 +pygments/filters/__init__.py,sha256=q8r8GfK3dO021TSHJdpwNwh6RHKbAL7ceCzohavWaN0,40338 +pygments/filters/__pycache__/__init__.cpython-310.pyc,, +pygments/formatter.py,sha256=Yz01yT1NSQXTF8GvsLxJSmez7ErTVOsxm3M6GVPuH-w,4154 +pygments/formatters/__init__.py,sha256=iRJiIk5375wDS08XLtJgTYEHzLd1_uvDGG0C85zQsfs,5388 +pygments/formatters/__pycache__/__init__.cpython-310.pyc,, +pygments/formatters/__pycache__/_mapping.cpython-310.pyc,, +pygments/formatters/__pycache__/bbcode.cpython-310.pyc,, +pygments/formatters/__pycache__/groff.cpython-310.pyc,, +pygments/formatters/__pycache__/html.cpython-310.pyc,, +pygments/formatters/__pycache__/img.cpython-310.pyc,, +pygments/formatters/__pycache__/irc.cpython-310.pyc,, +pygments/formatters/__pycache__/latex.cpython-310.pyc,, +pygments/formatters/__pycache__/other.cpython-310.pyc,, +pygments/formatters/__pycache__/pangomarkup.cpython-310.pyc,, +pygments/formatters/__pycache__/rtf.cpython-310.pyc,, +pygments/formatters/__pycache__/svg.cpython-310.pyc,, +pygments/formatters/__pycache__/terminal.cpython-310.pyc,, +pygments/formatters/__pycache__/terminal256.cpython-310.pyc,, +pygments/formatters/_mapping.py,sha256=1Cw37FuQlNacnxRKmtlPX4nyLoX9_ttko5ZwscNUZZ4,4176 +pygments/formatters/bbcode.py,sha256=7zcNcnoNj-dCyJlrHnmtq0V2o8ZGD14N5anFV4FQ5PE,3290 +pygments/formatters/groff.py,sha256=va2xlSCN-e_i0c_Dz0dg3HV9Ajt9G45PXaCi7CEsLdg,5070 +pygments/formatters/html.py,sha256=C0BdFXcODAHHHHVRiE5G6G3dUG_BHk938w90w-og1ZI,35574 +pygments/formatters/img.py,sha256=kzcmeDavdndLUV9TDy-LLdr3OwlhUfep1dAT7H-nQoY,21914 +pygments/formatters/irc.py,sha256=Jkze75ztayIkhNijfnFIsqOUR-Yz5fwEQM_oeWdOnRU,4945 +pygments/formatters/latex.py,sha256=48gMb8ziYgyQVJ4Ofx8x3Ka2l0RBomgYgn5zjeQK_vM,19303 +pygments/formatters/other.py,sha256=RzJhlXeYHyLxiC5vESy41WUK0FOqJPxvMiR6Von0z5Q,5025 +pygments/formatters/pangomarkup.py,sha256=0i4H7NLsxcxzFCJU5ONDJmhlLvsSLCnaFn-FXA5SMQk,2200 +pygments/formatters/rtf.py,sha256=8xghaGMBBXq2XNj-ZWNzYAeX_GqIDMqUBiJLDCulzNI,4990 +pygments/formatters/svg.py,sha256=VxjE-iqarQXJEFRissuLbsooXUCVXWgObQ7c4ub-5zg,7299 +pygments/formatters/terminal.py,sha256=P_dr7GLyRTIKg8LEceCOr5B5eGzGQBELA3JQOMvZ8VA,4626 +pygments/formatters/terminal256.py,sha256=_xYtNUUTAie5Bh7S98nrt7XIlLUURzDykosP7tT7044,11717 +pygments/lexer.py,sha256=MXnx0PyK98ubxsr6GQQ7D3kJey3CQJeqcJlr6vpmpjA,34541 +pygments/lexers/__init__.py,sha256=zIVAQGUmmzrjrNGeOEn0j178RNUqIb6bN8dnqIihfSA,12082 +pygments/lexers/__pycache__/__init__.cpython-310.pyc,, +pygments/lexers/__pycache__/_ada_builtins.cpython-310.pyc,, +pygments/lexers/__pycache__/_asy_builtins.cpython-310.pyc,, +pygments/lexers/__pycache__/_cl_builtins.cpython-310.pyc,, +pygments/lexers/__pycache__/_cocoa_builtins.cpython-310.pyc,, +pygments/lexers/__pycache__/_csound_builtins.cpython-310.pyc,, +pygments/lexers/__pycache__/_css_builtins.cpython-310.pyc,, +pygments/lexers/__pycache__/_julia_builtins.cpython-310.pyc,, +pygments/lexers/__pycache__/_lasso_builtins.cpython-310.pyc,, +pygments/lexers/__pycache__/_lilypond_builtins.cpython-310.pyc,, +pygments/lexers/__pycache__/_lua_builtins.cpython-310.pyc,, +pygments/lexers/__pycache__/_mapping.cpython-310.pyc,, +pygments/lexers/__pycache__/_mql_builtins.cpython-310.pyc,, +pygments/lexers/__pycache__/_mysql_builtins.cpython-310.pyc,, +pygments/lexers/__pycache__/_openedge_builtins.cpython-310.pyc,, +pygments/lexers/__pycache__/_php_builtins.cpython-310.pyc,, +pygments/lexers/__pycache__/_postgres_builtins.cpython-310.pyc,, +pygments/lexers/__pycache__/_qlik_builtins.cpython-310.pyc,, +pygments/lexers/__pycache__/_scheme_builtins.cpython-310.pyc,, +pygments/lexers/__pycache__/_scilab_builtins.cpython-310.pyc,, +pygments/lexers/__pycache__/_sourcemod_builtins.cpython-310.pyc,, +pygments/lexers/__pycache__/_stan_builtins.cpython-310.pyc,, +pygments/lexers/__pycache__/_stata_builtins.cpython-310.pyc,, +pygments/lexers/__pycache__/_tsql_builtins.cpython-310.pyc,, +pygments/lexers/__pycache__/_usd_builtins.cpython-310.pyc,, +pygments/lexers/__pycache__/_vbscript_builtins.cpython-310.pyc,, +pygments/lexers/__pycache__/_vim_builtins.cpython-310.pyc,, +pygments/lexers/__pycache__/actionscript.cpython-310.pyc,, +pygments/lexers/__pycache__/ada.cpython-310.pyc,, +pygments/lexers/__pycache__/agile.cpython-310.pyc,, +pygments/lexers/__pycache__/algebra.cpython-310.pyc,, +pygments/lexers/__pycache__/ambient.cpython-310.pyc,, +pygments/lexers/__pycache__/amdgpu.cpython-310.pyc,, +pygments/lexers/__pycache__/ampl.cpython-310.pyc,, +pygments/lexers/__pycache__/apdlexer.cpython-310.pyc,, +pygments/lexers/__pycache__/apl.cpython-310.pyc,, +pygments/lexers/__pycache__/archetype.cpython-310.pyc,, +pygments/lexers/__pycache__/arrow.cpython-310.pyc,, +pygments/lexers/__pycache__/arturo.cpython-310.pyc,, +pygments/lexers/__pycache__/asc.cpython-310.pyc,, +pygments/lexers/__pycache__/asm.cpython-310.pyc,, +pygments/lexers/__pycache__/automation.cpython-310.pyc,, +pygments/lexers/__pycache__/bare.cpython-310.pyc,, +pygments/lexers/__pycache__/basic.cpython-310.pyc,, +pygments/lexers/__pycache__/bdd.cpython-310.pyc,, +pygments/lexers/__pycache__/berry.cpython-310.pyc,, +pygments/lexers/__pycache__/bibtex.cpython-310.pyc,, +pygments/lexers/__pycache__/boa.cpython-310.pyc,, +pygments/lexers/__pycache__/business.cpython-310.pyc,, +pygments/lexers/__pycache__/c_cpp.cpython-310.pyc,, +pygments/lexers/__pycache__/c_like.cpython-310.pyc,, +pygments/lexers/__pycache__/capnproto.cpython-310.pyc,, +pygments/lexers/__pycache__/carbon.cpython-310.pyc,, +pygments/lexers/__pycache__/cddl.cpython-310.pyc,, +pygments/lexers/__pycache__/chapel.cpython-310.pyc,, +pygments/lexers/__pycache__/clean.cpython-310.pyc,, +pygments/lexers/__pycache__/comal.cpython-310.pyc,, +pygments/lexers/__pycache__/compiled.cpython-310.pyc,, +pygments/lexers/__pycache__/configs.cpython-310.pyc,, +pygments/lexers/__pycache__/console.cpython-310.pyc,, +pygments/lexers/__pycache__/cplint.cpython-310.pyc,, +pygments/lexers/__pycache__/crystal.cpython-310.pyc,, +pygments/lexers/__pycache__/csound.cpython-310.pyc,, +pygments/lexers/__pycache__/css.cpython-310.pyc,, +pygments/lexers/__pycache__/d.cpython-310.pyc,, +pygments/lexers/__pycache__/dalvik.cpython-310.pyc,, +pygments/lexers/__pycache__/data.cpython-310.pyc,, +pygments/lexers/__pycache__/dax.cpython-310.pyc,, +pygments/lexers/__pycache__/devicetree.cpython-310.pyc,, +pygments/lexers/__pycache__/diff.cpython-310.pyc,, +pygments/lexers/__pycache__/dotnet.cpython-310.pyc,, +pygments/lexers/__pycache__/dsls.cpython-310.pyc,, +pygments/lexers/__pycache__/dylan.cpython-310.pyc,, +pygments/lexers/__pycache__/ecl.cpython-310.pyc,, +pygments/lexers/__pycache__/eiffel.cpython-310.pyc,, +pygments/lexers/__pycache__/elm.cpython-310.pyc,, +pygments/lexers/__pycache__/elpi.cpython-310.pyc,, +pygments/lexers/__pycache__/email.cpython-310.pyc,, +pygments/lexers/__pycache__/erlang.cpython-310.pyc,, +pygments/lexers/__pycache__/esoteric.cpython-310.pyc,, +pygments/lexers/__pycache__/ezhil.cpython-310.pyc,, +pygments/lexers/__pycache__/factor.cpython-310.pyc,, +pygments/lexers/__pycache__/fantom.cpython-310.pyc,, +pygments/lexers/__pycache__/felix.cpython-310.pyc,, +pygments/lexers/__pycache__/fift.cpython-310.pyc,, +pygments/lexers/__pycache__/floscript.cpython-310.pyc,, +pygments/lexers/__pycache__/forth.cpython-310.pyc,, +pygments/lexers/__pycache__/fortran.cpython-310.pyc,, +pygments/lexers/__pycache__/foxpro.cpython-310.pyc,, +pygments/lexers/__pycache__/freefem.cpython-310.pyc,, +pygments/lexers/__pycache__/func.cpython-310.pyc,, +pygments/lexers/__pycache__/functional.cpython-310.pyc,, +pygments/lexers/__pycache__/futhark.cpython-310.pyc,, +pygments/lexers/__pycache__/gcodelexer.cpython-310.pyc,, +pygments/lexers/__pycache__/gdscript.cpython-310.pyc,, +pygments/lexers/__pycache__/go.cpython-310.pyc,, +pygments/lexers/__pycache__/grammar_notation.cpython-310.pyc,, +pygments/lexers/__pycache__/graph.cpython-310.pyc,, +pygments/lexers/__pycache__/graphics.cpython-310.pyc,, +pygments/lexers/__pycache__/graphviz.cpython-310.pyc,, +pygments/lexers/__pycache__/gsql.cpython-310.pyc,, +pygments/lexers/__pycache__/haskell.cpython-310.pyc,, +pygments/lexers/__pycache__/haxe.cpython-310.pyc,, +pygments/lexers/__pycache__/hdl.cpython-310.pyc,, +pygments/lexers/__pycache__/hexdump.cpython-310.pyc,, +pygments/lexers/__pycache__/html.cpython-310.pyc,, +pygments/lexers/__pycache__/idl.cpython-310.pyc,, +pygments/lexers/__pycache__/igor.cpython-310.pyc,, +pygments/lexers/__pycache__/inferno.cpython-310.pyc,, +pygments/lexers/__pycache__/installers.cpython-310.pyc,, +pygments/lexers/__pycache__/int_fiction.cpython-310.pyc,, +pygments/lexers/__pycache__/iolang.cpython-310.pyc,, +pygments/lexers/__pycache__/j.cpython-310.pyc,, +pygments/lexers/__pycache__/javascript.cpython-310.pyc,, +pygments/lexers/__pycache__/jmespath.cpython-310.pyc,, +pygments/lexers/__pycache__/jslt.cpython-310.pyc,, +pygments/lexers/__pycache__/jsonnet.cpython-310.pyc,, +pygments/lexers/__pycache__/julia.cpython-310.pyc,, +pygments/lexers/__pycache__/jvm.cpython-310.pyc,, +pygments/lexers/__pycache__/kuin.cpython-310.pyc,, +pygments/lexers/__pycache__/lilypond.cpython-310.pyc,, +pygments/lexers/__pycache__/lisp.cpython-310.pyc,, +pygments/lexers/__pycache__/macaulay2.cpython-310.pyc,, +pygments/lexers/__pycache__/make.cpython-310.pyc,, +pygments/lexers/__pycache__/markup.cpython-310.pyc,, +pygments/lexers/__pycache__/math.cpython-310.pyc,, +pygments/lexers/__pycache__/matlab.cpython-310.pyc,, +pygments/lexers/__pycache__/maxima.cpython-310.pyc,, +pygments/lexers/__pycache__/meson.cpython-310.pyc,, +pygments/lexers/__pycache__/mime.cpython-310.pyc,, +pygments/lexers/__pycache__/minecraft.cpython-310.pyc,, +pygments/lexers/__pycache__/mips.cpython-310.pyc,, +pygments/lexers/__pycache__/ml.cpython-310.pyc,, +pygments/lexers/__pycache__/modeling.cpython-310.pyc,, +pygments/lexers/__pycache__/modula2.cpython-310.pyc,, +pygments/lexers/__pycache__/monte.cpython-310.pyc,, +pygments/lexers/__pycache__/mosel.cpython-310.pyc,, +pygments/lexers/__pycache__/ncl.cpython-310.pyc,, +pygments/lexers/__pycache__/nimrod.cpython-310.pyc,, +pygments/lexers/__pycache__/nit.cpython-310.pyc,, +pygments/lexers/__pycache__/nix.cpython-310.pyc,, +pygments/lexers/__pycache__/oberon.cpython-310.pyc,, +pygments/lexers/__pycache__/objective.cpython-310.pyc,, +pygments/lexers/__pycache__/ooc.cpython-310.pyc,, +pygments/lexers/__pycache__/other.cpython-310.pyc,, +pygments/lexers/__pycache__/parasail.cpython-310.pyc,, +pygments/lexers/__pycache__/parsers.cpython-310.pyc,, +pygments/lexers/__pycache__/pascal.cpython-310.pyc,, +pygments/lexers/__pycache__/pawn.cpython-310.pyc,, +pygments/lexers/__pycache__/perl.cpython-310.pyc,, +pygments/lexers/__pycache__/phix.cpython-310.pyc,, +pygments/lexers/__pycache__/php.cpython-310.pyc,, +pygments/lexers/__pycache__/pointless.cpython-310.pyc,, +pygments/lexers/__pycache__/pony.cpython-310.pyc,, +pygments/lexers/__pycache__/praat.cpython-310.pyc,, +pygments/lexers/__pycache__/procfile.cpython-310.pyc,, +pygments/lexers/__pycache__/prolog.cpython-310.pyc,, +pygments/lexers/__pycache__/promql.cpython-310.pyc,, +pygments/lexers/__pycache__/python.cpython-310.pyc,, +pygments/lexers/__pycache__/q.cpython-310.pyc,, +pygments/lexers/__pycache__/qlik.cpython-310.pyc,, +pygments/lexers/__pycache__/qvt.cpython-310.pyc,, +pygments/lexers/__pycache__/r.cpython-310.pyc,, +pygments/lexers/__pycache__/rdf.cpython-310.pyc,, +pygments/lexers/__pycache__/rebol.cpython-310.pyc,, +pygments/lexers/__pycache__/resource.cpython-310.pyc,, +pygments/lexers/__pycache__/ride.cpython-310.pyc,, +pygments/lexers/__pycache__/rita.cpython-310.pyc,, +pygments/lexers/__pycache__/rnc.cpython-310.pyc,, +pygments/lexers/__pycache__/roboconf.cpython-310.pyc,, +pygments/lexers/__pycache__/robotframework.cpython-310.pyc,, +pygments/lexers/__pycache__/ruby.cpython-310.pyc,, +pygments/lexers/__pycache__/rust.cpython-310.pyc,, +pygments/lexers/__pycache__/sas.cpython-310.pyc,, +pygments/lexers/__pycache__/savi.cpython-310.pyc,, +pygments/lexers/__pycache__/scdoc.cpython-310.pyc,, +pygments/lexers/__pycache__/scripting.cpython-310.pyc,, +pygments/lexers/__pycache__/sgf.cpython-310.pyc,, +pygments/lexers/__pycache__/shell.cpython-310.pyc,, +pygments/lexers/__pycache__/sieve.cpython-310.pyc,, +pygments/lexers/__pycache__/slash.cpython-310.pyc,, +pygments/lexers/__pycache__/smalltalk.cpython-310.pyc,, +pygments/lexers/__pycache__/smithy.cpython-310.pyc,, +pygments/lexers/__pycache__/smv.cpython-310.pyc,, +pygments/lexers/__pycache__/snobol.cpython-310.pyc,, +pygments/lexers/__pycache__/solidity.cpython-310.pyc,, +pygments/lexers/__pycache__/sophia.cpython-310.pyc,, +pygments/lexers/__pycache__/special.cpython-310.pyc,, +pygments/lexers/__pycache__/spice.cpython-310.pyc,, +pygments/lexers/__pycache__/sql.cpython-310.pyc,, +pygments/lexers/__pycache__/srcinfo.cpython-310.pyc,, +pygments/lexers/__pycache__/stata.cpython-310.pyc,, +pygments/lexers/__pycache__/supercollider.cpython-310.pyc,, +pygments/lexers/__pycache__/tal.cpython-310.pyc,, +pygments/lexers/__pycache__/tcl.cpython-310.pyc,, +pygments/lexers/__pycache__/teal.cpython-310.pyc,, +pygments/lexers/__pycache__/templates.cpython-310.pyc,, +pygments/lexers/__pycache__/teraterm.cpython-310.pyc,, +pygments/lexers/__pycache__/testing.cpython-310.pyc,, +pygments/lexers/__pycache__/text.cpython-310.pyc,, +pygments/lexers/__pycache__/textedit.cpython-310.pyc,, +pygments/lexers/__pycache__/textfmts.cpython-310.pyc,, +pygments/lexers/__pycache__/theorem.cpython-310.pyc,, +pygments/lexers/__pycache__/thingsdb.cpython-310.pyc,, +pygments/lexers/__pycache__/tlb.cpython-310.pyc,, +pygments/lexers/__pycache__/tnt.cpython-310.pyc,, +pygments/lexers/__pycache__/trafficscript.cpython-310.pyc,, +pygments/lexers/__pycache__/typoscript.cpython-310.pyc,, +pygments/lexers/__pycache__/ul4.cpython-310.pyc,, +pygments/lexers/__pycache__/unicon.cpython-310.pyc,, +pygments/lexers/__pycache__/urbi.cpython-310.pyc,, +pygments/lexers/__pycache__/usd.cpython-310.pyc,, +pygments/lexers/__pycache__/varnish.cpython-310.pyc,, +pygments/lexers/__pycache__/verification.cpython-310.pyc,, +pygments/lexers/__pycache__/web.cpython-310.pyc,, +pygments/lexers/__pycache__/webassembly.cpython-310.pyc,, +pygments/lexers/__pycache__/webidl.cpython-310.pyc,, +pygments/lexers/__pycache__/webmisc.cpython-310.pyc,, +pygments/lexers/__pycache__/wgsl.cpython-310.pyc,, +pygments/lexers/__pycache__/whiley.cpython-310.pyc,, +pygments/lexers/__pycache__/wowtoc.cpython-310.pyc,, +pygments/lexers/__pycache__/wren.cpython-310.pyc,, +pygments/lexers/__pycache__/x10.cpython-310.pyc,, +pygments/lexers/__pycache__/xorg.cpython-310.pyc,, +pygments/lexers/__pycache__/yang.cpython-310.pyc,, +pygments/lexers/__pycache__/zig.cpython-310.pyc,, +pygments/lexers/_ada_builtins.py,sha256=Z5IiSpdugeKU4H-SEczWPYG6EO0e-R7lwP7thfORooU,1543 +pygments/lexers/_asy_builtins.py,sha256=qn1PmuijZ0P5Mkd1hWmH1arUt03wGWR7QNZf7ACBcCQ,27287 +pygments/lexers/_cl_builtins.py,sha256=n0Y1jei9ssrZ58Ev4GMxDTspYXU58TyAhLJzBApLttE,13994 +pygments/lexers/_cocoa_builtins.py,sha256=LvaPwfjM2r73yJwTMNu1SiDKzWWqzhJBjN_kivnYsyo,105182 +pygments/lexers/_csound_builtins.py,sha256=IY2H0Eg8iBFdmWwecXGwDC41Glrw_bWLenQCtp6DHzg,18414 +pygments/lexers/_css_builtins.py,sha256=IuSVV88A8b37-XsXGF4_6P6XF5Wv3wd3SxYOS1fOGyU,12446 +pygments/lexers/_julia_builtins.py,sha256=evrvUJjAKN8bCeBooXqAeGnWRc0qBqG_W2TMRPWq7Q4,11883 +pygments/lexers/_lasso_builtins.py,sha256=9Ld87CsxAB9UTV77I9W6s_bv4p-kc2grOnc8Ew7cy3s,134510 +pygments/lexers/_lilypond_builtins.py,sha256=rVmINQYq3iQ9-5W_jGrwW4Q9OX_zEX37I-pn5i8Ya1c,108094 +pygments/lexers/_lua_builtins.py,sha256=x8gSOJzBlwMFH9XFxwgF0-3kMn066YRQTLJyM_fl22s,8116 +pygments/lexers/_mapping.py,sha256=Wf3eD6HwNtDw-5X2jI31IG9bfiUhH1SBzC0SLum_qlM,65633 +pygments/lexers/_mql_builtins.py,sha256=j2K4s3Ye_tYEfJEyUKxvqR3ns_ZOLHGaiPDhkGRk40k,24713 +pygments/lexers/_mysql_builtins.py,sha256=8LqPsM38R2Et1U8sg-oy09aedb-jO1DgVGmssDUw6kg,25842 +pygments/lexers/_openedge_builtins.py,sha256=ZK0Vwj0PfCtg5WpOXCvI0OUnozrNbQxY_HNB_JhAXQc,49398 +pygments/lexers/_php_builtins.py,sha256=ns_E12wFe4Ce3EP38B0DRhAnhHTrdh7WfhjnDWgnJJ4,107930 +pygments/lexers/_postgres_builtins.py,sha256=LQbzTa5ICPqTspfBk7_4JV6bkjB5lz7uuWAUNRj6W4E,13355 +pygments/lexers/_qlik_builtins.py,sha256=zc-fq_8mXsR_XVzTEXFRjGbuwdACJ3O9QrMiEGfuKxQ,12595 +pygments/lexers/_scheme_builtins.py,sha256=ZdZg6-MK7Zt2qqOSBUS5D9YzULtlJIuUxvk39r-HTNc,32564 +pygments/lexers/_scilab_builtins.py,sha256=ib-wZROxsKBi-csMVlGBFHpzDzkT0FPn2wZZN29_9Rw,52413 +pygments/lexers/_sourcemod_builtins.py,sha256=nV2ZcNTvMY7x4oQ2niSNV1XTH9bkXbcAt2-A6ODs55k,26781 +pygments/lexers/_stan_builtins.py,sha256=gl_po01tnvV_tGj31jKHqaSnybhow9ElvFjYU4vWdIs,13445 +pygments/lexers/_stata_builtins.py,sha256=hIGKIkcalQetIwOoN30uflOYgYIOlG3mJ6H6f82edro,27227 +pygments/lexers/_tsql_builtins.py,sha256=wDKfDkftAUjPQW1RPjAwsaLE6VZeTCyCy21z44Uz7Vc,15460 +pygments/lexers/_usd_builtins.py,sha256=H7AYHzkaizd4mFrMtjvI913cX9YdK4qs9JrOlIdcl7c,1658 +pygments/lexers/_vbscript_builtins.py,sha256=EhzEYIk-DBIuU0sMg_davSSL1w-o3enlT1S9uzljZfM,4225 +pygments/lexers/_vim_builtins.py,sha256=BG929NCy6g3LHhpj8R_ueUWqLbuIt0kyCJhxR1Q5SJo,57066 +pygments/lexers/actionscript.py,sha256=lVrwbX2OYnN-KMGd4j3y0z-bWHdNxDDcf8peFMo9x2E,11676 +pygments/lexers/ada.py,sha256=3PAvDXPLpvlpLCSSVl3k1RcBPm7M2LzI3ZU1MJDPqD4,5320 +pygments/lexers/agile.py,sha256=C5m07vIsCir2Amrv0QK0Ah1HbTcjBOBwMdF-x2r__6E,876 +pygments/lexers/algebra.py,sha256=ns54jf39mw-oh8gFZ0mj9Z2zYK98Rq5XJfA99-EjmTE,9873 +pygments/lexers/ambient.py,sha256=u333k5mScy3cUUDQEJdxMQvOEX16aqpTd1DiJeTYzqE,2606 +pygments/lexers/amdgpu.py,sha256=f46YvzV1sD3eEfcdkRYIjkS1YTtHyVJT5T2awL48dlo,1670 +pygments/lexers/ampl.py,sha256=lfHAA0ZG4Dv38l5wTYi6InlXXXJ65FaXLjZU0tR_sWw,4177 +pygments/lexers/apdlexer.py,sha256=EbgslrWGNFYOa8a-fN-PMv4_pCv3Kbdo7TIHN_DCXAg,30766 +pygments/lexers/apl.py,sha256=f4QwKpfzMiUPRXCzmcBfN99TV2YVKyNzZ09Ey0bubYc,3405 +pygments/lexers/archetype.py,sha256=pps0tkPaK1VPJePJg0HyaGfTTwEpApgJ-qg9MJ9a6yE,11469 +pygments/lexers/arrow.py,sha256=wnI3F9Zo9HaYImF2pgksdosy3hkztFyA5GGycbtQoIM,3565 +pygments/lexers/arturo.py,sha256=wIFytTnZAkKVtHVjKK5FK2XLRie_hcv8YSs1Z2UAFlA,11417 +pygments/lexers/asc.py,sha256=2UWRy1MEjFFAEJhnRrbnNLkuJPxkX01rS5csR8h1kqI,1621 +pygments/lexers/asm.py,sha256=2sSPg4tLOPzUTQoTAh8pL5tWbdS_KmqQSr9BTQLVRt0,41243 +pygments/lexers/automation.py,sha256=Zgal7cKSlj0SaHAXx98gHjNM1tvCVIO2UykseFquNy4,19815 +pygments/lexers/bare.py,sha256=0WEBxv-FSgow1RFZzaXGFo00iwklIF5FpjJZDOOWbDo,3021 +pygments/lexers/basic.py,sha256=cxZ7oKq924j8_gDolL_IDV4CSN2vXKk6S7DIw2WlTc8,27923 +pygments/lexers/bdd.py,sha256=JsA-W_-oICZKrZS1i7NNYrRmDRVf3iuI1PufUdMkQhU,1652 +pygments/lexers/berry.py,sha256=swc0EY-bEf0wNFUhfvdkgWmP-PXV8PGvhNagqtsUqmA,3211 +pygments/lexers/bibtex.py,sha256=jzuo9lEZHPKzAAMpIeIWkNTr5I1LO-TMn1V9SdyHT1o,4723 +pygments/lexers/boa.py,sha256=bi5ZlPV61Xehq8bmSdFyqt3BN1jC03pB4t5Foa4vKPw,3915 +pygments/lexers/business.py,sha256=-QHRTWCdabWV8SIbKZ1oLH5NQ3-blSPES8jjIbEvD_I,28112 +pygments/lexers/c_cpp.py,sha256=aXnfgewGmhXwK0-Ii6prW8qT1bJdBOMnDU_C6_d6exU,17791 +pygments/lexers/c_like.py,sha256=uWObWqxC4d-ZyyzEG2yajKZgpq4iINyAcqw7LMnnxZU,29206 +pygments/lexers/capnproto.py,sha256=fE3wK-3ZBzPsDaFf9EkE1dnGDRhJbcCqjyBXRm8GlD4,2175 +pygments/lexers/carbon.py,sha256=HA5UMPQnDa55KCqU9dm6cuvqBuEgb9ZAPv2bCV7K1SE,3231 +pygments/lexers/cddl.py,sha256=PZS6611__hY36NZj8n9Q__JMXNLSm_aMWLpC51axc-M,5182 +pygments/lexers/chapel.py,sha256=1oFt0h0Rh7JnF2qw1QtT0XzkUanV-Xb9Xi9B9ZcHaIA,5157 +pygments/lexers/clean.py,sha256=afJe0orU7Ux_pmmrbSNYPLrTCkY_z0MJTmhUBqPtyJU,6395 +pygments/lexers/comal.py,sha256=9IwxfxVBVMn7Uj2xo-WCr7RhLRDrDe6wjTdAi5hWT2g,3156 +pygments/lexers/compiled.py,sha256=xv8krgoDgd07QDXVPaa5uip1kl9tBprkGT1K5-DwiWE,1407 +pygments/lexers/configs.py,sha256=PChZPzlJBbeeIPPF2soAVbH7GZ653CZMPl7lOe016U0,42338 +pygments/lexers/console.py,sha256=17k4Ngrs0EsaJg90ud6dle-I1SvjoOiYJ-xuGpLesTI,4148 +pygments/lexers/cplint.py,sha256=HrKuhRKjK-atw1FKT_zu4FJjlHOM5BppRzoxisXbpZM,1390 +pygments/lexers/crystal.py,sha256=W7v6oZtbm-aqiM9IOqIypKkudxQICWRdoy-ZyWUdt6s,15756 +pygments/lexers/csound.py,sha256=yuzpCdZuHDmr2eaNodglDrCgX1W62xtQvjitnHlXC6s,16994 +pygments/lexers/css.py,sha256=lZKXESVwZRYTjjRkyB4cYpXk9CHcVxU_embzFRtPhhY,25322 +pygments/lexers/d.py,sha256=f1dFv2mAXqLKSJQ59m66u1Mj9us3fDskxltlrJ8EBmM,9875 +pygments/lexers/dalvik.py,sha256=0Ii9KIUWT5FkJkLKuUcHoHPhav4eEHqsWZL2_ikP1ZU,4607 +pygments/lexers/data.py,sha256=86RLrfLKYxNhjE_1eTjiz0HJxY-393QyyEC37lN98bk,26940 +pygments/lexers/dax.py,sha256=od3D5zfaryI5MO93E_OA-TUpekAcjXv73l6kNit57oI,8099 +pygments/lexers/devicetree.py,sha256=4GKiuZC5bYwG_gIl30fZH8VV2zo4cqwdemQrQgWH7ZQ,4020 +pygments/lexers/diff.py,sha256=VAyAFRFmyMH865rEJ37I3TpyrpLUoEMU95durw6HLRc,5278 +pygments/lexers/dotnet.py,sha256=VjJWh7vslMNIoQdPFNUlAZI0ExuLFV6EdrywYaIjqQU,37623 +pygments/lexers/dsls.py,sha256=iSiDn_HsIeiYx8PFUTai5KHzISWLbClz2hwQudFrgmg,36774 +pygments/lexers/dylan.py,sha256=kTowexiIoOnu-xJ9evkuMBc_7Yr1vxzMITbsCcM_WdI,10380 +pygments/lexers/ecl.py,sha256=Cezl6tWf-a8hMEEUfJqYI3EPf6sSS3kRz0GiOuFIQ4Y,6372 +pygments/lexers/eiffel.py,sha256=jt_49tqubN-gLnobCJn10oWxkCW5MosbUBtm5XjnaI4,2690 +pygments/lexers/elm.py,sha256=OpKdJV4nlVGBv8G8lDeeLdQPbDzaJWtn-TJmS8N9N5w,3152 +pygments/lexers/elpi.py,sha256=3_dxhdKG3yO7yeK4r52XmDt6-UZ2vEuI7FZe5jTcSlg,6370 +pygments/lexers/email.py,sha256=EB3YvRDEP6_B6B1wzq0vS4_zrBX52zdyXxiNI3KHgxs,4742 +pygments/lexers/erlang.py,sha256=EhFx_0D9w85DCJR9FyUprFPiaDvJps3xy-Kn4whWcjs,19170 +pygments/lexers/esoteric.py,sha256=V--w2W-Jyl4yB8A00f4GikVeZXe_5lWHE0RMnfuoLTY,10396 +pygments/lexers/ezhil.py,sha256=xu9wMEESVWCLgNitSS0IS855TSJ3Yb2KXBrxmYqHKSo,3273 +pygments/lexers/factor.py,sha256=iVSIZaT7-qAI41wP__p2XjTSyREBSyAErPLVGP4bMeU,19531 +pygments/lexers/fantom.py,sha256=0DylUHKCeBMfQK4QczavL5ugyPTV0u5H0Lk0YTv6_mU,10197 +pygments/lexers/felix.py,sha256=fJsd0mNaSwkjU32-103-9XDzzz2lj-ONPiW8JkZAqxM,9646 +pygments/lexers/fift.py,sha256=ISH11Bvz15ZsMjTMdLDsHFx2HYgpGyDUlvi1CN8MC8Q,1621 +pygments/lexers/floscript.py,sha256=UYPHl2Ygez7RfBPTU00hUMXrU10mB996vz6rFisAmTs,2668 +pygments/lexers/forth.py,sha256=PzfXkhpusFIGVwrzVsqLgljlybN92OeU0_E3rHup2m0,7194 +pygments/lexers/fortran.py,sha256=i7xVuZEQnYruMo4xfvGI0izozI1qJvcPO8Dr7KRU0Vg,10336 +pygments/lexers/foxpro.py,sha256=XmVcWgw70vh31gri3LhfrB2YQ-RhkUkBKly0xHt8VQs,26212 +pygments/lexers/freefem.py,sha256=e_YjjHZu8PzQBykLzhpY2RJHjCnLxnlmoGj-5RinP6c,26914 +pygments/lexers/func.py,sha256=h6IHCdydWKpQcamC1XAGJjaGK-UDvh9iM0ZuWQK05dQ,3622 +pygments/lexers/functional.py,sha256=IpvPKomRGDqGs_MZZjkX5niMGZO9s5X1Dk0HDyO9zWM,674 +pygments/lexers/futhark.py,sha256=NwNYLxQ1feJwtPjG54VmSmo_ZtcTqtlzr0QQppmxWUM,3732 +pygments/lexers/gcodelexer.py,sha256=H754t2DKkgJYF-mzm4uI9dqc0qE02fjlZZfXM0eg6Lc,826 +pygments/lexers/gdscript.py,sha256=DFvf9eJgJic5DUHt2lrJksSu5X6eXRfrh30t5yAVSzY,7543 +pygments/lexers/go.py,sha256=7SiL-LKgT6BPX44KASMgt4mne5KOusaiAfN13YxHn5g,3761 +pygments/lexers/grammar_notation.py,sha256=SNQNggmjYCC0yRN2m2r_33X2pa8bw0AxLJsG1G5FjdQ,7980 +pygments/lexers/graph.py,sha256=AHtLRCnQdeY5fQdMJItngN67PBVlxWn2Eq_0ua4VlJI,3861 +pygments/lexers/graphics.py,sha256=AqhzeSjpQwk1Vrj_OT5jKDJMonB90Sr01mM3q90WGVg,39026 +pygments/lexers/graphviz.py,sha256=_yJaR2CW--2ljvnPdNjsVOvosPoUJw0pb3Of33nWBtk,1935 +pygments/lexers/gsql.py,sha256=7GDWo1Wvt5UmJhAC8HQND1kbdONBRE1YhdawBzgGrHA,3991 +pygments/lexers/haskell.py,sha256=RkYEh9-amHeRS0-dU5Nyz4RL4KKJz27PsWhNpf-C7NA,32898 +pygments/lexers/haxe.py,sha256=W4ILlVNk1D6USMa2Kkr00IFaoqtUIxd5cO8_xWzo23k,30976 +pygments/lexers/hdl.py,sha256=xA5YnwhgaOTzvLpE1VIP8j7l5LM2FjkpssZyMe3sPtY,22520 +pygments/lexers/hexdump.py,sha256=QLvXzWmo2_xqHMy55OTXUB15CokyQLMzHvmXuwMj6z8,3603 +pygments/lexers/html.py,sha256=MTahzHDswG59eYeNbEwKP16pkY4DV2F2M3Rm-ZDqmWI,19879 +pygments/lexers/idl.py,sha256=bhS43u_ycIVN-dxlL0rkVDW0Kunuv4nCgMiw4CrEVTk,15450 +pygments/lexers/igor.py,sha256=lwYCukIE6R4Ly5WAFcjs03m5T7HNK9FpXlYjoJg33gY,30631 +pygments/lexers/inferno.py,sha256=0pRpoR7W1Kp8q_9mxY43rYw_RYef3ruJ6xV1LwYbz3A,3136 +pygments/lexers/installers.py,sha256=5_jhlzWYi_6LMEr8BnpbjgiScZ_G3Q7AH6fTG4WrPRc,13178 +pygments/lexers/int_fiction.py,sha256=CkGFrMPiZZ6aQ607E4yfZDTcYpz1pdrbd4azyx7XVX8,57119 +pygments/lexers/iolang.py,sha256=ieom-sc8xdXbHi4g5LDofvLduKZdVBSOEwXocKmQU2g,1906 +pygments/lexers/j.py,sha256=Kd0Rga_1uwU_YhfXebvGuHKpOXM2SVH0_x_CqkCJVCk,4854 +pygments/lexers/javascript.py,sha256=y4ve9s2jq4UaTr9PhkNERIlu2DpbP_l64N_r2JJOBV0,62859 +pygments/lexers/jmespath.py,sha256=3P4_YQXh4IoohDQhoh0pquyFuUHVd88g7KYmVYg3NoM,2059 +pygments/lexers/jslt.py,sha256=cvH2LIuUnkhaqhfWvkIjS7sSx2FpXSEvl3rOF47d6Y0,3701 +pygments/lexers/jsonnet.py,sha256=CiJT00Tp0lBg9j_1EW-d6_poumtHoP2TmEQVDlf3cTs,5635 +pygments/lexers/julia.py,sha256=F5zuRm7OSZQeV1na7lasypEDGreLAzOdfaKmH1HIxgE,11646 +pygments/lexers/jvm.py,sha256=nyRvIF12oTZRmU0qDhgOQx8AsUgoZj1zMU8tDGyOP8U,72929 +pygments/lexers/kuin.py,sha256=AVUDd6JAy1jClIYeQDPcV-O7xGfb7x7fojN7hb7ANHU,11406 +pygments/lexers/lilypond.py,sha256=_A5P7PaITP8COXG8dy9nS7CzfdKY2UOe1XLGtucuip4,9753 +pygments/lexers/lisp.py,sha256=lIeqd1varBR8dCUi3MNr60Ikxf4W9sFsF7KW6n0lrR4,144039 +pygments/lexers/macaulay2.py,sha256=xc7ZUhQhfnRIoRBnWIbVw89KmZHac7qO1eQm2lSvnWA,31914 +pygments/lexers/make.py,sha256=Pif0_6zvfwAYd3cm2oKMDJHdySP2T7CzHZPFnGMmboI,7618 +pygments/lexers/markup.py,sha256=A_9ldnhEXDByWZL77eTq-JdyLnF_KAJ0by7jjzU70G4,58129 +pygments/lexers/math.py,sha256=Wl6lU1VWevtQXymt6jdDeuz9LEMiPKl1On3Zm3QXQ8M,676 +pygments/lexers/matlab.py,sha256=WplG578_mB6sHlDDfgY83SMadCcqD_sN5Jb593rSr6w,132852 +pygments/lexers/maxima.py,sha256=tLSjeDIBZKHRoMludgF7oBdz1xTAHyvIEG6BshyBXyM,2716 +pygments/lexers/meson.py,sha256=ij0CgbEULfqLMcY_BQ7PxmCwWOYLc9XZwtrALFSinEA,4337 +pygments/lexers/mime.py,sha256=-wj3pvAQzNTC8fTZk9AV4Q-LIQhMUocet-j2kqGj5gs,7538 +pygments/lexers/minecraft.py,sha256=-Tb9aNbNM8gXgq69uaCxfmyTQlJ9dYYTK9UaFbSE2CI,13846 +pygments/lexers/mips.py,sha256=JBfvOPp5HTGp6b0kynkjzuJOTRAdTsJJdjPWLAtu1fo,4604 +pygments/lexers/ml.py,sha256=WlIdrpHCP8Z8OB5nkDXA6NyTvxPuc0tOueobOc8V840,35324 +pygments/lexers/modeling.py,sha256=3KxuIs1-lb_FN921kCCgjq84R69ATEp6K1EQyWaxp7M,13524 +pygments/lexers/modula2.py,sha256=z-4QbG4Bgjd-0ONC9SadglqCW2QmIMl-60b_n35V-70,53073 +pygments/lexers/monte.py,sha256=pKPKOkwxcGzJLVisA-H7xJJW9JUh2SsXyDi32mF5nSQ,6290 +pygments/lexers/mosel.py,sha256=_JeaaK5Jn0r7JcuLl62u1sl6uInkrP9g4EosCf9Z-IQ,9187 +pygments/lexers/ncl.py,sha256=O6CckyU8yABKmx8xmj4q6E2isWORmvNO7Xl1JX5NwVQ,63962 +pygments/lexers/nimrod.py,sha256=O_8dxk9x3vlYFPYjpe8iqQcCrcZmNnBE_Ld1lzO7xVI,6416 +pygments/lexers/nit.py,sha256=Ghja_AX8DIg_KA-rmvgmL76kZI-lq3pARMiebYi9Nqw,2726 +pygments/lexers/nix.py,sha256=qeKFMOSHa627SlkPsbpIOfzLu2ej-JdgGkDAqt4isP4,4015 +pygments/lexers/oberon.py,sha256=LgYgzGPus7w1lJLUAu2cmIRQGEgQiid34QH5Upa7Uro,4169 +pygments/lexers/objective.py,sha256=VoUeZYa1aO5rU69dDpv4Ob5FOYyr3nm-eJ3m0kuti0U,22961 +pygments/lexers/ooc.py,sha256=BEj7kfOimF_Qi62R-B8bmYGy_5QIE1jS20NfrnNE9Ss,2982 +pygments/lexers/other.py,sha256=oXVtTELCPFxwuJxN5j_iYrt0Q9Aonq-GkotncUFPpeE,1744 +pygments/lexers/parasail.py,sha256=MxO40OTg_5z_EnMyb6weQHjhtzL1WgSwfjCXc0zl82Y,2720 +pygments/lexers/parsers.py,sha256=JiQT3IMsf2f0JLbiDpupZNSsHnMUH57OoAr0D_3AvbY,25904 +pygments/lexers/pascal.py,sha256=EHZi_mh4V7LuGXtcbTQnrrfqDDXcGyVwDvJmN8XRcps,30880 +pygments/lexers/pawn.py,sha256=fNq73VwQoXeKiRFKYIKzzOClcUb2eLPJIhymlnxKZlg,8146 +pygments/lexers/perl.py,sha256=82_7saaR3qBFlSnWYyEtkir7uvXTeUZqFUhjdkdTTXs,39170 +pygments/lexers/phix.py,sha256=48JEQK_0ijjipwDl1F-ik0B_CGUMsZOvXlvXzIqHVmk,23252 +pygments/lexers/php.py,sha256=b4sVWZTMq0t2GMlaFmzYWJna9WuDQFIm-vdqXkb89xo,13040 +pygments/lexers/pointless.py,sha256=dUATlYVUZkbggQ6PUymDKhB0UKqDo-KCf0Fp_EjWsTM,1975 +pygments/lexers/pony.py,sha256=k03DAhS-_G8SZsfXZOjF5YkQaMQ28_uy68_CMaxuUC4,3244 +pygments/lexers/praat.py,sha256=rTl5GSoJ58LQxRf_Ek0A1H4iCm2IVQFxEwSvbMki7tw,12677 +pygments/lexers/procfile.py,sha256=naQZcdvxVUjT56R0U6_YpgNCgfmNE9Xjzx9uQesl-Cg,1156 +pygments/lexers/prolog.py,sha256=d010T34HBjbf8I1PoCiU2mDPQlMLhBG8-eFbAILqy7Q,12351 +pygments/lexers/promql.py,sha256=Qw0VXIJGRkw6ZiSzvtR0KFiWmPuyI9xxXgDl_l3cHmc,4715 +pygments/lexers/python.py,sha256=Dxdo6Pej2cdLI-LdR7jw18NQegVp3_YQIgVNV2jbOWU,53376 +pygments/lexers/q.py,sha256=Vw36x6rIp2U1b8GUtUbMlcD0MVqW3unCZEMBEt-PflQ,6932 +pygments/lexers/qlik.py,sha256=gCAQCe1Tuy_cMI4n51Sb8fG50L73AgmUMEWMmZRHeJg,3665 +pygments/lexers/qvt.py,sha256=IjHyopkDochlQt_fIf7Mrxw84pIg-gj4BkDHtEiKb_U,6072 +pygments/lexers/r.py,sha256=xMSNpNN3Hm0W51-TEfvzPeOGtobM2nIjGVmIoVydlfU,6185 +pygments/lexers/rdf.py,sha256=9aVmpa5FSE3rZwekkSRYp-qxi4Yg_SlFbX5kIPjgQdU,15790 +pygments/lexers/rebol.py,sha256=TMT3JlXoWvJbZwZdLuekwgv584HEP1mfsD2g9Oqj0IU,18248 +pygments/lexers/resource.py,sha256=KxxQJi9NPmghpa1mekxUFBd8eaiSB9pV_F4Eds4kK0k,2902 +pygments/lexers/ride.py,sha256=0mT89oluoz5lUT8ar6uPiSwTIBwyMc6oHYnrM5QY7Vo,5056 +pygments/lexers/rita.py,sha256=gPbMhlCyS_ekzXIKboXGEmtGZlSSUx0k6qcuWEHuM6s,1128 +pygments/lexers/rnc.py,sha256=SjXKJWNifTTWQC9NlcWNmdhkln0REEpEvaY6nVy6n4w,1973 +pygments/lexers/roboconf.py,sha256=HY0dSPJxg7knQ-cM6YotX8EoVjuQi-LeKYKeWpQyF94,1962 +pygments/lexers/robotframework.py,sha256=MJ4cnUDZWDrXCpYi-kJLqe1HpzJ24DMtNswDeuSnVCc,18449 +pygments/lexers/ruby.py,sha256=74k_3VNHUiJGVbqdAI9wALjir3CjpjhJiGM1gPir8iU,22775 +pygments/lexers/rust.py,sha256=Oq5bFgf_hcOLxiBLhzPArUFXgg3Ude_xpeKPC3g-HDI,8216 +pygments/lexers/sas.py,sha256=u0vkPLehX7UERsKIkooC4IFJdTf44L2_Qqdpx1De7wk,9400 +pygments/lexers/savi.py,sha256=3A563B-Wzp5AGZG0ruSQiPbe-c3uYGwCPUmnPJSEKOk,4645 +pygments/lexers/scdoc.py,sha256=cOeE0NUl7_PK9U6UwPMpoSfeFgyG5qIgJyw8oM7Qa-g,2239 +pygments/lexers/scripting.py,sha256=EkXKzWLg-jpsV8rep2YW6fDsCDz-d3fY1qv1QVE7MI8,70014 +pygments/lexers/sgf.py,sha256=Oa3SNL31wN8rhY0gby61kbPxttvRQJTRN38CSMUiMJE,1986 +pygments/lexers/shell.py,sha256=oC115DNmEzPYPdKN5jNUz-gV44c_qVb2Y5OfGO3gQ_U,36466 +pygments/lexers/sieve.py,sha256=lLcCLdvj-AeudiG2xq2zTN16v0zSEXK5vcr1keg0TxA,2441 +pygments/lexers/slash.py,sha256=_soPrmF1ylAw7IWfRHTMMUdifwy4oNV5FpYMBQsVSyM,8482 +pygments/lexers/smalltalk.py,sha256=9UNqjCWOay3nb5BVqN2Muw-Ci63WnscW6xJcGnNWVq4,7206 +pygments/lexers/smithy.py,sha256=FMvWXKvjF_hUNqI7BmZYbVRrPg5_AnnzORHPp3skcXs,2660 +pygments/lexers/smv.py,sha256=VyWuTjtAhaZmu6oZG3Om_kU3NhorVz9ivzeu_mfRjwo,2773 +pygments/lexers/snobol.py,sha256=Wp7ViMnddy79tWJjsgSB9kIPFh_OhaM4Y2tZjWDuvMI,2732 +pygments/lexers/solidity.py,sha256=Mhmypb5WzxGdBaQpySae9NbiFJllkEezditjHajd7RA,3127 +pygments/lexers/sophia.py,sha256=0gARv0DbMi7DWUc793pd4f7IKxSeOlkjk_eez8tLihs,3330 +pygments/lexers/special.py,sha256=SDWqBKmWmKyvi8VNfPpW1V4g7ergad4RfUumDh6bNrk,3414 +pygments/lexers/spice.py,sha256=2cE4npHPtc2tsIrI8rTbSZt4uRovx5H1YeKQZFL2d3s,2733 +pygments/lexers/sql.py,sha256=j-3EXShmUyB30w7zAfO8uv0ojK8ycQhq6gc94aQOz7I,42086 +pygments/lexers/srcinfo.py,sha256=x_6DsZ0mKVbI_v_G5bLBQl0WyFwj3tXmOqfHIB6zve4,1693 +pygments/lexers/stata.py,sha256=-IRfLl_rpuOiKs0Vnpc6OEKuA6AXbklW6RBGc7xzGEM,6416 +pygments/lexers/supercollider.py,sha256=Ua4RbmCRYPz7PcT1uyloAbfKc9kZim7nAKr55E26scY,3698 +pygments/lexers/tal.py,sha256=_wLncXDRKsBDQQYkUkq4tGGNjN5oj3VFhqoRZUcBYSE,2639 +pygments/lexers/tcl.py,sha256=STjHSlVeWo-Eg4tKqn_7m3_3efcmHP0WCoL1_PK5tt0,5513 +pygments/lexers/teal.py,sha256=t8eOzrIiImVuUtkBlSPl9Y4olrCAZ21SQB-T67WZasQ,3523 +pygments/lexers/templates.py,sha256=Eawt5MXOe1V2RB_vhp6097GQMjoKHPSEWHKifhdMazw,72610 +pygments/lexers/teraterm.py,sha256=71NiLefy40L6R4B-qy-ho8Uy4kAQqsi7iLxexCDS5rU,9719 +pygments/lexers/testing.py,sha256=Ue93uh36l7JKc0cUDnLmk-E221b5y7qt6xXHvaJRxt4,10767 +pygments/lexers/text.py,sha256=ntF8QwsuhsqyQdxMB6H7MYP7o8A7xSxHe0UMTZLKSK8,1029 +pygments/lexers/textedit.py,sha256=xVU-3K5-0KEkb0pJ4hJjrjpnz9hJaIuLQOxfk9nLWjM,7609 +pygments/lexers/textfmts.py,sha256=DDijMmBwcKGrYW2qbwz8W3vD3Uq6wpX_9w7fYKYnV2M,15192 +pygments/lexers/theorem.py,sha256=o3L_nfHpkio4l5RIj0UQ-CqWUEztt7Q5vh5lqDHZ-Co,20157 +pygments/lexers/thingsdb.py,sha256=FwelchVBXKf3nc78UgA9SyJbHta3EMdrLnQizIxS5SE,4228 +pygments/lexers/tlb.py,sha256=sQCsK3j8zqGVI_KCuursmOr4JIs3sfpqF_wPpQpyKM0,1377 +pygments/lexers/tnt.py,sha256=uvdcsw5NRZjbFouXBET3-w8I7LG9hqzMXiK6s_GK2ZY,10457 +pygments/lexers/trafficscript.py,sha256=GDl_7cSFit1anVH7KNH0qVts1eHcp_GGxpzIYWZabeg,1474 +pygments/lexers/typoscript.py,sha256=nIAUIlbL5sVqpTEt34YdUGDNmu60a7itBYaaUMuzAIs,8207 +pygments/lexers/ul4.py,sha256=XOm5dWiWtWN3RQMpA5VHvl1J1jg014SK27aJnVjq1C0,8956 +pygments/lexers/unicon.py,sha256=4MDnwsgXzLlm0zaDqYr9uHFNspgCzQRNzyxClVQ-RMI,18512 +pygments/lexers/urbi.py,sha256=3CkxfMOqpSVZpOq7_4YrWcmjq4B3CF_IDGIxAsedWQ0,6037 +pygments/lexers/usd.py,sha256=7FiS_KV1Q9Cvf51fAHmMqr5QDz1OtjqTkp1S-8VyQTw,3513 +pygments/lexers/varnish.py,sha256=LYL6rhIw-ApJRT4qkxFaxG71OPbHsiFv4mtfr0m1OPY,7273 +pygments/lexers/verification.py,sha256=1C1ntqvZmrCtzHV9eDIga1LtQ4jpAlb6GnWkNucEJXQ,3885 +pygments/lexers/web.py,sha256=lscit_NgXsHDL8sjvNvAFriPBe24cz0b2rBGFFpYlv8,894 +pygments/lexers/webassembly.py,sha256=HGFp4qMAK0ejx0omrThEtIvl_ArKOeS7b4yZkipqmIo,5699 +pygments/lexers/webidl.py,sha256=VeqO7i3Y-e0ObtLxn1sniGmL_CvOWekaP2XyUFzDlLQ,10517 +pygments/lexers/webmisc.py,sha256=veICtUXL33effcYDX8_FU1F0Q5FfZfzcC2Tyu5SYT9A,40549 +pygments/lexers/wgsl.py,sha256=Mffgj3x5tFwsKWihw2kbhSmhvGNEgQc_pJi6C3mEQxc,11920 +pygments/lexers/whiley.py,sha256=SbbftaItSgIdczzT8qOV8mH1m6dD3aM2EvRk4ila6Co,4018 +pygments/lexers/wowtoc.py,sha256=o_01SGTJ3jecVHEpkhqHdwI66XQVi8wNeajVYPbd4Bo,4021 +pygments/lexers/wren.py,sha256=I3LaIzy3aa0aDXJd9PJp-SiJtgJHktISHdQ_zQuMHLY,3239 +pygments/lexers/x10.py,sha256=p3VwQg70e8ZR2iwR2kY-yojTyD_s3xVJMLTCWrpz6Hc,1920 +pygments/lexers/xorg.py,sha256=rXKVNQiiniNoaM4VTkLFj106NLddCBo1BV45BTxT1HE,902 +pygments/lexers/yang.py,sha256=rx08okYvJgWMe6jMRkt-ysEuaTi85X5DE0Q5EHb-Ehg,4500 +pygments/lexers/zig.py,sha256=B5QZGfEoNkoAG5EZxHk28MZ1n2Q1Gvx11kcvTQ6N5X8,3953 +pygments/modeline.py,sha256=eF2vO4LpOGoPvIKKkbPfnyut8hT4UiebZPpb-BYGQdI,986 +pygments/plugin.py,sha256=k_gtJHBriDDWiNinQ-h_qnDUm7EnPLuXaTGH3Cd5pZw,2579 +pygments/regexopt.py,sha256=jg1ALogcYGU96TQS9isBl6dCrvw5y5--BP_K-uFk_8s,3072 +pygments/scanner.py,sha256=b_nu5_f3HCgSdp5S_aNRBQ1MSCm4ZjDwec2OmTRickw,3092 +pygments/sphinxext.py,sha256=MWLG74mLD1iqqrUbx7ZN6APuZ5eGi88yPbK0zajl3VQ,6816 +pygments/style.py,sha256=ePJAMWuctRHvKhdIFkZT9CAGEdHBZxx-Bv7PURa8NB4,6245 +pygments/styles/__init__.py,sha256=pVdtmEjFYxEO6Lf-duCMbfy_aB_FwXwD9Hzj1otwOow,3676 +pygments/styles/__pycache__/__init__.cpython-310.pyc,, +pygments/styles/__pycache__/abap.cpython-310.pyc,, +pygments/styles/__pycache__/algol.cpython-310.pyc,, +pygments/styles/__pycache__/algol_nu.cpython-310.pyc,, +pygments/styles/__pycache__/arduino.cpython-310.pyc,, +pygments/styles/__pycache__/autumn.cpython-310.pyc,, +pygments/styles/__pycache__/borland.cpython-310.pyc,, +pygments/styles/__pycache__/bw.cpython-310.pyc,, +pygments/styles/__pycache__/colorful.cpython-310.pyc,, +pygments/styles/__pycache__/default.cpython-310.pyc,, +pygments/styles/__pycache__/dracula.cpython-310.pyc,, +pygments/styles/__pycache__/emacs.cpython-310.pyc,, +pygments/styles/__pycache__/friendly.cpython-310.pyc,, +pygments/styles/__pycache__/friendly_grayscale.cpython-310.pyc,, +pygments/styles/__pycache__/fruity.cpython-310.pyc,, +pygments/styles/__pycache__/gh_dark.cpython-310.pyc,, +pygments/styles/__pycache__/gruvbox.cpython-310.pyc,, +pygments/styles/__pycache__/igor.cpython-310.pyc,, +pygments/styles/__pycache__/inkpot.cpython-310.pyc,, +pygments/styles/__pycache__/lilypond.cpython-310.pyc,, +pygments/styles/__pycache__/lovelace.cpython-310.pyc,, +pygments/styles/__pycache__/manni.cpython-310.pyc,, +pygments/styles/__pycache__/material.cpython-310.pyc,, +pygments/styles/__pycache__/monokai.cpython-310.pyc,, +pygments/styles/__pycache__/murphy.cpython-310.pyc,, +pygments/styles/__pycache__/native.cpython-310.pyc,, +pygments/styles/__pycache__/nord.cpython-310.pyc,, +pygments/styles/__pycache__/onedark.cpython-310.pyc,, +pygments/styles/__pycache__/paraiso_dark.cpython-310.pyc,, +pygments/styles/__pycache__/paraiso_light.cpython-310.pyc,, +pygments/styles/__pycache__/pastie.cpython-310.pyc,, +pygments/styles/__pycache__/perldoc.cpython-310.pyc,, +pygments/styles/__pycache__/rainbow_dash.cpython-310.pyc,, +pygments/styles/__pycache__/rrt.cpython-310.pyc,, +pygments/styles/__pycache__/sas.cpython-310.pyc,, +pygments/styles/__pycache__/solarized.cpython-310.pyc,, +pygments/styles/__pycache__/staroffice.cpython-310.pyc,, +pygments/styles/__pycache__/stata_dark.cpython-310.pyc,, +pygments/styles/__pycache__/stata_light.cpython-310.pyc,, +pygments/styles/__pycache__/tango.cpython-310.pyc,, +pygments/styles/__pycache__/trac.cpython-310.pyc,, +pygments/styles/__pycache__/vim.cpython-310.pyc,, +pygments/styles/__pycache__/vs.cpython-310.pyc,, +pygments/styles/__pycache__/xcode.cpython-310.pyc,, +pygments/styles/__pycache__/zenburn.cpython-310.pyc,, +pygments/styles/abap.py,sha256=pvsya8aKMVAkVeAsOumTamTsbnpTSaGNn3AUrYkbN_o,705 +pygments/styles/algol.py,sha256=Zpxg6alN3GogkpUWcp_EJlnqD_CBC9oxsvYkCOHLDHk,2216 +pygments/styles/algol_nu.py,sha256=JyBOI8tzg27aOr5Ua8JNPLi6d4BYTixFdkPBbKqEiAw,2231 +pygments/styles/arduino.py,sha256=Vsg-NzWKZZb4qMxgzE_Y2TX9lSx3FoUppRGUt8CSilk,4443 +pygments/styles/autumn.py,sha256=vW1xxGF7Sa6IQTBlKerrufIXY52O4QMglDazMPb7_Ek,2096 +pygments/styles/borland.py,sha256=hWDB1gJT-_3_exWgJ-49GJh1gwTNrOyQXp53zYer9cM,1514 +pygments/styles/bw.py,sha256=BSDFekRBkr7c156YahNtmJ9gxBwjxIO4J_p6olEB4t0,1308 +pygments/styles/colorful.py,sha256=ZbiSqyr-ZA4T-1RtHauihdJc05-Kt-lSFbJSO_jIwgU,2730 +pygments/styles/default.py,sha256=LSIWGkEJq5VI2qFkCjoDtHrlVPODKHgjADBsmD_kTEQ,2488 +pygments/styles/dracula.py,sha256=w_P_4Khe38U7BuEbbFHTwCGHBDLwAN7L9i6bKMnki48,3314 +pygments/styles/emacs.py,sha256=IpMu1Rlfe7ukZ17loTqy1NBxP-YTpGIjAuss-3lVVq0,2439 +pygments/styles/friendly.py,sha256=e8c1p4PwJDGoaR7myygugbEkP9PoHl1p17w5R1s5xGI,2502 +pygments/styles/friendly_grayscale.py,sha256=WHiGg5n6eN7Nd3TgMfSO_nUzjsulUJG0w9vWbQ6AAzw,2707 +pygments/styles/fruity.py,sha256=RHODyvBNzfoMsCXpo73rVE2P861U5Sp4y4Yeh5S5qA0,1274 +pygments/styles/gh_dark.py,sha256=o8MLrC_CA_RTLr7BoRdrXumBl6CvBEP1fDY_hqElDew,3481 +pygments/styles/gruvbox.py,sha256=N8HjBr8bmiCfqf0H_BSuSFxH9cM-sS7AYmvvK3NMPFE,3230 +pygments/styles/igor.py,sha256=WLVI14RraRiyO570MBPMTboieVvUyCxvToymTW33tec,692 +pygments/styles/inkpot.py,sha256=9zP09w_sdHagTqv2sIQXdZAn9HYCppQtiNKVoLWiSBA,2302 +pygments/styles/lilypond.py,sha256=wh-ip2qKgUTxdh82QKYCPdueDXhnCj-yatftcgWCljo,2016 +pygments/styles/lovelace.py,sha256=fZ8NAWw-4625onSvDxWbZoPRrQ65BrcTjVy3PqS5D30,3117 +pygments/styles/manni.py,sha256=CRsrOSBbQAXpV9JmnkVtHPp_cQIfpLL1tOA_3uG6dM8,2350 +pygments/styles/material.py,sha256=B4bBRcdTo87UGtNcmN4UUmdiFgv2hxacVne-eaJIzLg,4083 +pygments/styles/monokai.py,sha256=iqbl4_RZMUjHUj8jz98m4iB817M1meiiToS26xgP8C4,5063 +pygments/styles/murphy.py,sha256=lhyTqRqpzrICQeIMo74oQQVrfsyvmVpDeCr96xOXAp4,2703 +pygments/styles/native.py,sha256=sJMoL1xHC9o17AGgg2WMJevqxtGXRbYDL87Sipm1tik,1948 +pygments/styles/nord.py,sha256=CFLY6iz19dANPlYGDAWoxcoNAwYCkOGg5Mg7AtepNhU,5244 +pygments/styles/onedark.py,sha256=BgsmXfNk_A4NUpNZYtl0C-Cj368DiLrlrBRlop8CixQ,1664 +pygments/styles/paraiso_dark.py,sha256=cgvn8V7vQXKzPLdThGS-P7YRN1cT08UDxnL0AcKOWMw,5526 +pygments/styles/paraiso_light.py,sha256=QnkhJ-lFcGr0YktkIL2S3Ch8qntu95NWg2R1sAuPGA0,5530 +pygments/styles/pastie.py,sha256=7w75VUNUMoDofO-KHBXCfUZMxynstTDZzkcsStafOdE,2425 +pygments/styles/perldoc.py,sha256=ykm2Qo9YtThYyvAfAMJ2KUNCujSAP6qJbzj57Dv0USI,2128 +pygments/styles/rainbow_dash.py,sha256=Bz6H7VU7nc8cfT_c9s-DLQv4WpSaQV-bCluR371jVGs,2432 +pygments/styles/rrt.py,sha256=PyyasbLgJEGP_P9sMWMSKM2cVhk0yF6p0vGvtMEytG8,874 +pygments/styles/sas.py,sha256=D2HCwKU2ojWy-NPJsjiUKSDKNeMfJ7e04K_Hqki-dWo,1393 +pygments/styles/solarized.py,sha256=rBI99bncVDviqQZpkb7_aUCZ8UW3tIR65UYQzhhC3mA,4078 +pygments/styles/staroffice.py,sha256=SQb2dU8N5iVDK6z7NnYF-0XQL-s2mcu47vcbeImZ2mc,770 +pygments/styles/stata_dark.py,sha256=uKZsvGdSMxfKPlmKvPLWa48C1jXwuxlYVb44Kp2t2ik,1198 +pygments/styles/stata_light.py,sha256=l5V1Sdz31jEkzO7CdSSBXrKWfoGgOShjarO5WtqX4DE,1227 +pygments/styles/tango.py,sha256=1vrbjUD6WJHAkoHHO9emWYycuTB13rBRAPOeHwhzE4c,7039 +pygments/styles/trac.py,sha256=kLK0nHm0nqK-Yu3MnROfR_PnEyhJJhF5RxxqFu4dfaM,1885 +pygments/styles/vim.py,sha256=LoSIHP2S8t9jaKE0apklZkkPVG0EiVSLmI9RwEv1sUU,1922 +pygments/styles/vs.py,sha256=TCDk9S4B5mEFVs5rKz2f6yjb6Qc_2hv8QyII1QCchOc,1026 +pygments/styles/xcode.py,sha256=8nrGsI4FXIPx3DrGoqhLz_U0jZgpgKfW1FA2oV2iJ4A,1453 +pygments/styles/zenburn.py,sha256=RWniXYptEN65ip_FZGHnd25RvujfHSmhSZSWioH0xY8,2148 +pygments/token.py,sha256=seNsmcch9OEHXYirh8Ool7w8xDhfNTbLj5rHAC-gc_o,6184 +pygments/unistring.py,sha256=FaUfG14NBJEKLQoY9qj6JYeXrpYcLmKulghdxOGFaOc,63223 +pygments/util.py,sha256=AEVY0qonyyEMgv4Do2dINrrqUAwUk2XYSqHM650uzek,10230 diff --git a/shared/package-files/01/0192970c92a98db0e761de8c290b1dd46c28baec4da09ae831f64dc6e0f5a1d6/blob b/shared/package-files/01/0192970c92a98db0e761de8c290b1dd46c28baec4da09ae831f64dc6e0f5a1d6/blob new file mode 100644 index 0000000000000000000000000000000000000000..c26151b3e060203aef2ba513fb7602a044790dbf Binary files /dev/null and b/shared/package-files/01/0192970c92a98db0e761de8c290b1dd46c28baec4da09ae831f64dc6e0f5a1d6/blob differ diff --git a/shared/package-files/01/019331d0166c3f31be6d9f5737c5a4a193f390769f1031e0f8233ac70439796e/blob b/shared/package-files/01/019331d0166c3f31be6d9f5737c5a4a193f390769f1031e0f8233ac70439796e/blob new file mode 100644 index 0000000000000000000000000000000000000000..6ce6dd9f6ad39497398a52b7cc780fe36c606d3d --- /dev/null +++ b/shared/package-files/01/019331d0166c3f31be6d9f5737c5a4a193f390769f1031e0f8233ac70439796e/blob @@ -0,0 +1,28 @@ +#pragma once + +// @generated by torchgen/gen.py from NativeFunction.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace at { +namespace native { +struct TORCH_API structured_bitwise_xor_out : public at::meta::structured_bitwise_xor_Tensor { +void impl(const at::Tensor & self, const at::Tensor & other, const at::Tensor & out); +}; +TORCH_API at::Tensor bitwise_xor(const at::Tensor & self, const at::Scalar & other); +TORCH_API at::Tensor & bitwise_xor_out(const at::Tensor & self, const at::Scalar & other, at::Tensor & out); +TORCH_API at::Tensor & bitwise_xor_(at::Tensor & self, const at::Scalar & other); +TORCH_API at::Tensor bitwise_xor(const at::Scalar & self, const at::Tensor & other); +TORCH_API at::Tensor & bitwise_xor_Scalar_Tensor_out(const at::Scalar & self, const at::Tensor & other, at::Tensor & out); +} // namespace native +} // namespace at diff --git a/shared/package-files/01/019338803b42b546628dd04bc7fdab43d6c009a545fc86c9348334cc0ead4e30/blob b/shared/package-files/01/019338803b42b546628dd04bc7fdab43d6c009a545fc86c9348334cc0ead4e30/blob new file mode 100644 index 0000000000000000000000000000000000000000..0b97f6165ee6e6787f54aa77310a22ce188d3c10 --- /dev/null +++ b/shared/package-files/01/019338803b42b546628dd04bc7fdab43d6c009a545fc86c9348334cc0ead4e30/blob @@ -0,0 +1,113 @@ +#pragma once + +// @generated by torchgen/gen.py from Function.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + + +#include + +namespace at { + + +// aten::upsample_bicubic2d.vec(Tensor input, SymInt[]? output_size, bool align_corners, float[]? scale_factors) -> Tensor +inline at::Tensor upsample_bicubic2d(const at::Tensor & input, at::OptionalIntArrayRef output_size, bool align_corners, c10::optional> scale_factors) { + return at::_ops::upsample_bicubic2d_vec::call(input, output_size.has_value() ? c10::make_optional(c10::fromIntArrayRefSlow(*output_size)) : c10::nullopt, align_corners, scale_factors); +} +namespace symint { + template ::value>> + at::Tensor upsample_bicubic2d(const at::Tensor & input, at::OptionalIntArrayRef output_size, bool align_corners, c10::optional> scale_factors) { + return at::_ops::upsample_bicubic2d_vec::call(input, output_size.has_value() ? c10::make_optional(c10::fromIntArrayRefSlow(*output_size)) : c10::nullopt, align_corners, scale_factors); + } +} + +// aten::upsample_bicubic2d.vec(Tensor input, SymInt[]? output_size, bool align_corners, float[]? scale_factors) -> Tensor +inline at::Tensor upsample_bicubic2d_symint(const at::Tensor & input, at::OptionalSymIntArrayRef output_size, bool align_corners, c10::optional> scale_factors) { + return at::_ops::upsample_bicubic2d_vec::call(input, output_size, align_corners, scale_factors); +} +namespace symint { + template ::value>> + at::Tensor upsample_bicubic2d(const at::Tensor & input, at::OptionalSymIntArrayRef output_size, bool align_corners, c10::optional> scale_factors) { + return at::_ops::upsample_bicubic2d_vec::call(input, output_size, align_corners, scale_factors); + } +} + +// aten::upsample_bicubic2d.out(Tensor self, SymInt[2] output_size, bool align_corners, float? scales_h=None, float? scales_w=None, *, Tensor(a!) out) -> Tensor(a!) +inline at::Tensor & upsample_bicubic2d_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) { + return at::_ops::upsample_bicubic2d_out::call(self, c10::fromIntArrayRefSlow(output_size), align_corners, scales_h, scales_w, out); +} +namespace symint { + template ::value>> + at::Tensor & upsample_bicubic2d_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) { + return at::_ops::upsample_bicubic2d_out::call(self, c10::fromIntArrayRefSlow(output_size), align_corners, scales_h, scales_w, out); + } +} + +// aten::upsample_bicubic2d.out(Tensor self, SymInt[2] output_size, bool align_corners, float? scales_h=None, float? scales_w=None, *, Tensor(a!) out) -> Tensor(a!) +inline at::Tensor & upsample_bicubic2d_outf(const at::Tensor & self, at::IntArrayRef output_size, bool align_corners, c10::optional scales_h, c10::optional scales_w, at::Tensor & out) { + return at::_ops::upsample_bicubic2d_out::call(self, c10::fromIntArrayRefSlow(output_size), align_corners, scales_h, scales_w, out); +} +namespace symint { + template ::value>> + at::Tensor & upsample_bicubic2d_outf(const at::Tensor & self, at::IntArrayRef output_size, bool align_corners, c10::optional scales_h, c10::optional scales_w, at::Tensor & out) { + return at::_ops::upsample_bicubic2d_out::call(self, c10::fromIntArrayRefSlow(output_size), align_corners, scales_h, scales_w, out); + } +} + +// aten::upsample_bicubic2d.out(Tensor self, SymInt[2] output_size, bool align_corners, float? scales_h=None, float? scales_w=None, *, Tensor(a!) out) -> Tensor(a!) +inline at::Tensor & upsample_bicubic2d_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) { + return at::_ops::upsample_bicubic2d_out::call(self, output_size, align_corners, scales_h, scales_w, out); +} +namespace symint { + template ::value>> + at::Tensor & upsample_bicubic2d_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) { + return at::_ops::upsample_bicubic2d_out::call(self, output_size, align_corners, scales_h, scales_w, out); + } +} + +// aten::upsample_bicubic2d.out(Tensor self, SymInt[2] output_size, bool align_corners, float? scales_h=None, float? scales_w=None, *, Tensor(a!) out) -> Tensor(a!) +inline at::Tensor & upsample_bicubic2d_symint_outf(const at::Tensor & self, c10::SymIntArrayRef output_size, bool align_corners, c10::optional scales_h, c10::optional scales_w, at::Tensor & out) { + return at::_ops::upsample_bicubic2d_out::call(self, output_size, align_corners, scales_h, scales_w, out); +} +namespace symint { + template ::value>> + at::Tensor & upsample_bicubic2d_outf(const at::Tensor & self, c10::SymIntArrayRef output_size, bool align_corners, c10::optional scales_h, c10::optional scales_w, at::Tensor & out) { + return at::_ops::upsample_bicubic2d_out::call(self, output_size, align_corners, scales_h, scales_w, out); + } +} + +// aten::upsample_bicubic2d(Tensor self, SymInt[2] output_size, bool align_corners, float? scales_h=None, float? scales_w=None) -> Tensor +inline at::Tensor upsample_bicubic2d(const at::Tensor & self, at::IntArrayRef output_size, bool align_corners, c10::optional scales_h=c10::nullopt, c10::optional scales_w=c10::nullopt) { + return at::_ops::upsample_bicubic2d::call(self, c10::fromIntArrayRefSlow(output_size), align_corners, scales_h, scales_w); +} +namespace symint { + template ::value>> + at::Tensor upsample_bicubic2d(const at::Tensor & self, at::IntArrayRef output_size, bool align_corners, c10::optional scales_h=c10::nullopt, c10::optional scales_w=c10::nullopt) { + return at::_ops::upsample_bicubic2d::call(self, c10::fromIntArrayRefSlow(output_size), align_corners, scales_h, scales_w); + } +} + +// aten::upsample_bicubic2d(Tensor self, SymInt[2] output_size, bool align_corners, float? scales_h=None, float? scales_w=None) -> Tensor +inline at::Tensor upsample_bicubic2d_symint(const at::Tensor & self, c10::SymIntArrayRef output_size, bool align_corners, c10::optional scales_h=c10::nullopt, c10::optional scales_w=c10::nullopt) { + return at::_ops::upsample_bicubic2d::call(self, output_size, align_corners, scales_h, scales_w); +} +namespace symint { + template ::value>> + at::Tensor upsample_bicubic2d(const at::Tensor & self, c10::SymIntArrayRef output_size, bool align_corners, c10::optional scales_h=c10::nullopt, c10::optional scales_w=c10::nullopt) { + return at::_ops::upsample_bicubic2d::call(self, output_size, align_corners, scales_h, scales_w); + } +} + +} diff --git a/shared/package-files/01/0193f369bc19146c204297f6faa2cd8bd1809f1ab59c6e6cbb336dc2f9959dd2/blob b/shared/package-files/01/0193f369bc19146c204297f6faa2cd8bd1809f1ab59c6e6cbb336dc2f9959dd2/blob new file mode 100644 index 0000000000000000000000000000000000000000..b2094e1a0857358494f1adcfd35329181303485c --- /dev/null +++ b/shared/package-files/01/0193f369bc19146c204297f6faa2cd8bd1809f1ab59c6e6cbb336dc2f9959dd2/blob @@ -0,0 +1,83 @@ +#pragma once + +// @generated by torchgen/gen.py from Operator.h + +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { +namespace _ops { + + +struct TORCH_API quantize_per_tensor { + using schema = at::Tensor (const at::Tensor &, double, int64_t, at::ScalarType); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::quantize_per_tensor") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "quantize_per_tensor(Tensor self, float scale, int zero_point, ScalarType dtype) -> Tensor") + static at::Tensor call(const at::Tensor & self, double scale, int64_t zero_point, at::ScalarType dtype); + static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, double scale, int64_t zero_point, at::ScalarType dtype); +}; + +struct TORCH_API quantize_per_tensor_tensor_qparams { + using schema = at::Tensor (const at::Tensor &, const 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::quantize_per_tensor") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "tensor_qparams") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "quantize_per_tensor.tensor_qparams(Tensor self, Tensor scale, Tensor zero_point, ScalarType dtype) -> Tensor") + static at::Tensor call(const at::Tensor & self, const at::Tensor & scale, const at::Tensor & zero_point, at::ScalarType dtype); + static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, const at::Tensor & scale, const at::Tensor & zero_point, at::ScalarType dtype); +}; + +struct TORCH_API quantize_per_tensor_tensors { + using schema = ::std::vector (at::TensorList, const 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::quantize_per_tensor") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "tensors") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "quantize_per_tensor.tensors(Tensor[] tensors, Tensor scales, Tensor zero_points, ScalarType dtype) -> Tensor[]") + static ::std::vector call(at::TensorList tensors, const at::Tensor & scales, const at::Tensor & zero_points, at::ScalarType dtype); + static ::std::vector redispatch(c10::DispatchKeySet dispatchKeySet, at::TensorList tensors, const at::Tensor & scales, const at::Tensor & zero_points, at::ScalarType dtype); +}; + +struct TORCH_API quantize_per_tensor_out { + using schema = at::Tensor & (const at::Tensor &, double, int64_t, at::ScalarType, at::Tensor &); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::quantize_per_tensor") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "out") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "quantize_per_tensor.out(Tensor self, float scale, int zero_point, ScalarType dtype, *, Tensor(a!) out) -> Tensor(a!)") + static at::Tensor & call(const at::Tensor & self, double scale, int64_t zero_point, at::ScalarType dtype, at::Tensor & out); + static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, double scale, int64_t zero_point, at::ScalarType dtype, at::Tensor & out); +}; + +struct TORCH_API quantize_per_tensor_tensor_qparams_out { + using schema = at::Tensor & (const at::Tensor &, const at::Tensor &, const at::Tensor &, at::ScalarType, at::Tensor &); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::quantize_per_tensor") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "tensor_qparams_out") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "quantize_per_tensor.tensor_qparams_out(Tensor self, Tensor scale, Tensor zero_point, ScalarType dtype, *, Tensor(a!) out) -> Tensor(a!)") + static at::Tensor & call(const at::Tensor & self, const at::Tensor & scale, const at::Tensor & zero_point, at::ScalarType dtype, at::Tensor & out); + static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, const at::Tensor & scale, const at::Tensor & zero_point, at::ScalarType dtype, at::Tensor & out); +}; + +struct TORCH_API quantize_per_tensor_tensors_out { + using schema = void (at::TensorList, const at::Tensor &, const at::Tensor &, at::ScalarType, at::TensorList); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::quantize_per_tensor") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "tensors_out") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "quantize_per_tensor.tensors_out(Tensor[] tensors, Tensor scales, Tensor zero_points, ScalarType dtype, *, Tensor(a!)[] out) -> ()") + static void call(at::TensorList tensors, const at::Tensor & scales, const at::Tensor & zero_points, at::ScalarType dtype, at::TensorList out); + static void redispatch(c10::DispatchKeySet dispatchKeySet, at::TensorList tensors, const at::Tensor & scales, const at::Tensor & zero_points, at::ScalarType dtype, at::TensorList out); +}; + +}} // namespace at::_ops diff --git a/shared/package-files/01/0196901c90313cc5fee77f365efb6fbec1b305fa7f79a9e1dddc73b66554e7bc/blob b/shared/package-files/01/0196901c90313cc5fee77f365efb6fbec1b305fa7f79a9e1dddc73b66554e7bc/blob new file mode 100644 index 0000000000000000000000000000000000000000..7440376d0e976f3442f1068411c476dbc451cc33 --- /dev/null +++ b/shared/package-files/01/0196901c90313cc5fee77f365efb6fbec1b305fa7f79a9e1dddc73b66554e7bc/blob @@ -0,0 +1,276 @@ +#pragma once + +#include +#include +#include +#include +#include +#include +#include + +namespace at { + +// The PtrTraits argument to the TensorAccessor/GenericPackedTensorAccessor +// is used to enable the __restrict__ keyword/modifier for the data +// passed to cuda. +template +struct DefaultPtrTraits { + typedef T* PtrType; +}; + +#if defined(__CUDACC__) || defined(__HIPCC__) +template +struct RestrictPtrTraits { + typedef T* __restrict__ PtrType; +}; +#endif + +// TensorAccessorBase and TensorAccessor are used for both CPU and CUDA tensors. +// For CUDA tensors it is used in device code (only). This means that we restrict ourselves +// to functions and types available there (e.g. IntArrayRef isn't). + +// The PtrTraits argument is only relevant to cuda to support `__restrict__` pointers. +template class PtrTraits = DefaultPtrTraits, typename index_t = int64_t> +class TensorAccessorBase { +public: + typedef typename PtrTraits::PtrType PtrType; + + C10_HOST_DEVICE TensorAccessorBase( + PtrType data_, + const index_t* sizes_, + const index_t* strides_) + : data_(data_), sizes_(sizes_), strides_(strides_) {} + C10_HOST IntArrayRef sizes() const { + return IntArrayRef(sizes_,N); + } + C10_HOST IntArrayRef strides() const { + return IntArrayRef(strides_,N); + } + C10_HOST_DEVICE index_t stride(index_t i) const { + return strides_[i]; + } + C10_HOST_DEVICE index_t size(index_t i) const { + return sizes_[i]; + } + C10_HOST_DEVICE PtrType data() { + return data_; + } + C10_HOST_DEVICE const PtrType data() const { + return data_; + } +protected: + PtrType data_; + const index_t* sizes_; + const index_t* strides_; +}; + +// The `TensorAccessor` is typically instantiated for CPU `Tensor`s using +// `Tensor.accessor()`. +// For CUDA `Tensor`s, `GenericPackedTensorAccessor` is used on the host and only +// indexing on the device uses `TensorAccessor`s. +template class PtrTraits = DefaultPtrTraits, typename index_t = int64_t> +class TensorAccessor : public TensorAccessorBase { +public: + typedef typename PtrTraits::PtrType PtrType; + + C10_HOST_DEVICE TensorAccessor( + PtrType data_, + const index_t* sizes_, + const index_t* strides_) + : TensorAccessorBase(data_,sizes_,strides_) {} + + C10_HOST_DEVICE TensorAccessor operator[](index_t i) { + return TensorAccessor(this->data_ + this->strides_[0]*i,this->sizes_+1,this->strides_+1); + } + + C10_HOST_DEVICE const TensorAccessor operator[](index_t i) const { + return TensorAccessor(this->data_ + this->strides_[0]*i,this->sizes_+1,this->strides_+1); + } +}; + +template class PtrTraits, typename index_t> +class TensorAccessor : public TensorAccessorBase { +public: + typedef typename PtrTraits::PtrType PtrType; + + C10_HOST_DEVICE TensorAccessor( + PtrType data_, + const index_t* sizes_, + const index_t* strides_) + : TensorAccessorBase(data_,sizes_,strides_) {} + C10_HOST_DEVICE T & operator[](index_t i) { + // NOLINTNEXTLINE(clang-analyzer-core.NullDereference) + return this->data_[this->strides_[0]*i]; + } + C10_HOST_DEVICE const T & operator[](index_t i) const { + return this->data_[this->strides_[0]*i]; + } +}; + + +// GenericPackedTensorAccessorBase and GenericPackedTensorAccessor are used on for CUDA `Tensor`s on the host +// and as +// In contrast to `TensorAccessor`s, they copy the strides and sizes on instantiation (on the host) +// in order to transfer them on the device when calling kernels. +// On the device, indexing of multidimensional tensors gives to `TensorAccessor`s. +// Use RestrictPtrTraits as PtrTraits if you want the tensor's data pointer to be marked as __restrict__. +// Instantiation from data, sizes, strides is only needed on the host and std::copy isn't available +// on the device, so those functions are host only. +template class PtrTraits = DefaultPtrTraits, typename index_t = int64_t> +class GenericPackedTensorAccessorBase { +public: + typedef typename PtrTraits::PtrType PtrType; + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-member-init) + C10_HOST GenericPackedTensorAccessorBase( + PtrType data_, + const index_t* sizes_, + const index_t* strides_) + : data_(data_) { + std::copy(sizes_, sizes_ + N, std::begin(this->sizes_)); + std::copy(strides_, strides_ + N, std::begin(this->strides_)); + } + + // if index_t is not int64_t, we want to have an int64_t constructor + template ::value>::type> + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-member-init) + C10_HOST GenericPackedTensorAccessorBase( + PtrType data_, + const source_index_t* sizes_, + const source_index_t* strides_) + : data_(data_) { + for (const auto i : c10::irange(N)) { + this->sizes_[i] = sizes_[i]; + this->strides_[i] = strides_[i]; + } + } + + C10_HOST_DEVICE index_t stride(index_t i) const { + return strides_[i]; + } + C10_HOST_DEVICE index_t size(index_t i) const { + return sizes_[i]; + } + C10_HOST_DEVICE PtrType data() { + return data_; + } + C10_HOST_DEVICE const PtrType data() const { + return data_; + } +protected: + PtrType data_; + // NOLINTNEXTLINE(*c-arrays*) + index_t sizes_[N]; + // NOLINTNEXTLINE(*c-arrays*) + index_t strides_[N]; + C10_HOST void bounds_check_(index_t i) const { + TORCH_CHECK_INDEX( + 0 <= i && i < index_t{N}, + "Index ", + i, + " is not within bounds of a tensor of dimension ", + N); + } +}; + +template class PtrTraits = DefaultPtrTraits, typename index_t = int64_t> +class GenericPackedTensorAccessor : public GenericPackedTensorAccessorBase { +public: + typedef typename PtrTraits::PtrType PtrType; + + C10_HOST GenericPackedTensorAccessor( + PtrType data_, + const index_t* sizes_, + const index_t* strides_) + : GenericPackedTensorAccessorBase(data_, sizes_, strides_) {} + + // if index_t is not int64_t, we want to have an int64_t constructor + template ::value>::type> + C10_HOST GenericPackedTensorAccessor( + PtrType data_, + const source_index_t* sizes_, + const source_index_t* strides_) + : GenericPackedTensorAccessorBase(data_, sizes_, strides_) {} + + C10_DEVICE TensorAccessor operator[](index_t i) { + index_t* new_sizes = this->sizes_ + 1; + index_t* new_strides = this->strides_ + 1; + return TensorAccessor(this->data_ + this->strides_[0]*i, new_sizes, new_strides); + } + + C10_DEVICE const TensorAccessor operator[](index_t i) const { + const index_t* new_sizes = this->sizes_ + 1; + const index_t* new_strides = this->strides_ + 1; + return TensorAccessor(this->data_ + this->strides_[0]*i, new_sizes, new_strides); + } + + /// Returns a PackedTensorAccessor of the same dimension after transposing the + /// two dimensions given. Does not actually move elements; transposition is + /// made by permuting the size/stride arrays. If the dimensions are not valid, + /// asserts. + C10_HOST GenericPackedTensorAccessor transpose( + index_t dim1, + index_t dim2) const { + this->bounds_check_(dim1); + this->bounds_check_(dim2); + GenericPackedTensorAccessor result( + this->data_, this->sizes_, this->strides_); + std::swap(result.strides_[dim1], result.strides_[dim2]); + std::swap(result.sizes_[dim1], result.sizes_[dim2]); + return result; + } +}; + +template class PtrTraits, typename index_t> +class GenericPackedTensorAccessor : public GenericPackedTensorAccessorBase { +public: + typedef typename PtrTraits::PtrType PtrType; + C10_HOST GenericPackedTensorAccessor( + PtrType data_, + const index_t* sizes_, + const index_t* strides_) + : GenericPackedTensorAccessorBase(data_, sizes_, strides_) {} + + // if index_t is not int64_t, we want to have an int64_t constructor + template ::value>::type> + C10_HOST GenericPackedTensorAccessor( + PtrType data_, + const source_index_t* sizes_, + const source_index_t* strides_) + : GenericPackedTensorAccessorBase(data_, sizes_, strides_) {} + + C10_DEVICE T & operator[](index_t i) { + return this->data_[this->strides_[0] * i]; + } + C10_DEVICE const T& operator[](index_t i) const { + return this->data_[this->strides_[0]*i]; + } + + // Same as in the general N-dimensional case, but note that in the + // 1-dimensional case the returned PackedTensorAccessor will always be an + // identical copy of the original + C10_HOST GenericPackedTensorAccessor transpose( + index_t dim1, + index_t dim2) const { + this->bounds_check_(dim1); + this->bounds_check_(dim2); + return GenericPackedTensorAccessor( + this->data_, this->sizes_, this->strides_); + } +}; + + +// Can't put this directly into the macro function args because of commas +#define AT_X GenericPackedTensorAccessor + +// Old name for `GenericPackedTensorAccessor` +template class PtrTraits = DefaultPtrTraits, typename index_t = int64_t> +C10_DEFINE_DEPRECATED_USING(PackedTensorAccessor, AT_X) + +#undef AT_X + +template class PtrTraits = DefaultPtrTraits> +using PackedTensorAccessor32 = GenericPackedTensorAccessor; + +template class PtrTraits = DefaultPtrTraits> +using PackedTensorAccessor64 = GenericPackedTensorAccessor; +} // namespace at diff --git a/shared/package-files/01/01976a81811873dc9a0c79db9fc00d1c30103487f3c6bc3a6d81b4043cd48e02/blob b/shared/package-files/01/01976a81811873dc9a0c79db9fc00d1c30103487f3c6bc3a6d81b4043cd48e02/blob new file mode 100644 index 0000000000000000000000000000000000000000..43bdecd446841da1866749ca8c6ebb9d86c7795b --- /dev/null +++ b/shared/package-files/01/01976a81811873dc9a0c79db9fc00d1c30103487f3c6bc3a6d81b4043cd48e02/blob @@ -0,0 +1,307 @@ +""" Python Character Mapping Codec iso8859_15 generated from 'MAPPINGS/ISO8859/8859-15.TXT' with gencodec.py. + +"""#" + +import codecs + +### Codec APIs + +class Codec(codecs.Codec): + + def encode(self,input,errors='strict'): + return codecs.charmap_encode(input,errors,encoding_table) + + def decode(self,input,errors='strict'): + return codecs.charmap_decode(input,errors,decoding_table) + +class IncrementalEncoder(codecs.IncrementalEncoder): + def encode(self, input, final=False): + return codecs.charmap_encode(input,self.errors,encoding_table)[0] + +class IncrementalDecoder(codecs.IncrementalDecoder): + def decode(self, input, final=False): + return codecs.charmap_decode(input,self.errors,decoding_table)[0] + +class StreamWriter(Codec,codecs.StreamWriter): + pass + +class StreamReader(Codec,codecs.StreamReader): + pass + +### encodings module API + +def getregentry(): + return codecs.CodecInfo( + name='iso8859-15', + encode=Codec().encode, + decode=Codec().decode, + incrementalencoder=IncrementalEncoder, + incrementaldecoder=IncrementalDecoder, + streamreader=StreamReader, + streamwriter=StreamWriter, + ) + + +### Decoding Table + +decoding_table = ( + '\x00' # 0x00 -> NULL + '\x01' # 0x01 -> START OF HEADING + '\x02' # 0x02 -> START OF TEXT + '\x03' # 0x03 -> END OF TEXT + '\x04' # 0x04 -> END OF TRANSMISSION + '\x05' # 0x05 -> ENQUIRY + '\x06' # 0x06 -> ACKNOWLEDGE + '\x07' # 0x07 -> BELL + '\x08' # 0x08 -> BACKSPACE + '\t' # 0x09 -> HORIZONTAL TABULATION + '\n' # 0x0A -> LINE FEED + '\x0b' # 0x0B -> VERTICAL TABULATION + '\x0c' # 0x0C -> FORM FEED + '\r' # 0x0D -> CARRIAGE RETURN + '\x0e' # 0x0E -> SHIFT OUT + '\x0f' # 0x0F -> SHIFT IN + '\x10' # 0x10 -> DATA LINK ESCAPE + '\x11' # 0x11 -> DEVICE CONTROL ONE + '\x12' # 0x12 -> DEVICE CONTROL TWO + '\x13' # 0x13 -> DEVICE CONTROL THREE + '\x14' # 0x14 -> DEVICE CONTROL FOUR + '\x15' # 0x15 -> NEGATIVE ACKNOWLEDGE + '\x16' # 0x16 -> SYNCHRONOUS IDLE + '\x17' # 0x17 -> END OF TRANSMISSION BLOCK + '\x18' # 0x18 -> CANCEL + '\x19' # 0x19 -> END OF MEDIUM + '\x1a' # 0x1A -> SUBSTITUTE + '\x1b' # 0x1B -> ESCAPE + '\x1c' # 0x1C -> FILE SEPARATOR + '\x1d' # 0x1D -> GROUP SEPARATOR + '\x1e' # 0x1E -> RECORD SEPARATOR + '\x1f' # 0x1F -> UNIT SEPARATOR + ' ' # 0x20 -> SPACE + '!' # 0x21 -> EXCLAMATION MARK + '"' # 0x22 -> QUOTATION MARK + '#' # 0x23 -> NUMBER SIGN + '$' # 0x24 -> DOLLAR SIGN + '%' # 0x25 -> PERCENT SIGN + '&' # 0x26 -> AMPERSAND + "'" # 0x27 -> APOSTROPHE + '(' # 0x28 -> LEFT PARENTHESIS + ')' # 0x29 -> RIGHT PARENTHESIS + '*' # 0x2A -> ASTERISK + '+' # 0x2B -> PLUS SIGN + ',' # 0x2C -> COMMA + '-' # 0x2D -> HYPHEN-MINUS + '.' # 0x2E -> FULL STOP + '/' # 0x2F -> SOLIDUS + '0' # 0x30 -> DIGIT ZERO + '1' # 0x31 -> DIGIT ONE + '2' # 0x32 -> DIGIT TWO + '3' # 0x33 -> DIGIT THREE + '4' # 0x34 -> DIGIT FOUR + '5' # 0x35 -> DIGIT FIVE + '6' # 0x36 -> DIGIT SIX + '7' # 0x37 -> DIGIT SEVEN + '8' # 0x38 -> DIGIT EIGHT + '9' # 0x39 -> DIGIT NINE + ':' # 0x3A -> COLON + ';' # 0x3B -> SEMICOLON + '<' # 0x3C -> LESS-THAN SIGN + '=' # 0x3D -> EQUALS SIGN + '>' # 0x3E -> GREATER-THAN SIGN + '?' # 0x3F -> QUESTION MARK + '@' # 0x40 -> COMMERCIAL AT + 'A' # 0x41 -> LATIN CAPITAL LETTER A + 'B' # 0x42 -> LATIN CAPITAL LETTER B + 'C' # 0x43 -> LATIN CAPITAL LETTER C + 'D' # 0x44 -> LATIN CAPITAL LETTER D + 'E' # 0x45 -> LATIN CAPITAL LETTER E + 'F' # 0x46 -> LATIN CAPITAL LETTER F + 'G' # 0x47 -> LATIN CAPITAL LETTER G + 'H' # 0x48 -> LATIN CAPITAL LETTER H + 'I' # 0x49 -> LATIN CAPITAL LETTER I + 'J' # 0x4A -> LATIN CAPITAL LETTER J + 'K' # 0x4B -> LATIN CAPITAL LETTER K + 'L' # 0x4C -> LATIN CAPITAL LETTER L + 'M' # 0x4D -> LATIN CAPITAL LETTER M + 'N' # 0x4E -> LATIN CAPITAL LETTER N + 'O' # 0x4F -> LATIN CAPITAL LETTER O + 'P' # 0x50 -> LATIN CAPITAL LETTER P + 'Q' # 0x51 -> LATIN CAPITAL LETTER Q + 'R' # 0x52 -> LATIN CAPITAL LETTER R + 'S' # 0x53 -> LATIN CAPITAL LETTER S + 'T' # 0x54 -> LATIN CAPITAL LETTER T + 'U' # 0x55 -> LATIN CAPITAL LETTER U + 'V' # 0x56 -> LATIN CAPITAL LETTER V + 'W' # 0x57 -> LATIN CAPITAL LETTER W + 'X' # 0x58 -> LATIN CAPITAL LETTER X + 'Y' # 0x59 -> LATIN CAPITAL LETTER Y + 'Z' # 0x5A -> LATIN CAPITAL LETTER Z + '[' # 0x5B -> LEFT SQUARE BRACKET + '\\' # 0x5C -> REVERSE SOLIDUS + ']' # 0x5D -> RIGHT SQUARE BRACKET + '^' # 0x5E -> CIRCUMFLEX ACCENT + '_' # 0x5F -> LOW LINE + '`' # 0x60 -> GRAVE ACCENT + 'a' # 0x61 -> LATIN SMALL LETTER A + 'b' # 0x62 -> LATIN SMALL LETTER B + 'c' # 0x63 -> LATIN SMALL LETTER C + 'd' # 0x64 -> LATIN SMALL LETTER D + 'e' # 0x65 -> LATIN SMALL LETTER E + 'f' # 0x66 -> LATIN SMALL LETTER F + 'g' # 0x67 -> LATIN SMALL LETTER G + 'h' # 0x68 -> LATIN SMALL LETTER H + 'i' # 0x69 -> LATIN SMALL LETTER I + 'j' # 0x6A -> LATIN SMALL LETTER J + 'k' # 0x6B -> LATIN SMALL LETTER K + 'l' # 0x6C -> LATIN SMALL LETTER L + 'm' # 0x6D -> LATIN SMALL LETTER M + 'n' # 0x6E -> LATIN SMALL LETTER N + 'o' # 0x6F -> LATIN SMALL LETTER O + 'p' # 0x70 -> LATIN SMALL LETTER P + 'q' # 0x71 -> LATIN SMALL LETTER Q + 'r' # 0x72 -> LATIN SMALL LETTER R + 's' # 0x73 -> LATIN SMALL LETTER S + 't' # 0x74 -> LATIN SMALL LETTER T + 'u' # 0x75 -> LATIN SMALL LETTER U + 'v' # 0x76 -> LATIN SMALL LETTER V + 'w' # 0x77 -> LATIN SMALL LETTER W + 'x' # 0x78 -> LATIN SMALL LETTER X + 'y' # 0x79 -> LATIN SMALL LETTER Y + 'z' # 0x7A -> LATIN SMALL LETTER Z + '{' # 0x7B -> LEFT CURLY BRACKET + '|' # 0x7C -> VERTICAL LINE + '}' # 0x7D -> RIGHT CURLY BRACKET + '~' # 0x7E -> TILDE + '\x7f' # 0x7F -> DELETE + '\x80' # 0x80 -> + '\x81' # 0x81 -> + '\x82' # 0x82 -> + '\x83' # 0x83 -> + '\x84' # 0x84 -> + '\x85' # 0x85 -> + '\x86' # 0x86 -> + '\x87' # 0x87 -> + '\x88' # 0x88 -> + '\x89' # 0x89 -> + '\x8a' # 0x8A -> + '\x8b' # 0x8B -> + '\x8c' # 0x8C -> + '\x8d' # 0x8D -> + '\x8e' # 0x8E -> + '\x8f' # 0x8F -> + '\x90' # 0x90 -> + '\x91' # 0x91 -> + '\x92' # 0x92 -> + '\x93' # 0x93 -> + '\x94' # 0x94 -> + '\x95' # 0x95 -> + '\x96' # 0x96 -> + '\x97' # 0x97 -> + '\x98' # 0x98 -> + '\x99' # 0x99 -> + '\x9a' # 0x9A -> + '\x9b' # 0x9B -> + '\x9c' # 0x9C -> + '\x9d' # 0x9D -> + '\x9e' # 0x9E -> + '\x9f' # 0x9F -> + '\xa0' # 0xA0 -> NO-BREAK SPACE + '\xa1' # 0xA1 -> INVERTED EXCLAMATION MARK + '\xa2' # 0xA2 -> CENT SIGN + '\xa3' # 0xA3 -> POUND SIGN + '\u20ac' # 0xA4 -> EURO SIGN + '\xa5' # 0xA5 -> YEN SIGN + '\u0160' # 0xA6 -> LATIN CAPITAL LETTER S WITH CARON + '\xa7' # 0xA7 -> SECTION SIGN + '\u0161' # 0xA8 -> LATIN SMALL LETTER S WITH CARON + '\xa9' # 0xA9 -> COPYRIGHT SIGN + '\xaa' # 0xAA -> FEMININE ORDINAL INDICATOR + '\xab' # 0xAB -> LEFT-POINTING DOUBLE ANGLE QUOTATION MARK + '\xac' # 0xAC -> NOT SIGN + '\xad' # 0xAD -> SOFT HYPHEN + '\xae' # 0xAE -> REGISTERED SIGN + '\xaf' # 0xAF -> MACRON + '\xb0' # 0xB0 -> DEGREE SIGN + '\xb1' # 0xB1 -> PLUS-MINUS SIGN + '\xb2' # 0xB2 -> SUPERSCRIPT TWO + '\xb3' # 0xB3 -> SUPERSCRIPT THREE + '\u017d' # 0xB4 -> LATIN CAPITAL LETTER Z WITH CARON + '\xb5' # 0xB5 -> MICRO SIGN + '\xb6' # 0xB6 -> PILCROW SIGN + '\xb7' # 0xB7 -> MIDDLE DOT + '\u017e' # 0xB8 -> LATIN SMALL LETTER Z WITH CARON + '\xb9' # 0xB9 -> SUPERSCRIPT ONE + '\xba' # 0xBA -> MASCULINE ORDINAL INDICATOR + '\xbb' # 0xBB -> RIGHT-POINTING DOUBLE ANGLE QUOTATION MARK + '\u0152' # 0xBC -> LATIN CAPITAL LIGATURE OE + '\u0153' # 0xBD -> LATIN SMALL LIGATURE OE + '\u0178' # 0xBE -> LATIN CAPITAL LETTER Y WITH DIAERESIS + '\xbf' # 0xBF -> INVERTED QUESTION MARK + '\xc0' # 0xC0 -> LATIN CAPITAL LETTER A WITH GRAVE + '\xc1' # 0xC1 -> LATIN CAPITAL LETTER A WITH ACUTE + '\xc2' # 0xC2 -> LATIN CAPITAL LETTER A WITH CIRCUMFLEX + '\xc3' # 0xC3 -> LATIN CAPITAL LETTER A WITH TILDE + '\xc4' # 0xC4 -> LATIN CAPITAL LETTER A WITH DIAERESIS + '\xc5' # 0xC5 -> LATIN CAPITAL LETTER A WITH RING ABOVE + '\xc6' # 0xC6 -> LATIN CAPITAL LETTER AE + '\xc7' # 0xC7 -> LATIN CAPITAL LETTER C WITH CEDILLA + '\xc8' # 0xC8 -> LATIN CAPITAL LETTER E WITH GRAVE + '\xc9' # 0xC9 -> LATIN CAPITAL LETTER E WITH ACUTE + '\xca' # 0xCA -> LATIN CAPITAL LETTER E WITH CIRCUMFLEX + '\xcb' # 0xCB -> LATIN CAPITAL LETTER E WITH DIAERESIS + '\xcc' # 0xCC -> LATIN CAPITAL LETTER I WITH GRAVE + '\xcd' # 0xCD -> LATIN CAPITAL LETTER I WITH ACUTE + '\xce' # 0xCE -> LATIN CAPITAL LETTER I WITH CIRCUMFLEX + '\xcf' # 0xCF -> LATIN CAPITAL LETTER I WITH DIAERESIS + '\xd0' # 0xD0 -> LATIN CAPITAL LETTER ETH + '\xd1' # 0xD1 -> LATIN CAPITAL LETTER N WITH TILDE + '\xd2' # 0xD2 -> LATIN CAPITAL LETTER O WITH GRAVE + '\xd3' # 0xD3 -> LATIN CAPITAL LETTER O WITH ACUTE + '\xd4' # 0xD4 -> LATIN CAPITAL LETTER O WITH CIRCUMFLEX + '\xd5' # 0xD5 -> LATIN CAPITAL LETTER O WITH TILDE + '\xd6' # 0xD6 -> LATIN CAPITAL LETTER O WITH DIAERESIS + '\xd7' # 0xD7 -> MULTIPLICATION SIGN + '\xd8' # 0xD8 -> LATIN CAPITAL LETTER O WITH STROKE + '\xd9' # 0xD9 -> LATIN CAPITAL LETTER U WITH GRAVE + '\xda' # 0xDA -> LATIN CAPITAL LETTER U WITH ACUTE + '\xdb' # 0xDB -> LATIN CAPITAL LETTER U WITH CIRCUMFLEX + '\xdc' # 0xDC -> LATIN CAPITAL LETTER U WITH DIAERESIS + '\xdd' # 0xDD -> LATIN CAPITAL LETTER Y WITH ACUTE + '\xde' # 0xDE -> LATIN CAPITAL LETTER THORN + '\xdf' # 0xDF -> LATIN SMALL LETTER SHARP S + '\xe0' # 0xE0 -> LATIN SMALL LETTER A WITH GRAVE + '\xe1' # 0xE1 -> LATIN SMALL LETTER A WITH ACUTE + '\xe2' # 0xE2 -> LATIN SMALL LETTER A WITH CIRCUMFLEX + '\xe3' # 0xE3 -> LATIN SMALL LETTER A WITH TILDE + '\xe4' # 0xE4 -> LATIN SMALL LETTER A WITH DIAERESIS + '\xe5' # 0xE5 -> LATIN SMALL LETTER A WITH RING ABOVE + '\xe6' # 0xE6 -> LATIN SMALL LETTER AE + '\xe7' # 0xE7 -> LATIN SMALL LETTER C WITH CEDILLA + '\xe8' # 0xE8 -> LATIN SMALL LETTER E WITH GRAVE + '\xe9' # 0xE9 -> LATIN SMALL LETTER E WITH ACUTE + '\xea' # 0xEA -> LATIN SMALL LETTER E WITH CIRCUMFLEX + '\xeb' # 0xEB -> LATIN SMALL LETTER E WITH DIAERESIS + '\xec' # 0xEC -> LATIN SMALL LETTER I WITH GRAVE + '\xed' # 0xED -> LATIN SMALL LETTER I WITH ACUTE + '\xee' # 0xEE -> LATIN SMALL LETTER I WITH CIRCUMFLEX + '\xef' # 0xEF -> LATIN SMALL LETTER I WITH DIAERESIS + '\xf0' # 0xF0 -> LATIN SMALL LETTER ETH + '\xf1' # 0xF1 -> LATIN SMALL LETTER N WITH TILDE + '\xf2' # 0xF2 -> LATIN SMALL LETTER O WITH GRAVE + '\xf3' # 0xF3 -> LATIN SMALL LETTER O WITH ACUTE + '\xf4' # 0xF4 -> LATIN SMALL LETTER O WITH CIRCUMFLEX + '\xf5' # 0xF5 -> LATIN SMALL LETTER O WITH TILDE + '\xf6' # 0xF6 -> LATIN SMALL LETTER O WITH DIAERESIS + '\xf7' # 0xF7 -> DIVISION SIGN + '\xf8' # 0xF8 -> LATIN SMALL LETTER O WITH STROKE + '\xf9' # 0xF9 -> LATIN SMALL LETTER U WITH GRAVE + '\xfa' # 0xFA -> LATIN SMALL LETTER U WITH ACUTE + '\xfb' # 0xFB -> LATIN SMALL LETTER U WITH CIRCUMFLEX + '\xfc' # 0xFC -> LATIN SMALL LETTER U WITH DIAERESIS + '\xfd' # 0xFD -> LATIN SMALL LETTER Y WITH ACUTE + '\xfe' # 0xFE -> LATIN SMALL LETTER THORN + '\xff' # 0xFF -> LATIN SMALL LETTER Y WITH DIAERESIS +) + +### Encoding table +encoding_table=codecs.charmap_build(decoding_table) diff --git a/shared/package-files/01/0197acf4b844fca07ed10fe7574432e6448e63437d72fbfb34f1297634f0073e/blob b/shared/package-files/01/0197acf4b844fca07ed10fe7574432e6448e63437d72fbfb34f1297634f0073e/blob new file mode 100644 index 0000000000000000000000000000000000000000..69a5d730bfb68e89e24beb04ad13fd3fa5881ae9 --- /dev/null +++ b/shared/package-files/01/0197acf4b844fca07ed10fe7574432e6448e63437d72fbfb34f1297634f0073e/blob @@ -0,0 +1,32 @@ +# flake8: noqa: F401 +r""" +This file is in the process of migration to `torch/ao/quantization`, and +is kept here for compatibility while the migration process is ongoing. +If you are adding a new entry/functionality, please, add it to the +`torch/ao/quantization/fake_quantize.py`, while adding an import statement +here. +""" + +from torch.ao.quantization.fake_quantize import ( + _is_fake_quant_script_module, + _is_per_channel, + _is_per_tensor, + _is_symmetric_quant, + default_fake_quant, + default_fixed_qparams_range_0to1_fake_quant, + default_fixed_qparams_range_neg1to1_fake_quant, + default_fused_act_fake_quant, + default_fused_per_channel_wt_fake_quant, + default_fused_wt_fake_quant, + default_histogram_fake_quant, + default_per_channel_weight_fake_quant, + default_weight_fake_quant, + disable_fake_quant, + disable_observer, + enable_fake_quant, + enable_observer, + FakeQuantize, + FakeQuantizeBase, + FixedQParamsFakeQuantize, + FusedMovingAvgObsFakeQuantize, +) diff --git a/shared/package-files/01/019883edc15298a107723745ecf4a6f5b4af949f819281f00940281d35ea8af3/blob b/shared/package-files/01/019883edc15298a107723745ecf4a6f5b4af949f819281f00940281d35ea8af3/blob new file mode 100644 index 0000000000000000000000000000000000000000..343915c0e074a3a170593e0e23920482f1a51d2c --- /dev/null +++ b/shared/package-files/01/019883edc15298a107723745ecf4a6f5b4af949f819281f00940281d35ea8af3/blob @@ -0,0 +1 @@ +{"dir_info": {}, "url": "file:///croot/archspec_1709217642129/work"} \ No newline at end of file diff --git a/shared/package-files/01/0198f1923365e3b464dcc324dfc32e87b82989b85fb3a11e4eb1cdb9b12c8130/blob b/shared/package-files/01/0198f1923365e3b464dcc324dfc32e87b82989b85fb3a11e4eb1cdb9b12c8130/blob new file mode 100644 index 0000000000000000000000000000000000000000..799f25cf6a48f1dfbf28833c401556d824a157d4 --- /dev/null +++ b/shared/package-files/01/0198f1923365e3b464dcc324dfc32e87b82989b85fb3a11e4eb1cdb9b12c8130/blob @@ -0,0 +1,22 @@ +from _typeshed import AnyPath +from types import CodeType +from typing import Any, List, Sequence, Text, Tuple + +def expr(source: Text) -> STType: ... +def suite(source: Text) -> STType: ... +def sequence2st(sequence: Sequence[Any]) -> STType: ... +def tuple2st(sequence: Sequence[Any]) -> STType: ... +def st2list(st: STType, line_info: bool = ..., col_info: bool = ...) -> List[Any]: ... +def st2tuple(st: STType, line_info: bool = ..., col_info: bool = ...) -> Tuple[Any]: ... +def compilest(st: STType, filename: AnyPath = ...) -> CodeType: ... +def isexpr(st: STType) -> bool: ... +def issuite(st: STType) -> bool: ... + +class ParserError(Exception): ... + +class STType: + def compile(self, filename: AnyPath = ...) -> CodeType: ... + def isexpr(self) -> bool: ... + def issuite(self) -> bool: ... + def tolist(self, line_info: bool = ..., col_info: bool = ...) -> List[Any]: ... + def totuple(self, line_info: bool = ..., col_info: bool = ...) -> Tuple[Any]: ... diff --git a/shared/package-files/01/019935d577ed59e842061890bfb591a94574b0b4b996d5352146ceb8744924df/blob b/shared/package-files/01/019935d577ed59e842061890bfb591a94574b0b4b996d5352146ceb8744924df/blob new file mode 100644 index 0000000000000000000000000000000000000000..78fe9d6995141ad238002e0b48feb94017dc272a --- /dev/null +++ b/shared/package-files/01/019935d577ed59e842061890bfb591a94574b0b4b996d5352146ceb8744924df/blob @@ -0,0 +1,332 @@ +""" +Convenience interface to N-D interpolation + +.. versionadded:: 0.9 + +""" +import numpy as np +from ._interpnd import (LinearNDInterpolator, NDInterpolatorBase, + CloughTocher2DInterpolator, _ndim_coords_from_arrays) +from scipy.spatial import cKDTree + +__all__ = ['griddata', 'NearestNDInterpolator', 'LinearNDInterpolator', + 'CloughTocher2DInterpolator'] + +#------------------------------------------------------------------------------ +# Nearest-neighbor interpolation +#------------------------------------------------------------------------------ + + +class NearestNDInterpolator(NDInterpolatorBase): + """NearestNDInterpolator(x, y). + + Nearest-neighbor interpolator in N > 1 dimensions. + + .. versionadded:: 0.9 + + Methods + ------- + __call__ + + Parameters + ---------- + x : (npoints, ndims) 2-D ndarray of floats + Data point coordinates. + y : (npoints, ) 1-D ndarray of float or complex + Data values. + rescale : boolean, optional + Rescale points to unit cube before performing interpolation. + This is useful if some of the input dimensions have + incommensurable units and differ by many orders of magnitude. + + .. versionadded:: 0.14.0 + tree_options : dict, optional + Options passed to the underlying ``cKDTree``. + + .. versionadded:: 0.17.0 + + See Also + -------- + griddata : + Interpolate unstructured D-D data. + LinearNDInterpolator : + Piecewise linear interpolator in N dimensions. + CloughTocher2DInterpolator : + Piecewise cubic, C1 smooth, curvature-minimizing interpolator in 2D. + interpn : Interpolation on a regular grid or rectilinear grid. + RegularGridInterpolator : Interpolator on a regular or rectilinear grid + in arbitrary dimensions (`interpn` wraps this + class). + + Notes + ----- + Uses ``scipy.spatial.cKDTree`` + + .. note:: For data on a regular grid use `interpn` instead. + + Examples + -------- + We can interpolate values on a 2D plane: + + >>> from scipy.interpolate import NearestNDInterpolator + >>> import numpy as np + >>> import matplotlib.pyplot as plt + >>> rng = np.random.default_rng() + >>> x = rng.random(10) - 0.5 + >>> y = rng.random(10) - 0.5 + >>> z = np.hypot(x, y) + >>> X = np.linspace(min(x), max(x)) + >>> Y = np.linspace(min(y), max(y)) + >>> X, Y = np.meshgrid(X, Y) # 2D grid for interpolation + >>> interp = NearestNDInterpolator(list(zip(x, y)), z) + >>> Z = interp(X, Y) + >>> plt.pcolormesh(X, Y, Z, shading='auto') + >>> plt.plot(x, y, "ok", label="input point") + >>> plt.legend() + >>> plt.colorbar() + >>> plt.axis("equal") + >>> plt.show() + + """ + + def __init__(self, x, y, rescale=False, tree_options=None): + NDInterpolatorBase.__init__(self, x, y, rescale=rescale, + need_contiguous=False, + need_values=False) + if tree_options is None: + tree_options = dict() + self.tree = cKDTree(self.points, **tree_options) + self.values = np.asarray(y) + + def __call__(self, *args, **query_options): + """ + Evaluate interpolator at given points. + + Parameters + ---------- + x1, x2, ... xn : array-like of float + Points where to interpolate data at. + x1, x2, ... xn can be array-like of float with broadcastable shape. + or x1 can be array-like of float with shape ``(..., ndim)`` + **query_options + This allows ``eps``, ``p``, ``distance_upper_bound``, and ``workers`` + being passed to the cKDTree's query function to be explicitly set. + See `scipy.spatial.cKDTree.query` for an overview of the different options. + + .. versionadded:: 1.12.0 + + """ + # For the sake of enabling subclassing, NDInterpolatorBase._set_xi performs + # some operations which are not required by NearestNDInterpolator.__call__, + # hence here we operate on xi directly, without calling a parent class function. + xi = _ndim_coords_from_arrays(args, ndim=self.points.shape[1]) + xi = self._check_call_shape(xi) + xi = self._scale_x(xi) + + # We need to handle two important cases: + # (1) the case where xi has trailing dimensions (..., ndim), and + # (2) the case where y has trailing dimensions + # We will first flatten xi to deal with case (1), + # do the computation in flattened array while retaining y's dimensionality, + # and then reshape the interpolated values back to match xi's shape. + + # Flatten xi for the query + xi_flat = xi.reshape(-1, xi.shape[-1]) + original_shape = xi.shape + flattened_shape = xi_flat.shape + + # if distance_upper_bound is set to not be infinite, + # then we need to consider the case where cKDtree + # does not find any points within distance_upper_bound to return. + # It marks those points as having infinte distance, which is what will be used + # below to mask the array and return only the points that were deemed + # to have a close enough neighbor to return something useful. + dist, i = self.tree.query(xi_flat, **query_options) + valid_mask = np.isfinite(dist) + + # create a holder interp_values array and fill with nans. + if self.values.ndim > 1: + interp_shape = flattened_shape[:-1] + self.values.shape[1:] + else: + interp_shape = flattened_shape[:-1] + + if np.issubdtype(self.values.dtype, np.complexfloating): + interp_values = np.full(interp_shape, np.nan, dtype=self.values.dtype) + else: + interp_values = np.full(interp_shape, np.nan) + + interp_values[valid_mask] = self.values[i[valid_mask], ...] + + if self.values.ndim > 1: + new_shape = original_shape[:-1] + self.values.shape[1:] + else: + new_shape = original_shape[:-1] + interp_values = interp_values.reshape(new_shape) + + return interp_values + + +#------------------------------------------------------------------------------ +# Convenience interface function +#------------------------------------------------------------------------------ + + +def griddata(points, values, xi, method='linear', fill_value=np.nan, + rescale=False): + """ + Interpolate unstructured D-D data. + + Parameters + ---------- + points : 2-D ndarray of floats with shape (n, D), or length D tuple of 1-D ndarrays with shape (n,). + Data point coordinates. + values : ndarray of float or complex, shape (n,) + Data values. + xi : 2-D ndarray of floats with shape (m, D), or length D tuple of ndarrays broadcastable to the same shape. + Points at which to interpolate data. + method : {'linear', 'nearest', 'cubic'}, optional + Method of interpolation. One of + + ``nearest`` + return the value at the data point closest to + the point of interpolation. See `NearestNDInterpolator` for + more details. + + ``linear`` + tessellate the input point set to N-D + simplices, and interpolate linearly on each simplex. See + `LinearNDInterpolator` for more details. + + ``cubic`` (1-D) + return the value determined from a cubic + spline. + + ``cubic`` (2-D) + return the value determined from a + piecewise cubic, continuously differentiable (C1), and + approximately curvature-minimizing polynomial surface. See + `CloughTocher2DInterpolator` for more details. + fill_value : float, optional + Value used to fill in for requested points outside of the + convex hull of the input points. If not provided, then the + default is ``nan``. This option has no effect for the + 'nearest' method. + rescale : bool, optional + Rescale points to unit cube before performing interpolation. + This is useful if some of the input dimensions have + incommensurable units and differ by many orders of magnitude. + + .. versionadded:: 0.14.0 + + Returns + ------- + ndarray + Array of interpolated values. + + See Also + -------- + LinearNDInterpolator : + Piecewise linear interpolator in N dimensions. + NearestNDInterpolator : + Nearest-neighbor interpolator in N dimensions. + CloughTocher2DInterpolator : + Piecewise cubic, C1 smooth, curvature-minimizing interpolator in 2D. + interpn : Interpolation on a regular grid or rectilinear grid. + RegularGridInterpolator : Interpolator on a regular or rectilinear grid + in arbitrary dimensions (`interpn` wraps this + class). + + Notes + ----- + + .. versionadded:: 0.9 + + .. note:: For data on a regular grid use `interpn` instead. + + Examples + -------- + + Suppose we want to interpolate the 2-D function + + >>> import numpy as np + >>> def func(x, y): + ... return x*(1-x)*np.cos(4*np.pi*x) * np.sin(4*np.pi*y**2)**2 + + on a grid in [0, 1]x[0, 1] + + >>> grid_x, grid_y = np.mgrid[0:1:100j, 0:1:200j] + + but we only know its values at 1000 data points: + + >>> rng = np.random.default_rng() + >>> points = rng.random((1000, 2)) + >>> values = func(points[:,0], points[:,1]) + + This can be done with `griddata` -- below we try out all of the + interpolation methods: + + >>> from scipy.interpolate import griddata + >>> grid_z0 = griddata(points, values, (grid_x, grid_y), method='nearest') + >>> grid_z1 = griddata(points, values, (grid_x, grid_y), method='linear') + >>> grid_z2 = griddata(points, values, (grid_x, grid_y), method='cubic') + + One can see that the exact result is reproduced by all of the + methods to some degree, but for this smooth function the piecewise + cubic interpolant gives the best results: + + >>> import matplotlib.pyplot as plt + >>> plt.subplot(221) + >>> plt.imshow(func(grid_x, grid_y).T, extent=(0,1,0,1), origin='lower') + >>> plt.plot(points[:,0], points[:,1], 'k.', ms=1) + >>> plt.title('Original') + >>> plt.subplot(222) + >>> plt.imshow(grid_z0.T, extent=(0,1,0,1), origin='lower') + >>> plt.title('Nearest') + >>> plt.subplot(223) + >>> plt.imshow(grid_z1.T, extent=(0,1,0,1), origin='lower') + >>> plt.title('Linear') + >>> plt.subplot(224) + >>> plt.imshow(grid_z2.T, extent=(0,1,0,1), origin='lower') + >>> plt.title('Cubic') + >>> plt.gcf().set_size_inches(6, 6) + >>> plt.show() + + """ # numpy/numpydoc#87 # noqa: E501 + + points = _ndim_coords_from_arrays(points) + + if points.ndim < 2: + ndim = points.ndim + else: + ndim = points.shape[-1] + + if ndim == 1 and method in ('nearest', 'linear', 'cubic'): + from ._interpolate import interp1d + points = points.ravel() + if isinstance(xi, tuple): + if len(xi) != 1: + raise ValueError("invalid number of dimensions in xi") + xi, = xi + # Sort points/values together, necessary as input for interp1d + idx = np.argsort(points) + points = points[idx] + values = values[idx] + if method == 'nearest': + fill_value = 'extrapolate' + ip = interp1d(points, values, kind=method, axis=0, bounds_error=False, + fill_value=fill_value) + return ip(xi) + elif method == 'nearest': + ip = NearestNDInterpolator(points, values, rescale=rescale) + return ip(xi) + elif method == 'linear': + ip = LinearNDInterpolator(points, values, fill_value=fill_value, + rescale=rescale) + return ip(xi) + elif method == 'cubic' and ndim == 2: + ip = CloughTocher2DInterpolator(points, values, fill_value=fill_value, + rescale=rescale) + return ip(xi) + else: + raise ValueError("Unknown interpolation method %r for " + "%d dimensional data" % (method, ndim)) diff --git a/shared/package-files/01/019997890d118d486d9effca2280c0d432aa87c904cb704e09b94fef7974f7f7/blob b/shared/package-files/01/019997890d118d486d9effca2280c0d432aa87c904cb704e09b94fef7974f7f7/blob new file mode 100644 index 0000000000000000000000000000000000000000..60dac9a81337d7a39ab6b108aeef0d4f8a5e838e --- /dev/null +++ b/shared/package-files/01/019997890d118d486d9effca2280c0d432aa87c904cb704e09b94fef7974f7f7/blob @@ -0,0 +1,26 @@ +#pragma once +// @generated by torchgen/gen.py from DispatchKeyFunction.h + +// NB: The implementing C++ file is RegisterDispatchKey.cpp + +// The only #includes we need are for custom classes that have defaults in the C++ API +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { + +namespace cuda { + +TORCH_API at::Tensor gelu(const at::Tensor & self, c10::string_view approximate="none"); +TORCH_API at::Tensor & gelu_out(at::Tensor & out, const at::Tensor & self, c10::string_view approximate="none"); +TORCH_API at::Tensor & gelu_outf(const at::Tensor & self, c10::string_view approximate, at::Tensor & out); +TORCH_API at::Tensor & gelu_(at::Tensor & self, c10::string_view approximate="none"); + +} // namespace cuda +} // namespace at diff --git a/shared/package-files/01/019e9da80e9f5e59b8f9e84109ff66d67ab8de350f2a66a7e3fdb086b381bad7/blob b/shared/package-files/01/019e9da80e9f5e59b8f9e84109ff66d67ab8de350f2a66a7e3fdb086b381bad7/blob new file mode 100644 index 0000000000000000000000000000000000000000..d11ec581de8d997162397c92690ef080ace2bb33 --- /dev/null +++ b/shared/package-files/01/019e9da80e9f5e59b8f9e84109ff66d67ab8de350f2a66a7e3fdb086b381bad7/blob @@ -0,0 +1,715 @@ +""" +Reducer using memory mapping for numpy arrays +""" +# Author: Thomas Moreau +# Copyright: 2017, Thomas Moreau +# License: BSD 3 clause + +import atexit +import errno +import os +import stat +import tempfile +import threading +import time +import warnings +import weakref +from mmap import mmap +from multiprocessing import util +from pickle import HIGHEST_PROTOCOL, PicklingError, dumps, loads, whichmodule +from uuid import uuid4 + +try: + WindowsError +except NameError: + WindowsError = type(None) + +try: + import numpy as np + from numpy.lib.stride_tricks import as_strided +except ImportError: + np = None + +from .backports import make_memmap +from .disk import delete_folder +from .externals.loky.backend import resource_tracker +from .numpy_pickle import dump, load, load_temporary_memmap + +# Some system have a ramdisk mounted by default, we can use it instead of /tmp +# as the default folder to dump big arrays to share with subprocesses. +SYSTEM_SHARED_MEM_FS = "/dev/shm" + +# Minimal number of bytes available on SYSTEM_SHARED_MEM_FS to consider using +# it as the default folder to dump big arrays to share with subprocesses. +SYSTEM_SHARED_MEM_FS_MIN_SIZE = int(2e9) + +# Folder and file permissions to chmod temporary files generated by the +# memmapping pool. Only the owner of the Python process can access the +# temporary files and folder. +FOLDER_PERMISSIONS = stat.S_IRUSR | stat.S_IWUSR | stat.S_IXUSR +FILE_PERMISSIONS = stat.S_IRUSR | stat.S_IWUSR + +# Set used in joblib workers, referencing the filenames of temporary memmaps +# created by joblib to speed up data communication. In child processes, we add +# a finalizer to these memmaps that sends a maybe_unlink call to the +# resource_tracker, in order to free main memory as fast as possible. +JOBLIB_MMAPS = set() + + +def _log_and_unlink(filename): + from .externals.loky.backend.resource_tracker import _resource_tracker + + util.debug( + "[FINALIZER CALL] object mapping to {} about to be deleted," + " decrementing the refcount of the file (pid: {})".format( + os.path.basename(filename), os.getpid() + ) + ) + _resource_tracker.maybe_unlink(filename, "file") + + +def add_maybe_unlink_finalizer(memmap): + util.debug( + "[FINALIZER ADD] adding finalizer to {} (id {}, filename {}, pid {})".format( + type(memmap), id(memmap), os.path.basename(memmap.filename), os.getpid() + ) + ) + weakref.finalize(memmap, _log_and_unlink, memmap.filename) + + +def unlink_file(filename): + """Wrapper around os.unlink with a retry mechanism. + + The retry mechanism has been implemented primarily to overcome a race + condition happening during the finalizer of a np.memmap: when a process + holding the last reference to a mmap-backed np.memmap/np.array is about to + delete this array (and close the reference), it sends a maybe_unlink + request to the resource_tracker. This request can be processed faster than + it takes for the last reference of the memmap to be closed, yielding (on + Windows) a PermissionError in the resource_tracker loop. + """ + NUM_RETRIES = 10 + for retry_no in range(1, NUM_RETRIES + 1): + try: + os.unlink(filename) + break + except PermissionError: + util.debug( + "[ResourceTracker] tried to unlink {}, got PermissionError".format( + filename + ) + ) + if retry_no == NUM_RETRIES: + raise + else: + time.sleep(0.2) + except FileNotFoundError: + # In case of a race condition when deleting the temporary folder, + # avoid noisy FileNotFoundError exception in the resource tracker. + pass + + +resource_tracker._CLEANUP_FUNCS["file"] = unlink_file + + +class _WeakArrayKeyMap: + """A variant of weakref.WeakKeyDictionary for unhashable numpy arrays. + + This datastructure will be used with numpy arrays as obj keys, therefore we + do not use the __get__ / __set__ methods to avoid any conflict with the + numpy fancy indexing syntax. + """ + + def __init__(self): + self._data = {} + + def get(self, obj): + ref, val = self._data[id(obj)] + if ref() is not obj: + # In case of race condition with on_destroy: could never be + # triggered by the joblib tests with CPython. + raise KeyError(obj) + return val + + def set(self, obj, value): + key = id(obj) + try: + ref, _ = self._data[key] + if ref() is not obj: + # In case of race condition with on_destroy: could never be + # triggered by the joblib tests with CPython. + raise KeyError(obj) + except KeyError: + # Insert the new entry in the mapping along with a weakref + # callback to automatically delete the entry from the mapping + # as soon as the object used as key is garbage collected. + def on_destroy(_): + del self._data[key] + + ref = weakref.ref(obj, on_destroy) + self._data[key] = ref, value + + def __getstate__(self): + raise PicklingError("_WeakArrayKeyMap is not pickleable") + + +############################################################################### +# Support for efficient transient pickling of numpy data structures + + +def _get_backing_memmap(a): + """Recursively look up the original np.memmap instance base if any.""" + b = getattr(a, "base", None) + if b is None: + # TODO: check scipy sparse datastructure if scipy is installed + # a nor its descendants do not have a memmap base + return None + + elif isinstance(b, mmap): + # a is already a real memmap instance. + return a + + else: + # Recursive exploration of the base ancestry + return _get_backing_memmap(b) + + +def _get_temp_dir(pool_folder_name, temp_folder=None): + """Get the full path to a subfolder inside the temporary folder. + + Parameters + ---------- + pool_folder_name : str + Sub-folder name used for the serialization of a pool instance. + + temp_folder: str, optional + Folder to be used by the pool for memmapping large arrays + for sharing memory with worker processes. If None, this will try in + order: + + - a folder pointed by the JOBLIB_TEMP_FOLDER environment + variable, + - /dev/shm if the folder exists and is writable: this is a + RAMdisk filesystem available by default on modern Linux + distributions, + - the default system temporary folder that can be + overridden with TMP, TMPDIR or TEMP environment + variables, typically /tmp under Unix operating systems. + + Returns + ------- + pool_folder : str + full path to the temporary folder + use_shared_mem : bool + whether the temporary folder is written to the system shared memory + folder or some other temporary folder. + """ + use_shared_mem = False + if temp_folder is None: + temp_folder = os.environ.get("JOBLIB_TEMP_FOLDER", None) + if temp_folder is None: + if os.path.exists(SYSTEM_SHARED_MEM_FS) and hasattr(os, "statvfs"): + try: + shm_stats = os.statvfs(SYSTEM_SHARED_MEM_FS) + available_nbytes = shm_stats.f_bsize * shm_stats.f_bavail + if available_nbytes > SYSTEM_SHARED_MEM_FS_MIN_SIZE: + # Try to see if we have write access to the shared mem + # folder only if it is reasonably large (that is 2GB or + # more). + temp_folder = SYSTEM_SHARED_MEM_FS + pool_folder = os.path.join(temp_folder, pool_folder_name) + if not os.path.exists(pool_folder): + os.makedirs(pool_folder) + use_shared_mem = True + except (IOError, OSError): + # Missing rights in the /dev/shm partition, fallback to regular + # temp folder. + temp_folder = None + if temp_folder is None: + # Fallback to the default tmp folder, typically /tmp + temp_folder = tempfile.gettempdir() + temp_folder = os.path.abspath(os.path.expanduser(temp_folder)) + pool_folder = os.path.join(temp_folder, pool_folder_name) + return pool_folder, use_shared_mem + + +def has_shareable_memory(a): + """Return True if a is backed by some mmap buffer directly or not.""" + return _get_backing_memmap(a) is not None + + +def _strided_from_memmap( + filename, + dtype, + mode, + offset, + order, + shape, + strides, + total_buffer_len, + unlink_on_gc_collect, +): + """Reconstruct an array view on a memory mapped file.""" + if mode == "w+": + # Do not zero the original data when unpickling + mode = "r+" + + if strides is None: + # Simple, contiguous memmap + return make_memmap( + filename, + dtype=dtype, + shape=shape, + mode=mode, + offset=offset, + order=order, + unlink_on_gc_collect=unlink_on_gc_collect, + ) + else: + # For non-contiguous data, memmap the total enclosing buffer and then + # extract the non-contiguous view with the stride-tricks API + base = make_memmap( + filename, + dtype=dtype, + shape=total_buffer_len, + offset=offset, + mode=mode, + order=order, + unlink_on_gc_collect=unlink_on_gc_collect, + ) + return as_strided(base, shape=shape, strides=strides) + + +def _reduce_memmap_backed(a, m): + """Pickling reduction for memmap backed arrays. + + a is expected to be an instance of np.ndarray (or np.memmap) + m is expected to be an instance of np.memmap on the top of the ``base`` + attribute ancestry of a. ``m.base`` should be the real python mmap object. + """ + # offset that comes from the striding differences between a and m + util.debug( + "[MEMMAP REDUCE] reducing a memmap-backed array (shape, {}, pid: {})".format( + a.shape, os.getpid() + ) + ) + try: + from numpy.lib.array_utils import byte_bounds + except (ModuleNotFoundError, ImportError): + # Backward-compat for numpy < 2.0 + from numpy import byte_bounds + a_start, a_end = byte_bounds(a) + m_start = byte_bounds(m)[0] + offset = a_start - m_start + + # offset from the backing memmap + offset += m.offset + + # 1D arrays are both F and C contiguous, so only set the flag in + # higher dimensions. See https://github.com/joblib/joblib/pull/1704. + if m.ndim > 1 and m.flags["F_CONTIGUOUS"]: + order = "F" + else: + # The backing memmap buffer is necessarily contiguous hence C if not + # Fortran + order = "C" + + if a.flags["F_CONTIGUOUS"] or a.flags["C_CONTIGUOUS"]: + # If the array is a contiguous view, no need to pass the strides + strides = None + total_buffer_len = None + else: + # Compute the total number of items to map from which the strided + # view will be extracted. + strides = a.strides + total_buffer_len = (a_end - a_start) // a.itemsize + + return ( + _strided_from_memmap, + ( + m.filename, + a.dtype, + m.mode, + offset, + order, + a.shape, + strides, + total_buffer_len, + False, + ), + ) + + +def reduce_array_memmap_backward(a): + """reduce a np.array or a np.memmap from a child process""" + m = _get_backing_memmap(a) + if isinstance(m, np.memmap) and m.filename not in JOBLIB_MMAPS: + # if a is backed by a memmaped file, reconstruct a using the + # memmaped file. + return _reduce_memmap_backed(a, m) + else: + # a is either a regular (not memmap-backed) numpy array, or an array + # backed by a shared temporary file created by joblib. In the latter + # case, in order to limit the lifespan of these temporary files, we + # serialize the memmap as a regular numpy array, and decref the + # file backing the memmap (done implicitly in a previously registered + # finalizer, see ``unlink_on_gc_collect`` for more details) + return (loads, (dumps(np.asarray(a), protocol=HIGHEST_PROTOCOL),)) + + +class ArrayMemmapForwardReducer(object): + """Reducer callable to dump large arrays to memmap files. + + Parameters + ---------- + max_nbytes: int + Threshold to trigger memmapping of large arrays to files created + a folder. + temp_folder_resolver: callable + An callable in charge of resolving a temporary folder name where files + for backing memmapped arrays are created. + mmap_mode: 'r', 'r+' or 'c' + Mode for the created memmap datastructure. See the documentation of + numpy.memmap for more details. Note: 'w+' is coerced to 'r+' + automatically to avoid zeroing the data on unpickling. + verbose: int, optional, 0 by default + If verbose > 0, memmap creations are logged. + If verbose > 1, both memmap creations, reuse and array pickling are + logged. + prewarm: bool, optional, False by default. + Force a read on newly memmapped array to make sure that OS pre-cache it + memory. This can be useful to avoid concurrent disk access when the + same data array is passed to different worker processes. + """ + + def __init__( + self, + max_nbytes, + temp_folder_resolver, + mmap_mode, + unlink_on_gc_collect, + verbose=0, + prewarm=True, + ): + self._max_nbytes = max_nbytes + self._temp_folder_resolver = temp_folder_resolver + self._mmap_mode = mmap_mode + self.verbose = int(verbose) + if prewarm == "auto": + self._prewarm = not self._temp_folder.startswith(SYSTEM_SHARED_MEM_FS) + else: + self._prewarm = prewarm + self._prewarm = prewarm + self._memmaped_arrays = _WeakArrayKeyMap() + self._temporary_memmaped_filenames = set() + self._unlink_on_gc_collect = unlink_on_gc_collect + + @property + def _temp_folder(self): + return self._temp_folder_resolver() + + def __reduce__(self): + # The ArrayMemmapForwardReducer is passed to the children processes: it + # needs to be pickled but the _WeakArrayKeyMap need to be skipped as + # it's only guaranteed to be consistent with the parent process memory + # garbage collection. + # Although this reducer is pickled, it is not needed in its destination + # process (child processes), as we only use this reducer to send + # memmaps from the parent process to the children processes. For this + # reason, we can afford skipping the resolver, (which would otherwise + # be unpicklable), and pass it as None instead. + args = (self._max_nbytes, None, self._mmap_mode, self._unlink_on_gc_collect) + kwargs = { + "verbose": self.verbose, + "prewarm": self._prewarm, + } + return ArrayMemmapForwardReducer, args, kwargs + + def __call__(self, a): + m = _get_backing_memmap(a) + if m is not None and isinstance(m, np.memmap): + # a is already backed by a memmap file, let's reuse it directly + return _reduce_memmap_backed(a, m) + + if ( + not a.dtype.hasobject + and self._max_nbytes is not None + and a.nbytes > self._max_nbytes + ): + # check that the folder exists (lazily create the pool temp folder + # if required) + try: + os.makedirs(self._temp_folder) + os.chmod(self._temp_folder, FOLDER_PERMISSIONS) + except OSError as e: + if e.errno != errno.EEXIST: + raise e + + try: + basename = self._memmaped_arrays.get(a) + except KeyError: + # Generate a new unique random filename. The process and thread + # ids are only useful for debugging purpose and to make it + # easier to cleanup orphaned files in case of hard process + # kill (e.g. by "kill -9" or segfault). + basename = "{}-{}-{}.pkl".format( + os.getpid(), id(threading.current_thread()), uuid4().hex + ) + self._memmaped_arrays.set(a, basename) + filename = os.path.join(self._temp_folder, basename) + + # In case the same array with the same content is passed several + # times to the pool subprocess children, serialize it only once + + is_new_memmap = filename not in self._temporary_memmaped_filenames + + # add the memmap to the list of temporary memmaps created by joblib + self._temporary_memmaped_filenames.add(filename) + + if self._unlink_on_gc_collect: + # Bump reference count of the memmap by 1 to account for + # shared usage of the memmap by a child process. The + # corresponding decref call will be executed upon calling + # resource_tracker.maybe_unlink, registered as a finalizer in + # the child. + # the incref/decref calls here are only possible when the child + # and the parent share the same resource_tracker. It is not the + # case for the multiprocessing backend, but it does not matter + # because unlinking a memmap from a child process is only + # useful to control the memory usage of long-lasting child + # processes, while the multiprocessing-based pools terminate + # their workers at the end of a map() call. + resource_tracker.register(filename, "file") + + if is_new_memmap: + # Incref each temporary memmap created by joblib one extra + # time. This means that these memmaps will only be deleted + # once an extra maybe_unlink() is called, which is done once + # all the jobs have completed (or been canceled) in the + # Parallel._terminate_backend() method. + resource_tracker.register(filename, "file") + + if not os.path.exists(filename): + util.debug( + "[ARRAY DUMP] Pickling new array (shape={}, dtype={}) " + "creating a new memmap at {}".format(a.shape, a.dtype, filename) + ) + for dumped_filename in dump(a, filename): + os.chmod(dumped_filename, FILE_PERMISSIONS) + + if self._prewarm: + # Warm up the data by accessing it. This operation ensures + # that the disk access required to create the memmapping + # file are performed in the reducing process and avoids + # concurrent memmap creation in multiple children + # processes. + load(filename, mmap_mode=self._mmap_mode).max() + + else: + util.debug( + "[ARRAY DUMP] Pickling known array (shape={}, dtype={}) " + "reusing memmap file: {}".format( + a.shape, a.dtype, os.path.basename(filename) + ) + ) + + # The worker process will use joblib.load to memmap the data + return ( + load_temporary_memmap, + (filename, self._mmap_mode, self._unlink_on_gc_collect), + ) + else: + # do not convert a into memmap, let pickler do its usual copy with + # the default system pickler + util.debug( + "[ARRAY DUMP] Pickling array (NO MEMMAPPING) (shape={}, " + " dtype={}).".format(a.shape, a.dtype) + ) + return (loads, (dumps(a, protocol=HIGHEST_PROTOCOL),)) + + +def get_memmapping_reducers( + forward_reducers=None, + backward_reducers=None, + temp_folder_resolver=None, + max_nbytes=1e6, + mmap_mode="r", + verbose=0, + prewarm=False, + unlink_on_gc_collect=True, + **kwargs, +): + """Construct a pair of memmapping reducer linked to a tmpdir. + + This function manage the creation and the clean up of the temporary folders + underlying the memory maps and should be use to get the reducers necessary + to construct joblib pool or executor. + """ + if forward_reducers is None: + forward_reducers = dict() + if backward_reducers is None: + backward_reducers = dict() + + if np is not None: + # Register smart numpy.ndarray reducers that detects memmap backed + # arrays and that is also able to dump to memmap large in-memory + # arrays over the max_nbytes threshold + forward_reduce_ndarray = ArrayMemmapForwardReducer( + max_nbytes, + temp_folder_resolver, + mmap_mode, + unlink_on_gc_collect, + verbose, + prewarm=prewarm, + ) + forward_reducers[np.ndarray] = forward_reduce_ndarray + forward_reducers[np.memmap] = forward_reduce_ndarray + + # Communication from child process to the parent process always + # pickles in-memory numpy.ndarray without dumping them as memmap + # to avoid confusing the caller and make it tricky to collect the + # temporary folder + backward_reducers[np.ndarray] = reduce_array_memmap_backward + backward_reducers[np.memmap] = reduce_array_memmap_backward + + return forward_reducers, backward_reducers + + +class TemporaryResourcesManager(object): + """Stateful object able to manage temporary folder and pickles + + It exposes: + - a per-context folder name resolving API that memmap-based reducers will + rely on to know where to pickle the temporary memmaps + - a temporary file/folder management API that internally uses the + resource_tracker. + """ + + def __init__(self, temp_folder_root=None, context_id=None): + self._current_temp_folder = None + self._temp_folder_root = temp_folder_root + self._use_shared_mem = None + self._cached_temp_folders = dict() + self._id = uuid4().hex + self._finalizers = {} + if context_id is None: + # It would be safer to not assign a default context id (less silent + # bugs), but doing this while maintaining backward compatibility + # with the previous, context-unaware version get_memmaping_executor + # exposes too many low-level details. + context_id = uuid4().hex + self.set_current_context(context_id) + + def set_current_context(self, context_id): + self._current_context_id = context_id + self.register_new_context(context_id) + + def register_new_context(self, context_id): + # Prepare a sub-folder name specific to a context (usually a unique id + # generated by each instance of the Parallel class). Do not create in + # advance to spare FS write access if no array is to be dumped). + if context_id in self._cached_temp_folders: + return + else: + # During its lifecycle, one Parallel object can have several + # executors associated to it (for instance, if a loky worker raises + # an exception, joblib shutdowns the executor and instantly + # recreates a new one before raising the error - see + # ``ensure_ready``. Because we don't want two executors tied to + # the same Parallel object (and thus the same context id) to + # register/use/delete the same folder, we also add an id specific + # to the current Manager (and thus specific to its associated + # executor) to the folder name. + new_folder_name = "joblib_memmapping_folder_{}_{}_{}".format( + os.getpid(), self._id, context_id + ) + new_folder_path, _ = _get_temp_dir(new_folder_name, self._temp_folder_root) + self.register_folder_finalizer(new_folder_path, context_id) + self._cached_temp_folders[context_id] = new_folder_path + + def resolve_temp_folder_name(self): + """Return a folder name specific to the currently activated context""" + return self._cached_temp_folders[self._current_context_id] + + # resource management API + + def register_folder_finalizer(self, pool_subfolder, context_id): + # Register the garbage collector at program exit in case caller forgets + # to call terminate explicitly: note we do not pass any reference to + # ensure that this callback won't prevent garbage collection of + # parallel instance and related file handler resources such as POSIX + # semaphores and pipes + pool_module_name = whichmodule(delete_folder, "delete_folder") + resource_tracker.register(pool_subfolder, "folder") + + def _cleanup(): + # In some cases the Python runtime seems to set delete_folder to + # None just before exiting when accessing the delete_folder + # function from the closure namespace. So instead we reimport + # the delete_folder function explicitly. + # https://github.com/joblib/joblib/issues/328 + # We cannot just use from 'joblib.pool import delete_folder' + # because joblib should only use relative imports to allow + # easy vendoring. + delete_folder = __import__( + pool_module_name, fromlist=["delete_folder"] + ).delete_folder + try: + delete_folder(pool_subfolder, allow_non_empty=True) + resource_tracker.unregister(pool_subfolder, "folder") + except OSError: + warnings.warn( + "Failed to delete temporary folder: {}".format(pool_subfolder) + ) + + self._finalizers[context_id] = atexit.register(_cleanup) + + def _clean_temporary_resources( + self, context_id=None, force=False, allow_non_empty=False + ): + """Clean temporary resources created by a process-based pool""" + if context_id is None: + # Iterates over a copy of the cache keys to avoid Error due to + # iterating over a changing size dictionary. + for context_id in list(self._cached_temp_folders): + self._clean_temporary_resources( + context_id, force=force, allow_non_empty=allow_non_empty + ) + else: + temp_folder = self._cached_temp_folders.get(context_id) + if temp_folder and os.path.exists(temp_folder): + for filename in os.listdir(temp_folder): + if force: + # Some workers have failed and the ref counted might + # be off. The workers should have shut down by this + # time so forcefully clean up the files. + resource_tracker.unregister( + os.path.join(temp_folder, filename), "file" + ) + else: + resource_tracker.maybe_unlink( + os.path.join(temp_folder, filename), "file" + ) + + # When forcing clean-up, try to delete the folder even if some + # files are still in it. Otherwise, try to delete the folder + allow_non_empty |= force + + # Clean up the folder if possible, either if it is empty or + # if none of the files in it are in used and allow_non_empty. + try: + delete_folder(temp_folder, allow_non_empty=allow_non_empty) + # Forget the folder once it has been deleted + self._cached_temp_folders.pop(context_id, None) + resource_tracker.unregister(temp_folder, "folder") + + # Also cancel the finalizers that gets triggered at gc. + finalizer = self._finalizers.pop(context_id, None) + if finalizer is not None: + atexit.unregister(finalizer) + + except OSError: + # Temporary folder cannot be deleted right now. + # This folder will be cleaned up by an atexit + # finalizer registered by the memmapping_reducer. + pass diff --git a/shared/package-files/01/019ee4816e7c471f4d6f76231519336a35ca68ab5b8448561cb731f0e1260fc8/blob b/shared/package-files/01/019ee4816e7c471f4d6f76231519336a35ca68ab5b8448561cb731f0e1260fc8/blob new file mode 100644 index 0000000000000000000000000000000000000000..bc850690c01177524b594eb99e66440365442e36 --- /dev/null +++ b/shared/package-files/01/019ee4816e7c471f4d6f76231519336a35ca68ab5b8448561cb731f0e1260fc8/blob @@ -0,0 +1,47 @@ +#pragma once + +// @generated by torchgen/gen.py from Function.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + + +#include + +namespace at { + + +// aten::conv_transpose3d.input(Tensor input, Tensor weight, Tensor? bias=None, SymInt[3] stride=1, SymInt[3] padding=0, SymInt[3] output_padding=0, SymInt groups=1, SymInt[3] dilation=1) -> Tensor +inline at::Tensor conv_transpose3d(const at::Tensor & input, const at::Tensor & weight, const c10::optional & bias={}, at::IntArrayRef stride=1, at::IntArrayRef padding=0, at::IntArrayRef output_padding=0, int64_t groups=1, at::IntArrayRef dilation=1) { + return at::_ops::conv_transpose3d_input::call(input, weight, bias, c10::fromIntArrayRefSlow(stride), c10::fromIntArrayRefSlow(padding), c10::fromIntArrayRefSlow(output_padding), groups, c10::fromIntArrayRefSlow(dilation)); +} +namespace symint { + template ::value>> + at::Tensor conv_transpose3d(const at::Tensor & input, const at::Tensor & weight, const c10::optional & bias={}, at::IntArrayRef stride=1, at::IntArrayRef padding=0, at::IntArrayRef output_padding=0, int64_t groups=1, at::IntArrayRef dilation=1) { + return at::_ops::conv_transpose3d_input::call(input, weight, bias, c10::fromIntArrayRefSlow(stride), c10::fromIntArrayRefSlow(padding), c10::fromIntArrayRefSlow(output_padding), groups, c10::fromIntArrayRefSlow(dilation)); + } +} + +// aten::conv_transpose3d.input(Tensor input, Tensor weight, Tensor? bias=None, SymInt[3] stride=1, SymInt[3] padding=0, SymInt[3] output_padding=0, SymInt groups=1, SymInt[3] dilation=1) -> Tensor +inline at::Tensor conv_transpose3d_symint(const at::Tensor & input, const at::Tensor & weight, const c10::optional & bias={}, c10::SymIntArrayRef stride=c10::SymInt(1), c10::SymIntArrayRef padding=c10::SymInt(0), c10::SymIntArrayRef output_padding=c10::SymInt(0), c10::SymInt groups=1, c10::SymIntArrayRef dilation=c10::SymInt(1)) { + return at::_ops::conv_transpose3d_input::call(input, weight, bias, stride, padding, output_padding, groups, dilation); +} +namespace symint { + template ::value>> + at::Tensor conv_transpose3d(const at::Tensor & input, const at::Tensor & weight, const c10::optional & bias={}, c10::SymIntArrayRef stride=c10::SymInt(1), c10::SymIntArrayRef padding=c10::SymInt(0), c10::SymIntArrayRef output_padding=c10::SymInt(0), c10::SymInt groups=1, c10::SymIntArrayRef dilation=c10::SymInt(1)) { + return at::_ops::conv_transpose3d_input::call(input, weight, bias, stride, padding, output_padding, groups, dilation); + } +} + +} diff --git a/shared/package-files/01/01a0d9fab1262b8b456ae7be2bd3f9cb74f1c6769017a27067fe8b03391d2d02/blob b/shared/package-files/01/01a0d9fab1262b8b456ae7be2bd3f9cb74f1c6769017a27067fe8b03391d2d02/blob new file mode 100644 index 0000000000000000000000000000000000000000..8a831c12ce4307fa8f371caa4137ad3f278e81f7 --- /dev/null +++ b/shared/package-files/01/01a0d9fab1262b8b456ae7be2bd3f9cb74f1c6769017a27067fe8b03391d2d02/blob @@ -0,0 +1,74 @@ +/* + pybind11/complex.h: Complex number support + + Copyright (c) 2016 Wenzel Jakob + + All rights reserved. Use of this source code is governed by a + BSD-style license that can be found in the LICENSE file. +*/ + +#pragma once + +#include "pybind11.h" + +#include + +/// glibc defines I as a macro which breaks things, e.g., boost template names +#ifdef I +# undef I +#endif + +PYBIND11_NAMESPACE_BEGIN(PYBIND11_NAMESPACE) + +template +struct format_descriptor, detail::enable_if_t::value>> { + static constexpr const char c = format_descriptor::c; + static constexpr const char value[3] = {'Z', c, '\0'}; + static std::string format() { return std::string(value); } +}; + +#ifndef PYBIND11_CPP17 + +template +constexpr const char + format_descriptor, + detail::enable_if_t::value>>::value[3]; + +#endif + +PYBIND11_NAMESPACE_BEGIN(detail) + +template +struct is_fmt_numeric, detail::enable_if_t::value>> { + static constexpr bool value = true; + static constexpr int index = is_fmt_numeric::index + 3; +}; + +template +class type_caster> { +public: + bool load(handle src, bool convert) { + if (!src) { + return false; + } + if (!convert && !PyComplex_Check(src.ptr())) { + return false; + } + Py_complex result = PyComplex_AsCComplex(src.ptr()); + if (result.real == -1.0 && PyErr_Occurred()) { + PyErr_Clear(); + return false; + } + value = std::complex((T) result.real, (T) result.imag); + return true; + } + + static handle + cast(const std::complex &src, return_value_policy /* policy */, handle /* parent */) { + return PyComplex_FromDoubles((double) src.real(), (double) src.imag()); + } + + PYBIND11_TYPE_CASTER(std::complex, const_name("complex")); +}; +PYBIND11_NAMESPACE_END(detail) +PYBIND11_NAMESPACE_END(PYBIND11_NAMESPACE) diff --git a/shared/package-files/01/01a2c1c51366ea47bc2742670d9b52afd83ddcb3cc566920c8b2ea43aa2f61f5/blob b/shared/package-files/01/01a2c1c51366ea47bc2742670d9b52afd83ddcb3cc566920c8b2ea43aa2f61f5/blob new file mode 100644 index 0000000000000000000000000000000000000000..80f0349b205e6072abeb63c4727a1efa060b2d36 --- /dev/null +++ b/shared/package-files/01/01a2c1c51366ea47bc2742670d9b52afd83ddcb3cc566920c8b2ea43aa2f61f5/blob @@ -0,0 +1,575 @@ +from __future__ import annotations + +from typing import ( + TYPE_CHECKING, + Literal, + NamedTuple, +) +import warnings + +import matplotlib as mpl +from matplotlib.artist import setp +import numpy as np + +from pandas._libs import lib +from pandas.util._decorators import cache_readonly +from pandas.util._exceptions import find_stack_level + +from pandas.core.dtypes.common import is_dict_like +from pandas.core.dtypes.generic import ABCSeries +from pandas.core.dtypes.missing import remove_na_arraylike + +import pandas as pd +import pandas.core.common as com +from pandas.util.version import Version + +from pandas.io.formats.printing import pprint_thing +from pandas.plotting._matplotlib.core import ( + LinePlot, + MPLPlot, +) +from pandas.plotting._matplotlib.groupby import create_iter_data_given_by +from pandas.plotting._matplotlib.style import get_standard_colors +from pandas.plotting._matplotlib.tools import ( + create_subplots, + flatten_axes, + maybe_adjust_figure, +) + +if TYPE_CHECKING: + from collections.abc import Collection + + from matplotlib.axes import Axes + from matplotlib.figure import Figure + from matplotlib.lines import Line2D + + from pandas._typing import MatplotlibColor + + +def _set_ticklabels(ax: Axes, labels: list[str], is_vertical: bool, **kwargs) -> None: + """Set the tick labels of a given axis. + + Due to https://github.com/matplotlib/matplotlib/pull/17266, we need to handle the + case of repeated ticks (due to `FixedLocator`) and thus we duplicate the number of + labels. + """ + ticks = ax.get_xticks() if is_vertical else ax.get_yticks() + if len(ticks) != len(labels): + i, remainder = divmod(len(ticks), len(labels)) + if Version(mpl.__version__) < Version("3.10"): + assert remainder == 0, remainder + labels *= i + if is_vertical: + ax.set_xticklabels(labels, **kwargs) + else: + ax.set_yticklabels(labels, **kwargs) + + +class BoxPlot(LinePlot): + @property + def _kind(self) -> Literal["box"]: + return "box" + + _layout_type = "horizontal" + + _valid_return_types = (None, "axes", "dict", "both") + + class BP(NamedTuple): + # namedtuple to hold results + ax: Axes + lines: dict[str, list[Line2D]] + + def __init__(self, data, return_type: str = "axes", **kwargs) -> None: + if return_type not in self._valid_return_types: + raise ValueError("return_type must be {None, 'axes', 'dict', 'both'}") + + self.return_type = return_type + # Do not call LinePlot.__init__ which may fill nan + MPLPlot.__init__(self, data, **kwargs) # pylint: disable=non-parent-init-called + + if self.subplots: + # Disable label ax sharing. Otherwise, all subplots shows last + # column label + if self.orientation == "vertical": + self.sharex = False + else: + self.sharey = False + + # error: Signature of "_plot" incompatible with supertype "MPLPlot" + @classmethod + def _plot( # type: ignore[override] + cls, ax: Axes, y: np.ndarray, column_num=None, return_type: str = "axes", **kwds + ): + ys: np.ndarray | list[np.ndarray] + if y.ndim == 2: + ys = [remove_na_arraylike(v) for v in y] + # Boxplot fails with empty arrays, so need to add a NaN + # if any cols are empty + # GH 8181 + ys = [v if v.size > 0 else np.array([np.nan]) for v in ys] + else: + ys = remove_na_arraylike(y) + bp = ax.boxplot(ys, **kwds) + + if return_type == "dict": + return bp, bp + elif return_type == "both": + return cls.BP(ax=ax, lines=bp), bp + else: + return ax, bp + + def _validate_color_args(self, color, colormap): + if color is lib.no_default: + return None + + if colormap is not None: + warnings.warn( + "'color' and 'colormap' cannot be used " + "simultaneously. Using 'color'", + stacklevel=find_stack_level(), + ) + + if isinstance(color, dict): + valid_keys = ["boxes", "whiskers", "medians", "caps"] + for key in color: + if key not in valid_keys: + raise ValueError( + f"color dict contains invalid key '{key}'. " + f"The key must be either {valid_keys}" + ) + return color + + @cache_readonly + def _color_attrs(self): + # get standard colors for default + # use 2 colors by default, for box/whisker and median + # flier colors isn't needed here + # because it can be specified by ``sym`` kw + return get_standard_colors(num_colors=3, colormap=self.colormap, color=None) + + @cache_readonly + def _boxes_c(self): + return self._color_attrs[0] + + @cache_readonly + def _whiskers_c(self): + return self._color_attrs[0] + + @cache_readonly + def _medians_c(self): + return self._color_attrs[2] + + @cache_readonly + def _caps_c(self): + return self._color_attrs[0] + + def _get_colors( + self, + num_colors=None, + color_kwds: dict[str, MatplotlibColor] + | MatplotlibColor + | Collection[MatplotlibColor] + | None = "color", + ) -> None: + pass + + def maybe_color_bp(self, bp) -> None: + if isinstance(self.color, dict): + boxes = self.color.get("boxes", self._boxes_c) + whiskers = self.color.get("whiskers", self._whiskers_c) + medians = self.color.get("medians", self._medians_c) + caps = self.color.get("caps", self._caps_c) + else: + # Other types are forwarded to matplotlib + # If None, use default colors + boxes = self.color or self._boxes_c + whiskers = self.color or self._whiskers_c + medians = self.color or self._medians_c + caps = self.color or self._caps_c + + color_tup = (boxes, whiskers, medians, caps) + maybe_color_bp(bp, color_tup=color_tup, **self.kwds) + + def _make_plot(self, fig: Figure) -> None: + if self.subplots: + self._return_obj = pd.Series(dtype=object) + + # Re-create iterated data if `by` is assigned by users + data = ( + create_iter_data_given_by(self.data, self._kind) + if self.by is not None + else self.data + ) + + # error: Argument "data" to "_iter_data" of "MPLPlot" has + # incompatible type "object"; expected "DataFrame | + # dict[Hashable, Series | DataFrame]" + for i, (label, y) in enumerate(self._iter_data(data=data)): # type: ignore[arg-type] + ax = self._get_ax(i) + kwds = self.kwds.copy() + + # When by is applied, show title for subplots to know which group it is + # just like df.boxplot, and need to apply T on y to provide right input + if self.by is not None: + y = y.T + ax.set_title(pprint_thing(label)) + + # When `by` is assigned, the ticklabels will become unique grouped + # values, instead of label which is used as subtitle in this case. + # error: "Index" has no attribute "levels"; maybe "nlevels"? + levels = self.data.columns.levels # type: ignore[attr-defined] + ticklabels = [pprint_thing(col) for col in levels[0]] + else: + ticklabels = [pprint_thing(label)] + + ret, bp = self._plot( + ax, y, column_num=i, return_type=self.return_type, **kwds + ) + self.maybe_color_bp(bp) + self._return_obj[label] = ret + _set_ticklabels( + ax=ax, labels=ticklabels, is_vertical=self.orientation == "vertical" + ) + else: + y = self.data.values.T + ax = self._get_ax(0) + kwds = self.kwds.copy() + + ret, bp = self._plot( + ax, y, column_num=0, return_type=self.return_type, **kwds + ) + self.maybe_color_bp(bp) + self._return_obj = ret + + labels = [pprint_thing(left) for left in self.data.columns] + if not self.use_index: + labels = [pprint_thing(key) for key in range(len(labels))] + _set_ticklabels( + ax=ax, labels=labels, is_vertical=self.orientation == "vertical" + ) + + def _make_legend(self) -> None: + pass + + def _post_plot_logic(self, ax: Axes, data) -> None: + # GH 45465: make sure that the boxplot doesn't ignore xlabel/ylabel + if self.xlabel: + ax.set_xlabel(pprint_thing(self.xlabel)) + if self.ylabel: + ax.set_ylabel(pprint_thing(self.ylabel)) + + @property + def orientation(self) -> Literal["horizontal", "vertical"]: + if self.kwds.get("vert", True): + return "vertical" + else: + return "horizontal" + + @property + def result(self): + if self.return_type is None: + return super().result + else: + return self._return_obj + + +def maybe_color_bp(bp, color_tup, **kwds) -> None: + # GH#30346, when users specifying those arguments explicitly, our defaults + # for these four kwargs should be overridden; if not, use Pandas settings + if not kwds.get("boxprops"): + setp(bp["boxes"], color=color_tup[0], alpha=1) + if not kwds.get("whiskerprops"): + setp(bp["whiskers"], color=color_tup[1], alpha=1) + if not kwds.get("medianprops"): + setp(bp["medians"], color=color_tup[2], alpha=1) + if not kwds.get("capprops"): + setp(bp["caps"], color=color_tup[3], alpha=1) + + +def _grouped_plot_by_column( + plotf, + data, + columns=None, + by=None, + numeric_only: bool = True, + grid: bool = False, + figsize: tuple[float, float] | None = None, + ax=None, + layout=None, + return_type=None, + **kwargs, +): + grouped = data.groupby(by, observed=False) + if columns is None: + if not isinstance(by, (list, tuple)): + by = [by] + columns = data._get_numeric_data().columns.difference(by) + naxes = len(columns) + fig, axes = create_subplots( + naxes=naxes, + sharex=kwargs.pop("sharex", True), + sharey=kwargs.pop("sharey", True), + figsize=figsize, + ax=ax, + layout=layout, + ) + + _axes = flatten_axes(axes) + + # GH 45465: move the "by" label based on "vert" + xlabel, ylabel = kwargs.pop("xlabel", None), kwargs.pop("ylabel", None) + if kwargs.get("vert", True): + xlabel = xlabel or by + else: + ylabel = ylabel or by + + ax_values = [] + + for i, col in enumerate(columns): + ax = _axes[i] + gp_col = grouped[col] + keys, values = zip(*gp_col) + re_plotf = plotf(keys, values, ax, xlabel=xlabel, ylabel=ylabel, **kwargs) + ax.set_title(col) + ax_values.append(re_plotf) + ax.grid(grid) + + result = pd.Series(ax_values, index=columns, copy=False) + + # Return axes in multiplot case, maybe revisit later # 985 + if return_type is None: + result = axes + + byline = by[0] if len(by) == 1 else by + fig.suptitle(f"Boxplot grouped by {byline}") + maybe_adjust_figure(fig, bottom=0.15, top=0.9, left=0.1, right=0.9, wspace=0.2) + + return result + + +def boxplot( + data, + column=None, + by=None, + ax=None, + fontsize: int | None = None, + rot: int = 0, + grid: bool = True, + figsize: tuple[float, float] | None = None, + layout=None, + return_type=None, + **kwds, +): + import matplotlib.pyplot as plt + + # validate return_type: + if return_type not in BoxPlot._valid_return_types: + raise ValueError("return_type must be {'axes', 'dict', 'both'}") + + if isinstance(data, ABCSeries): + data = data.to_frame("x") + column = "x" + + def _get_colors(): + # num_colors=3 is required as method maybe_color_bp takes the colors + # in positions 0 and 2. + # if colors not provided, use same defaults as DataFrame.plot.box + result = get_standard_colors(num_colors=3) + result = np.take(result, [0, 0, 2]) + result = np.append(result, "k") + + colors = kwds.pop("color", None) + if colors: + if is_dict_like(colors): + # replace colors in result array with user-specified colors + # taken from the colors dict parameter + # "boxes" value placed in position 0, "whiskers" in 1, etc. + valid_keys = ["boxes", "whiskers", "medians", "caps"] + key_to_index = dict(zip(valid_keys, range(4))) + for key, value in colors.items(): + if key in valid_keys: + result[key_to_index[key]] = value + else: + raise ValueError( + f"color dict contains invalid key '{key}'. " + f"The key must be either {valid_keys}" + ) + else: + result.fill(colors) + + return result + + def plot_group(keys, values, ax: Axes, **kwds): + # GH 45465: xlabel/ylabel need to be popped out before plotting happens + xlabel, ylabel = kwds.pop("xlabel", None), kwds.pop("ylabel", None) + if xlabel: + ax.set_xlabel(pprint_thing(xlabel)) + if ylabel: + ax.set_ylabel(pprint_thing(ylabel)) + + keys = [pprint_thing(x) for x in keys] + values = [np.asarray(remove_na_arraylike(v), dtype=object) for v in values] + bp = ax.boxplot(values, **kwds) + if fontsize is not None: + ax.tick_params(axis="both", labelsize=fontsize) + + # GH 45465: x/y are flipped when "vert" changes + _set_ticklabels( + ax=ax, labels=keys, is_vertical=kwds.get("vert", True), rotation=rot + ) + maybe_color_bp(bp, color_tup=colors, **kwds) + + # Return axes in multiplot case, maybe revisit later # 985 + if return_type == "dict": + return bp + elif return_type == "both": + return BoxPlot.BP(ax=ax, lines=bp) + else: + return ax + + colors = _get_colors() + if column is None: + columns = None + elif isinstance(column, (list, tuple)): + columns = column + else: + columns = [column] + + if by is not None: + # Prefer array return type for 2-D plots to match the subplot layout + # https://github.com/pandas-dev/pandas/pull/12216#issuecomment-241175580 + result = _grouped_plot_by_column( + plot_group, + data, + columns=columns, + by=by, + grid=grid, + figsize=figsize, + ax=ax, + layout=layout, + return_type=return_type, + **kwds, + ) + else: + if return_type is None: + return_type = "axes" + if layout is not None: + raise ValueError("The 'layout' keyword is not supported when 'by' is None") + + if ax is None: + rc = {"figure.figsize": figsize} if figsize is not None else {} + with plt.rc_context(rc): + ax = plt.gca() + data = data._get_numeric_data() + naxes = len(data.columns) + if naxes == 0: + raise ValueError( + "boxplot method requires numerical columns, nothing to plot." + ) + if columns is None: + columns = data.columns + else: + data = data[columns] + + result = plot_group(columns, data.values.T, ax, **kwds) + ax.grid(grid) + + return result + + +def boxplot_frame( + self, + column=None, + by=None, + ax=None, + fontsize: int | None = None, + rot: int = 0, + grid: bool = True, + figsize: tuple[float, float] | None = None, + layout=None, + return_type=None, + **kwds, +): + import matplotlib.pyplot as plt + + ax = boxplot( + self, + column=column, + by=by, + ax=ax, + fontsize=fontsize, + grid=grid, + rot=rot, + figsize=figsize, + layout=layout, + return_type=return_type, + **kwds, + ) + plt.draw_if_interactive() + return ax + + +def boxplot_frame_groupby( + grouped, + subplots: bool = True, + column=None, + fontsize: int | None = None, + rot: int = 0, + grid: bool = True, + ax=None, + figsize: tuple[float, float] | None = None, + layout=None, + sharex: bool = False, + sharey: bool = True, + **kwds, +): + if subplots is True: + naxes = len(grouped) + fig, axes = create_subplots( + naxes=naxes, + squeeze=False, + ax=ax, + sharex=sharex, + sharey=sharey, + figsize=figsize, + layout=layout, + ) + axes = flatten_axes(axes) + + ret = pd.Series(dtype=object) + + for (key, group), ax in zip(grouped, axes): + d = group.boxplot( + ax=ax, column=column, fontsize=fontsize, rot=rot, grid=grid, **kwds + ) + ax.set_title(pprint_thing(key)) + ret.loc[key] = d + maybe_adjust_figure(fig, bottom=0.15, top=0.9, left=0.1, right=0.9, wspace=0.2) + else: + keys, frames = zip(*grouped) + if grouped.axis == 0: + df = pd.concat(frames, keys=keys, axis=1) + elif len(frames) > 1: + df = frames[0].join(frames[1::]) + else: + df = frames[0] + + # GH 16748, DataFrameGroupby fails when subplots=False and `column` argument + # is assigned, and in this case, since `df` here becomes MI after groupby, + # so we need to couple the keys (grouped values) and column (original df + # column) together to search for subset to plot + if column is not None: + column = com.convert_to_list_like(column) + multi_key = pd.MultiIndex.from_product([keys, column]) + column = list(multi_key.values) + ret = df.boxplot( + column=column, + fontsize=fontsize, + rot=rot, + grid=grid, + ax=ax, + figsize=figsize, + layout=layout, + **kwds, + ) + return ret diff --git a/shared/package-files/01/01a5d5690844df8f5caae8f8b736cd0781c9ee36eb11ee9ebb4dc1d22d4389f9/blob b/shared/package-files/01/01a5d5690844df8f5caae8f8b736cd0781c9ee36eb11ee9ebb4dc1d22d4389f9/blob new file mode 100644 index 0000000000000000000000000000000000000000..f850bebc99bc22b57f42be1828e222f1cb889696 --- /dev/null +++ b/shared/package-files/01/01a5d5690844df8f5caae8f8b736cd0781c9ee36eb11ee9ebb4dc1d22d4389f9/blob @@ -0,0 +1,83 @@ +lark-1.1.9.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +lark-1.1.9.dist-info/LICENSE,sha256=gmPlZS0Hzss62t8FFAtl5wz6Fp7OxfUg_hZxR5zhKoM,1073 +lark-1.1.9.dist-info/METADATA,sha256=6eU3NTAZjd5KuZCVaPAeKzKib0wskofu_815-T5aM8o,1878 +lark-1.1.9.dist-info/RECORD,, +lark-1.1.9.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +lark-1.1.9.dist-info/WHEEL,sha256=oiQVh_5PnQM0E3gPdiz09WCNmwiHDMaGer_elqB3coM,92 +lark-1.1.9.dist-info/entry_points.txt,sha256=WXYg_uCUdFlxQDPUhli3HFah37bNNFQfXLdzCqsacGI,61 +lark-1.1.9.dist-info/top_level.txt,sha256=dyS6jg8hCHHkXWvsfcIMO8rjlv_bdzAxiE0lkkzJ5hk,5 +lark/__init__.py,sha256=eOoOFH7rcPzKXd4rxJPkRl6LL7tMzpvuMjQk1afNHh8,782 +lark/__pycache__/__init__.cpython-310.pyc,, +lark/__pycache__/ast_utils.cpython-310.pyc,, +lark/__pycache__/common.cpython-310.pyc,, +lark/__pycache__/exceptions.cpython-310.pyc,, +lark/__pycache__/grammar.cpython-310.pyc,, +lark/__pycache__/indenter.cpython-310.pyc,, +lark/__pycache__/lark.cpython-310.pyc,, +lark/__pycache__/lexer.cpython-310.pyc,, +lark/__pycache__/load_grammar.cpython-310.pyc,, +lark/__pycache__/parse_tree_builder.cpython-310.pyc,, +lark/__pycache__/parser_frontends.cpython-310.pyc,, +lark/__pycache__/reconstruct.cpython-310.pyc,, +lark/__pycache__/tree.cpython-310.pyc,, +lark/__pycache__/tree_matcher.cpython-310.pyc,, +lark/__pycache__/tree_templates.cpython-310.pyc,, +lark/__pycache__/utils.cpython-310.pyc,, +lark/__pycache__/visitors.cpython-310.pyc,, +lark/__pyinstaller/__init__.py,sha256=16uejyuvS4VwfnVtDxk7SRZIzCCMX-j0_DBr39-0-5Y,188 +lark/__pyinstaller/__pycache__/__init__.cpython-310.pyc,, +lark/__pyinstaller/__pycache__/hook-lark.cpython-310.pyc,, +lark/__pyinstaller/hook-lark.py,sha256=RhJHTAnAeNjs9sqTpAQvAxYPhAKJA2NLKD4oh-IvDuc,613 +lark/ast_utils.py,sha256=0F8sUE8O1AYrJLbl-DaVYIc5iGWxuzCeybw-am23M7A,2176 +lark/common.py,sha256=4PL55HJGsq_erZjVfmKHL6N3f9-WoN-rwae-ffGA8bo,3192 +lark/exceptions.py,sha256=kb-KYAicBFOXaNlNbloLGO4Im9fzrOjWoLhIn9SaAkE,11231 +lark/grammar.py,sha256=8GvxXySoEMsEHpOuYvFe4QG-Jgb8FWGKh80zgep8r4E,3795 +lark/grammars/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +lark/grammars/__pycache__/__init__.cpython-310.pyc,, +lark/grammars/common.lark,sha256=aTv39kqbl8haIV6D88I0-dWf_C6jl3X8y9GKPt7yddE,944 +lark/grammars/lark.lark,sha256=mp2F9PYTmm8Jl7vjjUslEeHrcL9ZwfhJnDlcqhzeAWI,1603 +lark/grammars/python.lark,sha256=p5S5hYeA20GEDAHql8gb4TsZvqfZN36PYrJZhauiokc,10943 +lark/grammars/unicode.lark,sha256=_0Clod4_uthpQK_Cd52ZjTPkNTwHuzI_sYbYDr1yGOg,103 +lark/indenter.py,sha256=tQiJiupGwi82AxhHJfnoTTvrVEux1DWeXdxzDDZiRs0,3174 +lark/lark.py,sha256=Vma7ftpU8ZU06Fzs-cykn84BR5DIzXuy6vOxZGhR66g,28948 +lark/lexer.py,sha256=XOaa7j03rb4mOE6MjrONxDIkT2nOKm9UGx0evt1Lr-c,24715 +lark/load_grammar.py,sha256=vCjrxlYmWlgUqBqCx_XzFSRoXRkQP-k-hDIT-ZZE__M,55374 +lark/parse_tree_builder.py,sha256=7dJkxZTKI7JEfde6u2vvQVItLtKMK0CQOR92_QuWEnY,14803 +lark/parser_frontends.py,sha256=sC80SGfpO_STC04ZjSDgYyuOsLP36i1fwd1-lIZgSY0,10422 +lark/parsers/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +lark/parsers/__pycache__/__init__.cpython-310.pyc,, +lark/parsers/__pycache__/cyk.cpython-310.pyc,, +lark/parsers/__pycache__/earley.cpython-310.pyc,, +lark/parsers/__pycache__/earley_common.cpython-310.pyc,, +lark/parsers/__pycache__/earley_forest.cpython-310.pyc,, +lark/parsers/__pycache__/grammar_analysis.cpython-310.pyc,, +lark/parsers/__pycache__/lalr_analysis.cpython-310.pyc,, +lark/parsers/__pycache__/lalr_interactive_parser.cpython-310.pyc,, +lark/parsers/__pycache__/lalr_parser.cpython-310.pyc,, +lark/parsers/__pycache__/lalr_parser_state.cpython-310.pyc,, +lark/parsers/__pycache__/xearley.cpython-310.pyc,, +lark/parsers/cyk.py,sha256=JCn8WHR-wYDs8jh58IGZ6TLSik5zuGsxEOale1mX5BQ,12532 +lark/parsers/earley.py,sha256=f5ywWiaEhQ4J4Uu2l5eMDwjEE68ZVD2xSnO-kNbCbTc,14904 +lark/parsers/earley_common.py,sha256=xKxOTEOR28Mcdqxq9kW2ftng2R0lFh5TAE1T8wxszeg,1623 +lark/parsers/earley_forest.py,sha256=yVC-QuVwCVopsrGmBMmvouqFI9lbBsY7z1M-RyYrLcs,32444 +lark/parsers/grammar_analysis.py,sha256=CB74F6imSuvRb7ffztoD3VoIhMZ6cuit0UFr-doximk,7309 +lark/parsers/lalr_analysis.py,sha256=b-XlcyuWIjJqvY-1UEn38FB2tuGV2qla8JQ5jGs767Q,12539 +lark/parsers/lalr_interactive_parser.py,sha256=d5A6QDlkgnQM88ysPpkDyuFpGX3zvZzTfCb5qheoXFA,5781 +lark/parsers/lalr_parser.py,sha256=HKCLf3Lxc8YfzQLA98r4TjBreESzKlGd8vmnxwJKXeE,4708 +lark/parsers/lalr_parser_state.py,sha256=Ii53q514pZgYJqakw1vy-u4gyliHpRU5klwVfNZMhUU,3833 +lark/parsers/xearley.py,sha256=g2Ugz3FS4pJCgjhdR3hoYFqb9RXZMQqS3cJDlywlOKw,7986 +lark/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +lark/reconstruct.py,sha256=VYq_x5n1Beht6-G42tQxJM4_BvEMTMawJCcWOAsgbhI,3870 +lark/tools/__init__.py,sha256=XG-dXUPh7DP8CC8EZb2b1GpaenKEHO6X-BjsHnYw2v0,2615 +lark/tools/__pycache__/__init__.cpython-310.pyc,, +lark/tools/__pycache__/nearley.cpython-310.pyc,, +lark/tools/__pycache__/serialize.cpython-310.pyc,, +lark/tools/__pycache__/standalone.cpython-310.pyc,, +lark/tools/nearley.py,sha256=QaVnT3ilHm9vgOP9vMdpPuDjIKqCsnANlk9WFDq14-0,6467 +lark/tools/serialize.py,sha256=_3uoeHRbvD29t0CZHMcHoWxy19FWQIrp0CN6r54WNl4,997 +lark/tools/standalone.py,sha256=sS18zzBeFp7i7NaWddLd49BDFpmWdn6rOmhA9gVjB1g,5823 +lark/tree.py,sha256=_FLqE2-4MRSPUsXIlgM-FUmROeMcnGsXuWS8ElSmz_k,9025 +lark/tree_matcher.py,sha256=CdrRMlkLNTF87X896HK3ax7XFZd-z4zhV7dlwBju3VY,6189 +lark/tree_templates.py,sha256=sSnfw1m8txAkJOYhcQrooG7xajVyVplunzTnNsxY720,6139 +lark/utils.py,sha256=6N1tfllFonTjWK7iVhq3BNXj7K-E1mdfFfuLwtkHEi0,12259 +lark/visitors.py,sha256=sCfr6WanU-rCYZZYE2pg8HIRjpcRL0tJfeq56Tn9qJE,21956 diff --git a/shared/package-files/01/01a6d20adb796eb64574552e125fa31f1e7f6162f3b936ff4829aec5b95bf937/blob b/shared/package-files/01/01a6d20adb796eb64574552e125fa31f1e7f6162f3b936ff4829aec5b95bf937/blob new file mode 100644 index 0000000000000000000000000000000000000000..3cbd3c089974919cd4732a3c9026d0883d361849 --- /dev/null +++ b/shared/package-files/01/01a6d20adb796eb64574552e125fa31f1e7f6162f3b936ff4829aec5b95bf937/blob @@ -0,0 +1,758 @@ +""" +Created on Sat Aug 22 20:24:42 2015 + +Author: Josef Perktold +License: BSD-3 +""" + + +from itertools import pairwise +import warnings + +import numpy as np +import pandas as pd +from pandas.api.types import CategoricalDtype +from scipy import stats + +from statsmodels.base.model import ( + GenericLikelihoodModel, + GenericLikelihoodModelResults, + LikelihoodModel, + Model, +) +import statsmodels.base.wrapper as wrap +from statsmodels.formula.formulatools import advance_eval_env + +# for results wrapper: +import statsmodels.regression.linear_model as lm +from statsmodels.tools._decorators import cache_readonly +from statsmodels.tools.docstring_helpers import Appender +from statsmodels.tools.sm_exceptions import SpecificationWarning +from statsmodels.tools.validation import string_like + + +class OrderedModel(GenericLikelihoodModel): + """ + Ordinal Model based on logistic or normal distribution + + The parameterization corresponds to the proportional odds model in the + logistic case. + The model assumes that the endogenous variable is ordered but that the + labels have no numeric interpretation besides the ordering. + + The model is based on a latent linear variable, where we observe only a + discretization. + + y_latent = X beta + u + + The observed variable is defined by the interval + + y = {0 if y_latent <= cut_0 + 1 if cut_0 < y_latent <= cut_1 + ... + K if cut_K < y_latent + + The probability of observing y=k conditional on the explanatory variables + X is given by + + prob(y = k | x) = Prob(cut_k < y_latent <= cut_k+1) + = Prob(cut_k - x beta < u <= cut_k+1 - x beta + = F(cut_k+1 - x beta) - F(cut_k - x beta) + + Where F is the cumulative distribution of u which is either the normal + or the logistic distribution, but can be set to any other continuous + distribution. We use standardized distributions to avoid identifiability + problems. + + Parameters + ---------- + endog : array_like + Endogenous or dependent ordered categorical variable with k levels. + Labels or values of endog will internally transformed to consecutive + integers, 0, 1, 2, ... + Series with ordered Categorical as dtype should be preferred as it + gives the order relation between the levels. + If endog is not a pandas Categorical, then categories are + sorted in lexicographic order (by numpy.unique). + exog : array_like + Exogenous, explanatory variables. This should not include an intercept. + A DataFrame is also accepted. + See Notes about constant when using formulas. + offset : array_like, optional + Offset is added to the linear prediction with coefficient equal to 1. + distr : {"probit", "logit"} or distribution instance, optional + The default is currently 'probit' which uses the normal distribution + and corresponds to an ordered Probit model. The distribution is + assumed to have the main methods of scipy.stats distributions, mainly + cdf, pdf and ppf. The inverse cdf, ppf, is only use to calculate + starting values. + **kwds + Extra keyword arguments passed to the model, for example + ``missing``. + + Notes + ----- + Status: experimental, core results are verified, still subclasses + `GenericLikelihoodModel` which will change in future versions. + + The parameterization of OrderedModel requires that there is no constant in + the model, neither explicit nor implicit. The constant is equivalent to + shifting all thresholds and is therefore not separately identified. + + Patsy's formula specification does not allow a design matrix without + explicit or implicit constant if there are categorical variables (or maybe + splines) among explanatory variables. As workaround, statsmodels removes an + explicit intercept. + + Consequently, there are two valid cases to get a design matrix without + intercept when using formulas: + + - specify a model without explicit and implicit intercept which is possible + if there are only numerical variables in the model. + - specify a model with an explicit intercept which statsmodels will remove. + + Models with an implicit intercept will be overparameterized, the parameter + estimates will not be fully identified, cov_params will not be invertible + and standard errors might contain nans. The computed results will be + dominated by numerical imprecision coming mainly from convergence tolerance + and numerical derivatives. + + The model will raise a ValueError if a remaining constant is detected. + + """ + + _formula_max_endog = np.inf + + def __init__(self, endog, exog, offset=None, distr="probit", **kwds): + + if distr == "probit": + self.distr = stats.norm + elif distr == "logit": + self.distr = stats.logistic + else: + self.distr = distr + + if offset is not None: + offset = np.asarray(offset) + + self.offset = offset + + endog, labels, is_pandas = self._check_inputs(endog, exog) + + super().__init__(endog, exog, **kwds) + k_levels = None # initialize + if not is_pandas: + if self.endog.ndim == 1: + unique, index = np.unique(self.endog, return_inverse=True) + self.endog = index + labels = unique + if np.isnan(labels).any(): + msg = ( + "NaN in dependent variable detected. " + "Missing values need to be removed." + ) + raise ValueError(msg) + elif self.endog.ndim == 2: + if not hasattr(self, "model_spec"): + raise ValueError("2-dim endog not supported") + # this branch is currently only in support of from_formula + # we need to initialize k_levels correctly for df_resid + k_levels = self.endog.shape[1] + labels = [] + # Note: Doing the following here would break from_formula + # self.endog = self.endog.argmax(1) + + if self.k_constant > 0: + raise ValueError("There should not be a constant in the model") + + self._initialize_labels(labels, k_levels=k_levels) + + # adjust df + self.k_extra = self.k_levels - 1 + self.df_model = self.k_vars + self.df_resid = self.nobs - (self.k_vars + self.k_extra) + + self.results_class = OrderedResults + + def _check_inputs(self, endog, exog): + """ + Handle endog that is pandas Categorical + + Checks if self.distrib is legal and provides Pandas ordered Categorical + support for endog. + + Parameters + ---------- + endog : array_like + Endogenous, dependent variable, 1-D. + exog : array_like + Exogenous, explanatory variables. + Currently not used. + + Returns + ------- + endog : array_like or pandas Series + If the original endog is a pandas ordered Categorical Series, + then the returned endog are the ``codes``, i.e., integer + representation of ordered categorical variable + labels : None or list + If original endog is pandas ordered Categorical Series, then the + categories are returned. Otherwise ``labels`` is None. + is_pandas : bool + This is True if original endog is a pandas ordered Categorical + Series and False otherwise. + """ + + if not isinstance(self.distr, stats.rv_continuous): + msg = f"{self.distr.name} is not a scipy.stats distribution." + warnings.warn(msg, RuntimeWarning, stacklevel=2) + + labels = None + is_pandas = False + if isinstance(endog, pd.Series): + if isinstance(endog.dtypes, CategoricalDtype): + if not endog.dtype.ordered: + warnings.warn( + "the endog has ordered == False, " + "risk of capturing a wrong order for the " + "categories. ordered == True preferred.", + SpecificationWarning, + stacklevel=2, + ) + + endog_name = endog.name + labels = endog.values.categories + endog = endog.cat.codes + if endog.min() == -1: # means there is a missing value + raise ValueError( + "missing values in categorical endog are not supported" + ) + endog.name = endog_name + is_pandas = True + + return endog, labels, is_pandas + + def _initialize_labels(self, labels, k_levels=None): + """ + Set up category labels, level count, and threshold names + + Parameters + ---------- + labels : sequence + The category labels of the ordered endogenous variable. + k_levels : int, optional + The number of levels/categories. If None, it is inferred from + the length of `labels`. + """ + self.labels = labels + if k_levels is None: + self.k_levels = len(labels) + else: + self.k_levels = k_levels + + if self.exog is not None: + self.nobs, self.k_vars = self.exog.shape + else: # no exog in model + self.nobs, self.k_vars = self.endog.shape[0], 0 + + threshold_names = [str(x) + "/" + str(y) for x, y in pairwise(labels)] + + # from GenericLikelihoodModel.fit + if self.exog is not None: + # avoid extending several times + if len(self.exog_names) > self.k_vars: + raise RuntimeError("something wrong with exog_names, too long") + self.exog_names.extend(threshold_names) + else: + self.data.xnames = threshold_names + + @classmethod + def from_formula(cls, formula, data, subset=None, drop_cols=None, *args, **kwargs): + + # we want an explicit Intercept in the model that we can remove + # Removing constant with "0 +" or "- 1" does not work for categ. exog + + endog_name = formula.split("~")[0].strip() + original_endog = data[endog_name] + advance_eval_env(kwargs) + model = super().from_formula( + formula, data, *args, drop_cols=["Intercept"], **kwargs + ) + + if model.endog.ndim == 2: + if not ( + isinstance(original_endog.dtype, CategoricalDtype) + and original_endog.dtype.ordered + ): + msg = ( + "Only ordered pandas Categorical are supported as " + "endog in formulas" + ) + raise ValueError(msg) + + labels = original_endog.values.categories + model._initialize_labels(labels) + model.endog = model.endog.argmax(1) + model.data.ynames = endog_name + + return model + + from_formula.__func__.__doc__ = Model.from_formula.__doc__ + + def cdf(self, x): + """ + Cdf evaluated at x + + Parameters + ---------- + x : array_like + Points at which cdf is evaluated. In the model `x` is the latent + variable plus threshold constants. + + Returns + ------- + ndarray + Value of the cumulative distribution function of the underlying + latent variable evaluated at x. + """ + return self.distr.cdf(x) + + def pdf(self, x): + """ + Pdf evaluated at x + + Parameters + ---------- + x : array_like + Points at which cdf is evaluated. In the model `x` is the latent + variable plus threshold constants. + + Returns + ------- + ndarray + Value of the probability density function of the underlying + latent variable evaluated at x. + """ + return self.distr.pdf(x) + + def prob(self, low, upp): + """ + Interval probability + + Probability that value is in interval (low, upp], computed as + + prob = cdf(upp) - cdf(low) + + Parameters + ---------- + low : array_like + Lower bound for interval + upp : array_like + Upper bound for interval + + Returns + ------- + float or ndarray + Probability that value falls in interval (low, upp] + """ + return np.maximum(self.cdf(upp) - self.cdf(low), 0) + + def transform_threshold_params(self, params): + """ + Transformation of the parameters in the optimization + + Parameters + ---------- + params : ndarray + Contains (exog_coef, transformed_thresholds) where exog_coef are + the coefficient for the explanatory variables in the linear term, + transformed threshold or cutoff points. The first, lowest threshold + is unchanged, all other thresholds are in terms of exponentiated + increments. + + Returns + ------- + thresh : ndarray + Thresh are the thresholds or cutoff constants for the intervals. + """ + th_params = params[-(self.k_levels - 1) :] + thresh = np.concatenate((th_params[:1], np.exp(th_params[1:]))).cumsum() + thresh = np.concatenate(([-np.inf], thresh, [np.inf])) + return thresh + + def transform_reverse_threshold_params(self, params): + """ + Obtain transformed thresholds from original thresholds or cutoffs + + Parameters + ---------- + params : ndarray + Threshold values, cutoff constants for choice intervals, which + need to be monotonically increasing. + + Returns + ------- + thresh_params : ndarray + Transformed threshold parameter. + The first, lowest threshold is unchanged, all other thresholds are + in terms of exponentiated increments. + Transformed parameters can be any real number without restrictions. + """ + thresh_params = np.concatenate((params[:1], np.log(np.diff(params[:-1])))) + return thresh_params + + def predict(self, params, exog=None, offset=None, which="prob"): + """ + Predicted probabilities for each level of the ordinal endog + + Parameters + ---------- + params : ndarray + Parameters for the Model, (exog_coef, transformed_thresholds). + exog : array_like, optional + Design / exogenous data. If exog is None, model exog is used. + offset : array_like, optional + Offset is added to the linear prediction with coefficient + equal to 1. If offset is not provided and exog + is None, uses the model's offset if present. If not, uses + 0 as the default value. + which : {"prob", "linpred", "cum", "cumprob"}, optional + Determines which statistic is predicted. + + - prob : predicted probabilities to be in each choice. 2-dim. + - linpred : 1-dim linear prediction of the latent variable + ``x b + offset`` + - cum or cumprob : predicted cumulative probability to be in + choice k or lower + + Returns + ------- + predicted values : ndarray + If which is "prob", then 2-dim predicted probabilities with + observations in rows and one column for each category or level of + the categorical dependent variable. + If which is "cumprob", then "prob" are cumulatively added to get the + cdf at k, i.e., probability of observing choice k or lower. + If which is "linpred", then the conditional prediction of the + latent variable is returned. In this case, the return is + one-dimensional. + """ + # note, exog and offset handling is in linpred + which = string_like( + which, "which", options=("prob", "linpred", "cum", "cumprob"), + lower=False, + ) + + thresh = self.transform_threshold_params(params) + xb = self._linpred(params, exog=exog, offset=offset) + if which == "linpred": + return xb + xb = xb[:, None] + low = thresh[:-1] - xb + upp = thresh[1:] - xb + if which == "prob": + prob = self.prob(low, upp) + return prob + else: # which in ("cum", "cumprob") + cumprob = self.cdf(upp) + return cumprob + + def _linpred(self, params, exog=None, offset=None): + """ + Linear prediction of latent variable `x b + offset` + + Parameters + ---------- + params : ndarray + Parameters for the model, (exog_coef, transformed_thresholds) + exog : array_like, optional + Design / exogenous data. If exog is None, model exog is used. + offset : array_like, optional + Offset is added to the linear prediction with coefficient + equal to 1. If offset is not provided and exog + is None, uses the model's offset if present. If not, uses + 0 as the default value. + + Returns + ------- + linear : ndarray + 1-dim linear prediction given by exog times linear params plus + offset. This is the prediction for the underlying latent variable. + If exog and offset are None, then the predicted values are zero. + """ + if exog is None: + exog = self.exog + if offset is None: + offset = self.offset + elif offset is None: + offset = 0 + + if offset is not None: + offset = np.asarray(offset) + + if exog is not None: + _exog = np.asarray(exog) + _params = np.asarray(params) + linpred = _exog.dot(_params[: -(self.k_levels - 1)]) + else: # means self.exog is also None + linpred = np.zeros(self.nobs) + if offset is not None: + linpred += offset + return linpred + + def _bounds(self, params): + """ + Integration bounds for the observation specific interval + + This defines the lower and upper bounds for the intervals of the + choices of all observations. + + The bounds for observation are given by + + a_{k_i-1} - linpred_i, a_k_i - linpred_i + + where + - k_i is the choice in observation i. + - a_{k_i-1} and a_k_i are thresholds (cutoffs) for choice k_i + - linpred_i is the linear prediction for observation i + + Parameters + ---------- + params : ndarray + Parameters for the model, (exog_coef, transformed_thresholds) + + Returns + ------- + low : ndarray + Lower bounds for choice intervals of each observation, + 1-dim with length nobs + upp : ndarray + Upper bounds for choice intervals of each observation, + 1-dim with length nobs. + """ + thresh = self.transform_threshold_params(params) + + thresh_i_low = thresh[self.endog] + thresh_i_upp = thresh[self.endog + 1] + xb = self._linpred(params) + low = thresh_i_low - xb + upp = thresh_i_upp - xb + return low, upp + + @Appender(GenericLikelihoodModel.loglike.__doc__) + def loglike(self, params): + + return self.loglikeobs(params).sum() + + def loglikeobs(self, params): + """ + Log-likelihood of OrderedModel for all observations + + Parameters + ---------- + params : array_like + The parameters of the model. + + Returns + ------- + loglike_obs : array_like + The log likelihood for each observation of the model evaluated + at ``params``. + """ + low, upp = self._bounds(params) + prob = self.prob(low, upp) + return np.log(prob + 1e-20) + + def score_obs_(self, params): + """ + Score, first derivative of loglike for each observation + + This currently only implements the derivative with respect to the + exog parameters, but not with respect to threshold parameters. + + Parameters + ---------- + params : ndarray + Parameters for the model, (exog_coef, transformed_thresholds) + + Returns + ------- + ndarray + The score for each observation with respect to the exog + parameters and the transformed threshold parameters, 2-dim + with shape (nobs, k_vars + k_levels - 1). + """ + low, upp = self._bounds(params) + + prob = self.prob(low, upp) + pdf_upp = self.pdf(upp) + pdf_low = self.pdf(low) + + # TODO the following doesn't work yet because of the incremental exp + # parameterization. The following was written based on Greene for the + # simple non-incremental parameterization. + # k = self.k_levels - 1 + # idx = self.endog + # score_factor = np.zeros((self.nobs, k + 1 + 2)) #+2 avoids idx bounds + # + # rows = np.arange(self.nobs) + # shift = 1 + # score_factor[rows, shift + idx-1] = -pdf_low + # score_factor[rows, shift + idx] = pdf_upp + # score_factor[:, 0] = pdf_upp - pdf_low + score_factor = (pdf_upp - pdf_low)[:, None] + score_factor /= prob[:, None] + + so = np.column_stack((-score_factor[:, :1] * self.exog, score_factor[:, 1:])) + return so + + @property + def start_params(self): + """ + Start parameters for the optimization corresponding to null model + + The threshold are computed from the observed frequencies and + transformed to the exponential increments parameterization. + The parameters for explanatory variables are set to zero. + + Returns + ------- + ndarray + Starting values for the parameters, (exog_coef, threshold). + """ + # start params based on model without exog + freq = np.bincount(self.endog) / len(self.endog) + start_ppf = self.distr.ppf(np.clip(freq.cumsum(), 0, 1)) + start_threshold = self.transform_reverse_threshold_params(start_ppf) + start_params = np.concatenate((np.zeros(self.k_vars), start_threshold)) + return start_params + + @Appender(LikelihoodModel.fit.__doc__) + def fit( + self, + start_params=None, + method="nm", + maxiter=500, + full_output=1, + disp=1, + callback=None, + retall=0, + **kwargs, + ): + + fit_method = super().fit + mlefit = fit_method( + start_params=start_params, + method=method, + maxiter=maxiter, + full_output=full_output, + disp=disp, + callback=callback, + **kwargs, + ) + # use the proper result class + ordmlefit = OrderedResults(self, mlefit) + + # TODO: temporary, needs better fix, modelwc adds 1 by default + ordmlefit.hasconst = 0 + + result = OrderedResultsWrapper(ordmlefit) + + return result + + +class OrderedResults(GenericLikelihoodModelResults): + """ + Results class for OrderedModel + + This class inherits from GenericLikelihoodModelResults and not all + inherited methods might be appropriate in this case. + """ + + def pred_table(self): + """ + Prediction table + + Returns + ------- + DataFrame + Table with observed and predicted counts, cross-tabulated by + category, with margins. + """ + # todo: add category labels + categories = np.arange(self.model.k_levels) + observed = pd.Categorical(self.model.endog, categories=categories, ordered=True) + predicted = pd.Categorical( + self.predict().argmax(1), categories=categories, ordered=True + ) + table = pd.crosstab( + predicted, observed.astype(int), margins=True, dropna=False + ).T.fillna(0) + return table + + @cache_readonly + def llnull(self): + """ + Value of the loglikelihood of model without explanatory variables + """ + params_null = self.model.start_params + return self.model.loglike(params_null) + + # next 3 are copied from discrete + @cache_readonly + def prsquared(self): + """ + McFadden's pseudo-R-squared. `1 - (llf / llnull)` + """ + return 1 - self.llf / self.llnull + + @cache_readonly + def llr(self): + """ + Likelihood ratio chi-squared statistic; `-2*(llnull - llf)` + """ + return -2 * (self.llnull - self.llf) + + @cache_readonly + def llr_pvalue(self): + """ + The chi-squared probability of getting a log-likelihood ratio + statistic greater than llr. llr has a chi-squared distribution + with degrees of freedom `df_model`. + """ + # number of restrictions is number of exog + return stats.distributions.chi2.sf(self.llr, self.model.k_vars) + + @cache_readonly + def resid_prob(self): + """ + Probability residual + + Probability-scale residual is ``P(Y < y) − P(Y > y)`` where `Y` is the + observed choice and ``y`` is a random variable corresponding to the + predicted distribution. + + Calculations based on work by: + + Shepherd BE, Li C, Liu Q (2016) Probability-scale residuals for + continuous, discrete, and censored data. + The Canadian Journal of Statistics. 44:463-476. + + Li C and Shepherd BE (2012) A new residual for ordinal outcomes. + Biometrika. 99: 473-480 + + """ + from statsmodels.stats.diagnostic_gen import prob_larger_ordinal_choice + + endog = self.model.endog + fitted = self.predict() + r = prob_larger_ordinal_choice(fitted)[1] + resid_prob = r[np.arange(endog.shape[0]), endog] + return resid_prob + + +class OrderedResultsWrapper(lm.RegressionResultsWrapper): + pass + + +wrap.populate_wrapper(OrderedResultsWrapper, OrderedResults) diff --git a/shared/package-files/01/01a70786ce09302c93ff193c95242a27edaa4fc9304d8a20b2a06c8546367d89/blob b/shared/package-files/01/01a70786ce09302c93ff193c95242a27edaa4fc9304d8a20b2a06c8546367d89/blob new file mode 100644 index 0000000000000000000000000000000000000000..7c6a519b821e2ee2847c3a816d37f57ecedf8e57 --- /dev/null +++ b/shared/package-files/01/01a70786ce09302c93ff193c95242a27edaa4fc9304d8a20b2a06c8546367d89/blob @@ -0,0 +1,22 @@ +#pragma once + +// @generated by torchgen/gen.py from NativeFunction.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + +namespace at { +namespace native { +TORCH_API at::Tensor zeros_like(const at::Tensor & self, c10::optional dtype={}, c10::optional layout={}, c10::optional device={}, c10::optional pin_memory={}, c10::optional memory_format=c10::nullopt); +TORCH_API at::Tensor & zeros_like_out(const at::Tensor & self, c10::optional memory_format, at::Tensor & out); +} // namespace native +} // namespace at diff --git a/shared/package-files/01/01a840341b0bcbc77a14a99582d786880c3597fe3059622d6584b23959e3fe79/blob b/shared/package-files/01/01a840341b0bcbc77a14a99582d786880c3597fe3059622d6584b23959e3fe79/blob new file mode 100644 index 0000000000000000000000000000000000000000..addcbe6951f8df093461c47848f8027dfdd406f2 --- /dev/null +++ b/shared/package-files/01/01a840341b0bcbc77a14a99582d786880c3597fe3059622d6584b23959e3fe79/blob @@ -0,0 +1,357 @@ +import numpy as np +from scipy.linalg import lstsq +from scipy._lib._util import float_factorial +from scipy.ndimage import convolve1d # type: ignore[attr-defined] +from ._arraytools import axis_slice + + +def savgol_coeffs(window_length, polyorder, deriv=0, delta=1.0, pos=None, + use="conv"): + """Compute the coefficients for a 1-D Savitzky-Golay FIR filter. + + Parameters + ---------- + window_length : int + The length of the filter window (i.e., the number of coefficients). + polyorder : int + The order of the polynomial used to fit the samples. + `polyorder` must be less than `window_length`. + deriv : int, optional + The order of the derivative to compute. This must be a + nonnegative integer. The default is 0, which means to filter + the data without differentiating. + delta : float, optional + The spacing of the samples to which the filter will be applied. + This is only used if deriv > 0. + pos : int or None, optional + If pos is not None, it specifies evaluation position within the + window. The default is the middle of the window. + use : str, optional + Either 'conv' or 'dot'. This argument chooses the order of the + coefficients. The default is 'conv', which means that the + coefficients are ordered to be used in a convolution. With + use='dot', the order is reversed, so the filter is applied by + dotting the coefficients with the data set. + + Returns + ------- + coeffs : 1-D ndarray + The filter coefficients. + + See Also + -------- + savgol_filter + + Notes + ----- + .. versionadded:: 0.14.0 + + References + ---------- + A. Savitzky, M. J. E. Golay, Smoothing and Differentiation of Data by + Simplified Least Squares Procedures. Analytical Chemistry, 1964, 36 (8), + pp 1627-1639. + Jianwen Luo, Kui Ying, and Jing Bai. 2005. Savitzky-Golay smoothing and + differentiation filter for even number data. Signal Process. + 85, 7 (July 2005), 1429-1434. + + Examples + -------- + >>> import numpy as np + >>> from scipy.signal import savgol_coeffs + >>> savgol_coeffs(5, 2) + array([-0.08571429, 0.34285714, 0.48571429, 0.34285714, -0.08571429]) + >>> savgol_coeffs(5, 2, deriv=1) + array([ 2.00000000e-01, 1.00000000e-01, 2.07548111e-16, -1.00000000e-01, + -2.00000000e-01]) + + Note that use='dot' simply reverses the coefficients. + + >>> savgol_coeffs(5, 2, pos=3) + array([ 0.25714286, 0.37142857, 0.34285714, 0.17142857, -0.14285714]) + >>> savgol_coeffs(5, 2, pos=3, use='dot') + array([-0.14285714, 0.17142857, 0.34285714, 0.37142857, 0.25714286]) + >>> savgol_coeffs(4, 2, pos=3, deriv=1, use='dot') + array([0.45, -0.85, -0.65, 1.05]) + + `x` contains data from the parabola x = t**2, sampled at + t = -1, 0, 1, 2, 3. `c` holds the coefficients that will compute the + derivative at the last position. When dotted with `x` the result should + be 6. + + >>> x = np.array([1, 0, 1, 4, 9]) + >>> c = savgol_coeffs(5, 2, pos=4, deriv=1, use='dot') + >>> c.dot(x) + 6.0 + """ + + # An alternative method for finding the coefficients when deriv=0 is + # t = np.arange(window_length) + # unit = (t == pos).astype(int) + # coeffs = np.polyval(np.polyfit(t, unit, polyorder), t) + # The method implemented here is faster. + + # To recreate the table of sample coefficients shown in the chapter on + # the Savitzy-Golay filter in the Numerical Recipes book, use + # window_length = nL + nR + 1 + # pos = nL + 1 + # c = savgol_coeffs(window_length, M, pos=pos, use='dot') + + if polyorder >= window_length: + raise ValueError("polyorder must be less than window_length.") + + halflen, rem = divmod(window_length, 2) + + if pos is None: + if rem == 0: + pos = halflen - 0.5 + else: + pos = halflen + + if not (0 <= pos < window_length): + raise ValueError("pos must be nonnegative and less than " + "window_length.") + + if use not in ['conv', 'dot']: + raise ValueError("`use` must be 'conv' or 'dot'") + + if deriv > polyorder: + coeffs = np.zeros(window_length) + return coeffs + + # Form the design matrix A. The columns of A are powers of the integers + # from -pos to window_length - pos - 1. The powers (i.e., rows) range + # from 0 to polyorder. (That is, A is a vandermonde matrix, but not + # necessarily square.) + x = np.arange(-pos, window_length - pos, dtype=float) + + if use == "conv": + # Reverse so that result can be used in a convolution. + x = x[::-1] + + order = np.arange(polyorder + 1).reshape(-1, 1) + A = x ** order + + # y determines which order derivative is returned. + y = np.zeros(polyorder + 1) + # The coefficient assigned to y[deriv] scales the result to take into + # account the order of the derivative and the sample spacing. + y[deriv] = float_factorial(deriv) / (delta ** deriv) + + # Find the least-squares solution of A*c = y + coeffs, _, _, _ = lstsq(A, y) + + return coeffs + + +def _polyder(p, m): + """Differentiate polynomials represented with coefficients. + + p must be a 1-D or 2-D array. In the 2-D case, each column gives + the coefficients of a polynomial; the first row holds the coefficients + associated with the highest power. m must be a nonnegative integer. + (numpy.polyder doesn't handle the 2-D case.) + """ + + if m == 0: + result = p + else: + n = len(p) + if n <= m: + result = np.zeros_like(p[:1, ...]) + else: + dp = p[:-m].copy() + for k in range(m): + rng = np.arange(n - k - 1, m - k - 1, -1) + dp *= rng.reshape((n - m,) + (1,) * (p.ndim - 1)) + result = dp + return result + + +def _fit_edge(x, window_start, window_stop, interp_start, interp_stop, + axis, polyorder, deriv, delta, y): + """ + Given an N-d array `x` and the specification of a slice of `x` from + `window_start` to `window_stop` along `axis`, create an interpolating + polynomial of each 1-D slice, and evaluate that polynomial in the slice + from `interp_start` to `interp_stop`. Put the result into the + corresponding slice of `y`. + """ + + # Get the edge into a (window_length, -1) array. + x_edge = axis_slice(x, start=window_start, stop=window_stop, axis=axis) + if axis == 0 or axis == -x.ndim: + xx_edge = x_edge + swapped = False + else: + xx_edge = x_edge.swapaxes(axis, 0) + swapped = True + xx_edge = xx_edge.reshape(xx_edge.shape[0], -1) + + # Fit the edges. poly_coeffs has shape (polyorder + 1, -1), + # where '-1' is the same as in xx_edge. + poly_coeffs = np.polyfit(np.arange(0, window_stop - window_start), + xx_edge, polyorder) + + if deriv > 0: + poly_coeffs = _polyder(poly_coeffs, deriv) + + # Compute the interpolated values for the edge. + i = np.arange(interp_start - window_start, interp_stop - window_start) + values = np.polyval(poly_coeffs, i.reshape(-1, 1)) / (delta ** deriv) + + # Now put the values into the appropriate slice of y. + # First reshape values to match y. + shp = list(y.shape) + shp[0], shp[axis] = shp[axis], shp[0] + values = values.reshape(interp_stop - interp_start, *shp[1:]) + if swapped: + values = values.swapaxes(0, axis) + # Get a view of the data to be replaced by values. + y_edge = axis_slice(y, start=interp_start, stop=interp_stop, axis=axis) + y_edge[...] = values + + +def _fit_edges_polyfit(x, window_length, polyorder, deriv, delta, axis, y): + """ + Use polynomial interpolation of x at the low and high ends of the axis + to fill in the halflen values in y. + + This function just calls _fit_edge twice, once for each end of the axis. + """ + halflen = window_length // 2 + _fit_edge(x, 0, window_length, 0, halflen, axis, + polyorder, deriv, delta, y) + n = x.shape[axis] + _fit_edge(x, n - window_length, n, n - halflen, n, axis, + polyorder, deriv, delta, y) + + +def savgol_filter(x, window_length, polyorder, deriv=0, delta=1.0, + axis=-1, mode='interp', cval=0.0): + """ Apply a Savitzky-Golay filter to an array. + + This is a 1-D filter. If `x` has dimension greater than 1, `axis` + determines the axis along which the filter is applied. + + Parameters + ---------- + x : array_like + The data to be filtered. If `x` is not a single or double precision + floating point array, it will be converted to type ``numpy.float64`` + before filtering. + window_length : int + The length of the filter window (i.e., the number of coefficients). + If `mode` is 'interp', `window_length` must be less than or equal + to the size of `x`. + polyorder : int + The order of the polynomial used to fit the samples. + `polyorder` must be less than `window_length`. + deriv : int, optional + The order of the derivative to compute. This must be a + nonnegative integer. The default is 0, which means to filter + the data without differentiating. + delta : float, optional + The spacing of the samples to which the filter will be applied. + This is only used if deriv > 0. Default is 1.0. + axis : int, optional + The axis of the array `x` along which the filter is to be applied. + Default is -1. + mode : str, optional + Must be 'mirror', 'constant', 'nearest', 'wrap' or 'interp'. This + determines the type of extension to use for the padded signal to + which the filter is applied. When `mode` is 'constant', the padding + value is given by `cval`. See the Notes for more details on 'mirror', + 'constant', 'wrap', and 'nearest'. + When the 'interp' mode is selected (the default), no extension + is used. Instead, a degree `polyorder` polynomial is fit to the + last `window_length` values of the edges, and this polynomial is + used to evaluate the last `window_length // 2` output values. + cval : scalar, optional + Value to fill past the edges of the input if `mode` is 'constant'. + Default is 0.0. + + Returns + ------- + y : ndarray, same shape as `x` + The filtered data. + + See Also + -------- + savgol_coeffs + + Notes + ----- + Details on the `mode` options: + + 'mirror': + Repeats the values at the edges in reverse order. The value + closest to the edge is not included. + 'nearest': + The extension contains the nearest input value. + 'constant': + The extension contains the value given by the `cval` argument. + 'wrap': + The extension contains the values from the other end of the array. + + For example, if the input is [1, 2, 3, 4, 5, 6, 7, 8], and + `window_length` is 7, the following shows the extended data for + the various `mode` options (assuming `cval` is 0):: + + mode | Ext | Input | Ext + -----------+---------+------------------------+--------- + 'mirror' | 4 3 2 | 1 2 3 4 5 6 7 8 | 7 6 5 + 'nearest' | 1 1 1 | 1 2 3 4 5 6 7 8 | 8 8 8 + 'constant' | 0 0 0 | 1 2 3 4 5 6 7 8 | 0 0 0 + 'wrap' | 6 7 8 | 1 2 3 4 5 6 7 8 | 1 2 3 + + .. versionadded:: 0.14.0 + + Examples + -------- + >>> import numpy as np + >>> from scipy.signal import savgol_filter + >>> np.set_printoptions(precision=2) # For compact display. + >>> x = np.array([2, 2, 5, 2, 1, 0, 1, 4, 9]) + + Filter with a window length of 5 and a degree 2 polynomial. Use + the defaults for all other parameters. + + >>> savgol_filter(x, 5, 2) + array([1.66, 3.17, 3.54, 2.86, 0.66, 0.17, 1. , 4. , 9. ]) + + Note that the last five values in x are samples of a parabola, so + when mode='interp' (the default) is used with polyorder=2, the last + three values are unchanged. Compare that to, for example, + `mode='nearest'`: + + >>> savgol_filter(x, 5, 2, mode='nearest') + array([1.74, 3.03, 3.54, 2.86, 0.66, 0.17, 1. , 4.6 , 7.97]) + + """ + if mode not in ["mirror", "constant", "nearest", "interp", "wrap"]: + raise ValueError("mode must be 'mirror', 'constant', 'nearest' " + "'wrap' or 'interp'.") + + x = np.asarray(x) + # Ensure that x is either single or double precision floating point. + if x.dtype != np.float64 and x.dtype != np.float32: + x = x.astype(np.float64) + + coeffs = savgol_coeffs(window_length, polyorder, deriv=deriv, delta=delta) + + if mode == "interp": + if window_length > x.shape[axis]: + raise ValueError("If mode is 'interp', window_length must be less " + "than or equal to the size of x.") + + # Do not pad. Instead, for the elements within `window_length // 2` + # of the ends of the sequence, use the polynomial that is fitted to + # the last `window_length` elements. + y = convolve1d(x, coeffs, axis=axis, mode="constant") + _fit_edges_polyfit(x, window_length, polyorder, deriv, delta, axis, y) + else: + # Any mode other than 'interp' is passed on to ndimage.convolve1d. + y = convolve1d(x, coeffs, axis=axis, mode=mode, cval=cval) + + return y diff --git a/shared/package-files/01/01a8d6ee0c70f9207ba52495a0bd77fc1378fac1f39eb1c658349ec546050e2d/blob b/shared/package-files/01/01a8d6ee0c70f9207ba52495a0bd77fc1378fac1f39eb1c658349ec546050e2d/blob new file mode 100644 index 0000000000000000000000000000000000000000..ad3401fb87cfd3a3001fbb8c4bcc074b821cb217 --- /dev/null +++ b/shared/package-files/01/01a8d6ee0c70f9207ba52495a0bd77fc1378fac1f39eb1c658349ec546050e2d/blob @@ -0,0 +1,39 @@ +#pragma once + +// @generated by torchgen/gen.py from Function.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + + +#include + +namespace at { + + +// aten::multilabel_margin_loss_forward.output(Tensor self, Tensor target, int reduction, *, Tensor(a!) output, Tensor(b!) is_target) -> (Tensor(a!), Tensor(b!)) +inline ::std::tuple multilabel_margin_loss_forward_out(at::Tensor & output, at::Tensor & is_target, const at::Tensor & self, const at::Tensor & target, int64_t reduction) { + return at::_ops::multilabel_margin_loss_forward_output::call(self, target, reduction, output, is_target); +} +// aten::multilabel_margin_loss_forward.output(Tensor self, Tensor target, int reduction, *, Tensor(a!) output, Tensor(b!) is_target) -> (Tensor(a!), Tensor(b!)) +inline ::std::tuple multilabel_margin_loss_forward_outf(const at::Tensor & self, const at::Tensor & target, int64_t reduction, at::Tensor & output, at::Tensor & is_target) { + return at::_ops::multilabel_margin_loss_forward_output::call(self, target, reduction, output, is_target); +} + +// aten::multilabel_margin_loss_forward(Tensor self, Tensor target, int reduction) -> (Tensor output, Tensor is_target) +inline ::std::tuple multilabel_margin_loss_forward(const at::Tensor & self, const at::Tensor & target, int64_t reduction) { + return at::_ops::multilabel_margin_loss_forward::call(self, target, reduction); +} + +} diff --git a/shared/package-files/01/01a9d4ac8908dfb8521494efd746a4a599a11f12aa1a7ff41ec2b787eb3a495e/blob b/shared/package-files/01/01a9d4ac8908dfb8521494efd746a4a599a11f12aa1a7ff41ec2b787eb3a495e/blob new file mode 100644 index 0000000000000000000000000000000000000000..434fb83fb492f190c4ba85b19f44c19f69ad1433 --- /dev/null +++ b/shared/package-files/01/01a9d4ac8908dfb8521494efd746a4a599a11f12aa1a7ff41ec2b787eb3a495e/blob @@ -0,0 +1,28 @@ +#pragma once +// @generated by torchgen/gen.py from DispatchKeyFunction.h + +// NB: The implementing C++ file is RegisterDispatchKey.cpp + +// The only #includes we need are for custom classes that have defaults in the C++ API +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { + +namespace compositeexplicitautograd { + +TORCH_API at::Tensor special_hermite_polynomial_h(const at::Scalar & x, const at::Tensor & n); +TORCH_API at::Tensor & special_hermite_polynomial_h_out(at::Tensor & out, const at::Scalar & x, const at::Tensor & n); +TORCH_API at::Tensor & special_hermite_polynomial_h_outf(const at::Scalar & x, const at::Tensor & n, at::Tensor & out); +TORCH_API at::Tensor special_hermite_polynomial_h(const at::Tensor & x, const at::Scalar & n); +TORCH_API at::Tensor & special_hermite_polynomial_h_out(at::Tensor & out, const at::Tensor & x, const at::Scalar & n); +TORCH_API at::Tensor & special_hermite_polynomial_h_outf(const at::Tensor & x, const at::Scalar & n, at::Tensor & out); + +} // namespace compositeexplicitautograd +} // namespace at diff --git a/shared/package-files/01/01aa0e43f3ee7e0ae09ce992ec045847275b754d63b1bebe0cabb6a17e762ee2/blob b/shared/package-files/01/01aa0e43f3ee7e0ae09ce992ec045847275b754d63b1bebe0cabb6a17e762ee2/blob new file mode 100644 index 0000000000000000000000000000000000000000..06e19eeca67663318709772ff23f76675545e19b --- /dev/null +++ b/shared/package-files/01/01aa0e43f3ee7e0ae09ce992ec045847275b754d63b1bebe0cabb6a17e762ee2/blob @@ -0,0 +1,622 @@ +import numpy as np +import pytest + +from pandas.core.dtypes.common import ensure_platform_int + +import pandas as pd +from pandas import ( + Index, + RangeIndex, +) +import pandas._testing as tm + + +class TestRangeIndex: + @pytest.fixture + def simple_index(self): + return RangeIndex(start=0, stop=20, step=2) + + def test_constructor_unwraps_index(self): + result = RangeIndex(1, 3) + expected = np.array([1, 2], dtype=np.int64) + 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_too_many_names(self, simple_index): + index = simple_index + with pytest.raises(ValueError, match="^Length"): + index.names = ["roger", "harold"] + + @pytest.mark.parametrize( + "index, start, stop, step", + [ + (RangeIndex(5), 0, 5, 1), + (RangeIndex(0, 5), 0, 5, 1), + (RangeIndex(5, step=2), 0, 5, 2), + (RangeIndex(1, 5, 2), 1, 5, 2), + ], + ) + def test_start_stop_step_attrs(self, index, start, stop, step): + # GH 25710 + assert index.start == start + assert index.stop == stop + assert index.step == step + + def test_copy(self): + i = RangeIndex(5, name="Foo") + i_copy = i.copy() + assert i_copy is not i + assert i_copy.identical(i) + assert i_copy._range == range(0, 5, 1) + assert i_copy.name == "Foo" + + def test_repr(self): + i = RangeIndex(5, name="Foo") + result = repr(i) + expected = "RangeIndex(start=0, stop=5, step=1, name='Foo')" + assert result == expected + + result = eval(result) + tm.assert_index_equal(result, i, exact=True) + + i = RangeIndex(5, 0, -1) + result = repr(i) + expected = "RangeIndex(start=5, stop=0, step=-1)" + assert result == expected + + result = eval(result) + tm.assert_index_equal(result, i, exact=True) + + def test_insert(self): + idx = RangeIndex(5, name="Foo") + result = idx[1:4] + + # test 0th element + tm.assert_index_equal(idx[0:4], result.insert(0, idx[0]), exact="equiv") + + # GH 18295 (test missing) + expected = Index([0, np.nan, 1, 2, 3, 4], dtype=np.float64) + for na in [np.nan, None, pd.NA]: + result = RangeIndex(5).insert(1, na) + tm.assert_index_equal(result, expected) + + result = RangeIndex(5).insert(1, pd.NaT) + expected = Index([0, pd.NaT, 1, 2, 3, 4], dtype=object) + tm.assert_index_equal(result, expected) + + def test_insert_edges_preserves_rangeindex(self): + idx = Index(range(4, 9, 2)) + + result = idx.insert(0, 2) + expected = Index(range(2, 9, 2)) + tm.assert_index_equal(result, expected, exact=True) + + result = idx.insert(3, 10) + expected = Index(range(4, 11, 2)) + tm.assert_index_equal(result, expected, exact=True) + + def test_insert_middle_preserves_rangeindex(self): + # insert in the middle + idx = Index(range(0, 3, 2)) + result = idx.insert(1, 1) + expected = Index(range(3)) + tm.assert_index_equal(result, expected, exact=True) + + idx = idx * 2 + result = idx.insert(1, 2) + expected = expected * 2 + tm.assert_index_equal(result, expected, exact=True) + + def test_delete(self): + idx = RangeIndex(5, name="Foo") + expected = idx[1:] + result = idx.delete(0) + tm.assert_index_equal(result, expected, exact=True) + assert result.name == expected.name + + expected = idx[:-1] + result = idx.delete(-1) + tm.assert_index_equal(result, expected, exact=True) + assert result.name == expected.name + + msg = "index 5 is out of bounds for axis 0 with size 5" + with pytest.raises((IndexError, ValueError), match=msg): + # either depending on numpy version + result = idx.delete(len(idx)) + + def test_delete_preserves_rangeindex(self): + idx = Index(range(2), name="foo") + + result = idx.delete([1]) + expected = Index(range(1), name="foo") + tm.assert_index_equal(result, expected, exact=True) + + result = idx.delete(1) + tm.assert_index_equal(result, expected, exact=True) + + def test_delete_preserves_rangeindex_middle(self): + idx = Index(range(3), name="foo") + result = idx.delete(1) + expected = idx[::2] + tm.assert_index_equal(result, expected, exact=True) + + result = idx.delete(-2) + tm.assert_index_equal(result, expected, exact=True) + + def test_delete_preserves_rangeindex_list_at_end(self): + idx = RangeIndex(0, 6, 1) + + loc = [2, 3, 4, 5] + result = idx.delete(loc) + expected = idx[:2] + tm.assert_index_equal(result, expected, exact=True) + + result = idx.delete(loc[::-1]) + tm.assert_index_equal(result, expected, exact=True) + + def test_delete_preserves_rangeindex_list_middle(self): + idx = RangeIndex(0, 6, 1) + + loc = [1, 2, 3, 4] + result = idx.delete(loc) + expected = RangeIndex(0, 6, 5) + tm.assert_index_equal(result, expected, exact=True) + + result = idx.delete(loc[::-1]) + tm.assert_index_equal(result, expected, exact=True) + + def test_delete_all_preserves_rangeindex(self): + idx = RangeIndex(0, 6, 1) + + loc = [0, 1, 2, 3, 4, 5] + result = idx.delete(loc) + expected = idx[:0] + tm.assert_index_equal(result, expected, exact=True) + + result = idx.delete(loc[::-1]) + tm.assert_index_equal(result, expected, exact=True) + + def test_delete_not_preserving_rangeindex(self): + idx = RangeIndex(0, 6, 1) + + loc = [0, 3, 5] + result = idx.delete(loc) + expected = Index([1, 2, 4]) + tm.assert_index_equal(result, expected, exact=True) + + result = idx.delete(loc[::-1]) + tm.assert_index_equal(result, expected, exact=True) + + def test_view(self): + i = RangeIndex(0, name="Foo") + i_view = i.view() + assert i_view.name == "Foo" + + i_view = i.view("i8") + tm.assert_numpy_array_equal(i.values, i_view) + + msg = "Passing a type in RangeIndex.view is deprecated" + with tm.assert_produces_warning(FutureWarning, match=msg): + i_view = i.view(RangeIndex) + tm.assert_index_equal(i, i_view) + + def test_dtype(self, simple_index): + index = simple_index + assert index.dtype == np.int64 + + def test_cache(self): + # GH 26565, GH26617, GH35432, GH53387 + # This test checks whether _cache has been set. + # Calling RangeIndex._cache["_data"] creates an int64 array of the same length + # as the RangeIndex and stores it in _cache. + idx = RangeIndex(0, 100, 10) + + assert idx._cache == {} + + repr(idx) + assert idx._cache == {} + + str(idx) + assert idx._cache == {} + + idx.get_loc(20) + assert idx._cache == {} + + 90 in idx # True + assert idx._cache == {} + + 91 in idx # False + assert idx._cache == {} + + idx.all() + assert idx._cache == {} + + idx.any() + assert idx._cache == {} + + for _ in idx: + pass + assert idx._cache == {} + + msg = "RangeIndex.format is deprecated" + with tm.assert_produces_warning(FutureWarning, match=msg): + idx.format() + assert idx._cache == {} + + df = pd.DataFrame({"a": range(10)}, index=idx) + + # df.__repr__ should not populate index cache + str(df) + assert idx._cache == {} + + df.loc[50] + assert idx._cache == {} + + with pytest.raises(KeyError, match="51"): + df.loc[51] + assert idx._cache == {} + + df.loc[10:50] + assert idx._cache == {} + + df.iloc[5:10] + assert idx._cache == {} + + # after calling take, _cache may contain other keys, but not "_data" + idx.take([3, 0, 1]) + assert "_data" not in idx._cache + + df.loc[[50]] + assert "_data" not in idx._cache + + df.iloc[[5, 6, 7, 8, 9]] + assert "_data" not in idx._cache + + # idx._cache should contain a _data entry after call to idx._data + idx._data + assert isinstance(idx._data, np.ndarray) + assert idx._data is idx._data # check cached value is reused + assert "_data" in idx._cache + expected = np.arange(0, 100, 10, dtype="int64") + tm.assert_numpy_array_equal(idx._cache["_data"], expected) + + def test_is_monotonic(self): + index = RangeIndex(0, 20, 2) + assert index.is_monotonic_increasing is True + assert index.is_monotonic_increasing is True + assert index.is_monotonic_decreasing is False + assert index._is_strictly_monotonic_increasing is True + assert index._is_strictly_monotonic_decreasing is False + + index = RangeIndex(4, 0, -1) + assert index.is_monotonic_increasing is False + assert index._is_strictly_monotonic_increasing is False + assert index.is_monotonic_decreasing is True + assert index._is_strictly_monotonic_decreasing is True + + index = RangeIndex(1, 2) + assert index.is_monotonic_increasing is True + assert index.is_monotonic_increasing is True + assert index.is_monotonic_decreasing is True + assert index._is_strictly_monotonic_increasing is True + assert index._is_strictly_monotonic_decreasing is True + + index = RangeIndex(2, 1) + assert index.is_monotonic_increasing is True + assert index.is_monotonic_increasing is True + assert index.is_monotonic_decreasing is True + assert index._is_strictly_monotonic_increasing is True + assert index._is_strictly_monotonic_decreasing is True + + index = RangeIndex(1, 1) + assert index.is_monotonic_increasing is True + assert index.is_monotonic_increasing is True + assert index.is_monotonic_decreasing is True + assert index._is_strictly_monotonic_increasing is True + assert index._is_strictly_monotonic_decreasing is True + + @pytest.mark.parametrize( + "left,right", + [ + (RangeIndex(0, 9, 2), RangeIndex(0, 10, 2)), + (RangeIndex(0), RangeIndex(1, -1, 3)), + (RangeIndex(1, 2, 3), RangeIndex(1, 3, 4)), + (RangeIndex(0, -9, -2), RangeIndex(0, -10, -2)), + ], + ) + def test_equals_range(self, left, right): + assert left.equals(right) + assert right.equals(left) + + def test_logical_compat(self, simple_index): + idx = simple_index + assert idx.all() == idx.values.all() + assert idx.any() == idx.values.any() + + def test_identical(self, simple_index): + index = simple_index + i = Index(index.copy()) + assert i.identical(index) + + # we don't allow object dtype for RangeIndex + if isinstance(index, RangeIndex): + return + + same_values_different_type = Index(i, dtype=object) + assert not i.identical(same_values_different_type) + + i = index.copy(dtype=object) + i = i.rename("foo") + same_values = Index(i, dtype=object) + assert same_values.identical(index.copy(dtype=object)) + + assert not i.identical(index) + assert Index(same_values, name="foo", dtype=object).identical(i) + + assert not index.copy(dtype=object).identical(index.copy(dtype="int64")) + + def test_nbytes(self): + # memory savings vs int index + idx = RangeIndex(0, 1000) + assert idx.nbytes < Index(idx._values).nbytes / 10 + + # constant memory usage + i2 = RangeIndex(0, 10) + assert idx.nbytes == i2.nbytes + + @pytest.mark.parametrize( + "start,stop,step", + [ + # can't + ("foo", "bar", "baz"), + # shouldn't + ("0", "1", "2"), + ], + ) + def test_cant_or_shouldnt_cast(self, start, stop, step): + msg = f"Wrong type {type(start)} for value {start}" + with pytest.raises(TypeError, match=msg): + RangeIndex(start, stop, step) + + def test_view_index(self, simple_index): + index = simple_index + msg = "Passing a type in RangeIndex.view is deprecated" + with tm.assert_produces_warning(FutureWarning, match=msg): + index.view(Index) + + def test_prevent_casting(self, simple_index): + index = simple_index + result = index.astype("O") + assert result.dtype == np.object_ + + def test_repr_roundtrip(self, simple_index): + index = simple_index + tm.assert_index_equal(eval(repr(index)), index) + + def test_slice_keep_name(self): + idx = RangeIndex(1, 2, name="asdf") + assert idx.name == idx[1:].name + + @pytest.mark.parametrize( + "index", + [ + RangeIndex(start=0, stop=20, step=2, name="foo"), + RangeIndex(start=18, stop=-1, step=-2, name="bar"), + ], + ids=["index_inc", "index_dec"], + ) + def test_has_duplicates(self, index): + assert index.is_unique + assert not index.has_duplicates + + def test_extended_gcd(self, simple_index): + index = simple_index + result = index._extended_gcd(6, 10) + assert result[0] == result[1] * 6 + result[2] * 10 + assert 2 == result[0] + + result = index._extended_gcd(10, 6) + assert 2 == result[1] * 10 + result[2] * 6 + assert 2 == result[0] + + def test_min_fitting_element(self): + result = RangeIndex(0, 20, 2)._min_fitting_element(1) + assert 2 == result + + result = RangeIndex(1, 6)._min_fitting_element(1) + assert 1 == result + + result = RangeIndex(18, -2, -2)._min_fitting_element(1) + assert 2 == result + + result = RangeIndex(5, 0, -1)._min_fitting_element(1) + assert 1 == result + + big_num = 500000000000000000000000 + + result = RangeIndex(5, big_num * 2, 1)._min_fitting_element(big_num) + assert big_num == result + + def test_slice_specialised(self, simple_index): + index = simple_index + index.name = "foo" + + # scalar indexing + res = index[1] + expected = 2 + assert res == expected + + res = index[-1] + expected = 18 + assert res == expected + + # slicing + # slice value completion + index_slice = index[:] + expected = index + tm.assert_index_equal(index_slice, expected) + + # positive slice values + index_slice = index[7:10:2] + expected = Index([14, 18], name="foo") + tm.assert_index_equal(index_slice, expected, exact="equiv") + + # negative slice values + index_slice = index[-1:-5:-2] + expected = Index([18, 14], name="foo") + tm.assert_index_equal(index_slice, expected, exact="equiv") + + # stop overshoot + index_slice = index[2:100:4] + expected = Index([4, 12], name="foo") + tm.assert_index_equal(index_slice, expected, exact="equiv") + + # reverse + index_slice = index[::-1] + expected = Index(index.values[::-1], name="foo") + tm.assert_index_equal(index_slice, expected, exact="equiv") + + index_slice = index[-8::-1] + expected = Index([4, 2, 0], name="foo") + tm.assert_index_equal(index_slice, expected, exact="equiv") + + index_slice = index[-40::-1] + expected = Index(np.array([], dtype=np.int64), name="foo") + tm.assert_index_equal(index_slice, expected, exact="equiv") + + index_slice = index[40::-1] + expected = Index(index.values[40::-1], name="foo") + tm.assert_index_equal(index_slice, expected, exact="equiv") + + index_slice = index[10::-1] + expected = Index(index.values[::-1], name="foo") + tm.assert_index_equal(index_slice, expected, exact="equiv") + + @pytest.mark.parametrize("step", set(range(-5, 6)) - {0}) + def test_len_specialised(self, step): + # make sure that our len is the same as np.arange calc + start, stop = (0, 5) if step > 0 else (5, 0) + + arr = np.arange(start, stop, step) + index = RangeIndex(start, stop, step) + assert len(index) == len(arr) + + index = RangeIndex(stop, start, step) + assert len(index) == 0 + + @pytest.mark.parametrize( + "indices, expected", + [ + ([RangeIndex(1, 12, 5)], RangeIndex(1, 12, 5)), + ([RangeIndex(0, 6, 4)], RangeIndex(0, 6, 4)), + ([RangeIndex(1, 3), RangeIndex(3, 7)], RangeIndex(1, 7)), + ([RangeIndex(1, 5, 2), RangeIndex(5, 6)], RangeIndex(1, 6, 2)), + ([RangeIndex(1, 3, 2), RangeIndex(4, 7, 3)], RangeIndex(1, 7, 3)), + ([RangeIndex(-4, 3, 2), RangeIndex(4, 7, 2)], RangeIndex(-4, 7, 2)), + ([RangeIndex(-4, -8), RangeIndex(-8, -12)], RangeIndex(0, 0)), + ([RangeIndex(-4, -8), RangeIndex(3, -4)], RangeIndex(0, 0)), + ([RangeIndex(-4, -8), RangeIndex(3, 5)], RangeIndex(3, 5)), + ([RangeIndex(-4, -2), RangeIndex(3, 5)], Index([-4, -3, 3, 4])), + ([RangeIndex(-2), RangeIndex(3, 5)], RangeIndex(3, 5)), + ([RangeIndex(2), RangeIndex(2)], Index([0, 1, 0, 1])), + ([RangeIndex(2), RangeIndex(2, 5), RangeIndex(5, 8, 4)], RangeIndex(0, 6)), + ( + [RangeIndex(2), RangeIndex(3, 5), RangeIndex(5, 8, 4)], + Index([0, 1, 3, 4, 5]), + ), + ( + [RangeIndex(-2, 2), RangeIndex(2, 5), RangeIndex(5, 8, 4)], + RangeIndex(-2, 6), + ), + ([RangeIndex(3), Index([-1, 3, 15])], Index([0, 1, 2, -1, 3, 15])), + ([RangeIndex(3), Index([-1, 3.1, 15.0])], Index([0, 1, 2, -1, 3.1, 15.0])), + ([RangeIndex(3), Index(["a", None, 14])], Index([0, 1, 2, "a", None, 14])), + ([RangeIndex(3, 1), Index(["a", None, 14])], Index(["a", None, 14])), + ], + ) + def test_append(self, indices, expected): + # GH16212 + result = indices[0].append(indices[1:]) + tm.assert_index_equal(result, expected, exact=True) + + if len(indices) == 2: + # Append single item rather than list + result2 = indices[0].append(indices[1]) + tm.assert_index_equal(result2, expected, exact=True) + + def test_engineless_lookup(self): + # GH 16685 + # Standard lookup on RangeIndex should not require the engine to be + # created + idx = RangeIndex(2, 10, 3) + + assert idx.get_loc(5) == 1 + tm.assert_numpy_array_equal( + idx.get_indexer([2, 8]), ensure_platform_int(np.array([0, 2])) + ) + with pytest.raises(KeyError, match="3"): + idx.get_loc(3) + + assert "_engine" not in idx._cache + + # Different types of scalars can be excluded immediately, no need to + # use the _engine + with pytest.raises(KeyError, match="'a'"): + idx.get_loc("a") + + assert "_engine" not in idx._cache + + def test_format_empty(self): + # GH35712 + empty_idx = RangeIndex(0) + msg = r"RangeIndex\.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) == [""] + + @pytest.mark.parametrize( + "ri", + [ + RangeIndex(0, -1, -1), + RangeIndex(0, 1, 1), + RangeIndex(1, 3, 2), + RangeIndex(0, -1, -2), + RangeIndex(-3, -5, -2), + ], + ) + def test_append_len_one(self, ri): + # GH39401 + result = ri.append([]) + tm.assert_index_equal(result, ri, exact=True) + + @pytest.mark.parametrize("base", [RangeIndex(0, 2), Index([0, 1])]) + def test_isin_range(self, base): + # GH#41151 + values = RangeIndex(0, 1) + result = base.isin(values) + expected = np.array([True, False]) + tm.assert_numpy_array_equal(result, expected) + + def test_sort_values_key(self): + # GH#43666, GH#52764 + sort_order = {8: 2, 6: 0, 4: 8, 2: 10, 0: 12} + values = RangeIndex(0, 10, 2) + result = values.sort_values(key=lambda x: x.map(sort_order)) + expected = Index([6, 8, 4, 2, 0], dtype="int64") + tm.assert_index_equal(result, expected, check_exact=True) + + # check this matches the Series.sort_values behavior + ser = values.to_series() + result2 = ser.sort_values(key=lambda x: x.map(sort_order)) + tm.assert_series_equal(result2, expected.to_series(), check_exact=True) + + def test_range_index_rsub_by_const(self): + # GH#53255 + result = 3 - RangeIndex(0, 4, 1) + expected = RangeIndex(3, -1, -1) + tm.assert_index_equal(result, expected) diff --git a/shared/package-files/01/01ab357b908cd2884c057350dad4996a8ee365b59393d2c0f39160949f0244b1/blob b/shared/package-files/01/01ab357b908cd2884c057350dad4996a8ee365b59393d2c0f39160949f0244b1/blob new file mode 100644 index 0000000000000000000000000000000000000000..f5a724bad4fa2b899ed536d38163a0545160fe8b --- /dev/null +++ b/shared/package-files/01/01ab357b908cd2884c057350dad4996a8ee365b59393d2c0f39160949f0244b1/blob @@ -0,0 +1,320 @@ +""" +Tests that work on the Python, C and PyArrow engines but do not have a +specific classification into the other test modules. +""" +import codecs +import csv +from io import StringIO +import os +from pathlib import Path + +import numpy as np +import pytest + +from pandas.compat import PY311 +from pandas.errors import ( + EmptyDataError, + ParserError, + ParserWarning, +) + +from pandas import DataFrame +import pandas._testing as tm + +xfail_pyarrow = pytest.mark.usefixtures("pyarrow_xfail") +skip_pyarrow = pytest.mark.usefixtures("pyarrow_skip") + + +def test_empty_decimal_marker(all_parsers): + data = """A|B|C +1|2,334|5 +10|13|10. +""" + # Parsers support only length-1 decimals + msg = "Only length-1 decimal markers supported" + parser = all_parsers + + if parser.engine == "pyarrow": + msg = ( + "only single character unicode strings can be " + "converted to Py_UCS4, got length 0" + ) + + with pytest.raises(ValueError, match=msg): + parser.read_csv(StringIO(data), decimal="") + + +def test_bad_stream_exception(all_parsers, csv_dir_path): + # see gh-13652 + # + # This test validates that both the Python engine and C engine will + # raise UnicodeDecodeError instead of C engine raising ParserError + # and swallowing the exception that caused read to fail. + path = os.path.join(csv_dir_path, "sauron.SHIFT_JIS.csv") + codec = codecs.lookup("utf-8") + utf8 = codecs.lookup("utf-8") + parser = all_parsers + msg = "'utf-8' codec can't decode byte" + + # Stream must be binary UTF8. + with open(path, "rb") as handle, codecs.StreamRecoder( + handle, utf8.encode, utf8.decode, codec.streamreader, codec.streamwriter + ) as stream: + with pytest.raises(UnicodeDecodeError, match=msg): + parser.read_csv(stream) + + +def test_malformed(all_parsers): + # see gh-6607 + parser = all_parsers + data = """ignore +A,B,C +1,2,3 # comment +1,2,3,4,5 +2,3,4 +""" + msg = "Expected 3 fields in line 4, saw 5" + err = ParserError + if parser.engine == "pyarrow": + msg = "The 'comment' option is not supported with the 'pyarrow' engine" + err = ValueError + with pytest.raises(err, match=msg): + parser.read_csv(StringIO(data), header=1, comment="#") + + +@pytest.mark.parametrize("nrows", [5, 3, None]) +def test_malformed_chunks(all_parsers, nrows): + data = """ignore +A,B,C +skip +1,2,3 +3,5,10 # comment +1,2,3,4,5 +2,3,4 +""" + parser = all_parsers + + if parser.engine == "pyarrow": + msg = "The 'iterator' option is not supported with the 'pyarrow' engine" + with pytest.raises(ValueError, match=msg): + parser.read_csv( + StringIO(data), + header=1, + comment="#", + iterator=True, + chunksize=1, + skiprows=[2], + ) + return + + msg = "Expected 3 fields in line 6, saw 5" + with parser.read_csv( + StringIO(data), header=1, comment="#", iterator=True, chunksize=1, skiprows=[2] + ) as reader: + with pytest.raises(ParserError, match=msg): + reader.read(nrows) + + +@xfail_pyarrow # does not raise +def test_catch_too_many_names(all_parsers): + # see gh-5156 + data = """\ +1,2,3 +4,,6 +7,8,9 +10,11,12\n""" + parser = all_parsers + msg = ( + "Too many columns specified: expected 4 and found 3" + if parser.engine == "c" + else "Number of passed names did not match " + "number of header fields in the file" + ) + + with pytest.raises(ValueError, match=msg): + parser.read_csv(StringIO(data), header=0, names=["a", "b", "c", "d"]) + + +@skip_pyarrow # CSV parse error: Empty CSV file or block +@pytest.mark.parametrize("nrows", [0, 1, 2, 3, 4, 5]) +def test_raise_on_no_columns(all_parsers, nrows): + parser = all_parsers + data = "\n" * nrows + + msg = "No columns to parse from file" + with pytest.raises(EmptyDataError, match=msg): + parser.read_csv(StringIO(data)) + + +def test_unexpected_keyword_parameter_exception(all_parsers): + # GH-34976 + parser = all_parsers + + msg = "{}\\(\\) got an unexpected keyword argument 'foo'" + with pytest.raises(TypeError, match=msg.format("read_csv")): + parser.read_csv("foo.csv", foo=1) + with pytest.raises(TypeError, match=msg.format("read_table")): + parser.read_table("foo.tsv", foo=1) + + +def test_suppress_error_output(all_parsers): + # see gh-15925 + parser = all_parsers + data = "a\n1\n1,2,3\n4\n5,6,7" + expected = DataFrame({"a": [1, 4]}) + + result = parser.read_csv(StringIO(data), on_bad_lines="skip") + tm.assert_frame_equal(result, expected) + + +def test_error_bad_lines(all_parsers): + # see gh-15925 + parser = all_parsers + data = "a\n1\n1,2,3\n4\n5,6,7" + + msg = "Expected 1 fields in line 3, saw 3" + + if parser.engine == "pyarrow": + # "CSV parse error: Expected 1 columns, got 3: 1,2,3" + pytest.skip(reason="https://github.com/apache/arrow/issues/38676") + + with pytest.raises(ParserError, match=msg): + parser.read_csv(StringIO(data), on_bad_lines="error") + + +def test_warn_bad_lines(all_parsers): + # see gh-15925 + parser = all_parsers + data = "a\n1\n1,2,3\n4\n5,6,7" + expected = DataFrame({"a": [1, 4]}) + match_msg = "Skipping line" + + expected_warning = ParserWarning + if parser.engine == "pyarrow": + match_msg = "Expected 1 columns, but found 3: 1,2,3" + expected_warning = (ParserWarning, DeprecationWarning) + + with tm.assert_produces_warning( + expected_warning, match=match_msg, check_stacklevel=False + ): + result = parser.read_csv(StringIO(data), on_bad_lines="warn") + tm.assert_frame_equal(result, expected) + + +def test_read_csv_wrong_num_columns(all_parsers): + # Too few columns. + data = """A,B,C,D,E,F +1,2,3,4,5,6 +6,7,8,9,10,11,12 +11,12,13,14,15,16 +""" + parser = all_parsers + msg = "Expected 6 fields in line 3, saw 7" + + if parser.engine == "pyarrow": + # Expected 6 columns, got 7: 6,7,8,9,10,11,12 + pytest.skip(reason="https://github.com/apache/arrow/issues/38676") + + with pytest.raises(ParserError, match=msg): + parser.read_csv(StringIO(data)) + + +def test_null_byte_char(request, all_parsers): + # see gh-2741 + data = "\x00,foo" + names = ["a", "b"] + parser = all_parsers + + if parser.engine == "c" or (parser.engine == "python" and PY311): + if parser.engine == "python" and PY311: + request.applymarker( + pytest.mark.xfail( + reason="In Python 3.11, this is read as an empty character not null" + ) + ) + expected = DataFrame([[np.nan, "foo"]], columns=names) + out = parser.read_csv(StringIO(data), names=names) + tm.assert_frame_equal(out, expected) + else: + if parser.engine == "pyarrow": + # CSV parse error: Empty CSV file or block: " + # cannot infer number of columns" + pytest.skip(reason="https://github.com/apache/arrow/issues/38676") + else: + msg = "NULL byte detected" + with pytest.raises(ParserError, match=msg): + parser.read_csv(StringIO(data), names=names) + + +@pytest.mark.filterwarnings("always::ResourceWarning") +def test_open_file(request, all_parsers): + # GH 39024 + parser = all_parsers + + msg = "Could not determine delimiter" + err = csv.Error + if parser.engine == "c": + msg = "the 'c' engine does not support sep=None with delim_whitespace=False" + err = ValueError + elif parser.engine == "pyarrow": + msg = ( + "the 'pyarrow' engine does not support sep=None with delim_whitespace=False" + ) + err = ValueError + + with tm.ensure_clean() as path: + file = Path(path) + file.write_bytes(b"\xe4\na\n1") + + with tm.assert_produces_warning(None): + # should not trigger a ResourceWarning + with pytest.raises(err, match=msg): + parser.read_csv(file, sep=None, encoding_errors="replace") + + +def test_invalid_on_bad_line(all_parsers): + parser = all_parsers + data = "a\n1\n1,2,3\n4\n5,6,7" + with pytest.raises(ValueError, match="Argument abc is invalid for on_bad_lines"): + parser.read_csv(StringIO(data), on_bad_lines="abc") + + +def test_bad_header_uniform_error(all_parsers): + parser = all_parsers + data = "+++123456789...\ncol1,col2,col3,col4\n1,2,3,4\n" + msg = "Expected 2 fields in line 2, saw 4" + if parser.engine == "c": + msg = ( + "Could not construct index. Requested to use 1 " + "number of columns, but 3 left to parse." + ) + elif parser.engine == "pyarrow": + # "CSV parse error: Expected 1 columns, got 4: col1,col2,col3,col4" + pytest.skip(reason="https://github.com/apache/arrow/issues/38676") + + with pytest.raises(ParserError, match=msg): + parser.read_csv(StringIO(data), index_col=0, on_bad_lines="error") + + +def test_on_bad_lines_warn_correct_formatting(all_parsers): + # see gh-15925 + parser = all_parsers + data = """1,2 +a,b +a,b,c +a,b,d +a,b +""" + expected = DataFrame({"1": "a", "2": ["b"] * 2}) + match_msg = "Skipping line" + + expected_warning = ParserWarning + if parser.engine == "pyarrow": + match_msg = "Expected 2 columns, but found 3: a,b,c" + expected_warning = (ParserWarning, DeprecationWarning) + + with tm.assert_produces_warning( + expected_warning, match=match_msg, check_stacklevel=False + ): + result = parser.read_csv(StringIO(data), on_bad_lines="warn") + tm.assert_frame_equal(result, expected) diff --git a/shared/package-files/01/01ac955f24dab8d24f6384a90cbcbd58d0ecf24df427c68dcf7f93d3987061fa/blob b/shared/package-files/01/01ac955f24dab8d24f6384a90cbcbd58d0ecf24df427c68dcf7f93d3987061fa/blob new file mode 100644 index 0000000000000000000000000000000000000000..38b8288c39f4ebacd9cadc58bba7b18416377c73 --- /dev/null +++ b/shared/package-files/01/01ac955f24dab8d24f6384a90cbcbd58d0ecf24df427c68dcf7f93d3987061fa/blob @@ -0,0 +1,872 @@ +"""test sparse matrix construction functions""" + +import numpy as np +from numpy import array +from numpy.testing import (assert_equal, assert_, + assert_array_equal, assert_array_almost_equal_nulp) +import pytest +from pytest import raises as assert_raises +from scipy._lib._testutils import check_free_memory + +from scipy.sparse import (csr_matrix, coo_matrix, + csr_array, coo_array, + csc_array, bsr_array, + dia_array, dok_array, + lil_array, csc_matrix, + bsr_matrix, dia_matrix, + lil_matrix, sparray, spmatrix, + _construct as construct) +from scipy.sparse._construct import rand as sprand + +sparse_formats = ['csr','csc','coo','bsr','dia','lil','dok'] + +#TODO check whether format=XXX is respected + + +def _sprandn(m, n, density=0.01, format="coo", dtype=None, rng=None): + # Helper function for testing. + rng = np.random.default_rng(rng) + data_rvs = rng.standard_normal + return construct.random(m, n, density, format, dtype, rng, data_rvs) + + +def _sprandn_array(m, n, density=0.01, format="coo", dtype=None, rng=None): + # Helper function for testing. + rng = np.random.default_rng(rng) + data_sampler = rng.standard_normal + return construct.random_array((m, n), density=density, format=format, dtype=dtype, + rng=rng, data_sampler=data_sampler) + + +class TestConstructUtils: + + @pytest.mark.parametrize("cls", [ + csc_array, csr_array, coo_array, bsr_array, + dia_array, dok_array, lil_array + ]) + def test_singleton_array_constructor(self, cls): + with pytest.raises( + ValueError, + match=( + 'scipy sparse array classes do not support ' + 'instantiation from a scalar' + ) + ): + cls(0) + + @pytest.mark.parametrize("cls", [ + csc_matrix, csr_matrix, coo_matrix, + bsr_matrix, dia_matrix, lil_matrix + ]) + def test_singleton_matrix_constructor(self, cls): + """ + This test is for backwards compatibility post scipy 1.13. + The behavior observed here is what is to be expected + with the older matrix classes. This test comes with the + exception of dok_matrix, which was not working pre scipy1.12 + (unlike the rest of these). + """ + assert cls(0).shape == (1, 1) + + def test_spdiags(self): + diags1 = array([[1, 2, 3, 4, 5]]) + diags2 = array([[1, 2, 3, 4, 5], + [6, 7, 8, 9,10]]) + diags3 = array([[1, 2, 3, 4, 5], + [6, 7, 8, 9,10], + [11,12,13,14,15]]) + + cases = [] + cases.append((diags1, 0, 1, 1, [[1]])) + cases.append((diags1, [0], 1, 1, [[1]])) + cases.append((diags1, [0], 2, 1, [[1],[0]])) + cases.append((diags1, [0], 1, 2, [[1,0]])) + cases.append((diags1, [1], 1, 2, [[0,2]])) + cases.append((diags1,[-1], 1, 2, [[0,0]])) + cases.append((diags1, [0], 2, 2, [[1,0],[0,2]])) + cases.append((diags1,[-1], 2, 2, [[0,0],[1,0]])) + cases.append((diags1, [3], 2, 2, [[0,0],[0,0]])) + cases.append((diags1, [0], 3, 4, [[1,0,0,0],[0,2,0,0],[0,0,3,0]])) + cases.append((diags1, [1], 3, 4, [[0,2,0,0],[0,0,3,0],[0,0,0,4]])) + cases.append((diags1, [2], 3, 5, [[0,0,3,0,0],[0,0,0,4,0],[0,0,0,0,5]])) + + cases.append((diags2, [0,2], 3, 3, [[1,0,8],[0,2,0],[0,0,3]])) + cases.append((diags2, [-1,0], 3, 4, [[6,0,0,0],[1,7,0,0],[0,2,8,0]])) + cases.append((diags2, [2,-3], 6, 6, [[0,0,3,0,0,0], + [0,0,0,4,0,0], + [0,0,0,0,5,0], + [6,0,0,0,0,0], + [0,7,0,0,0,0], + [0,0,8,0,0,0]])) + + cases.append((diags3, [-1,0,1], 6, 6, [[6,12, 0, 0, 0, 0], + [1, 7,13, 0, 0, 0], + [0, 2, 8,14, 0, 0], + [0, 0, 3, 9,15, 0], + [0, 0, 0, 4,10, 0], + [0, 0, 0, 0, 5, 0]])) + cases.append((diags3, [-4,2,-1], 6, 5, [[0, 0, 8, 0, 0], + [11, 0, 0, 9, 0], + [0,12, 0, 0,10], + [0, 0,13, 0, 0], + [1, 0, 0,14, 0], + [0, 2, 0, 0,15]])) + cases.append((diags3, [-1, 1, 2], len(diags3[0]), len(diags3[0]), + [[0, 7, 13, 0, 0], + [1, 0, 8, 14, 0], + [0, 2, 0, 9, 15], + [0, 0, 3, 0, 10], + [0, 0, 0, 4, 0]])) + + for d, o, m, n, result in cases: + if len(d[0]) == m and m == n: + assert_equal(construct.spdiags(d, o).toarray(), result) + assert_equal(construct.spdiags(d, o, m, n).toarray(), result) + assert_equal(construct.spdiags(d, o, (m, n)).toarray(), result) + + def test_diags(self): + a = array([1, 2, 3, 4, 5]) + b = array([6, 7, 8, 9, 10]) + c = array([11, 12, 13, 14, 15]) + + cases = [] + cases.append((a[:1], 0, (1, 1), [[1]])) + cases.append(([a[:1]], [0], (1, 1), [[1]])) + cases.append(([a[:1]], [0], (2, 1), [[1],[0]])) + cases.append(([a[:1]], [0], (1, 2), [[1,0]])) + cases.append(([a[:1]], [1], (1, 2), [[0,1]])) + cases.append(([a[:2]], [0], (2, 2), [[1,0],[0,2]])) + cases.append(([a[:1]],[-1], (2, 2), [[0,0],[1,0]])) + cases.append(([a[:3]], [0], (3, 4), [[1,0,0,0],[0,2,0,0],[0,0,3,0]])) + cases.append(([a[:3]], [1], (3, 4), [[0,1,0,0],[0,0,2,0],[0,0,0,3]])) + cases.append(([a[:1]], [-2], (3, 5), [[0,0,0,0,0],[0,0,0,0,0],[1,0,0,0,0]])) + cases.append(([a[:2]], [-1], (3, 5), [[0,0,0,0,0],[1,0,0,0,0],[0,2,0,0,0]])) + cases.append(([a[:3]], [0], (3, 5), [[1,0,0,0,0],[0,2,0,0,0],[0,0,3,0,0]])) + cases.append(([a[:3]], [1], (3, 5), [[0,1,0,0,0],[0,0,2,0,0],[0,0,0,3,0]])) + cases.append(([a[:3]], [2], (3, 5), [[0,0,1,0,0],[0,0,0,2,0],[0,0,0,0,3]])) + cases.append(([a[:2]], [3], (3, 5), [[0,0,0,1,0],[0,0,0,0,2],[0,0,0,0,0]])) + cases.append(([a[:1]], [4], (3, 5), [[0,0,0,0,1],[0,0,0,0,0],[0,0,0,0,0]])) + cases.append(([a[:1]], [-4], (5, 3), [[0,0,0],[0,0,0],[0,0,0],[0,0,0],[1,0,0]])) + cases.append(([a[:2]], [-3], (5, 3), [[0,0,0],[0,0,0],[0,0,0],[1,0,0],[0,2,0]])) + cases.append(([a[:3]], [-2], (5, 3), [[0,0,0],[0,0,0],[1,0,0],[0,2,0],[0,0,3]])) + cases.append(([a[:3]], [-1], (5, 3), [[0,0,0],[1,0,0],[0,2,0],[0,0,3],[0,0,0]])) + cases.append(([a[:3]], [0], (5, 3), [[1,0,0],[0,2,0],[0,0,3],[0,0,0],[0,0,0]])) + cases.append(([a[:2]], [1], (5, 3), [[0,1,0],[0,0,2],[0,0,0],[0,0,0],[0,0,0]])) + cases.append(([a[:1]], [2], (5, 3), [[0,0,1],[0,0,0],[0,0,0],[0,0,0],[0,0,0]])) + + cases.append(([a[:3],b[:1]], [0,2], (3, 3), [[1,0,6],[0,2,0],[0,0,3]])) + cases.append(([a[:2],b[:3]], [-1,0], (3, 4), [[6,0,0,0],[1,7,0,0],[0,2,8,0]])) + cases.append(([a[:4],b[:3]], [2,-3], (6, 6), [[0,0,1,0,0,0], + [0,0,0,2,0,0], + [0,0,0,0,3,0], + [6,0,0,0,0,4], + [0,7,0,0,0,0], + [0,0,8,0,0,0]])) + + cases.append(([a[:4],b,c[:4]], [-1,0,1], (5, 5), [[6,11, 0, 0, 0], + [1, 7,12, 0, 0], + [0, 2, 8,13, 0], + [0, 0, 3, 9,14], + [0, 0, 0, 4,10]])) + cases.append(([a[:2],b[:3],c], [-4,2,-1], (6, 5), [[0, 0, 6, 0, 0], + [11, 0, 0, 7, 0], + [0,12, 0, 0, 8], + [0, 0,13, 0, 0], + [1, 0, 0,14, 0], + [0, 2, 0, 0,15]])) + + # too long arrays are OK + cases.append(([a], [0], (1, 1), [[1]])) + cases.append(([a[:3],b], [0,2], (3, 3), [[1, 0, 6], [0, 2, 0], [0, 0, 3]])) + cases.append(( + np.array([[1, 2, 3], [4, 5, 6]]), + [0,-1], + (3, 3), + [[1, 0, 0], [4, 2, 0], [0, 5, 3]] + )) + + # scalar case: broadcasting + cases.append(([1,-2,1], [1,0,-1], (3, 3), [[-2, 1, 0], + [1, -2, 1], + [0, 1, -2]])) + + for d, o, shape, result in cases: + err_msg = f"{d!r} {o!r} {shape!r} {result!r}" + assert_equal(construct.diags(d, offsets=o, shape=shape).toarray(), + result, err_msg=err_msg) + + if (shape[0] == shape[1] + and hasattr(d[0], '__len__') + and len(d[0]) <= max(shape)): + # should be able to find the shape automatically + assert_equal(construct.diags(d, offsets=o).toarray(), result, + err_msg=err_msg) + + def test_diags_default(self): + a = array([1, 2, 3, 4, 5]) + assert_equal(construct.diags(a).toarray(), np.diag(a)) + + def test_diags_default_bad(self): + a = array([[1, 2, 3, 4, 5], [2, 3, 4, 5, 6]]) + assert_raises(ValueError, construct.diags, a) + + def test_diags_bad(self): + a = array([1, 2, 3, 4, 5]) + b = array([6, 7, 8, 9, 10]) + c = array([11, 12, 13, 14, 15]) + + cases = [] + cases.append(([a[:0]], 0, (1, 1))) + cases.append(([a[:4],b,c[:3]], [-1,0,1], (5, 5))) + cases.append(([a[:2],c,b[:3]], [-4,2,-1], (6, 5))) + cases.append(([a[:2],c,b[:3]], [-4,2,-1], None)) + cases.append(([], [-4,2,-1], None)) + cases.append(([1], [-5], (4, 4))) + cases.append(([a], 0, None)) + + for d, o, shape in cases: + assert_raises(ValueError, construct.diags, d, offsets=o, shape=shape) + + assert_raises(TypeError, construct.diags, [[None]], offsets=[0]) + + def test_diags_vs_diag(self): + # Check that + # + # diags([a, b, ...], [i, j, ...]) == diag(a, i) + diag(b, j) + ... + # + + rng = np.random.RandomState(1234) + + for n_diags in [1, 2, 3, 4, 5, 10]: + n = 1 + n_diags//2 + rng.randint(0, 10) + + offsets = np.arange(-n+1, n-1) + rng.shuffle(offsets) + offsets = offsets[:n_diags] + + diagonals = [rng.rand(n - abs(q)) for q in offsets] + + mat = construct.diags(diagonals, offsets=offsets) + dense_mat = sum([np.diag(x, j) for x, j in zip(diagonals, offsets)]) + + assert_array_almost_equal_nulp(mat.toarray(), dense_mat) + + if len(offsets) == 1: + mat = construct.diags(diagonals[0], offsets=offsets[0]) + dense_mat = np.diag(diagonals[0], offsets[0]) + assert_array_almost_equal_nulp(mat.toarray(), dense_mat) + + def test_diags_dtype(self): + x = construct.diags([2.2], offsets=[0], shape=(2, 2), dtype=int) + assert_equal(x.dtype, int) + assert_equal(x.toarray(), [[2, 0], [0, 2]]) + + def test_diags_one_diagonal(self): + d = list(range(5)) + for k in range(-5, 6): + assert_equal(construct.diags(d, offsets=k).toarray(), + construct.diags([d], offsets=[k]).toarray()) + + def test_diags_empty(self): + x = construct.diags([]) + assert_equal(x.shape, (0, 0)) + + @pytest.mark.parametrize("identity", [construct.identity, construct.eye_array]) + def test_identity(self, identity): + assert_equal(identity(1).toarray(), [[1]]) + assert_equal(identity(2).toarray(), [[1,0],[0,1]]) + + I = identity(3, dtype='int8', format='dia') + assert_equal(I.dtype, np.dtype('int8')) + assert_equal(I.format, 'dia') + + for fmt in sparse_formats: + I = identity(3, format=fmt) + assert_equal(I.format, fmt) + assert_equal(I.toarray(), [[1,0,0],[0,1,0],[0,0,1]]) + + @pytest.mark.parametrize("eye", [construct.eye, construct.eye_array]) + def test_eye(self, eye): + assert_equal(eye(1,1).toarray(), [[1]]) + assert_equal(eye(2,3).toarray(), [[1,0,0],[0,1,0]]) + assert_equal(eye(3,2).toarray(), [[1,0],[0,1],[0,0]]) + assert_equal(eye(3,3).toarray(), [[1,0,0],[0,1,0],[0,0,1]]) + + assert_equal(eye(3,3,dtype='int16').dtype, np.dtype('int16')) + + for m in [3, 5]: + for n in [3, 5]: + for k in range(-5,6): + # scipy.sparse.eye deviates from np.eye here. np.eye will + # create arrays of all 0's when the diagonal offset is + # greater than the size of the array. For sparse arrays + # this makes less sense, especially as it results in dia + # arrays with negative diagonals. Therefore sp.sparse.eye + # validates that diagonal offsets fall within the shape of + # the array. See gh-18555. + if (k > 0 and k > n) or (k < 0 and abs(k) > m): + with pytest.raises( + ValueError, match="Offset.*out of bounds" + ): + eye(m, n, k=k) + + else: + assert_equal( + eye(m, n, k=k).toarray(), + np.eye(m, n, k=k) + ) + if m == n: + assert_equal( + eye(m, k=k).toarray(), + np.eye(m, n, k=k) + ) + + @pytest.mark.parametrize("eye", [construct.eye, construct.eye_array]) + def test_eye_one(self, eye): + assert_equal(eye(1).toarray(), [[1]]) + assert_equal(eye(2).toarray(), [[1,0],[0,1]]) + + I = eye(3, dtype='int8', format='dia') + assert_equal(I.dtype, np.dtype('int8')) + assert_equal(I.format, 'dia') + + for fmt in sparse_formats: + I = eye(3, format=fmt) + assert_equal(I.format, fmt) + assert_equal(I.toarray(), [[1,0,0],[0,1,0],[0,0,1]]) + + def test_eye_array_vs_matrix(self): + assert isinstance(construct.eye_array(3), sparray) + assert not isinstance(construct.eye(3), sparray) + + def test_kron(self): + cases = [] + + cases.append(array([[0]])) + cases.append(array([[-1]])) + cases.append(array([[4]])) + cases.append(array([[10]])) + cases.append(array([[0],[0]])) + cases.append(array([[0,0]])) + cases.append(array([[1,2],[3,4]])) + cases.append(array([[0,2],[5,0]])) + cases.append(array([[0,2,-6],[8,0,14]])) + cases.append(array([[5,4],[0,0],[6,0]])) + cases.append(array([[5,4,4],[1,0,0],[6,0,8]])) + cases.append(array([[0,1,0,2,0,5,8]])) + cases.append(array([[0.5,0.125,0,3.25],[0,2.5,0,0]])) + + # test all cases with some formats + for a in cases: + ca = csr_array(a) + for b in cases: + cb = csr_array(b) + expected = np.kron(a, b) + for fmt in sparse_formats[1:4]: + result = construct.kron(ca, cb, format=fmt) + assert_equal(result.format, fmt) + assert_array_equal(result.toarray(), expected) + assert isinstance(result, sparray) + + # test one case with all formats + a = cases[-1] + b = cases[-3] + ca = csr_array(a) + cb = csr_array(b) + + expected = np.kron(a, b) + for fmt in sparse_formats: + result = construct.kron(ca, cb, format=fmt) + assert_equal(result.format, fmt) + assert_array_equal(result.toarray(), expected) + assert isinstance(result, sparray) + + # check that spmatrix returned when both inputs are spmatrix + result = construct.kron(csr_matrix(a), csr_matrix(b), format=fmt) + assert_equal(result.format, fmt) + assert_array_equal(result.toarray(), expected) + assert isinstance(result, spmatrix) + + def test_kron_ndim_exceptions(self): + with pytest.raises(ValueError, match='requires 2D input'): + construct.kron([[0], [1]], csr_array([0, 1])) + with pytest.raises(ValueError, match='requires 2D input'): + construct.kron(csr_array([0, 1]), [[0], [1]]) + # no exception if sparse arrays are not input (spmatrix inferred) + construct.kron([[0], [1]], [0, 1]) + + def test_kron_large(self): + n = 2**16 + a = construct.diags_array([1], shape=(1, n), offsets=n-1) + b = construct.diags_array([1], shape=(n, 1), offsets=1-n) + + construct.kron(a, a) + construct.kron(b, b) + + def test_kronsum(self): + cases = [] + + cases.append(array([[0]])) + cases.append(array([[-1]])) + cases.append(array([[4]])) + cases.append(array([[10]])) + cases.append(array([[1,2],[3,4]])) + cases.append(array([[0,2],[5,0]])) + cases.append(array([[0,2,-6],[8,0,14],[0,3,0]])) + cases.append(array([[1,0,0],[0,5,-1],[4,-2,8]])) + + # test all cases with default format + for a in cases: + for b in cases: + result = construct.kronsum(csr_array(a), csr_array(b)).toarray() + expected = (np.kron(np.eye(b.shape[0]), a) + + np.kron(b, np.eye(a.shape[0]))) + assert_array_equal(result, expected) + + # check that spmatrix returned when both inputs are spmatrix + result = construct.kronsum(csr_matrix(a), csr_matrix(b)).toarray() + assert_array_equal(result, expected) + + def test_kronsum_ndim_exceptions(self): + with pytest.raises(ValueError, match='requires 2D input'): + construct.kronsum([[0], [1]], csr_array([0, 1])) + with pytest.raises(ValueError, match='requires 2D input'): + construct.kronsum(csr_array([0, 1]), [[0], [1]]) + # no exception if sparse arrays are not input (spmatrix inferred) + construct.kronsum([[0, 1], [1, 0]], [2]) + + @pytest.mark.parametrize("coo_cls", [coo_matrix, coo_array]) + def test_vstack(self, coo_cls): + A = coo_cls([[1,2],[3,4]]) + B = coo_cls([[5,6]]) + + expected = array([[1, 2], + [3, 4], + [5, 6]]) + assert_equal(construct.vstack([A, B]).toarray(), expected) + assert_equal(construct.vstack([A, B], dtype=np.float32).dtype, + np.float32) + + assert_equal(construct.vstack([A.todok(), B.todok()]).toarray(), expected) + + assert_equal(construct.vstack([A.tocsr(), B.tocsr()]).toarray(), + expected) + result = construct.vstack([A.tocsr(), B.tocsr()], + format="csr", dtype=np.float32) + assert_equal(result.dtype, np.float32) + assert_equal(result.indices.dtype, np.int32) + assert_equal(result.indptr.dtype, np.int32) + + assert_equal(construct.vstack([A.tocsc(), B.tocsc()]).toarray(), + expected) + result = construct.vstack([A.tocsc(), B.tocsc()], + format="csc", dtype=np.float32) + assert_equal(result.dtype, np.float32) + assert_equal(result.indices.dtype, np.int32) + assert_equal(result.indptr.dtype, np.int32) + + def test_vstack_maintain64bit_idx_dtype(self): + # see gh-20389 v/hstack returns int32 idx_dtype with input int64 idx_dtype + X = csr_array([[1, 0, 0], [0, 1, 0], [0, 1, 0]]) + X.indptr = X.indptr.astype(np.int64) + X.indices = X.indices.astype(np.int64) + assert construct.vstack([X, X]).indptr.dtype == np.int64 + assert construct.hstack([X, X]).indptr.dtype == np.int64 + + X = csc_array([[1, 0, 0], [0, 1, 0], [0, 1, 0]]) + X.indptr = X.indptr.astype(np.int64) + X.indices = X.indices.astype(np.int64) + assert construct.vstack([X, X]).indptr.dtype == np.int64 + assert construct.hstack([X, X]).indptr.dtype == np.int64 + + X = coo_array([[1, 0, 0], [0, 1, 0], [0, 1, 0]]) + X.coords = tuple(co.astype(np.int64) for co in X.coords) + assert construct.vstack([X, X]).coords[0].dtype == np.int64 + assert construct.hstack([X, X]).coords[0].dtype == np.int64 + + def test_vstack_matrix_or_array(self): + A = [[1,2],[3,4]] + B = [[5,6]] + assert isinstance(construct.vstack([coo_array(A), coo_array(B)]), sparray) + assert isinstance(construct.vstack([coo_array(A), coo_matrix(B)]), sparray) + assert isinstance(construct.vstack([coo_matrix(A), coo_array(B)]), sparray) + assert isinstance(construct.vstack([coo_matrix(A), coo_matrix(B)]), spmatrix) + + def test_vstack_1d_with_2d(self): + # fixes gh-21064 + arr = csr_array([[1, 0, 0], [0, 1, 0]]) + arr1d = csr_array([1, 0, 0]) + arr1dcoo = coo_array([1, 0, 0]) + assert construct.vstack([arr, np.array([0, 0, 0])]).shape == (3, 3) + assert construct.hstack([arr1d, np.array([[0]])]).shape == (1, 4) + assert construct.hstack([arr1d, arr1d]).shape == (1, 6) + assert construct.vstack([arr1d, arr1d]).shape == (2, 3) + + # check csr specialty stacking code like _stack_along_minor_axis + assert construct.hstack([arr, arr]).shape == (2, 6) + assert construct.hstack([arr1d, arr1d]).shape == (1, 6) + + assert construct.hstack([arr1d, arr1dcoo]).shape == (1, 6) + assert construct.vstack([arr, arr1dcoo]).shape == (3, 3) + assert construct.vstack([arr1d, arr1dcoo]).shape == (2, 3) + + with pytest.raises(ValueError, match="incompatible row dimensions"): + construct.hstack([arr, np.array([0, 0])]) + with pytest.raises(ValueError, match="incompatible column dimensions"): + construct.vstack([arr, np.array([0, 0])]) + + @pytest.mark.parametrize("coo_cls", [coo_matrix, coo_array]) + def test_hstack(self, coo_cls): + A = coo_cls([[1,2],[3,4]]) + B = coo_cls([[5],[6]]) + + expected = array([[1, 2, 5], + [3, 4, 6]]) + assert_equal(construct.hstack([A, B]).toarray(), expected) + assert_equal(construct.hstack([A, B], dtype=np.float32).dtype, + np.float32) + + assert_equal(construct.hstack([A.todok(), B.todok()]).toarray(), expected) + + assert_equal(construct.hstack([A.tocsc(), B.tocsc()]).toarray(), + expected) + assert_equal(construct.hstack([A.tocsc(), B.tocsc()], + dtype=np.float32).dtype, + np.float32) + assert_equal(construct.hstack([A.tocsr(), B.tocsr()]).toarray(), + expected) + assert_equal(construct.hstack([A.tocsr(), B.tocsr()], + dtype=np.float32).dtype, + np.float32) + + def test_hstack_matrix_or_array(self): + A = [[1,2],[3,4]] + B = [[5],[6]] + assert isinstance(construct.hstack([coo_array(A), coo_array(B)]), sparray) + assert isinstance(construct.hstack([coo_array(A), coo_matrix(B)]), sparray) + assert isinstance(construct.hstack([coo_matrix(A), coo_array(B)]), sparray) + assert isinstance(construct.hstack([coo_matrix(A), coo_matrix(B)]), spmatrix) + + @pytest.mark.parametrize("block_array", (construct.bmat, construct.block_array)) + def test_block_creation(self, block_array): + + A = coo_array([[1, 2], [3, 4]]) + B = coo_array([[5],[6]]) + C = coo_array([[7]]) + D = coo_array((0, 0)) + + expected = array([[1, 2, 5], + [3, 4, 6], + [0, 0, 7]]) + assert_equal(block_array([[A, B], [None, C]]).toarray(), expected) + E = csr_array((1, 2), dtype=np.int32) + assert_equal(block_array([[A.tocsr(), B.tocsr()], + [E, C.tocsr()]]).toarray(), + expected) + assert_equal(block_array([[A.tocsc(), B.tocsc()], + [E.tocsc(), C.tocsc()]]).toarray(), + expected) + + expected = array([[1, 2, 0], + [3, 4, 0], + [0, 0, 7]]) + assert_equal(block_array([[A, None], [None, C]]).toarray(), expected) + assert_equal(block_array([[A.tocsr(), E.T.tocsr()], + [E, C.tocsr()]]).toarray(), + expected) + assert_equal(block_array([[A.tocsc(), E.T.tocsc()], + [E.tocsc(), C.tocsc()]]).toarray(), + expected) + + Z = csr_array((1, 1), dtype=np.int32) + expected = array([[0, 5], + [0, 6], + [7, 0]]) + assert_equal(block_array([[None, B], [C, None]]).toarray(), expected) + assert_equal(block_array([[E.T.tocsr(), B.tocsr()], + [C.tocsr(), Z]]).toarray(), + expected) + assert_equal(block_array([[E.T.tocsc(), B.tocsc()], + [C.tocsc(), Z.tocsc()]]).toarray(), + expected) + + expected = np.empty((0, 0)) + assert_equal(block_array([[None, None]]).toarray(), expected) + assert_equal(block_array([[None, D], [D, None]]).toarray(), + expected) + + # test bug reported in gh-5976 + expected = array([[7]]) + assert_equal(block_array([[None, D], [C, None]]).toarray(), + expected) + + # test failure cases + with assert_raises(ValueError) as excinfo: + block_array([[A], [B]]) + excinfo.match(r'Got blocks\[1,0\]\.shape\[1\] == 1, expected 2') + + with assert_raises(ValueError) as excinfo: + block_array([[A.tocsr()], [B.tocsr()]]) + excinfo.match(r'incompatible dimensions for axis 1') + + with assert_raises(ValueError) as excinfo: + block_array([[A.tocsc()], [B.tocsc()]]) + excinfo.match(r'Mismatching dimensions along axis 1: ({1, 2}|{2, 1})') + + with assert_raises(ValueError) as excinfo: + block_array([[A, C]]) + excinfo.match(r'Got blocks\[0,1\]\.shape\[0\] == 1, expected 2') + + with assert_raises(ValueError) as excinfo: + block_array([[A.tocsr(), C.tocsr()]]) + excinfo.match(r'Mismatching dimensions along axis 0: ({1, 2}|{2, 1})') + + with assert_raises(ValueError) as excinfo: + block_array([[A.tocsc(), C.tocsc()]]) + excinfo.match(r'incompatible dimensions for axis 0') + + def test_block_return_type(self): + block = construct.block_array + + # csr format ensures we hit _compressed_sparse_stack + # shape of F,G ensure we hit _stack_along_minor_axis + # list version ensure we hit the path with neither helper function + Fl, Gl = [[1, 2],[3, 4]], [[7], [5]] + Fm, Gm = csr_matrix(Fl), csr_matrix(Gl) + assert isinstance(block([[None, Fl], [Gl, None]], format="csr"), sparray) + assert isinstance(block([[None, Fm], [Gm, None]], format="csr"), sparray) + assert isinstance(block([[Fm, Gm]], format="csr"), sparray) + + def test_bmat_return_type(self): + """This can be removed after sparse matrix is removed""" + bmat = construct.bmat + # check return type. if any input _is_array output array, else matrix + Fl, Gl = [[1, 2],[3, 4]], [[7], [5]] + Fm, Gm = csr_matrix(Fl), csr_matrix(Gl) + Fa, Ga = csr_array(Fl), csr_array(Gl) + assert isinstance(bmat([[Fa, Ga]], format="csr"), sparray) + assert isinstance(bmat([[Fm, Gm]], format="csr"), spmatrix) + assert isinstance(bmat([[None, Fa], [Ga, None]], format="csr"), sparray) + assert isinstance(bmat([[None, Fm], [Ga, None]], format="csr"), sparray) + assert isinstance(bmat([[None, Fm], [Gm, None]], format="csr"), spmatrix) + assert isinstance(bmat([[None, Fl], [Gl, None]], format="csr"), spmatrix) + + # type returned by _compressed_sparse_stack (all csr) + assert isinstance(bmat([[Ga, Ga]], format="csr"), sparray) + assert isinstance(bmat([[Gm, Ga]], format="csr"), sparray) + assert isinstance(bmat([[Ga, Gm]], format="csr"), sparray) + assert isinstance(bmat([[Gm, Gm]], format="csr"), spmatrix) + # shape is 2x2 so no _stack_along_minor_axis + assert isinstance(bmat([[Fa, Fm]], format="csr"), sparray) + assert isinstance(bmat([[Fm, Fm]], format="csr"), spmatrix) + + # type returned by _compressed_sparse_stack (all csc) + assert isinstance(bmat([[Gm.tocsc(), Ga.tocsc()]], format="csc"), sparray) + assert isinstance(bmat([[Gm.tocsc(), Gm.tocsc()]], format="csc"), spmatrix) + # shape is 2x2 so no _stack_along_minor_axis + assert isinstance(bmat([[Fa.tocsc(), Fm.tocsc()]], format="csr"), sparray) + assert isinstance(bmat([[Fm.tocsc(), Fm.tocsc()]], format="csr"), spmatrix) + + # type returned when mixed input + assert isinstance(bmat([[Gl, Ga]], format="csr"), sparray) + assert isinstance(bmat([[Gm.tocsc(), Ga]], format="csr"), sparray) + assert isinstance(bmat([[Gm.tocsc(), Gm]], format="csr"), spmatrix) + assert isinstance(bmat([[Gm, Gm]], format="csc"), spmatrix) + + @pytest.mark.slow + @pytest.mark.thread_unsafe + @pytest.mark.xfail_on_32bit("Can't create large array for test") + def test_concatenate_int32_overflow(self): + """ test for indptr overflow when concatenating matrices """ + check_free_memory(30000) + + n = 33000 + A = csr_array(np.ones((n, n), dtype=bool)) + B = A.copy() + C = construct._compressed_sparse_stack((A, B), axis=0, + return_spmatrix=False) + + assert_(np.all(np.equal(np.diff(C.indptr), n))) + assert_equal(C.indices.dtype, np.int64) + assert_equal(C.indptr.dtype, np.int64) + + def test_block_diag_basic(self): + """ basic test for block_diag """ + A = coo_array([[1,2],[3,4]]) + B = coo_array([[5],[6]]) + C = coo_array([[7]]) + + expected = array([[1, 2, 0, 0], + [3, 4, 0, 0], + [0, 0, 5, 0], + [0, 0, 6, 0], + [0, 0, 0, 7]]) + + ABC = construct.block_diag((A, B, C)) + assert_equal(ABC.toarray(), expected) + assert ABC.coords[0].dtype == np.int32 + + def test_block_diag_idx_dtype(self): + X = coo_array([[1, 0, 0], [0, 1, 0], [0, 1, 0]]) + X.coords = tuple(co.astype(np.int64) for co in X.coords) + assert construct.block_diag([X, X]).coords[0].dtype == np.int64 + + def test_block_diag_scalar_1d_args(self): + """ block_diag with scalar and 1d arguments """ + # one 1d matrix and a scalar + assert_array_equal(construct.block_diag([[2,3], 4]).toarray(), + [[2, 3, 0], [0, 0, 4]]) + # 1d sparse arrays + A = coo_array([1,0,3]) + B = coo_array([0,4]) + assert_array_equal(construct.block_diag([A, B]).toarray(), + [[1, 0, 3, 0, 0], [0, 0, 0, 0, 4]]) + + def test_block_diag_1(self): + """ block_diag with one matrix """ + assert_equal(construct.block_diag([[1, 0]]).toarray(), + array([[1, 0]])) + assert_equal(construct.block_diag([[[1, 0]]]).toarray(), + array([[1, 0]])) + assert_equal(construct.block_diag([[[1], [0]]]).toarray(), + array([[1], [0]])) + # just on scalar + assert_equal(construct.block_diag([1]).toarray(), + array([[1]])) + + def test_block_diag_sparse_arrays(self): + """ block_diag with sparse arrays """ + + A = coo_array([[1, 2, 3]], shape=(1, 3)) + B = coo_array([[4, 5]], shape=(1, 2)) + assert_equal(construct.block_diag([A, B]).toarray(), + array([[1, 2, 3, 0, 0], [0, 0, 0, 4, 5]])) + + A = coo_array([[1], [2], [3]], shape=(3, 1)) + B = coo_array([[4], [5]], shape=(2, 1)) + assert_equal(construct.block_diag([A, B]).toarray(), + array([[1, 0], [2, 0], [3, 0], [0, 4], [0, 5]])) + + def test_block_diag_return_type(self): + A, B = coo_array([[1, 2, 3]]), coo_matrix([[2, 3, 4]]) + assert isinstance(construct.block_diag([A, A]), sparray) + assert isinstance(construct.block_diag([A, B]), sparray) + assert isinstance(construct.block_diag([B, A]), sparray) + assert isinstance(construct.block_diag([B, B]), spmatrix) + + def test_random_sampling(self): + # Simple sanity checks for sparse random sampling. + for f in sprand, _sprandn: + for t in [np.float32, np.float64, np.longdouble, + np.int32, np.int64, np.complex64, np.complex128]: + x = f(5, 10, density=0.1, dtype=t) + assert_equal(x.dtype, t) + assert_equal(x.shape, (5, 10)) + assert_equal(x.nnz, 5) + + x1 = f(5, 10, density=0.1, rng=4321) + assert_equal(x1.dtype, np.float64) + + x2 = f(5, 10, density=0.1, rng=np.random.default_rng(4321)) + + assert_array_equal(x1.data, x2.data) + assert_array_equal(x1.row, x2.row) + assert_array_equal(x1.col, x2.col) + + for density in [0.0, 0.1, 0.5, 1.0]: + x = f(5, 10, density=density) + assert_equal(x.nnz, int(density * np.prod(x.shape))) + + for fmt in ['coo', 'csc', 'csr', 'lil']: + x = f(5, 10, format=fmt) + assert_equal(x.format, fmt) + + assert_raises(ValueError, lambda: f(5, 10, 1.1)) + assert_raises(ValueError, lambda: f(5, 10, -0.1)) + + @pytest.mark.parametrize("rng", [None, 4321, np.random.default_rng(4321)]) + def test_rand(self, rng): + # Simple distributional checks for sparse.rand. + x = sprand(10, 20, density=0.5, dtype=np.float64, rng=rng) + assert_(np.all(np.less_equal(0, x.data))) + assert_(np.all(np.less_equal(x.data, 1))) + + @pytest.mark.parametrize("rng", [None, 4321, np.random.default_rng(4321)]) + def test_randn(self, rng): + # Simple distributional checks for sparse.randn. + # Statistically, some of these should be negative + # and some should be greater than 1. + x = _sprandn(10, 20, density=0.5, dtype=np.float64, rng=rng) + assert_(np.any(np.less(x.data, 0))) + assert_(np.any(np.less(1, x.data))) + x = _sprandn_array(10, 20, density=0.5, dtype=np.float64, rng=rng) + assert_(np.any(np.less(x.data, 0))) + assert_(np.any(np.less(1, x.data))) + + def test_random_accept_str_dtype(self): + # anything that np.dtype can convert to a dtype should be accepted + # for the dtype + construct.random(10, 10, dtype='d') + construct.random_array((10, 10), dtype='d') + construct.random_array((10, 10, 10), dtype='d') + construct.random_array((10, 10, 10, 10, 10), dtype='d') + + def test_random_array_maintains_array_shape(self): + # preserve use of old random_state during SPEC 7 transition + arr = construct.random_array((0, 4), density=0.3, dtype=int, random_state=0) + assert arr.shape == (0, 4) + + arr = construct.random_array((10, 10, 10), density=0.3, dtype=int, rng=0) + assert arr.shape == (10, 10, 10) + + arr = construct.random_array((10, 10, 10, 10, 10), density=0.3, dtype=int, + rng=0) + assert arr.shape == (10, 10, 10, 10, 10) + + def test_random_array_idx_dtype(self): + A = construct.random_array((10, 10)) + assert A.coords[0].dtype == np.int32 + + def test_random_sparse_matrix_returns_correct_number_of_non_zero_elements(self): + # A 10 x 10 matrix, with density of 12.65%, should have 13 nonzero elements. + # 10 x 10 x 0.1265 = 12.65, which should be rounded up to 13, not 12. + sparse_matrix = construct.random(10, 10, density=0.1265) + assert_equal(sparse_matrix.count_nonzero(),13) + # check random_array + sparse_array = construct.random_array((10, 10), density=0.1265) + assert_equal(sparse_array.count_nonzero(),13) + assert isinstance(sparse_array, sparray) + # check big size + shape = (2**33, 2**33) + sparse_array = construct.random_array(shape, density=2.7105e-17) + assert_equal(sparse_array.count_nonzero(),2000) + + # for n-D + # check random_array + sparse_array = construct.random_array((10, 10, 10, 10), density=0.12658) + assert_equal(sparse_array.count_nonzero(),1266) + assert isinstance(sparse_array, sparray) + # check big size + shape = (2**33, 2**33, 2**33) + sparse_array = construct.random_array(shape, density=2.7105e-28) + assert_equal(sparse_array.count_nonzero(),172) + + +def test_diags_array(): + """Tests of diags_array that do not rely on diags wrapper.""" + diag = np.arange(1, 5) + + assert_array_equal(construct.diags_array(diag).toarray(), np.diag(diag)) + + assert_array_equal( + construct.diags_array(diag, offsets=2).toarray(), np.diag(diag, k=2) + ) + + assert_array_equal( + construct.diags_array(diag, offsets=2, shape=(4, 4)).toarray(), + np.diag(diag, k=2)[:4, :4] + ) + + # Offset outside bounds when shape specified + with pytest.raises(ValueError, match=".*out of bounds"): + construct.diags(np.arange(1, 5), 5, shape=(4, 4)) diff --git a/shared/package-files/01/01acd960ca30f6ccdbbc2fd67cad747398fe2d0440ce7a3a57558909bb69e0c5/blob b/shared/package-files/01/01acd960ca30f6ccdbbc2fd67cad747398fe2d0440ce7a3a57558909bb69e0c5/blob new file mode 100644 index 0000000000000000000000000000000000000000..59935d1abade2f39a58380d6e6f89d99c6dd3051 --- /dev/null +++ b/shared/package-files/01/01acd960ca30f6ccdbbc2fd67cad747398fe2d0440ce7a3a57558909bb69e0c5/blob @@ -0,0 +1,179 @@ +from sympy.core.numbers import (I, Rational, oo, pi, zoo) +from sympy.core.singleton import S +from sympy.core.symbol import (Dummy, Symbol) +from sympy.functions.elementary.hyperbolic import atanh +from sympy.functions.elementary.miscellaneous import sqrt +from sympy.functions.elementary.trigonometric import (sin, tan) +from sympy.functions.special.gamma_functions import gamma +from sympy.functions.special.hyper import (hyper, meijerg) +from sympy.integrals.integrals import Integral +from sympy.series.order import O +from sympy.functions.special.elliptic_integrals import (elliptic_k as K, + elliptic_f as F, elliptic_e as E, elliptic_pi as P) +from sympy.core.random import (test_derivative_numerically as td, + random_complex_number as randcplx, + verify_numerically as tn) +from sympy.abc import z, m, n + +i = Symbol('i', integer=True) +j = Symbol('k', integer=True, positive=True) +t = Dummy('t') + +def test_K(): + assert K(0) == pi/2 + assert K(S.Half) == 8*pi**Rational(3, 2)/gamma(Rational(-1, 4))**2 + assert K(1) is zoo + assert K(-1) == gamma(Rational(1, 4))**2/(4*sqrt(2*pi)) + assert K(oo) == 0 + assert K(-oo) == 0 + assert K(I*oo) == 0 + assert K(-I*oo) == 0 + assert K(zoo) == 0 + + assert K(z).diff(z) == (E(z) - (1 - z)*K(z))/(2*z*(1 - z)) + assert td(K(z), z) + + zi = Symbol('z', real=False) + assert K(zi).conjugate() == K(zi.conjugate()) + zr = Symbol('z', negative=True) + assert K(zr).conjugate() == K(zr) + + assert K(z).rewrite(hyper) == \ + (pi/2)*hyper((S.Half, S.Half), (S.One,), z) + assert tn(K(z), (pi/2)*hyper((S.Half, S.Half), (S.One,), z)) + assert K(z).rewrite(meijerg) == \ + meijerg(((S.Half, S.Half), []), ((S.Zero,), (S.Zero,)), -z)/2 + assert tn(K(z), meijerg(((S.Half, S.Half), []), ((S.Zero,), (S.Zero,)), -z)/2) + + assert K(z).series(z) == pi/2 + pi*z/8 + 9*pi*z**2/128 + \ + 25*pi*z**3/512 + 1225*pi*z**4/32768 + 3969*pi*z**5/131072 + O(z**6) + + assert K(m).rewrite(Integral).dummy_eq( + Integral(1/sqrt(1 - m*sin(t)**2), (t, 0, pi/2))) + +def test_F(): + assert F(z, 0) == z + assert F(0, m) == 0 + assert F(pi*i/2, m) == i*K(m) + assert F(z, oo) == 0 + assert F(z, -oo) == 0 + + assert F(-z, m) == -F(z, m) + + assert F(z, m).diff(z) == 1/sqrt(1 - m*sin(z)**2) + assert F(z, m).diff(m) == E(z, m)/(2*m*(1 - m)) - F(z, m)/(2*m) - \ + sin(2*z)/(4*(1 - m)*sqrt(1 - m*sin(z)**2)) + r = randcplx() + assert td(F(z, r), z) + assert td(F(r, m), m) + + mi = Symbol('m', real=False) + assert F(z, mi).conjugate() == F(z.conjugate(), mi.conjugate()) + mr = Symbol('m', negative=True) + assert F(z, mr).conjugate() == F(z.conjugate(), mr) + + assert F(z, m).series(z) == \ + z + z**5*(3*m**2/40 - m/30) + m*z**3/6 + O(z**6) + + assert F(z, m).rewrite(Integral).dummy_eq( + Integral(1/sqrt(1 - m*sin(t)**2), (t, 0, z))) + +def test_E(): + assert E(z, 0) == z + assert E(0, m) == 0 + assert E(i*pi/2, m) == i*E(m) + assert E(z, oo) is zoo + assert E(z, -oo) is zoo + assert E(0) == pi/2 + assert E(1) == 1 + assert E(oo) == I*oo + assert E(-oo) is oo + assert E(zoo) is zoo + + assert E(-z, m) == -E(z, m) + + assert E(z, m).diff(z) == sqrt(1 - m*sin(z)**2) + assert E(z, m).diff(m) == (E(z, m) - F(z, m))/(2*m) + assert E(z).diff(z) == (E(z) - K(z))/(2*z) + r = randcplx() + assert td(E(r, m), m) + assert td(E(z, r), z) + assert td(E(z), z) + + mi = Symbol('m', real=False) + assert E(z, mi).conjugate() == E(z.conjugate(), mi.conjugate()) + assert E(mi).conjugate() == E(mi.conjugate()) + mr = Symbol('m', negative=True) + assert E(z, mr).conjugate() == E(z.conjugate(), mr) + assert E(mr).conjugate() == E(mr) + + assert E(z).rewrite(hyper) == (pi/2)*hyper((Rational(-1, 2), S.Half), (S.One,), z) + assert tn(E(z), (pi/2)*hyper((Rational(-1, 2), S.Half), (S.One,), z)) + assert E(z).rewrite(meijerg) == \ + -meijerg(((S.Half, Rational(3, 2)), []), ((S.Zero,), (S.Zero,)), -z)/4 + assert tn(E(z), -meijerg(((S.Half, Rational(3, 2)), []), ((S.Zero,), (S.Zero,)), -z)/4) + + assert E(z, m).series(z) == \ + z + z**5*(-m**2/40 + m/30) - m*z**3/6 + O(z**6) + assert E(z).series(z) == pi/2 - pi*z/8 - 3*pi*z**2/128 - \ + 5*pi*z**3/512 - 175*pi*z**4/32768 - 441*pi*z**5/131072 + O(z**6) + + assert E(z, m).rewrite(Integral).dummy_eq( + Integral(sqrt(1 - m*sin(t)**2), (t, 0, z))) + assert E(m).rewrite(Integral).dummy_eq( + Integral(sqrt(1 - m*sin(t)**2), (t, 0, pi/2))) + +def test_P(): + assert P(0, z, m) == F(z, m) + assert P(1, z, m) == F(z, m) + \ + (sqrt(1 - m*sin(z)**2)*tan(z) - E(z, m))/(1 - m) + assert P(n, i*pi/2, m) == i*P(n, m) + assert P(n, z, 0) == atanh(sqrt(n - 1)*tan(z))/sqrt(n - 1) + assert P(n, z, n) == F(z, n) - P(1, z, n) + tan(z)/sqrt(1 - n*sin(z)**2) + assert P(oo, z, m) == 0 + assert P(-oo, z, m) == 0 + assert P(n, z, oo) == 0 + assert P(n, z, -oo) == 0 + assert P(0, m) == K(m) + assert P(1, m) is zoo + assert P(n, 0) == pi/(2*sqrt(1 - n)) + assert P(2, 1) is -oo + assert P(-1, 1) is oo + assert P(n, n) == E(n)/(1 - n) + + assert P(n, -z, m) == -P(n, z, m) + + ni, mi = Symbol('n', real=False), Symbol('m', real=False) + assert P(ni, z, mi).conjugate() == \ + P(ni.conjugate(), z.conjugate(), mi.conjugate()) + nr, mr = Symbol('n', negative=True), \ + Symbol('m', negative=True) + assert P(nr, z, mr).conjugate() == P(nr, z.conjugate(), mr) + assert P(n, m).conjugate() == P(n.conjugate(), m.conjugate()) + + assert P(n, z, m).diff(n) == (E(z, m) + (m - n)*F(z, m)/n + + (n**2 - m)*P(n, z, m)/n - n*sqrt(1 - + m*sin(z)**2)*sin(2*z)/(2*(1 - n*sin(z)**2)))/(2*(m - n)*(n - 1)) + assert P(n, z, m).diff(z) == 1/(sqrt(1 - m*sin(z)**2)*(1 - n*sin(z)**2)) + assert P(n, z, m).diff(m) == (E(z, m)/(m - 1) + P(n, z, m) - + m*sin(2*z)/(2*(m - 1)*sqrt(1 - m*sin(z)**2)))/(2*(n - m)) + assert P(n, m).diff(n) == (E(m) + (m - n)*K(m)/n + + (n**2 - m)*P(n, m)/n)/(2*(m - n)*(n - 1)) + assert P(n, m).diff(m) == (E(m)/(m - 1) + P(n, m))/(2*(n - m)) + + # These tests fail due to + # https://github.com/fredrik-johansson/mpmath/issues/571#issuecomment-777201962 + # https://github.com/sympy/sympy/issues/20933#issuecomment-777080385 + # + # rx, ry = randcplx(), randcplx() + # assert td(P(n, rx, ry), n) + # assert td(P(rx, z, ry), z) + # assert td(P(rx, ry, m), m) + + assert P(n, z, m).series(z) == z + z**3*(m/6 + n/3) + \ + z**5*(3*m**2/40 + m*n/10 - m/30 + n**2/5 - n/15) + O(z**6) + + assert P(n, z, m).rewrite(Integral).dummy_eq( + Integral(1/((1 - n*sin(t)**2)*sqrt(1 - m*sin(t)**2)), (t, 0, z))) + assert P(n, m).rewrite(Integral).dummy_eq( + Integral(1/((1 - n*sin(t)**2)*sqrt(1 - m*sin(t)**2)), (t, 0, pi/2))) diff --git a/shared/package-files/01/01b20c23e9ca7c868b86b6bd109e153f4e21bd6aeec88522ef93976c6f4c2e7d/blob b/shared/package-files/01/01b20c23e9ca7c868b86b6bd109e153f4e21bd6aeec88522ef93976c6f4c2e7d/blob new file mode 100644 index 0000000000000000000000000000000000000000..9b0c42399e9ab626c250bef0e5b2434515aebea7 --- /dev/null +++ b/shared/package-files/01/01b20c23e9ca7c868b86b6bd109e153f4e21bd6aeec88522ef93976c6f4c2e7d/blob @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:01b20c23e9ca7c868b86b6bd109e153f4e21bd6aeec88522ef93976c6f4c2e7d +size 1589832 diff --git a/shared/package-files/01/01b2231bf45b5a2df0b91411f8e03786e366662e5824ea4c99353a66656e8017/blob b/shared/package-files/01/01b2231bf45b5a2df0b91411f8e03786e366662e5824ea4c99353a66656e8017/blob new file mode 100644 index 0000000000000000000000000000000000000000..514c2d932f171c942833430cfe4cd7c9dd50298c --- /dev/null +++ b/shared/package-files/01/01b2231bf45b5a2df0b91411f8e03786e366662e5824ea4c99353a66656e8017/blob @@ -0,0 +1,231 @@ +import numpy as np +from scipy.optimize import minimize_scalar + +from statsmodels.robust import mad +from statsmodels.tools.validation import string_like + + +class BoxCox: + """ + Mixin class to allow for a Box-Cox transformation. + """ + + def transform_boxcox(self, x, lmbda=None, method="guerrero", **kwargs): + """ + Performs a Box-Cox transformation on the data array x. If lmbda is None, + the indicated method is used to estimate a suitable lambda parameter. + + Parameters + ---------- + x : array_like + The data to transform. + lmbda : float or None, optional + The lambda parameter for the Box-Cox transform. If None, a value + will be estimated by means of the specified method. + method : {'guerrero', 'loglik'}, optional + The method to estimate the lambda parameter. Will only be used if + lmbda is None, and defaults to 'guerrero', detailed in Guerrero + (1993). 'loglik' maximizes the profile likelihood. + **kwargs + Options for the specified method. + * For 'guerrero', this entails window_length, the grouping + parameter, scale, the dispersion measure, and options, to be + passed to the optimizer. + * For 'loglik': options, to be passed to the optimizer. + + Returns + ------- + y : ndarray + The transformed series. + lmbda : float + The lmbda parameter used to transform the series. + + References + ---------- + Guerrero, Victor M. 1993. "Time-series analysis supported by power + transformations". *Journal of Forecasting*. 12 (1): 37-48. + + Guerrero, Victor M. and Perera, Rafael. 2004. "Variance Stabilizing + Power Transformation for Time Series," *Journal of Modern Applied + Statistical Methods*. 3 (2): 357-369. + + Box, G. E. P., and D. R. Cox. 1964. "An Analysis of Transformations". + *Journal of the Royal Statistical Society*. 26 (2): 211-252. + """ + x = np.asarray(x) + + if np.any(x <= 0): + raise ValueError("Non-positive x.") + + if lmbda is None: + lmbda = self._est_lambda(x, method=method, **kwargs) + + # if less than 0.01, treat lambda as zero. + if np.isclose(lmbda, 0.0): + y = np.log(x) + else: + y = (np.power(x, lmbda) - 1.0) / lmbda + + return y, lmbda + + def untransform_boxcox(self, x, lmbda, method="naive"): + """ + Back-transforms the Box-Cox transformed data array, by means of the + indicated method. The provided argument lmbda should be the lambda + parameter that was used to initially transform the data. + + Parameters + ---------- + x : array_like + The transformed series. + lmbda : float + The lambda parameter that was used to transform the series. + method : {'naive'}, optional + Indicates the method to be used in the untransformation. Defaults + to 'naive', which reverses the transformation. + + NOTE: 'naive' is implemented natively, while other methods may be + available in subclasses! + + Returns + ------- + y : ndarray + The untransformed series. + """ + method = string_like(method, "method", options=("naive",)) + x = np.asarray(x) + + if method == "naive": + if np.isclose(lmbda, 0.0): + y = np.exp(x) + else: + y = np.power(lmbda * x + 1, 1.0 / lmbda) + + return y + + def _est_lambda(self, x, bounds=(-1, 2), method="guerrero", **kwargs): + """ + Computes an estimate for the lambda parameter in the Box-Cox + transformation using method. + + Parameters + ---------- + x : array_like + The untransformed data. + bounds : tuple, optional + Numeric 2-tuple, that indicate the solution space for the lambda + parameter. Default (-1, 2). + method : {'guerrero', 'loglik'}, optional + The method by which to estimate lambda. Defaults to 'guerrero', but + the profile likelihood ('loglik') is also available. + **kwargs + Options for the specified method. + * For 'guerrero': window_length (int), the seasonality/grouping + parameter. Scale ({'mad', 'sd'}), the dispersion measure. Options + (dict), to be passed to the optimizer. + * For 'loglik': Options (dict), to be passed to the optimizer. + + Returns + ------- + lmbda : float + The lambda parameter. + """ + method = string_like(method, "method", options=("guerrero", "loglik")) + + if len(bounds) != 2: + raise ValueError(f"Bounds of length {len(bounds)} not understood.") + elif bounds[0] >= bounds[1]: + raise ValueError("Lower bound exceeds upper bound.") + + if method == "guerrero": + lmbda = self._guerrero_cv(x, bounds=bounds, **kwargs) + else: # method == "loglik" + lmbda = self._loglik_boxcox(x, bounds=bounds, **kwargs) + + return lmbda + + def _guerrero_cv(self, x, bounds, window_length=4, scale="sd", options=None): + """ + Computes lambda using guerrero's coefficient of variation. If no + seasonality is present in the data, window_length is set to 4 (as + per Guerrero and Perera, (2004)). + + NOTE: Seasonality-specific auxiliaries *should* provide their own + seasonality parameter. + + Parameters + ---------- + x : array_like + The untransformed data. + bounds : tuple + Numeric 2-tuple, that indicate the solution space for the lambda + parameter. + window_length : int, optional + Seasonality/grouping parameter. Default 4, as per Guerrero and + Perera (2004). NOTE: this indicates the length of the individual + groups, not the total number of groups! + scale : {'sd', 'mad'}, optional + The dispersion measure to be used. 'sd' indicates the sample + standard deviation, but the more robust 'mad' is also available. + options : dict, optional + The options (as a dict) to be passed to the optimizer. + + Returns + ------- + float + The estimated lambda parameter. + """ + options = {"maxiter": 25} if options is None else options + nobs = len(x) + groups = int(nobs / window_length) + + # remove the first n < window_length observations from consideration. + grouped_data = np.reshape( + x[nobs - (groups * window_length) : nobs], (groups, window_length) + ) + mean = np.mean(grouped_data, 1) + + scale = string_like(scale, "scale", options=("sd", "mad")) + if scale == "sd": + dispersion = np.std(grouped_data, 1, ddof=1) + else: # scale == "mad" + dispersion = mad(grouped_data, axis=1) + + def optim(lmbda): + rat = np.divide(dispersion, np.power(mean, 1 - lmbda)) # eq 6, p 40 + return np.std(rat, ddof=1) / np.mean(rat) + + res = minimize_scalar(optim, bounds=bounds, method="bounded", options=options) + return res.x + + def _loglik_boxcox(self, x, bounds, options=None): + """ + Taken from the Stata manual on Box-Cox regressions, where this is the + special case of 'lhs only'. As an estimator for the variance, the + sample variance is used, by means of the well-known formula. + + Parameters + ---------- + x : array_like + The untransformed data. + bounds : tuple + Numeric 2-tuple, that indicate the solution space for the lambda + parameter. + options : dict, optional + The options (as a dict) to be passed to the optimizer. + + Returns + ------- + float + The estimated lambda parameter. + """ + options = {"maxiter": 25} if options is None else options + sum_x = np.sum(np.log(x)) + nobs = len(x) + + def optim(lmbda): + y, lmbda = self.transform_boxcox(x, lmbda) + return (1 - lmbda) * sum_x + (nobs / 2.0) * np.log(np.var(y)) + + res = minimize_scalar(optim, bounds=bounds, method="bounded", options=options) + return res.x diff --git a/shared/package-files/01/01b25e52251098399ddcaf7f3c6c55bf156183e9550f372be6c0a5c2d6eddaa2/blob b/shared/package-files/01/01b25e52251098399ddcaf7f3c6c55bf156183e9550f372be6c0a5c2d6eddaa2/blob new file mode 100644 index 0000000000000000000000000000000000000000..c2d5d2769afe2d2ea6140ab68a94e42bf71457a6 Binary files /dev/null and b/shared/package-files/01/01b25e52251098399ddcaf7f3c6c55bf156183e9550f372be6c0a5c2d6eddaa2/blob differ diff --git a/shared/package-files/01/01b2a9b1084b6a0424f27eec488c761f75f053a409608ec36a9ee0ede0d38097/blob b/shared/package-files/01/01b2a9b1084b6a0424f27eec488c761f75f053a409608ec36a9ee0ede0d38097/blob new file mode 100644 index 0000000000000000000000000000000000000000..c7982c2b97c3e1cacf5812a9ddd9d20fdda66496 --- /dev/null +++ b/shared/package-files/01/01b2a9b1084b6a0424f27eec488c761f75f053a409608ec36a9ee0ede0d38097/blob @@ -0,0 +1,42 @@ +r"""Fixer for unicode. + +* Changes unicode to str and unichr to chr. + +* If "...\u..." is not unicode literal change it into "...\\u...". + +* Change u"..." into "...". + +""" + +from ..pgen2 import token +from .. import fixer_base + +_mapping = {"unichr" : "chr", "unicode" : "str"} + +class FixUnicode(fixer_base.BaseFix): + BM_compatible = True + PATTERN = "STRING | 'unicode' | 'unichr'" + + def start_tree(self, tree, filename): + super(FixUnicode, self).start_tree(tree, filename) + self.unicode_literals = 'unicode_literals' in tree.future_features + + def transform(self, node, results): + if node.type == token.NAME: + new = node.clone() + new.value = _mapping[node.value] + return new + elif node.type == token.STRING: + val = node.value + if not self.unicode_literals and val[0] in '\'"' and '\\' in val: + val = r'\\'.join([ + v.replace('\\u', r'\\u').replace('\\U', r'\\U') + for v in val.split(r'\\') + ]) + if val[0] in 'uU': + val = val[1:] + if val == node.value: + return node + new = node.clone() + new.value = val + return new diff --git a/shared/package-files/01/01b4354929dced7355fdc73abd07198b7a375458068d3734a2888cbab89857f5/blob b/shared/package-files/01/01b4354929dced7355fdc73abd07198b7a375458068d3734a2888cbab89857f5/blob new file mode 100644 index 0000000000000000000000000000000000000000..45fe2f844f1db78d1f094756f291821352f17696 --- /dev/null +++ b/shared/package-files/01/01b4354929dced7355fdc73abd07198b7a375458068d3734a2888cbab89857f5/blob @@ -0,0 +1,96 @@ +""" +Created on Mar. 12, 2024 11:10:14 a.m. + +Author: Josef Perktold +License: BSD-3 +""" + +import numpy as np +from numpy.testing import assert_allclose +import pytest + +from statsmodels.robust.norms import ( + AndrewWave, + Hampel, + HuberT, + StudentT, + TrimmedMean, + TukeyBiweight, + TukeyQuartic, +) +from statsmodels.robust.tools import ( + _get_tuning_param, + _var_normal, + _var_normal_jump, + tuning_s_estimator_mean, +) + +effs = [0.9, 0.95, 0.98, 0.99] + +results_menenez = [ + (HuberT, {}, [0.9818, 1.345, 1.7459, 2.0102]), + (TukeyBiweight, {}, [3.8827, 4.6851, 5.9207, 7.0414]), + (TukeyQuartic, {}, [3.1576, 3.6175, 4.2103, 4.6664]), + (TukeyQuartic, dict(k=2), [3.8827, 4.6851, 5.9207, 7.0414]), # biweight + (StudentT, dict(df=1), [1.7249, 2.3849, 3.3962, 4.2904]), # Cauchy + (AndrewWave, {}, [1.1117, 1.338, 1.6930, 2.0170]), + # (Hampel(), [4.4209, 5.4, 7.00609, 8.0456]),ru + # rounding problem in Hampel, menenez use a as tuning parameter + (Hampel, {}, [4.4208, 5.5275, 7.006, 8.0456]), + (TrimmedMean, {}, [2.5003, 2.7955, 3.1365, 3.3682]), +] + + +@pytest.mark.slow +@pytest.mark.parametrize("case", results_menenez) +def test_eff(case): + norm_cls, norm_kwargs, res2 = case + norm = norm_cls(**norm_kwargs) + use_jump = False + + if norm.continuous == 2: + var_func = _var_normal + else: + var_func = _var_normal_jump + use_jump = True + + res_eff = [] + for c in res2: + norm._set_tuning_param(c, inplace=True) + res_eff.append(1 / var_func(norm)) + + assert_allclose(res_eff, effs, atol=0.0005) + + for c in res2: + # bp = stats.norm.expect(lambda x : norm.rho(x)) / norm.rho(norm.c) + norm._set_tuning_param(c, inplace=True) + eff = 1 / var_func(norm) + tune = _get_tuning_param(norm, eff, use_jump=use_jump) + assert_allclose(tune, c, rtol=1e-6, atol=5e-4) + + +def test_hampel_eff(): + # we cannot solve for multiple tuning parameters + eff = 0.95 + # tuning parameters from Menezes et al 2021 + res_eff = 1 / _var_normal_jump(Hampel(a=1.35, b=2.70, c=5.40)) + assert_allclose(res_eff, eff, atol=0.005) + + +def test_tuning_biweight(): + # regression numbers but verified at 5 decimals + norm = TukeyBiweight() + res = tuning_s_estimator_mean(norm, breakdown=0.5) + res1 = [0.28682611623149523, 1.5476449837305166, 0.1996004163055662] + assert_allclose(res.all[1:], res1, rtol=1e-7) + + +@pytest.mark.parametrize("case", results_menenez) +def test_tuning_smoke(case): + # regression numbers but verified at 5 decimals + norm_cls, norm_kwargs, _ = case + norm = norm_cls(**norm_kwargs) + # norm = Norm() + if np.isfinite(norm.max_rho()): + res = tuning_s_estimator_mean(norm, breakdown=0.5) + assert res is not None diff --git a/shared/package-files/01/01b4a63d6036791f6cc4b5382070bd69d5ee7138ded343f2732455a719faed38/blob b/shared/package-files/01/01b4a63d6036791f6cc4b5382070bd69d5ee7138ded343f2732455a719faed38/blob new file mode 100644 index 0000000000000000000000000000000000000000..10e5a1606fbdfa05181cf395000b421b065a85e3 --- /dev/null +++ b/shared/package-files/01/01b4a63d6036791f6cc4b5382070bd69d5ee7138ded343f2732455a719faed38/blob @@ -0,0 +1,22 @@ +#pragma once + +// @generated by torchgen/gen.py from NativeFunction.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + +namespace at { +namespace native { +TORCH_API at::Tensor & _cudnn_rnn_flatten_weight_out_symint(at::TensorList weight_arr, int64_t weight_stride0, c10::SymInt input_size, int64_t mode, c10::SymInt hidden_size, c10::SymInt proj_size, int64_t num_layers, bool batch_first, bool bidirectional, at::Tensor & out); +TORCH_API at::Tensor _cudnn_rnn_flatten_weight(at::TensorList weight_arr, int64_t weight_stride0, int64_t input_size, int64_t mode, int64_t hidden_size, int64_t proj_size, int64_t num_layers, bool batch_first, bool bidirectional); +} // namespace native +} // namespace at diff --git a/shared/package-files/01/01b59fd5021e9f39fd61590fad1662b2915ceb58e17fe2ef4566b01423326b9b/blob b/shared/package-files/01/01b59fd5021e9f39fd61590fad1662b2915ceb58e17fe2ef4566b01423326b9b/blob new file mode 100644 index 0000000000000000000000000000000000000000..e0607e9c0d5dc725a38083a9a4f1cc24feed3b14 --- /dev/null +++ b/shared/package-files/01/01b59fd5021e9f39fd61590fad1662b2915ceb58e17fe2ef4566b01423326b9b/blob @@ -0,0 +1,62 @@ +#!/usr/bin/env python3 + +# Copyright (c) Facebook, Inc. and its affiliates. +# All rights reserved. +# +# This source code is licensed under the BSD-style license found in the +# LICENSE file in the root directory of this source tree. + +import os +import socket +from string import Template +from typing import List, Any + + +def get_env_variable_or_raise(env_name: str) -> str: + r""" + Tries to retrieve environment variable. Raises ``ValueError`` + if no environment variable found. + + Args: + env_name (str): Name of the env variable + """ + value = os.environ.get(env_name, None) + if value is None: + msg = f"Environment variable {env_name} expected, but not set" + raise ValueError(msg) + return value + + +def get_socket_with_port() -> socket.socket: + addrs = socket.getaddrinfo( + host="localhost", port=None, family=socket.AF_UNSPEC, type=socket.SOCK_STREAM + ) + for addr in addrs: + family, type, proto, _, _ = addr + s = socket.socket(family, type, proto) + try: + s.bind(("localhost", 0)) + s.listen(0) + return s + except OSError as e: + s.close() + raise RuntimeError("Failed to create a socket") + + +class macros: + """ + Defines simple macros for caffe2.distributed.launch cmd args substitution + """ + + local_rank = "${local_rank}" + + @staticmethod + def substitute(args: List[Any], local_rank: str) -> List[str]: + args_sub = [] + for arg in args: + if isinstance(arg, str): + sub = Template(arg).safe_substitute(local_rank=local_rank) + args_sub.append(sub) + else: + args_sub.append(arg) + return args_sub diff --git a/shared/package-files/01/01b665feba503fd53684d00ca6f322550fa41d414e09da482ab97f48d64b8a5b/blob b/shared/package-files/01/01b665feba503fd53684d00ca6f322550fa41d414e09da482ab97f48d64b8a5b/blob new file mode 100644 index 0000000000000000000000000000000000000000..4b8c1850cd0dad3d654216ae45dad04dafaa983b --- /dev/null +++ b/shared/package-files/01/01b665feba503fd53684d00ca6f322550fa41d414e09da482ab97f48d64b8a5b/blob @@ -0,0 +1,11015 @@ +# Copyright 2002 Gary Strangman. All rights reserved +# Copyright 2002-2016 The SciPy Developers +# +# The original code from Gary Strangman was heavily adapted for +# use in SciPy by Travis Oliphant. The original code came with the +# following disclaimer: +# +# This software is provided "as-is". There are no expressed or implied +# warranties of any kind, including, but not limited to, the warranties +# of merchantability and fitness for a given application. In no event +# shall Gary Strangman be liable for any direct, indirect, incidental, +# special, exemplary or consequential damages (including, but not limited +# to, 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. + +""" +A collection of basic statistical functions for Python. + +References +---------- +.. [CRCProbStat2000] Zwillinger, D. and Kokoska, S. (2000). CRC Standard + Probability and Statistics Tables and Formulae. Chapman & Hall: New + York. 2000. + +""" +import warnings +import math +from math import gcd +from collections import namedtuple +from collections.abc import Sequence + +import numpy as np +from numpy import array, asarray, ma + +from scipy import sparse +from scipy.spatial import distance_matrix + +from scipy.optimize import milp, LinearConstraint +from scipy._lib._util import (check_random_state, _get_nan, + _rename_parameter, _contains_nan, + AxisError, _lazywhere) +from scipy._lib.deprecation import _deprecate_positional_args + + +import scipy.special as special +# Import unused here but needs to stay until end of deprecation periode +# See https://github.com/scipy/scipy/issues/15765#issuecomment-1875564522 +from scipy import linalg # noqa: F401 +from . import distributions +from . import _mstats_basic as mstats_basic + +from ._stats_mstats_common import _find_repeats, theilslopes, siegelslopes +from ._stats import _kendall_dis, _toint64, _weightedrankedtau + +from dataclasses import dataclass, field +from ._hypotests import _all_partitions +from ._stats_pythran import _compute_outer_prob_inside_method +from ._resampling import (MonteCarloMethod, PermutationMethod, BootstrapMethod, + monte_carlo_test, permutation_test, bootstrap, + _batch_generator) +from ._axis_nan_policy import (_axis_nan_policy_factory, + _broadcast_concatenate, _broadcast_shapes, + _broadcast_array_shapes_remove_axis, SmallSampleWarning, + too_small_1d_not_omit, too_small_1d_omit, + too_small_nd_not_omit, too_small_nd_omit) +from ._binomtest import _binary_search_for_binom_tst as _binary_search +from scipy._lib._bunch import _make_tuple_bunch +from scipy import stats +from scipy.optimize import root_scalar +from scipy._lib._util import normalize_axis_index +from scipy._lib._array_api import ( + _asarray, + array_namespace, + is_numpy, + xp_size, + xp_moveaxis_to_end, + xp_sign, + xp_vector_norm, + xp_broadcast_promote, +) +from scipy._lib import array_api_extra as xpx +from scipy._lib.deprecation import _deprecated + + +# Functions/classes in other files should be added in `__init__.py`, not here +__all__ = ['find_repeats', 'gmean', 'hmean', 'pmean', 'mode', 'tmean', 'tvar', + 'tmin', 'tmax', 'tstd', 'tsem', 'moment', + 'skew', 'kurtosis', 'describe', 'skewtest', 'kurtosistest', + 'normaltest', 'jarque_bera', + 'scoreatpercentile', 'percentileofscore', + 'cumfreq', 'relfreq', 'obrientransform', + 'sem', 'zmap', 'zscore', 'gzscore', 'iqr', 'gstd', + 'median_abs_deviation', + 'sigmaclip', 'trimboth', 'trim1', 'trim_mean', + 'f_oneway', 'pearsonr', 'fisher_exact', + 'spearmanr', 'pointbiserialr', + 'kendalltau', 'weightedtau', + 'linregress', 'siegelslopes', 'theilslopes', 'ttest_1samp', + 'ttest_ind', 'ttest_ind_from_stats', 'ttest_rel', + 'kstest', 'ks_1samp', 'ks_2samp', + 'chisquare', 'power_divergence', + 'tiecorrect', 'ranksums', 'kruskal', 'friedmanchisquare', + 'rankdata', 'combine_pvalues', 'quantile_test', + 'wasserstein_distance', 'wasserstein_distance_nd', 'energy_distance', + 'brunnermunzel', 'alexandergovern', + 'expectile', 'lmoment'] + + +def _chk_asarray(a, axis, *, xp=None): + if xp is None: + xp = array_namespace(a) + + if axis is None: + a = xp.reshape(a, (-1,)) + outaxis = 0 + else: + a = xp.asarray(a) + outaxis = axis + + if a.ndim == 0: + a = xp.reshape(a, (-1,)) + + return a, outaxis + + +def _chk2_asarray(a, b, axis): + if axis is None: + a = np.ravel(a) + b = np.ravel(b) + outaxis = 0 + else: + a = np.asarray(a) + b = np.asarray(b) + outaxis = axis + + if a.ndim == 0: + a = np.atleast_1d(a) + if b.ndim == 0: + b = np.atleast_1d(b) + + return a, b, outaxis + + +def _convert_common_float(*arrays, xp=None): + xp = array_namespace(*arrays) if xp is None else xp + arrays = [_asarray(array, subok=True) for array in arrays] + dtypes = [(xp.asarray(1.).dtype if xp.isdtype(array.dtype, 'integral') + else array.dtype) for array in arrays] + dtype = xp.result_type(*dtypes) + arrays = [xp.astype(array, dtype, copy=False) for array in arrays] + return arrays[0] if len(arrays)==1 else tuple(arrays) + + +SignificanceResult = _make_tuple_bunch('SignificanceResult', + ['statistic', 'pvalue'], []) + + +# note that `weights` are paired with `x` +@_axis_nan_policy_factory( + lambda x: x, n_samples=1, n_outputs=1, too_small=0, paired=True, + result_to_tuple=lambda x: (x,), kwd_samples=['weights']) +def gmean(a, axis=0, dtype=None, weights=None): + r"""Compute the weighted geometric mean along the specified axis. + + The weighted geometric mean of the array :math:`a_i` associated to weights + :math:`w_i` is: + + .. math:: + + \exp \left( \frac{ \sum_{i=1}^n w_i \ln a_i }{ \sum_{i=1}^n w_i } + \right) \, , + + and, with equal weights, it gives: + + .. math:: + + \sqrt[n]{ \prod_{i=1}^n a_i } \, . + + Parameters + ---------- + a : array_like + Input array or object that can be converted to an array. + axis : int or None, optional + Axis along which the geometric mean is computed. Default is 0. + If None, compute over the whole array `a`. + dtype : dtype, optional + Type to which the input arrays are cast before the calculation is + performed. + weights : array_like, optional + The `weights` array must be broadcastable to the same shape as `a`. + Default is None, which gives each value a weight of 1.0. + + Returns + ------- + gmean : ndarray + See `dtype` parameter above. + + See Also + -------- + numpy.mean : Arithmetic average + numpy.average : Weighted average + hmean : Harmonic mean + + Notes + ----- + The sample geometric mean is the exponential of the mean of the natural + logarithms of the observations. + Negative observations will produce NaNs in the output because the *natural* + logarithm (as opposed to the *complex* logarithm) is defined only for + non-negative reals. + + References + ---------- + .. [1] "Weighted Geometric Mean", *Wikipedia*, + https://en.wikipedia.org/wiki/Weighted_geometric_mean. + .. [2] Grossman, J., Grossman, M., Katz, R., "Averages: A New Approach", + Archimedes Foundation, 1983 + + Examples + -------- + >>> from scipy.stats import gmean + >>> gmean([1, 4]) + 2.0 + >>> gmean([1, 2, 3, 4, 5, 6, 7]) + 3.3800151591412964 + >>> gmean([1, 4, 7], weights=[3, 1, 3]) + 2.80668351922014 + + """ + xp = array_namespace(a, weights) + a = xp.asarray(a, dtype=dtype) + + if weights is not None: + weights = xp.asarray(weights, dtype=dtype) + + with np.errstate(divide='ignore'): + log_a = xp.log(a) + + return xp.exp(_xp_mean(log_a, axis=axis, weights=weights)) + + +@_axis_nan_policy_factory( + lambda x: x, n_samples=1, n_outputs=1, too_small=0, paired=True, + result_to_tuple=lambda x: (x,), kwd_samples=['weights']) +def hmean(a, axis=0, dtype=None, *, weights=None): + r"""Calculate the weighted harmonic mean along the specified axis. + + The weighted harmonic mean of the array :math:`a_i` associated to weights + :math:`w_i` is: + + .. math:: + + \frac{ \sum_{i=1}^n w_i }{ \sum_{i=1}^n \frac{w_i}{a_i} } \, , + + and, with equal weights, it gives: + + .. math:: + + \frac{ n }{ \sum_{i=1}^n \frac{1}{a_i} } \, . + + Parameters + ---------- + a : array_like + Input array, masked array or object that can be converted to an array. + axis : int or None, optional + Axis along which the harmonic mean is computed. Default is 0. + If None, compute over the whole array `a`. + dtype : dtype, optional + Type of the returned array and of the accumulator in which the + elements are summed. If `dtype` is not specified, it defaults to the + dtype of `a`, unless `a` has an integer `dtype` with a precision less + than that of the default platform integer. In that case, the default + platform integer is used. + weights : array_like, optional + The weights array can either be 1-D (in which case its length must be + the size of `a` along the given `axis`) or of the same shape as `a`. + Default is None, which gives each value a weight of 1.0. + + .. versionadded:: 1.9 + + Returns + ------- + hmean : ndarray + See `dtype` parameter above. + + See Also + -------- + numpy.mean : Arithmetic average + numpy.average : Weighted average + gmean : Geometric mean + + Notes + ----- + The sample harmonic mean is the reciprocal of the mean of the reciprocals + of the observations. + + The harmonic mean is computed over a single dimension of the input + array, axis=0 by default, or all values in the array if axis=None. + float64 intermediate and return values are used for integer inputs. + + The harmonic mean is only defined if all observations are non-negative; + otherwise, the result is NaN. + + References + ---------- + .. [1] "Weighted Harmonic Mean", *Wikipedia*, + https://en.wikipedia.org/wiki/Harmonic_mean#Weighted_harmonic_mean + .. [2] Ferger, F., "The nature and use of the harmonic mean", Journal of + the American Statistical Association, vol. 26, pp. 36-40, 1931 + + Examples + -------- + >>> from scipy.stats import hmean + >>> hmean([1, 4]) + 1.6000000000000001 + >>> hmean([1, 2, 3, 4, 5, 6, 7]) + 2.6997245179063363 + >>> hmean([1, 4, 7], weights=[3, 1, 3]) + 1.9029126213592233 + + """ + xp = array_namespace(a, weights) + a = xp.asarray(a, dtype=dtype) + + if weights is not None: + weights = xp.asarray(weights, dtype=dtype) + + negative_mask = a < 0 + if xp.any(negative_mask): + # `where` avoids having to be careful about dtypes and will work with + # JAX. This is the exceptional case, so it's OK to be a little slower. + # Won't work for array_api_strict for now, but see data-apis/array-api#807 + a = xp.where(negative_mask, xp.nan, a) + message = ("The harmonic mean is only defined if all elements are " + "non-negative; otherwise, the result is NaN.") + warnings.warn(message, RuntimeWarning, stacklevel=2) + + with np.errstate(divide='ignore'): + return 1.0 / _xp_mean(1.0 / a, axis=axis, weights=weights) + + +@_axis_nan_policy_factory( + lambda x: x, n_samples=1, n_outputs=1, too_small=0, paired=True, + result_to_tuple=lambda x: (x,), kwd_samples=['weights']) +def pmean(a, p, *, axis=0, dtype=None, weights=None): + r"""Calculate the weighted power mean along the specified axis. + + The weighted power mean of the array :math:`a_i` associated to weights + :math:`w_i` is: + + .. math:: + + \left( \frac{ \sum_{i=1}^n w_i a_i^p }{ \sum_{i=1}^n w_i } + \right)^{ 1 / p } \, , + + and, with equal weights, it gives: + + .. math:: + + \left( \frac{ 1 }{ n } \sum_{i=1}^n a_i^p \right)^{ 1 / p } \, . + + When ``p=0``, it returns the geometric mean. + + This mean is also called generalized mean or Hölder mean, and must not be + confused with the Kolmogorov generalized mean, also called + quasi-arithmetic mean or generalized f-mean [3]_. + + Parameters + ---------- + a : array_like + Input array, masked array or object that can be converted to an array. + p : int or float + Exponent. + axis : int or None, optional + Axis along which the power mean is computed. Default is 0. + If None, compute over the whole array `a`. + dtype : dtype, optional + Type of the returned array and of the accumulator in which the + elements are summed. If `dtype` is not specified, it defaults to the + dtype of `a`, unless `a` has an integer `dtype` with a precision less + than that of the default platform integer. In that case, the default + platform integer is used. + weights : array_like, optional + The weights array can either be 1-D (in which case its length must be + the size of `a` along the given `axis`) or of the same shape as `a`. + Default is None, which gives each value a weight of 1.0. + + Returns + ------- + pmean : ndarray, see `dtype` parameter above. + Output array containing the power mean values. + + See Also + -------- + numpy.average : Weighted average + gmean : Geometric mean + hmean : Harmonic mean + + Notes + ----- + The power mean is computed over a single dimension of the input + array, ``axis=0`` by default, or all values in the array if ``axis=None``. + float64 intermediate and return values are used for integer inputs. + + The power mean is only defined if all observations are non-negative; + otherwise, the result is NaN. + + .. versionadded:: 1.9 + + References + ---------- + .. [1] "Generalized Mean", *Wikipedia*, + https://en.wikipedia.org/wiki/Generalized_mean + .. [2] Norris, N., "Convexity properties of generalized mean value + functions", The Annals of Mathematical Statistics, vol. 8, + pp. 118-120, 1937 + .. [3] Bullen, P.S., Handbook of Means and Their Inequalities, 2003 + + Examples + -------- + >>> from scipy.stats import pmean, hmean, gmean + >>> pmean([1, 4], 1.3) + 2.639372938300652 + >>> pmean([1, 2, 3, 4, 5, 6, 7], 1.3) + 4.157111214492084 + >>> pmean([1, 4, 7], -2, weights=[3, 1, 3]) + 1.4969684896631954 + + For p=-1, power mean is equal to harmonic mean: + + >>> pmean([1, 4, 7], -1, weights=[3, 1, 3]) + 1.9029126213592233 + >>> hmean([1, 4, 7], weights=[3, 1, 3]) + 1.9029126213592233 + + For p=0, power mean is defined as the geometric mean: + + >>> pmean([1, 4, 7], 0, weights=[3, 1, 3]) + 2.80668351922014 + >>> gmean([1, 4, 7], weights=[3, 1, 3]) + 2.80668351922014 + + """ + if not isinstance(p, (int, float)): + raise ValueError("Power mean only defined for exponent of type int or " + "float.") + if p == 0: + return gmean(a, axis=axis, dtype=dtype, weights=weights) + + xp = array_namespace(a, weights) + a = xp.asarray(a, dtype=dtype) + + if weights is not None: + weights = xp.asarray(weights, dtype=dtype) + + negative_mask = a < 0 + if xp.any(negative_mask): + # `where` avoids having to be careful about dtypes and will work with + # JAX. This is the exceptional case, so it's OK to be a little slower. + # Won't work for array_api_strict for now, but see data-apis/array-api#807 + a = xp.where(negative_mask, np.nan, a) + message = ("The power mean is only defined if all elements are " + "non-negative; otherwise, the result is NaN.") + warnings.warn(message, RuntimeWarning, stacklevel=2) + + with np.errstate(divide='ignore', invalid='ignore'): + return _xp_mean(a**float(p), axis=axis, weights=weights)**(1/p) + + +ModeResult = namedtuple('ModeResult', ('mode', 'count')) + + +def _mode_result(mode, count): + # When a slice is empty, `_axis_nan_policy` automatically produces + # NaN for `mode` and `count`. This is a reasonable convention for `mode`, + # but `count` should not be NaN; it should be zero. + i = np.isnan(count) + if i.shape == (): + count = np.asarray(0, dtype=count.dtype)[()] if i else count + else: + count[i] = 0 + return ModeResult(mode, count) + + +@_axis_nan_policy_factory(_mode_result, override={'vectorization': True, + 'nan_propagation': False}) +def mode(a, axis=0, nan_policy='propagate', keepdims=False): + r"""Return an array of the modal (most common) value in the passed array. + + If there is more than one such value, only one is returned. + The bin-count for the modal bins is also returned. + + Parameters + ---------- + a : array_like + Numeric, n-dimensional array of which to find mode(s). + axis : int or None, optional + Axis along which to operate. Default is 0. If None, compute over + the whole array `a`. + nan_policy : {'propagate', 'raise', 'omit'}, optional + Defines how to handle when input contains nan. + The following options are available (default is 'propagate'): + + * 'propagate': treats nan as it would treat any other value + * 'raise': throws an error + * 'omit': performs the calculations ignoring nan values + keepdims : bool, optional + If set to ``False``, the `axis` over which the statistic is taken + is consumed (eliminated from the output array). If set to ``True``, + the `axis` is retained with size one, and the result will broadcast + correctly against the input array. + + Returns + ------- + mode : ndarray + Array of modal values. + count : ndarray + Array of counts for each mode. + + Notes + ----- + The mode is calculated using `numpy.unique`. + In NumPy versions 1.21 and after, all NaNs - even those with different + binary representations - are treated as equivalent and counted as separate + instances of the same value. + + By convention, the mode of an empty array is NaN, and the associated count + is zero. + + Examples + -------- + >>> import numpy as np + >>> a = np.array([[3, 0, 3, 7], + ... [3, 2, 6, 2], + ... [1, 7, 2, 8], + ... [3, 0, 6, 1], + ... [3, 2, 5, 5]]) + >>> from scipy import stats + >>> stats.mode(a, keepdims=True) + ModeResult(mode=array([[3, 0, 6, 1]]), count=array([[4, 2, 2, 1]])) + + To get mode of whole array, specify ``axis=None``: + + >>> stats.mode(a, axis=None, keepdims=True) + ModeResult(mode=[[3]], count=[[5]]) + >>> stats.mode(a, axis=None, keepdims=False) + ModeResult(mode=3, count=5) + + """ + # `axis`, `nan_policy`, and `keepdims` are handled by `_axis_nan_policy` + if not np.issubdtype(a.dtype, np.number): + message = ("Argument `a` is not recognized as numeric. " + "Support for input that cannot be coerced to a numeric " + "array was deprecated in SciPy 1.9.0 and removed in SciPy " + "1.11.0. Please consider `np.unique`.") + raise TypeError(message) + + if a.size == 0: + NaN = _get_nan(a) + return ModeResult(*np.array([NaN, 0], dtype=NaN.dtype)) + + vals, cnts = np.unique(a, return_counts=True) + modes, counts = vals[cnts.argmax()], cnts.max() + return ModeResult(modes[()], counts[()]) + + +def _put_val_to_limits(a, limits, inclusive, val=np.nan, xp=None): + """Replace elements outside limits with a value. + + This is primarily a utility function. + + Parameters + ---------- + a : array + limits : (float or None, float or None) + A tuple consisting of the (lower limit, upper limit). Elements in the + input array less than the lower limit or greater than the upper limit + will be replaced with `val`. None implies no limit. + inclusive : (bool, bool) + A tuple consisting of the (lower flag, upper flag). These flags + determine whether values exactly equal to lower or upper are allowed. + val : float, default: NaN + The value with which extreme elements of the array are replaced. + + """ + xp = array_namespace(a) if xp is None else xp + mask = xp.zeros(a.shape, dtype=xp.bool) + if limits is None: + return a, mask + lower_limit, upper_limit = limits + lower_include, upper_include = inclusive + if lower_limit is not None: + mask |= (a < lower_limit) if lower_include else a <= lower_limit + if upper_limit is not None: + mask |= (a > upper_limit) if upper_include else a >= upper_limit + if xp.all(mask): + raise ValueError("No array values within given limits") + if xp.any(mask): + # hopefully this (and many other instances of this idiom) are temporary when + # data-apis/array-api#807 is resolved + dtype = xp.asarray(1.).dtype if xp.isdtype(a.dtype, 'integral') else a.dtype + a = xp.where(mask, xp.asarray(val, dtype=dtype), a) + return a, mask + + +@_axis_nan_policy_factory( + lambda x: x, n_outputs=1, default_axis=None, + result_to_tuple=lambda x: (x,) +) +def tmean(a, limits=None, inclusive=(True, True), axis=None): + """Compute the trimmed mean. + + This function finds the arithmetic mean of given values, ignoring values + outside the given `limits`. + + Parameters + ---------- + a : array_like + Array of values. + limits : None or (lower limit, upper limit), optional + Values in the input array less than the lower limit or greater than the + upper limit will be ignored. When limits is None (default), then all + values are used. Either of the limit values in the tuple can also be + None representing a half-open interval. + inclusive : (bool, bool), optional + A tuple consisting of the (lower flag, upper flag). These flags + determine whether values exactly equal to the lower or upper limits + are included. The default value is (True, True). + axis : int or None, optional + Axis along which to compute test. Default is None. + + Returns + ------- + tmean : ndarray + Trimmed mean. + + See Also + -------- + trim_mean : Returns mean after trimming a proportion from both tails. + + Examples + -------- + >>> import numpy as np + >>> from scipy import stats + >>> x = np.arange(20) + >>> stats.tmean(x) + 9.5 + >>> stats.tmean(x, (3,17)) + 10.0 + + """ + xp = array_namespace(a) + a, mask = _put_val_to_limits(a, limits, inclusive, val=0., xp=xp) + # explicit dtype specification required due to data-apis/array-api-compat#152 + sum = xp.sum(a, axis=axis, dtype=a.dtype) + n = xp.sum(xp.asarray(~mask, dtype=a.dtype), axis=axis, dtype=a.dtype) + mean = _lazywhere(n != 0, (sum, n), xp.divide, xp.nan) + return mean[()] if mean.ndim == 0 else mean + + +@_axis_nan_policy_factory( + lambda x: x, n_outputs=1, result_to_tuple=lambda x: (x,) +) +def tvar(a, limits=None, inclusive=(True, True), axis=0, ddof=1): + """Compute the trimmed variance. + + This function computes the sample variance of an array of values, + while ignoring values which are outside of given `limits`. + + Parameters + ---------- + a : array_like + Array of values. + limits : None or (lower limit, upper limit), optional + Values in the input array less than the lower limit or greater than the + upper limit will be ignored. When limits is None, then all values are + used. Either of the limit values in the tuple can also be None + representing a half-open interval. The default value is None. + inclusive : (bool, bool), optional + A tuple consisting of the (lower flag, upper flag). These flags + determine whether values exactly equal to the lower or upper limits + are included. The default value is (True, True). + axis : int or None, optional + Axis along which to operate. Default is 0. If None, compute over the + whole array `a`. + ddof : int, optional + Delta degrees of freedom. Default is 1. + + Returns + ------- + tvar : float + Trimmed variance. + + Notes + ----- + `tvar` computes the unbiased sample variance, i.e. it uses a correction + factor ``n / (n - 1)``. + + Examples + -------- + >>> import numpy as np + >>> from scipy import stats + >>> x = np.arange(20) + >>> stats.tvar(x) + 35.0 + >>> stats.tvar(x, (3,17)) + 20.0 + + """ + xp = array_namespace(a) + a, _ = _put_val_to_limits(a, limits, inclusive, xp=xp) + with warnings.catch_warnings(): + warnings.simplefilter("ignore", SmallSampleWarning) + # Currently, this behaves like nan_policy='omit' for alternative array + # backends, but nan_policy='propagate' will be handled for other backends + # by the axis_nan_policy decorator shortly. + return _xp_var(a, correction=ddof, axis=axis, nan_policy='omit', xp=xp) + +@_axis_nan_policy_factory( + lambda x: x, n_outputs=1, result_to_tuple=lambda x: (x,) +) +def tmin(a, lowerlimit=None, axis=0, inclusive=True, nan_policy='propagate'): + """Compute the trimmed minimum. + + This function finds the minimum value of an array `a` along the + specified axis, but only considering values greater than a specified + lower limit. + + Parameters + ---------- + a : array_like + Array of values. + lowerlimit : None or float, optional + Values in the input array less than the given limit will be ignored. + When lowerlimit is None, then all values are used. The default value + is None. + axis : int or None, optional + Axis along which to operate. Default is 0. If None, compute over the + whole array `a`. + inclusive : {True, False}, optional + This flag determines whether values exactly equal to the lower limit + are included. The default value is True. + + Returns + ------- + tmin : float, int or ndarray + Trimmed minimum. + + Examples + -------- + >>> import numpy as np + >>> from scipy import stats + >>> x = np.arange(20) + >>> stats.tmin(x) + 0 + + >>> stats.tmin(x, 13) + 13 + + >>> stats.tmin(x, 13, inclusive=False) + 14 + + """ + xp = array_namespace(a) + + # remember original dtype; _put_val_to_limits might need to change it + dtype = a.dtype + a, mask = _put_val_to_limits(a, (lowerlimit, None), (inclusive, None), + val=xp.inf, xp=xp) + + min = xp.min(a, axis=axis) + n = xp.sum(xp.asarray(~mask, dtype=a.dtype), axis=axis) + res = xp.where(n != 0, min, xp.nan) + + if not xp.any(xp.isnan(res)): + # needed if input is of integer dtype + res = xp.astype(res, dtype, copy=False) + + return res[()] if res.ndim == 0 else res + + +@_axis_nan_policy_factory( + lambda x: x, n_outputs=1, result_to_tuple=lambda x: (x,) +) +def tmax(a, upperlimit=None, axis=0, inclusive=True, nan_policy='propagate'): + """Compute the trimmed maximum. + + This function computes the maximum value of an array along a given axis, + while ignoring values larger than a specified upper limit. + + Parameters + ---------- + a : array_like + Array of values. + upperlimit : None or float, optional + Values in the input array greater than the given limit will be ignored. + When upperlimit is None, then all values are used. The default value + is None. + axis : int or None, optional + Axis along which to operate. Default is 0. If None, compute over the + whole array `a`. + inclusive : {True, False}, optional + This flag determines whether values exactly equal to the upper limit + are included. The default value is True. + + Returns + ------- + tmax : float, int or ndarray + Trimmed maximum. + + Examples + -------- + >>> import numpy as np + >>> from scipy import stats + >>> x = np.arange(20) + >>> stats.tmax(x) + 19 + + >>> stats.tmax(x, 13) + 13 + + >>> stats.tmax(x, 13, inclusive=False) + 12 + + """ + xp = array_namespace(a) + + # remember original dtype; _put_val_to_limits might need to change it + dtype = a.dtype + a, mask = _put_val_to_limits(a, (None, upperlimit), (None, inclusive), + val=-xp.inf, xp=xp) + + max = xp.max(a, axis=axis) + n = xp.sum(xp.asarray(~mask, dtype=a.dtype), axis=axis) + res = xp.where(n != 0, max, xp.nan) + + if not xp.any(xp.isnan(res)): + # needed if input is of integer dtype + res = xp.astype(res, dtype, copy=False) + + return res[()] if res.ndim == 0 else res + + +@_axis_nan_policy_factory( + lambda x: x, n_outputs=1, result_to_tuple=lambda x: (x,) +) +def tstd(a, limits=None, inclusive=(True, True), axis=0, ddof=1): + """Compute the trimmed sample standard deviation. + + This function finds the sample standard deviation of given values, + ignoring values outside the given `limits`. + + Parameters + ---------- + a : array_like + Array of values. + limits : None or (lower limit, upper limit), optional + Values in the input array less than the lower limit or greater than the + upper limit will be ignored. When limits is None, then all values are + used. Either of the limit values in the tuple can also be None + representing a half-open interval. The default value is None. + inclusive : (bool, bool), optional + A tuple consisting of the (lower flag, upper flag). These flags + determine whether values exactly equal to the lower or upper limits + are included. The default value is (True, True). + axis : int or None, optional + Axis along which to operate. Default is 0. If None, compute over the + whole array `a`. + ddof : int, optional + Delta degrees of freedom. Default is 1. + + Returns + ------- + tstd : float + Trimmed sample standard deviation. + + Notes + ----- + `tstd` computes the unbiased sample standard deviation, i.e. it uses a + correction factor ``n / (n - 1)``. + + Examples + -------- + >>> import numpy as np + >>> from scipy import stats + >>> x = np.arange(20) + >>> stats.tstd(x) + 5.9160797830996161 + >>> stats.tstd(x, (3,17)) + 4.4721359549995796 + + """ + return tvar(a, limits, inclusive, axis, ddof, _no_deco=True)**0.5 + + +@_axis_nan_policy_factory( + lambda x: x, n_outputs=1, result_to_tuple=lambda x: (x,) +) +def tsem(a, limits=None, inclusive=(True, True), axis=0, ddof=1): + """Compute the trimmed standard error of the mean. + + This function finds the standard error of the mean for given + values, ignoring values outside the given `limits`. + + Parameters + ---------- + a : array_like + Array of values. + limits : None or (lower limit, upper limit), optional + Values in the input array less than the lower limit or greater than the + upper limit will be ignored. When limits is None, then all values are + used. Either of the limit values in the tuple can also be None + representing a half-open interval. The default value is None. + inclusive : (bool, bool), optional + A tuple consisting of the (lower flag, upper flag). These flags + determine whether values exactly equal to the lower or upper limits + are included. The default value is (True, True). + axis : int or None, optional + Axis along which to operate. Default is 0. If None, compute over the + whole array `a`. + ddof : int, optional + Delta degrees of freedom. Default is 1. + + Returns + ------- + tsem : float + Trimmed standard error of the mean. + + Notes + ----- + `tsem` uses unbiased sample standard deviation, i.e. it uses a + correction factor ``n / (n - 1)``. + + Examples + -------- + >>> import numpy as np + >>> from scipy import stats + >>> x = np.arange(20) + >>> stats.tsem(x) + 1.3228756555322954 + >>> stats.tsem(x, (3,17)) + 1.1547005383792515 + + """ + xp = array_namespace(a) + a, _ = _put_val_to_limits(a, limits, inclusive, xp=xp) + + with warnings.catch_warnings(): + warnings.simplefilter("ignore", SmallSampleWarning) + # Currently, this behaves like nan_policy='omit' for alternative array + # backends, but nan_policy='propagate' will be handled for other backends + # by the axis_nan_policy decorator shortly. + sd = _xp_var(a, correction=ddof, axis=axis, nan_policy='omit', xp=xp)**0.5 + + n_obs = xp.sum(~xp.isnan(a), axis=axis, dtype=sd.dtype) + return sd / n_obs**0.5 + + +##################################### +# MOMENTS # +##################################### + + +def _moment_outputs(kwds, default_order=1): + order = np.atleast_1d(kwds.get('order', default_order)) + message = "`order` must be a scalar or a non-empty 1D array." + if order.size == 0 or order.ndim > 1: + raise ValueError(message) + return len(order) + + +def _moment_result_object(*args): + if len(args) == 1: + return args[0] + return np.asarray(args) + + +# When `order` is array-like with size > 1, moment produces an *array* +# rather than a tuple, but the zeroth dimension is to be treated like +# separate outputs. It is important to make the distinction between +# separate outputs when adding the reduced axes back (`keepdims=True`). +def _moment_tuple(x, n_out): + return tuple(x) if n_out > 1 else (x,) + + +# `moment` fits into the `_axis_nan_policy` pattern, but it is a bit unusual +# because the number of outputs is variable. Specifically, +# `result_to_tuple=lambda x: (x,)` may be surprising for a function that +# can produce more than one output, but it is intended here. +# When `moment is called to produce the output: +# - `result_to_tuple` packs the returned array into a single-element tuple, +# - `_moment_result_object` extracts and returns that single element. +# However, when the input array is empty, `moment` is never called. Instead, +# - `_check_empty_inputs` is used to produce an empty array with the +# appropriate dimensions. +# - A list comprehension creates the appropriate number of copies of this +# array, depending on `n_outputs`. +# - This list - which may have multiple elements - is passed into +# `_moment_result_object`. +# - If there is a single output, `_moment_result_object` extracts and returns +# the single output from the list. +# - If there are multiple outputs, and therefore multiple elements in the list, +# `_moment_result_object` converts the list of arrays to a single array and +# returns it. +# Currently, this leads to a slight inconsistency: when the input array is +# empty, there is no distinction between the `moment` function being called +# with parameter `order=1` and `order=[1]`; the latter *should* produce +# the same as the former but with a singleton zeroth dimension. +@_rename_parameter('moment', 'order') +@_axis_nan_policy_factory( # noqa: E302 + _moment_result_object, n_samples=1, result_to_tuple=_moment_tuple, + n_outputs=_moment_outputs +) +def moment(a, order=1, axis=0, nan_policy='propagate', *, center=None): + r"""Calculate the nth moment about the mean for a sample. + + A moment is a specific quantitative measure of the shape of a set of + points. It is often used to calculate coefficients of skewness and kurtosis + due to its close relationship with them. + + Parameters + ---------- + a : array_like + Input array. + order : int or 1-D array_like of ints, optional + Order of central moment that is returned. Default is 1. + axis : int or None, optional + Axis along which the central moment is computed. Default is 0. + If None, compute over the whole array `a`. + nan_policy : {'propagate', 'raise', 'omit'}, optional + Defines how to handle when input contains nan. + The following options are available (default is 'propagate'): + + * 'propagate': returns nan + * 'raise': throws an error + * 'omit': performs the calculations ignoring nan values + + center : float or None, optional + The point about which moments are taken. This can be the sample mean, + the origin, or any other be point. If `None` (default) compute the + center as the sample mean. + + Returns + ------- + n-th moment about the `center` : ndarray or float + The appropriate moment along the given axis or over all values if axis + is None. The denominator for the moment calculation is the number of + observations, no degrees of freedom correction is done. + + See Also + -------- + kurtosis, skew, describe + + Notes + ----- + The k-th moment of a data sample is: + + .. math:: + + m_k = \frac{1}{n} \sum_{i = 1}^n (x_i - c)^k + + Where `n` is the number of samples, and `c` is the center around which the + moment is calculated. This function uses exponentiation by squares [1]_ for + efficiency. + + Note that, if `a` is an empty array (``a.size == 0``), array `moment` with + one element (`moment.size == 1`) is treated the same as scalar `moment` + (``np.isscalar(moment)``). This might produce arrays of unexpected shape. + + References + ---------- + .. [1] https://eli.thegreenplace.net/2009/03/21/efficient-integer-exponentiation-algorithms + + Examples + -------- + >>> from scipy.stats import moment + >>> moment([1, 2, 3, 4, 5], order=1) + 0.0 + >>> moment([1, 2, 3, 4, 5], order=2) + 2.0 + + """ + xp = array_namespace(a) + a, axis = _chk_asarray(a, axis, xp=xp) + + if xp.isdtype(a.dtype, 'integral'): + a = xp.asarray(a, dtype=xp.float64) + else: + a = xp.asarray(a) + + order = xp.asarray(order, dtype=a.dtype) + if xp_size(order) == 0: + # This is tested by `_moment_outputs`, which is run by the `_axis_nan_policy` + # decorator. Currently, the `_axis_nan_policy` decorator is skipped when `a` + # is a non-NumPy array, so we need to check again. When the decorator is + # updated for array API compatibility, we can remove this second check. + raise ValueError("`order` must be a scalar or a non-empty 1D array.") + if xp.any(order != xp.round(order)): + raise ValueError("All elements of `order` must be integral.") + order = order[()] if order.ndim == 0 else order + + # for array_like order input, return a value for each. + if order.ndim > 0: + # Calculated the mean once at most, and only if it will be used + calculate_mean = center is None and xp.any(order > 1) + mean = xp.mean(a, axis=axis, keepdims=True) if calculate_mean else None + mmnt = [] + for i in range(order.shape[0]): + order_i = order[i] + if center is None and order_i > 1: + mmnt.append(_moment(a, order_i, axis, mean=mean)[np.newaxis, ...]) + else: + mmnt.append(_moment(a, order_i, axis, mean=center)[np.newaxis, ...]) + return xp.concat(mmnt, axis=0) + else: + return _moment(a, order, axis, mean=center) + + +def _demean(a, mean, axis, *, xp, precision_warning=True): + # subtracts `mean` from `a` and returns the result, + # warning if there is catastrophic cancellation. `mean` + # must be the mean of `a` along axis with `keepdims=True`. + # Used in e.g. `_moment`, `_zscore`, `_xp_var`. See gh-15905. + a_zero_mean = a - mean + + if xp_size(a_zero_mean) == 0: + return a_zero_mean + + eps = xp.finfo(mean.dtype).eps * 10 + + with np.errstate(divide='ignore', invalid='ignore'): + rel_diff = xp.max(xp.abs(a_zero_mean), axis=axis, + keepdims=True) / xp.abs(mean) + with np.errstate(invalid='ignore'): + precision_loss = xp.any(rel_diff < eps) + n = (xp_size(a) if axis is None + # compact way to deal with axis tuples or ints + else np.prod(np.asarray(a.shape)[np.asarray(axis)])) + + if precision_loss and n > 1 and precision_warning: + message = ("Precision loss occurred in moment calculation due to " + "catastrophic cancellation. This occurs when the data " + "are nearly identical. Results may be unreliable.") + warnings.warn(message, RuntimeWarning, stacklevel=5) + return a_zero_mean + + +def _moment(a, order, axis, *, mean=None, xp=None): + """Vectorized calculation of raw moment about specified center + + When `mean` is None, the mean is computed and used as the center; + otherwise, the provided value is used as the center. + + """ + xp = array_namespace(a) if xp is None else xp + + if xp.isdtype(a.dtype, 'integral'): + a = xp.asarray(a, dtype=xp.float64) + + dtype = a.dtype + + # moment of empty array is the same regardless of order + if xp_size(a) == 0: + return xp.mean(a, axis=axis) + + if order == 0 or (order == 1 and mean is None): + # By definition the zeroth moment is always 1, and the first *central* + # moment is 0. + shape = list(a.shape) + del shape[axis] + + temp = (xp.ones(shape, dtype=dtype) if order == 0 + else xp.zeros(shape, dtype=dtype)) + return temp[()] if temp.ndim == 0 else temp + + # Exponentiation by squares: form exponent sequence + n_list = [order] + current_n = order + while current_n > 2: + if current_n % 2: + current_n = (current_n - 1) / 2 + else: + current_n /= 2 + n_list.append(current_n) + + # Starting point for exponentiation by squares + mean = (xp.mean(a, axis=axis, keepdims=True) if mean is None + else xp.asarray(mean, dtype=dtype)) + mean = mean[()] if mean.ndim == 0 else mean + a_zero_mean = _demean(a, mean, axis, xp=xp) + + if n_list[-1] == 1: + s = xp.asarray(a_zero_mean, copy=True) + else: + s = a_zero_mean**2 + + # Perform multiplications + for n in n_list[-2::-1]: + s = s**2 + if n % 2: + s *= a_zero_mean + return xp.mean(s, axis=axis) + + +def _var(x, axis=0, ddof=0, mean=None, xp=None): + # Calculate variance of sample, warning if precision is lost + xp = array_namespace(x) if xp is None else xp + var = _moment(x, 2, axis, mean=mean, xp=xp) + if ddof != 0: + n = x.shape[axis] if axis is not None else xp_size(x) + var *= np.divide(n, n-ddof) # to avoid error on division by zero + return var + + +@_axis_nan_policy_factory( + lambda x: x, result_to_tuple=lambda x: (x,), n_outputs=1 +) +# nan_policy handled by `_axis_nan_policy`, but needs to be left +# in signature to preserve use as a positional argument +def skew(a, axis=0, bias=True, nan_policy='propagate'): + r"""Compute the sample skewness of a data set. + + For normally distributed data, the skewness should be about zero. For + unimodal continuous distributions, a skewness value greater than zero means + that there is more weight in the right tail of the distribution. The + function `skewtest` can be used to determine if the skewness value + is close enough to zero, statistically speaking. + + Parameters + ---------- + a : ndarray + Input array. + axis : int or None, optional + Axis along which skewness is calculated. Default is 0. + If None, compute over the whole array `a`. + bias : bool, optional + If False, then the calculations are corrected for statistical bias. + nan_policy : {'propagate', 'raise', 'omit'}, optional + Defines how to handle when input contains nan. + The following options are available (default is 'propagate'): + + * 'propagate': returns nan + * 'raise': throws an error + * 'omit': performs the calculations ignoring nan values + + Returns + ------- + skewness : ndarray + The skewness of values along an axis, returning NaN where all values + are equal. + + Notes + ----- + The sample skewness is computed as the Fisher-Pearson coefficient + of skewness, i.e. + + .. math:: + + g_1=\frac{m_3}{m_2^{3/2}} + + where + + .. math:: + + m_i=\frac{1}{N}\sum_{n=1}^N(x[n]-\bar{x})^i + + is the biased sample :math:`i\texttt{th}` central moment, and + :math:`\bar{x}` is + the sample mean. If ``bias`` is False, the calculations are + corrected for bias and the value computed is the adjusted + Fisher-Pearson standardized moment coefficient, i.e. + + .. math:: + + G_1=\frac{k_3}{k_2^{3/2}}= + \frac{\sqrt{N(N-1)}}{N-2}\frac{m_3}{m_2^{3/2}}. + + References + ---------- + .. [1] Zwillinger, D. and Kokoska, S. (2000). CRC Standard + Probability and Statistics Tables and Formulae. Chapman & Hall: New + York. 2000. + Section 2.2.24.1 + + Examples + -------- + >>> from scipy.stats import skew + >>> skew([1, 2, 3, 4, 5]) + 0.0 + >>> skew([2, 8, 0, 4, 1, 9, 9, 0]) + 0.2650554122698573 + + """ + xp = array_namespace(a) + a, axis = _chk_asarray(a, axis, xp=xp) + n = a.shape[axis] + + mean = xp.mean(a, axis=axis, keepdims=True) + mean_reduced = xp.squeeze(mean, axis=axis) # needed later + m2 = _moment(a, 2, axis, mean=mean, xp=xp) + m3 = _moment(a, 3, axis, mean=mean, xp=xp) + with np.errstate(all='ignore'): + eps = xp.finfo(m2.dtype).eps + zero = m2 <= (eps * mean_reduced)**2 + vals = xp.where(zero, xp.asarray(xp.nan), m3 / m2**1.5) + if not bias: + can_correct = ~zero & (n > 2) + if xp.any(can_correct): + m2 = m2[can_correct] + m3 = m3[can_correct] + nval = ((n - 1.0) * n)**0.5 / (n - 2.0) * m3 / m2**1.5 + vals[can_correct] = nval + + return vals[()] if vals.ndim == 0 else vals + + +@_axis_nan_policy_factory( + lambda x: x, result_to_tuple=lambda x: (x,), n_outputs=1 +) +# nan_policy handled by `_axis_nan_policy`, but needs to be left +# in signature to preserve use as a positional argument +def kurtosis(a, axis=0, fisher=True, bias=True, nan_policy='propagate'): + """Compute the kurtosis (Fisher or Pearson) of a dataset. + + Kurtosis is the fourth central moment divided by the square of the + variance. If Fisher's definition is used, then 3.0 is subtracted from + the result to give 0.0 for a normal distribution. + + If bias is False then the kurtosis is calculated using k statistics to + eliminate bias coming from biased moment estimators + + Use `kurtosistest` to see if result is close enough to normal. + + Parameters + ---------- + a : array + Data for which the kurtosis is calculated. + axis : int or None, optional + Axis along which the kurtosis is calculated. Default is 0. + If None, compute over the whole array `a`. + fisher : bool, optional + If True, Fisher's definition is used (normal ==> 0.0). If False, + Pearson's definition is used (normal ==> 3.0). + bias : bool, optional + If False, then the calculations are corrected for statistical bias. + nan_policy : {'propagate', 'raise', 'omit'}, optional + Defines how to handle when input contains nan. 'propagate' returns nan, + 'raise' throws an error, 'omit' performs the calculations ignoring nan + values. Default is 'propagate'. + + Returns + ------- + kurtosis : array + The kurtosis of values along an axis, returning NaN where all values + are equal. + + References + ---------- + .. [1] Zwillinger, D. and Kokoska, S. (2000). CRC Standard + Probability and Statistics Tables and Formulae. Chapman & Hall: New + York. 2000. + + Examples + -------- + In Fisher's definition, the kurtosis of the normal distribution is zero. + In the following example, the kurtosis is close to zero, because it was + calculated from the dataset, not from the continuous distribution. + + >>> import numpy as np + >>> from scipy.stats import norm, kurtosis + >>> data = norm.rvs(size=1000, random_state=3) + >>> kurtosis(data) + -0.06928694200380558 + + The distribution with a higher kurtosis has a heavier tail. + The zero valued kurtosis of the normal distribution in Fisher's definition + can serve as a reference point. + + >>> import matplotlib.pyplot as plt + >>> import scipy.stats as stats + >>> from scipy.stats import kurtosis + + >>> x = np.linspace(-5, 5, 100) + >>> ax = plt.subplot() + >>> distnames = ['laplace', 'norm', 'uniform'] + + >>> for distname in distnames: + ... if distname == 'uniform': + ... dist = getattr(stats, distname)(loc=-2, scale=4) + ... else: + ... dist = getattr(stats, distname) + ... data = dist.rvs(size=1000) + ... kur = kurtosis(data, fisher=True) + ... y = dist.pdf(x) + ... ax.plot(x, y, label="{}, {}".format(distname, round(kur, 3))) + ... ax.legend() + + The Laplace distribution has a heavier tail than the normal distribution. + The uniform distribution (which has negative kurtosis) has the thinnest + tail. + + """ + xp = array_namespace(a) + a, axis = _chk_asarray(a, axis, xp=xp) + + n = a.shape[axis] + mean = xp.mean(a, axis=axis, keepdims=True) + mean_reduced = xp.squeeze(mean, axis=axis) # needed later + m2 = _moment(a, 2, axis, mean=mean, xp=xp) + m4 = _moment(a, 4, axis, mean=mean, xp=xp) + with np.errstate(all='ignore'): + zero = m2 <= (xp.finfo(m2.dtype).eps * mean_reduced)**2 + NaN = _get_nan(m4, xp=xp) + vals = xp.where(zero, NaN, m4 / m2**2.0) + + if not bias: + can_correct = ~zero & (n > 3) + if xp.any(can_correct): + m2 = m2[can_correct] + m4 = m4[can_correct] + nval = 1.0/(n-2)/(n-3) * ((n**2-1.0)*m4/m2**2.0 - 3*(n-1)**2.0) + vals[can_correct] = nval + 3.0 + + vals = vals - 3 if fisher else vals + return vals[()] if vals.ndim == 0 else vals + + +DescribeResult = namedtuple('DescribeResult', + ('nobs', 'minmax', 'mean', 'variance', 'skewness', + 'kurtosis')) + + +def describe(a, axis=0, ddof=1, bias=True, nan_policy='propagate'): + """Compute several descriptive statistics of the passed array. + + Parameters + ---------- + a : array_like + Input data. + axis : int or None, optional + Axis along which statistics are calculated. Default is 0. + If None, compute over the whole array `a`. + ddof : int, optional + Delta degrees of freedom (only for variance). Default is 1. + bias : bool, optional + If False, then the skewness and kurtosis calculations are corrected + for statistical bias. + nan_policy : {'propagate', 'raise', 'omit'}, optional + Defines how to handle when input contains nan. + The following options are available (default is 'propagate'): + + * 'propagate': returns nan + * 'raise': throws an error + * 'omit': performs the calculations ignoring nan values + + Returns + ------- + nobs : int or ndarray of ints + Number of observations (length of data along `axis`). + When 'omit' is chosen as nan_policy, the length along each axis + slice is counted separately. + minmax: tuple of ndarrays or floats + Minimum and maximum value of `a` along the given axis. + mean : ndarray or float + Arithmetic mean of `a` along the given axis. + variance : ndarray or float + Unbiased variance of `a` along the given axis; denominator is number + of observations minus one. + skewness : ndarray or float + Skewness of `a` along the given axis, based on moment calculations + with denominator equal to the number of observations, i.e. no degrees + of freedom correction. + kurtosis : ndarray or float + Kurtosis (Fisher) of `a` along the given axis. The kurtosis is + normalized so that it is zero for the normal distribution. No + degrees of freedom are used. + + Raises + ------ + ValueError + If size of `a` is 0. + + See Also + -------- + skew, kurtosis + + Examples + -------- + >>> import numpy as np + >>> from scipy import stats + >>> a = np.arange(10) + >>> stats.describe(a) + DescribeResult(nobs=10, minmax=(0, 9), mean=4.5, + variance=9.166666666666666, skewness=0.0, + kurtosis=-1.2242424242424244) + >>> b = [[1, 2], [3, 4]] + >>> stats.describe(b) + DescribeResult(nobs=2, minmax=(array([1, 2]), array([3, 4])), + mean=array([2., 3.]), variance=array([2., 2.]), + skewness=array([0., 0.]), kurtosis=array([-2., -2.])) + + """ + xp = array_namespace(a) + a, axis = _chk_asarray(a, axis, xp=xp) + + contains_nan, nan_policy = _contains_nan(a, nan_policy) + + if contains_nan and nan_policy == 'omit': + # only NumPy gets here; `_contains_nan` raises error for the rest + a = ma.masked_invalid(a) + return mstats_basic.describe(a, axis, ddof, bias) + + if xp_size(a) == 0: + raise ValueError("The input must not be empty.") + + n = a.shape[axis] + mm = (xp.min(a, axis=axis), xp.max(a, axis=axis)) + m = xp.mean(a, axis=axis) + v = _var(a, axis=axis, ddof=ddof, xp=xp) + sk = skew(a, axis, bias=bias) + kurt = kurtosis(a, axis, bias=bias) + + return DescribeResult(n, mm, m, v, sk, kurt) + +##################################### +# NORMALITY TESTS # +##################################### + + +def _get_pvalue(statistic, distribution, alternative, symmetric=True, xp=None): + """Get p-value given the statistic, (continuous) distribution, and alternative""" + xp = array_namespace(statistic) if xp is None else xp + + if alternative == 'less': + pvalue = distribution.cdf(statistic) + elif alternative == 'greater': + pvalue = distribution.sf(statistic) + elif alternative == 'two-sided': + pvalue = 2 * (distribution.sf(xp.abs(statistic)) if symmetric + else xp.minimum(distribution.cdf(statistic), + distribution.sf(statistic))) + else: + message = "`alternative` must be 'less', 'greater', or 'two-sided'." + raise ValueError(message) + + return pvalue + + +SkewtestResult = namedtuple('SkewtestResult', ('statistic', 'pvalue')) + + +@_axis_nan_policy_factory(SkewtestResult, n_samples=1, too_small=7) +# nan_policy handled by `_axis_nan_policy`, but needs to be left +# in signature to preserve use as a positional argument +def skewtest(a, axis=0, nan_policy='propagate', alternative='two-sided'): + r"""Test whether the skew is different from the normal distribution. + + This function tests the null hypothesis that the skewness of + the population that the sample was drawn from is the same + as that of a corresponding normal distribution. + + Parameters + ---------- + a : array + The data to be tested. Must contain at least eight observations. + axis : int or None, optional + Axis along which statistics are calculated. Default is 0. + If None, compute over the whole array `a`. + nan_policy : {'propagate', 'raise', 'omit'}, optional + Defines how to handle when input contains nan. + The following options are available (default is 'propagate'): + + * 'propagate': returns nan + * 'raise': throws an error + * 'omit': performs the calculations ignoring nan values + + alternative : {'two-sided', 'less', 'greater'}, optional + Defines the alternative hypothesis. Default is 'two-sided'. + The following options are available: + + * 'two-sided': the skewness of the distribution underlying the sample + is different from that of the normal distribution (i.e. 0) + * 'less': the skewness of the distribution underlying the sample + is less than that of the normal distribution + * 'greater': the skewness of the distribution underlying the sample + is greater than that of the normal distribution + + .. versionadded:: 1.7.0 + + Returns + ------- + statistic : float + The computed z-score for this test. + pvalue : float + The p-value for the hypothesis test. + + See Also + -------- + :ref:`hypothesis_skewtest` : Extended example + + Notes + ----- + The sample size must be at least 8. + + References + ---------- + .. [1] R. B. D'Agostino, A. J. Belanger and R. B. D'Agostino Jr., + "A suggestion for using powerful and informative tests of + normality", American Statistician 44, pp. 316-321, 1990. + + Examples + -------- + + >>> from scipy.stats import skewtest + >>> skewtest([1, 2, 3, 4, 5, 6, 7, 8]) + SkewtestResult(statistic=1.0108048609177787, pvalue=0.3121098361421897) + >>> skewtest([2, 8, 0, 4, 1, 9, 9, 0]) + SkewtestResult(statistic=0.44626385374196975, pvalue=0.6554066631275459) + >>> skewtest([1, 2, 3, 4, 5, 6, 7, 8000]) + SkewtestResult(statistic=3.571773510360407, pvalue=0.0003545719905823133) + >>> skewtest([100, 100, 100, 100, 100, 100, 100, 101]) + SkewtestResult(statistic=3.5717766638478072, pvalue=0.000354567720281634) + >>> skewtest([1, 2, 3, 4, 5, 6, 7, 8], alternative='less') + SkewtestResult(statistic=1.0108048609177787, pvalue=0.8439450819289052) + >>> skewtest([1, 2, 3, 4, 5, 6, 7, 8], alternative='greater') + SkewtestResult(statistic=1.0108048609177787, pvalue=0.15605491807109484) + + For a more detailed example, see :ref:`hypothesis_skewtest`. + """ + xp = array_namespace(a) + a, axis = _chk_asarray(a, axis, xp=xp) + + b2 = skew(a, axis, _no_deco=True) + n = a.shape[axis] + if n < 8: + message = ("`skewtest` requires at least 8 observations; " + f"only {n=} observations were given.") + raise ValueError(message) + + y = b2 * math.sqrt(((n + 1) * (n + 3)) / (6.0 * (n - 2))) + beta2 = (3.0 * (n**2 + 27*n - 70) * (n+1) * (n+3) / + ((n-2.0) * (n+5) * (n+7) * (n+9))) + W2 = -1 + math.sqrt(2 * (beta2 - 1)) + delta = 1 / math.sqrt(0.5 * math.log(W2)) + alpha = math.sqrt(2.0 / (W2 - 1)) + y = xp.where(y == 0, xp.asarray(1, dtype=y.dtype), y) + Z = delta * xp.log(y / alpha + xp.sqrt((y / alpha)**2 + 1)) + + pvalue = _get_pvalue(Z, _SimpleNormal(), alternative, xp=xp) + + Z = Z[()] if Z.ndim == 0 else Z + pvalue = pvalue[()] if pvalue.ndim == 0 else pvalue + return SkewtestResult(Z, pvalue) + + +KurtosistestResult = namedtuple('KurtosistestResult', ('statistic', 'pvalue')) + + +@_axis_nan_policy_factory(KurtosistestResult, n_samples=1, too_small=4) +def kurtosistest(a, axis=0, nan_policy='propagate', alternative='two-sided'): + r"""Test whether a dataset has normal kurtosis. + + This function tests the null hypothesis that the kurtosis + of the population from which the sample was drawn is that + of the normal distribution. + + Parameters + ---------- + a : array + Array of the sample data. Must contain at least five observations. + axis : int or None, optional + Axis along which to compute test. Default is 0. If None, + compute over the whole array `a`. + nan_policy : {'propagate', 'raise', 'omit'}, optional + Defines how to handle when input contains nan. + The following options are available (default is 'propagate'): + + * 'propagate': returns nan + * 'raise': throws an error + * 'omit': performs the calculations ignoring nan values + alternative : {'two-sided', 'less', 'greater'}, optional + Defines the alternative hypothesis. + The following options are available (default is 'two-sided'): + + * 'two-sided': the kurtosis of the distribution underlying the sample + is different from that of the normal distribution + * 'less': the kurtosis of the distribution underlying the sample + is less than that of the normal distribution + * 'greater': the kurtosis of the distribution underlying the sample + is greater than that of the normal distribution + + .. versionadded:: 1.7.0 + + Returns + ------- + statistic : float + The computed z-score for this test. + pvalue : float + The p-value for the hypothesis test. + + See Also + -------- + :ref:`hypothesis_kurtosistest` : Extended example + + Notes + ----- + Valid only for n>20. This function uses the method described in [1]_. + + References + ---------- + .. [1] F. J. Anscombe, W. J. Glynn, "Distribution of the kurtosis + statistic b2 for normal samples", Biometrika, vol. 70, pp. 227-234, 1983. + + Examples + -------- + + >>> import numpy as np + >>> from scipy.stats import kurtosistest + >>> kurtosistest(list(range(20))) + KurtosistestResult(statistic=-1.7058104152122062, pvalue=0.08804338332528348) + >>> kurtosistest(list(range(20)), alternative='less') + KurtosistestResult(statistic=-1.7058104152122062, pvalue=0.04402169166264174) + >>> kurtosistest(list(range(20)), alternative='greater') + KurtosistestResult(statistic=-1.7058104152122062, pvalue=0.9559783083373583) + >>> rng = np.random.default_rng() + >>> s = rng.normal(0, 1, 1000) + >>> kurtosistest(s) + KurtosistestResult(statistic=-1.475047944490622, pvalue=0.14019965402996987) + + For a more detailed example, see :ref:`hypothesis_kurtosistest`. + """ + xp = array_namespace(a) + a, axis = _chk_asarray(a, axis, xp=xp) + + n = a.shape[axis] + + if n < 5: + message = ("`kurtosistest` requires at least 5 observations; " + f"only {n=} observations were given.") + raise ValueError(message) + if n < 20: + message = ("`kurtosistest` p-value may be inaccurate with fewer than 20 " + f"observations; only {n=} observations were given.") + warnings.warn(message, stacklevel=2) + b2 = kurtosis(a, axis, fisher=False, _no_deco=True) + + E = 3.0*(n-1) / (n+1) + varb2 = 24.0*n*(n-2)*(n-3) / ((n+1)*(n+1.)*(n+3)*(n+5)) # [1]_ Eq. 1 + x = (b2-E) / varb2**0.5 # [1]_ Eq. 4 + # [1]_ Eq. 2: + sqrtbeta1 = 6.0*(n*n-5*n+2)/((n+7)*(n+9)) * ((6.0*(n+3)*(n+5)) + / (n*(n-2)*(n-3)))**0.5 + # [1]_ Eq. 3: + A = 6.0 + 8.0/sqrtbeta1 * (2.0/sqrtbeta1 + (1+4.0/(sqrtbeta1**2))**0.5) + term1 = 1 - 2/(9.0*A) + denom = 1 + x * (2/(A-4.0))**0.5 + NaN = _get_nan(x, xp=xp) + term2 = xp_sign(denom) * xp.where(denom == 0.0, NaN, + ((1-2.0/A)/xp.abs(denom))**(1/3)) + if xp.any(denom == 0): + msg = ("Test statistic not defined in some cases due to division by " + "zero. Return nan in that case...") + warnings.warn(msg, RuntimeWarning, stacklevel=2) + + Z = (term1 - term2) / (2/(9.0*A))**0.5 # [1]_ Eq. 5 + + pvalue = _get_pvalue(Z, _SimpleNormal(), alternative, xp=xp) + + Z = Z[()] if Z.ndim == 0 else Z + pvalue = pvalue[()] if pvalue.ndim == 0 else pvalue + return KurtosistestResult(Z, pvalue) + + +NormaltestResult = namedtuple('NormaltestResult', ('statistic', 'pvalue')) + + +@_axis_nan_policy_factory(NormaltestResult, n_samples=1, too_small=7) +def normaltest(a, axis=0, nan_policy='propagate'): + r"""Test whether a sample differs from a normal distribution. + + This function tests the null hypothesis that a sample comes + from a normal distribution. It is based on D'Agostino and + Pearson's [1]_, [2]_ test that combines skew and kurtosis to + produce an omnibus test of normality. + + Parameters + ---------- + a : array_like + The array containing the sample to be tested. Must contain + at least eight observations. + axis : int or None, optional + Axis along which to compute test. Default is 0. If None, + compute over the whole array `a`. + nan_policy : {'propagate', 'raise', 'omit'}, optional + Defines how to handle when input contains nan. + The following options are available (default is 'propagate'): + + * 'propagate': returns nan + * 'raise': throws an error + * 'omit': performs the calculations ignoring nan values + + Returns + ------- + statistic : float or array + ``s^2 + k^2``, where ``s`` is the z-score returned by `skewtest` and + ``k`` is the z-score returned by `kurtosistest`. + pvalue : float or array + A 2-sided chi squared probability for the hypothesis test. + + See Also + -------- + :ref:`hypothesis_normaltest` : Extended example + + References + ---------- + .. [1] D'Agostino, R. B. (1971), "An omnibus test of normality for + moderate and large sample size", Biometrika, 58, 341-348 + .. [2] D'Agostino, R. and Pearson, E. S. (1973), "Tests for departure from + normality", Biometrika, 60, 613-622 + + Examples + -------- + + >>> import numpy as np + >>> from scipy import stats + >>> rng = np.random.default_rng() + >>> pts = 1000 + >>> a = rng.normal(0, 1, size=pts) + >>> b = rng.normal(2, 1, size=pts) + >>> x = np.concatenate((a, b)) + >>> res = stats.normaltest(x) + >>> res.statistic + 53.619... # random + >>> res.pvalue + 2.273917413209226e-12 # random + + For a more detailed example, see :ref:`hypothesis_normaltest`. + """ + xp = array_namespace(a) + + s, _ = skewtest(a, axis, _no_deco=True) + k, _ = kurtosistest(a, axis, _no_deco=True) + statistic = s*s + k*k + + chi2 = _SimpleChi2(xp.asarray(2.)) + pvalue = _get_pvalue(statistic, chi2, alternative='greater', symmetric=False, xp=xp) + + statistic = statistic[()] if statistic.ndim == 0 else statistic + pvalue = pvalue[()] if pvalue.ndim == 0 else pvalue + + return NormaltestResult(statistic, pvalue) + + +@_axis_nan_policy_factory(SignificanceResult, default_axis=None) +def jarque_bera(x, *, axis=None): + r"""Perform the Jarque-Bera goodness of fit test on sample data. + + The Jarque-Bera test tests whether the sample data has the skewness and + kurtosis matching a normal distribution. + + Note that this test only works for a large enough number of data samples + (>2000) as the test statistic asymptotically has a Chi-squared distribution + with 2 degrees of freedom. + + Parameters + ---------- + x : array_like + Observations of a random variable. + axis : int or None, default: 0 + If an int, the axis of the input along which to compute the statistic. + The statistic of each axis-slice (e.g. row) of the input will appear in + a corresponding element of the output. + If ``None``, the input will be raveled before computing the statistic. + + Returns + ------- + result : SignificanceResult + An object with the following attributes: + + statistic : float + The test statistic. + pvalue : float + The p-value for the hypothesis test. + + See Also + -------- + :ref:`hypothesis_jarque_bera` : Extended example + + References + ---------- + .. [1] Jarque, C. and Bera, A. (1980) "Efficient tests for normality, + homoscedasticity and serial independence of regression residuals", + 6 Econometric Letters 255-259. + + Examples + -------- + + >>> import numpy as np + >>> from scipy import stats + >>> rng = np.random.default_rng() + >>> x = rng.normal(0, 1, 100000) + >>> jarque_bera_test = stats.jarque_bera(x) + >>> jarque_bera_test + Jarque_beraResult(statistic=3.3415184718131554, pvalue=0.18810419594996775) + >>> jarque_bera_test.statistic + 3.3415184718131554 + >>> jarque_bera_test.pvalue + 0.18810419594996775 + + For a more detailed example, see :ref:`hypothesis_jarque_bera`. + """ + xp = array_namespace(x) + x = xp.asarray(x) + if axis is None: + x = xp.reshape(x, (-1,)) + axis = 0 + + n = x.shape[axis] + if n == 0: + raise ValueError('At least one observation is required.') + + mu = xp.mean(x, axis=axis, keepdims=True) + diffx = x - mu + s = skew(diffx, axis=axis, _no_deco=True) + k = kurtosis(diffx, axis=axis, _no_deco=True) + statistic = n / 6 * (s**2 + k**2 / 4) + + chi2 = _SimpleChi2(xp.asarray(2.)) + pvalue = _get_pvalue(statistic, chi2, alternative='greater', symmetric=False, xp=xp) + + statistic = statistic[()] if statistic.ndim == 0 else statistic + pvalue = pvalue[()] if pvalue.ndim == 0 else pvalue + + return SignificanceResult(statistic, pvalue) + + +##################################### +# FREQUENCY FUNCTIONS # +##################################### + + +def scoreatpercentile(a, per, limit=(), interpolation_method='fraction', + axis=None): + """Calculate the score at a given percentile of the input sequence. + + For example, the score at ``per=50`` is the median. If the desired quantile + lies between two data points, we interpolate between them, according to + the value of `interpolation`. If the parameter `limit` is provided, it + should be a tuple (lower, upper) of two values. + + Parameters + ---------- + a : array_like + A 1-D array of values from which to extract score. + per : array_like + Percentile(s) at which to extract score. Values should be in range + [0,100]. + limit : tuple, optional + Tuple of two scalars, the lower and upper limits within which to + compute the percentile. Values of `a` outside + this (closed) interval will be ignored. + interpolation_method : {'fraction', 'lower', 'higher'}, optional + Specifies the interpolation method to use, + when the desired quantile lies between two data points `i` and `j` + The following options are available (default is 'fraction'): + + * 'fraction': ``i + (j - i) * fraction`` where ``fraction`` is the + fractional part of the index surrounded by ``i`` and ``j`` + * 'lower': ``i`` + * 'higher': ``j`` + + axis : int, optional + Axis along which the percentiles are computed. Default is None. If + None, compute over the whole array `a`. + + Returns + ------- + score : float or ndarray + Score at percentile(s). + + See Also + -------- + percentileofscore, numpy.percentile + + Notes + ----- + This function will become obsolete in the future. + For NumPy 1.9 and higher, `numpy.percentile` provides all the functionality + that `scoreatpercentile` provides. And it's significantly faster. + Therefore it's recommended to use `numpy.percentile` for users that have + numpy >= 1.9. + + Examples + -------- + >>> import numpy as np + >>> from scipy import stats + >>> a = np.arange(100) + >>> stats.scoreatpercentile(a, 50) + 49.5 + + """ + # adapted from NumPy's percentile function. When we require numpy >= 1.8, + # the implementation of this function can be replaced by np.percentile. + a = np.asarray(a) + if a.size == 0: + # empty array, return nan(s) with shape matching `per` + if np.isscalar(per): + return np.nan + else: + return np.full(np.asarray(per).shape, np.nan, dtype=np.float64) + + if limit: + a = a[(limit[0] <= a) & (a <= limit[1])] + + sorted_ = np.sort(a, axis=axis) + if axis is None: + axis = 0 + + return _compute_qth_percentile(sorted_, per, interpolation_method, axis) + + +# handle sequence of per's without calling sort multiple times +def _compute_qth_percentile(sorted_, per, interpolation_method, axis): + if not np.isscalar(per): + score = [_compute_qth_percentile(sorted_, i, + interpolation_method, axis) + for i in per] + return np.array(score) + + if not (0 <= per <= 100): + raise ValueError("percentile must be in the range [0, 100]") + + indexer = [slice(None)] * sorted_.ndim + idx = per / 100. * (sorted_.shape[axis] - 1) + + if int(idx) != idx: + # round fractional indices according to interpolation method + if interpolation_method == 'lower': + idx = int(np.floor(idx)) + elif interpolation_method == 'higher': + idx = int(np.ceil(idx)) + elif interpolation_method == 'fraction': + pass # keep idx as fraction and interpolate + else: + raise ValueError("interpolation_method can only be 'fraction', " + "'lower' or 'higher'") + + i = int(idx) + if i == idx: + indexer[axis] = slice(i, i + 1) + weights = array(1) + sumval = 1.0 + else: + indexer[axis] = slice(i, i + 2) + j = i + 1 + weights = array([(j - idx), (idx - i)], float) + wshape = [1] * sorted_.ndim + wshape[axis] = 2 + weights.shape = wshape + sumval = weights.sum() + + # Use np.add.reduce (== np.sum but a little faster) to coerce data type + return np.add.reduce(sorted_[tuple(indexer)] * weights, axis=axis) / sumval + + +def percentileofscore(a, score, kind='rank', nan_policy='propagate'): + """Compute the percentile rank of a score relative to a list of scores. + + A `percentileofscore` of, for example, 80% means that 80% of the + scores in `a` are below the given score. In the case of gaps or + ties, the exact definition depends on the optional keyword, `kind`. + + Parameters + ---------- + a : array_like + A 1-D array to which `score` is compared. + score : array_like + Scores to compute percentiles for. + kind : {'rank', 'weak', 'strict', 'mean'}, optional + Specifies the interpretation of the resulting score. + The following options are available (default is 'rank'): + + * 'rank': Average percentage ranking of score. In case of multiple + matches, average the percentage rankings of all matching scores. + * 'weak': This kind corresponds to the definition of a cumulative + distribution function. A percentileofscore of 80% means that 80% + of values are less than or equal to the provided score. + * 'strict': Similar to "weak", except that only values that are + strictly less than the given score are counted. + * 'mean': The average of the "weak" and "strict" scores, often used + in testing. See https://en.wikipedia.org/wiki/Percentile_rank + nan_policy : {'propagate', 'raise', 'omit'}, optional + Specifies how to treat `nan` values in `a`. + The following options are available (default is 'propagate'): + + * 'propagate': returns nan (for each value in `score`). + * 'raise': throws an error + * 'omit': performs the calculations ignoring nan values + + Returns + ------- + pcos : float + Percentile-position of score (0-100) relative to `a`. + + See Also + -------- + numpy.percentile + scipy.stats.scoreatpercentile, scipy.stats.rankdata + + Examples + -------- + Three-quarters of the given values lie below a given score: + + >>> import numpy as np + >>> from scipy import stats + >>> stats.percentileofscore([1, 2, 3, 4], 3) + 75.0 + + With multiple matches, note how the scores of the two matches, 0.6 + and 0.8 respectively, are averaged: + + >>> stats.percentileofscore([1, 2, 3, 3, 4], 3) + 70.0 + + Only 2/5 values are strictly less than 3: + + >>> stats.percentileofscore([1, 2, 3, 3, 4], 3, kind='strict') + 40.0 + + But 4/5 values are less than or equal to 3: + + >>> stats.percentileofscore([1, 2, 3, 3, 4], 3, kind='weak') + 80.0 + + The average between the weak and the strict scores is: + + >>> stats.percentileofscore([1, 2, 3, 3, 4], 3, kind='mean') + 60.0 + + Score arrays (of any dimensionality) are supported: + + >>> stats.percentileofscore([1, 2, 3, 3, 4], [2, 3]) + array([40., 70.]) + + The inputs can be infinite: + + >>> stats.percentileofscore([-np.inf, 0, 1, np.inf], [1, 2, np.inf]) + array([75., 75., 100.]) + + If `a` is empty, then the resulting percentiles are all `nan`: + + >>> stats.percentileofscore([], [1, 2]) + array([nan, nan]) + """ + + a = np.asarray(a) + n = len(a) + score = np.asarray(score) + + # Nan treatment + cna, npa = _contains_nan(a, nan_policy) + cns, nps = _contains_nan(score, nan_policy) + + if (cna or cns) and nan_policy == 'raise': + raise ValueError("The input contains nan values") + + if cns: + # If a score is nan, then the output should be nan + # (also if nan_policy is "omit", because it only applies to `a`) + score = ma.masked_where(np.isnan(score), score) + + if cna: + if nan_policy == "omit": + # Don't count nans + a = ma.masked_where(np.isnan(a), a) + n = a.count() + + if nan_policy == "propagate": + # All outputs should be nans + n = 0 + + # Cannot compare to empty list ==> nan + if n == 0: + perct = np.full_like(score, np.nan, dtype=np.float64) + + else: + # Prepare broadcasting + score = score[..., None] + + def count(x): + return np.count_nonzero(x, -1) + + # Main computations/logic + if kind == 'rank': + left = count(a < score) + right = count(a <= score) + plus1 = left < right + perct = (left + right + plus1) * (50.0 / n) + elif kind == 'strict': + perct = count(a < score) * (100.0 / n) + elif kind == 'weak': + perct = count(a <= score) * (100.0 / n) + elif kind == 'mean': + left = count(a < score) + right = count(a <= score) + perct = (left + right) * (50.0 / n) + else: + raise ValueError( + "kind can only be 'rank', 'strict', 'weak' or 'mean'") + + # Re-insert nan values + perct = ma.filled(perct, np.nan) + + if perct.ndim == 0: + return perct[()] + return perct + + +HistogramResult = namedtuple('HistogramResult', + ('count', 'lowerlimit', 'binsize', 'extrapoints')) + + +def _histogram(a, numbins=10, defaultlimits=None, weights=None, + printextras=False): + """Create a histogram. + + Separate the range into several bins and return the number of instances + in each bin. + + Parameters + ---------- + a : array_like + Array of scores which will be put into bins. + numbins : int, optional + The number of bins to use for the histogram. Default is 10. + defaultlimits : tuple (lower, upper), optional + The lower and upper values for the range of the histogram. + If no value is given, a range slightly larger than the range of the + values in a is used. Specifically ``(a.min() - s, a.max() + s)``, + where ``s = (1/2)(a.max() - a.min()) / (numbins - 1)``. + weights : array_like, optional + The weights for each value in `a`. Default is None, which gives each + value a weight of 1.0 + printextras : bool, optional + If True, if there are extra points (i.e. the points that fall outside + the bin limits) a warning is raised saying how many of those points + there are. Default is False. + + Returns + ------- + count : ndarray + Number of points (or sum of weights) in each bin. + lowerlimit : float + Lowest value of histogram, the lower limit of the first bin. + binsize : float + The size of the bins (all bins have the same size). + extrapoints : int + The number of points outside the range of the histogram. + + See Also + -------- + numpy.histogram + + Notes + ----- + This histogram is based on numpy's histogram but has a larger range by + default if default limits is not set. + + """ + a = np.ravel(a) + if defaultlimits is None: + if a.size == 0: + # handle empty arrays. Undetermined range, so use 0-1. + defaultlimits = (0, 1) + else: + # no range given, so use values in `a` + data_min = a.min() + data_max = a.max() + # Have bins extend past min and max values slightly + s = (data_max - data_min) / (2. * (numbins - 1.)) + defaultlimits = (data_min - s, data_max + s) + + # use numpy's histogram method to compute bins + hist, bin_edges = np.histogram(a, bins=numbins, range=defaultlimits, + weights=weights) + # hist are not always floats, convert to keep with old output + hist = np.array(hist, dtype=float) + # fixed width for bins is assumed, as numpy's histogram gives + # fixed width bins for int values for 'bins' + binsize = bin_edges[1] - bin_edges[0] + # calculate number of extra points + extrapoints = len([v for v in a + if defaultlimits[0] > v or v > defaultlimits[1]]) + if extrapoints > 0 and printextras: + warnings.warn(f"Points outside given histogram range = {extrapoints}", + stacklevel=3,) + + return HistogramResult(hist, defaultlimits[0], binsize, extrapoints) + + +CumfreqResult = namedtuple('CumfreqResult', + ('cumcount', 'lowerlimit', 'binsize', + 'extrapoints')) + + +def cumfreq(a, numbins=10, defaultreallimits=None, weights=None): + """Return a cumulative frequency histogram, using the histogram function. + + A cumulative histogram is a mapping that counts the cumulative number of + observations in all of the bins up to the specified bin. + + Parameters + ---------- + a : array_like + Input array. + numbins : int, optional + The number of bins to use for the histogram. Default is 10. + defaultreallimits : tuple (lower, upper), optional + The lower and upper values for the range of the histogram. + If no value is given, a range slightly larger than the range of the + values in `a` is used. Specifically ``(a.min() - s, a.max() + s)``, + where ``s = (1/2)(a.max() - a.min()) / (numbins - 1)``. + weights : array_like, optional + The weights for each value in `a`. Default is None, which gives each + value a weight of 1.0 + + Returns + ------- + cumcount : ndarray + Binned values of cumulative frequency. + lowerlimit : float + Lower real limit + binsize : float + Width of each bin. + extrapoints : int + Extra points. + + Examples + -------- + >>> import numpy as np + >>> import matplotlib.pyplot as plt + >>> from scipy import stats + >>> rng = np.random.default_rng() + >>> x = [1, 4, 2, 1, 3, 1] + >>> res = stats.cumfreq(x, numbins=4, defaultreallimits=(1.5, 5)) + >>> res.cumcount + array([ 1., 2., 3., 3.]) + >>> res.extrapoints + 3 + + Create a normal distribution with 1000 random values + + >>> samples = stats.norm.rvs(size=1000, random_state=rng) + + Calculate cumulative frequencies + + >>> res = stats.cumfreq(samples, numbins=25) + + Calculate space of values for x + + >>> x = res.lowerlimit + np.linspace(0, res.binsize*res.cumcount.size, + ... res.cumcount.size) + + Plot histogram and cumulative histogram + + >>> fig = plt.figure(figsize=(10, 4)) + >>> ax1 = fig.add_subplot(1, 2, 1) + >>> ax2 = fig.add_subplot(1, 2, 2) + >>> ax1.hist(samples, bins=25) + >>> ax1.set_title('Histogram') + >>> ax2.bar(x, res.cumcount, width=res.binsize) + >>> ax2.set_title('Cumulative histogram') + >>> ax2.set_xlim([x.min(), x.max()]) + + >>> plt.show() + + """ + h, l, b, e = _histogram(a, numbins, defaultreallimits, weights=weights) + cumhist = np.cumsum(h * 1, axis=0) + return CumfreqResult(cumhist, l, b, e) + + +RelfreqResult = namedtuple('RelfreqResult', + ('frequency', 'lowerlimit', 'binsize', + 'extrapoints')) + + +def relfreq(a, numbins=10, defaultreallimits=None, weights=None): + """Return a relative frequency histogram, using the histogram function. + + A relative frequency histogram is a mapping of the number of + observations in each of the bins relative to the total of observations. + + Parameters + ---------- + a : array_like + Input array. + numbins : int, optional + The number of bins to use for the histogram. Default is 10. + defaultreallimits : tuple (lower, upper), optional + The lower and upper values for the range of the histogram. + If no value is given, a range slightly larger than the range of the + values in a is used. Specifically ``(a.min() - s, a.max() + s)``, + where ``s = (1/2)(a.max() - a.min()) / (numbins - 1)``. + weights : array_like, optional + The weights for each value in `a`. Default is None, which gives each + value a weight of 1.0 + + Returns + ------- + frequency : ndarray + Binned values of relative frequency. + lowerlimit : float + Lower real limit. + binsize : float + Width of each bin. + extrapoints : int + Extra points. + + Examples + -------- + >>> import numpy as np + >>> import matplotlib.pyplot as plt + >>> from scipy import stats + >>> rng = np.random.default_rng() + >>> a = np.array([2, 4, 1, 2, 3, 2]) + >>> res = stats.relfreq(a, numbins=4) + >>> res.frequency + array([ 0.16666667, 0.5 , 0.16666667, 0.16666667]) + >>> np.sum(res.frequency) # relative frequencies should add up to 1 + 1.0 + + Create a normal distribution with 1000 random values + + >>> samples = stats.norm.rvs(size=1000, random_state=rng) + + Calculate relative frequencies + + >>> res = stats.relfreq(samples, numbins=25) + + Calculate space of values for x + + >>> x = res.lowerlimit + np.linspace(0, res.binsize*res.frequency.size, + ... res.frequency.size) + + Plot relative frequency histogram + + >>> fig = plt.figure(figsize=(5, 4)) + >>> ax = fig.add_subplot(1, 1, 1) + >>> ax.bar(x, res.frequency, width=res.binsize) + >>> ax.set_title('Relative frequency histogram') + >>> ax.set_xlim([x.min(), x.max()]) + + >>> plt.show() + + """ + a = np.asanyarray(a) + h, l, b, e = _histogram(a, numbins, defaultreallimits, weights=weights) + h = h / a.shape[0] + + return RelfreqResult(h, l, b, e) + + +##################################### +# VARIABILITY FUNCTIONS # +##################################### + +def obrientransform(*samples): + """Compute the O'Brien transform on input data (any number of arrays). + + Used to test for homogeneity of variance prior to running one-way stats. + Each array in ``*samples`` is one level of a factor. + If `f_oneway` is run on the transformed data and found significant, + the variances are unequal. From Maxwell and Delaney [1]_, p.112. + + Parameters + ---------- + sample1, sample2, ... : array_like + Any number of arrays. + + Returns + ------- + obrientransform : ndarray + Transformed data for use in an ANOVA. The first dimension + of the result corresponds to the sequence of transformed + arrays. If the arrays given are all 1-D of the same length, + the return value is a 2-D array; otherwise it is a 1-D array + of type object, with each element being an ndarray. + + Raises + ------ + ValueError + If the mean of the transformed data is not equal to the original + variance, indicating a lack of convergence in the O'Brien transform. + + References + ---------- + .. [1] S. E. Maxwell and H. D. Delaney, "Designing Experiments and + Analyzing Data: A Model Comparison Perspective", Wadsworth, 1990. + + Examples + -------- + We'll test the following data sets for differences in their variance. + + >>> x = [10, 11, 13, 9, 7, 12, 12, 9, 10] + >>> y = [13, 21, 5, 10, 8, 14, 10, 12, 7, 15] + + Apply the O'Brien transform to the data. + + >>> from scipy.stats import obrientransform + >>> tx, ty = obrientransform(x, y) + + Use `scipy.stats.f_oneway` to apply a one-way ANOVA test to the + transformed data. + + >>> from scipy.stats import f_oneway + >>> F, p = f_oneway(tx, ty) + >>> p + 0.1314139477040335 + + If we require that ``p < 0.05`` for significance, we cannot conclude + that the variances are different. + + """ + TINY = np.sqrt(np.finfo(float).eps) + + # `arrays` will hold the transformed arguments. + arrays = [] + sLast = None + + for sample in samples: + a = np.asarray(sample) + n = len(a) + mu = np.mean(a) + sq = (a - mu)**2 + sumsq = sq.sum() + + # The O'Brien transform. + t = ((n - 1.5) * n * sq - 0.5 * sumsq) / ((n - 1) * (n - 2)) + + # Check that the mean of the transformed data is equal to the + # original variance. + var = sumsq / (n - 1) + if abs(var - np.mean(t)) > TINY: + raise ValueError('Lack of convergence in obrientransform.') + + arrays.append(t) + sLast = a.shape + + if sLast: + for arr in arrays[:-1]: + if sLast != arr.shape: + return np.array(arrays, dtype=object) + return np.array(arrays) + + +@_axis_nan_policy_factory( + lambda x: x, result_to_tuple=lambda x: (x,), n_outputs=1, too_small=1 +) +def sem(a, axis=0, ddof=1, nan_policy='propagate'): + """Compute standard error of the mean. + + Calculate the standard error of the mean (or standard error of + measurement) of the values in the input array. + + Parameters + ---------- + a : array_like + An array containing the values for which the standard error is + returned. Must contain at least two observations. + axis : int or None, optional + Axis along which to operate. Default is 0. If None, compute over + the whole array `a`. + ddof : int, optional + Delta degrees-of-freedom. How many degrees of freedom to adjust + for bias in limited samples relative to the population estimate + of variance. Defaults to 1. + nan_policy : {'propagate', 'raise', 'omit'}, optional + Defines how to handle when input contains nan. + The following options are available (default is 'propagate'): + + * 'propagate': returns nan + * 'raise': throws an error + * 'omit': performs the calculations ignoring nan values + + Returns + ------- + s : ndarray or float + The standard error of the mean in the sample(s), along the input axis. + + Notes + ----- + The default value for `ddof` is different to the default (0) used by other + ddof containing routines, such as np.std and np.nanstd. + + Examples + -------- + Find standard error along the first axis: + + >>> import numpy as np + >>> from scipy import stats + >>> a = np.arange(20).reshape(5,4) + >>> stats.sem(a) + array([ 2.8284, 2.8284, 2.8284, 2.8284]) + + Find standard error across the whole array, using n degrees of freedom: + + >>> stats.sem(a, axis=None, ddof=0) + 1.2893796958227628 + + """ + xp = array_namespace(a) + if axis is None: + a = xp.reshape(a, (-1,)) + axis = 0 + a = xpx.atleast_nd(xp.asarray(a), ndim=1, xp=xp) + n = a.shape[axis] + s = xp.std(a, axis=axis, correction=ddof) / n**0.5 + return s + + +def _isconst(x): + """ + Check if all values in x are the same. nans are ignored. + + x must be a 1d array. + + The return value is a 1d array with length 1, so it can be used + in np.apply_along_axis. + """ + y = x[~np.isnan(x)] + if y.size == 0: + return np.array([True]) + else: + return (y[0] == y).all(keepdims=True) + + +def zscore(a, axis=0, ddof=0, nan_policy='propagate'): + """ + Compute the z score. + + Compute the z score of each value in the sample, relative to the + sample mean and standard deviation. + + Parameters + ---------- + a : array_like + An array like object containing the sample data. + axis : int or None, optional + Axis along which to operate. Default is 0. If None, compute over + the whole array `a`. + ddof : int, optional + Degrees of freedom correction in the calculation of the + standard deviation. Default is 0. + nan_policy : {'propagate', 'raise', 'omit'}, optional + Defines how to handle when input contains nan. 'propagate' returns nan, + 'raise' throws an error, 'omit' performs the calculations ignoring nan + values. Default is 'propagate'. Note that when the value is 'omit', + nans in the input also propagate to the output, but they do not affect + the z-scores computed for the non-nan values. + + Returns + ------- + zscore : array_like + The z-scores, standardized by mean and standard deviation of + input array `a`. + + See Also + -------- + numpy.mean : Arithmetic average + numpy.std : Arithmetic standard deviation + scipy.stats.gzscore : Geometric standard score + + Notes + ----- + This function preserves ndarray subclasses, and works also with + matrices and masked arrays (it uses `asanyarray` instead of + `asarray` for parameters). + + References + ---------- + .. [1] "Standard score", *Wikipedia*, + https://en.wikipedia.org/wiki/Standard_score. + .. [2] Huck, S. W., Cross, T. L., Clark, S. B, "Overcoming misconceptions + about Z-scores", Teaching Statistics, vol. 8, pp. 38-40, 1986 + + Examples + -------- + >>> import numpy as np + >>> a = np.array([ 0.7972, 0.0767, 0.4383, 0.7866, 0.8091, + ... 0.1954, 0.6307, 0.6599, 0.1065, 0.0508]) + >>> from scipy import stats + >>> stats.zscore(a) + array([ 1.1273, -1.247 , -0.0552, 1.0923, 1.1664, -0.8559, 0.5786, + 0.6748, -1.1488, -1.3324]) + + Computing along a specified axis, using n-1 degrees of freedom + (``ddof=1``) to calculate the standard deviation: + + >>> b = np.array([[ 0.3148, 0.0478, 0.6243, 0.4608], + ... [ 0.7149, 0.0775, 0.6072, 0.9656], + ... [ 0.6341, 0.1403, 0.9759, 0.4064], + ... [ 0.5918, 0.6948, 0.904 , 0.3721], + ... [ 0.0921, 0.2481, 0.1188, 0.1366]]) + >>> stats.zscore(b, axis=1, ddof=1) + array([[-0.19264823, -1.28415119, 1.07259584, 0.40420358], + [ 0.33048416, -1.37380874, 0.04251374, 1.00081084], + [ 0.26796377, -1.12598418, 1.23283094, -0.37481053], + [-0.22095197, 0.24468594, 1.19042819, -1.21416216], + [-0.82780366, 1.4457416 , -0.43867764, -0.1792603 ]]) + + An example with ``nan_policy='omit'``: + + >>> x = np.array([[25.11, 30.10, np.nan, 32.02, 43.15], + ... [14.95, 16.06, 121.25, 94.35, 29.81]]) + >>> stats.zscore(x, axis=1, nan_policy='omit') + array([[-1.13490897, -0.37830299, nan, -0.08718406, 1.60039602], + [-0.91611681, -0.89090508, 1.4983032 , 0.88731639, -0.5785977 ]]) + """ + return zmap(a, a, axis=axis, ddof=ddof, nan_policy=nan_policy) + + +def gzscore(a, *, axis=0, ddof=0, nan_policy='propagate'): + """ + Compute the geometric standard score. + + Compute the geometric z score of each strictly positive value in the + sample, relative to the geometric mean and standard deviation. + Mathematically the geometric z score can be evaluated as:: + + gzscore = log(a/gmu) / log(gsigma) + + where ``gmu`` (resp. ``gsigma``) is the geometric mean (resp. standard + deviation). + + Parameters + ---------- + a : array_like + Sample data. + axis : int or None, optional + Axis along which to operate. Default is 0. If None, compute over + the whole array `a`. + ddof : int, optional + Degrees of freedom correction in the calculation of the + standard deviation. Default is 0. + nan_policy : {'propagate', 'raise', 'omit'}, optional + Defines how to handle when input contains nan. 'propagate' returns nan, + 'raise' throws an error, 'omit' performs the calculations ignoring nan + values. Default is 'propagate'. Note that when the value is 'omit', + nans in the input also propagate to the output, but they do not affect + the geometric z scores computed for the non-nan values. + + Returns + ------- + gzscore : array_like + The geometric z scores, standardized by geometric mean and geometric + standard deviation of input array `a`. + + See Also + -------- + gmean : Geometric mean + gstd : Geometric standard deviation + zscore : Standard score + + Notes + ----- + This function preserves ndarray subclasses, and works also with + matrices and masked arrays (it uses ``asanyarray`` instead of + ``asarray`` for parameters). + + .. versionadded:: 1.8 + + References + ---------- + .. [1] "Geometric standard score", *Wikipedia*, + https://en.wikipedia.org/wiki/Geometric_standard_deviation#Geometric_standard_score. + + Examples + -------- + Draw samples from a log-normal distribution: + + >>> import numpy as np + >>> from scipy.stats import zscore, gzscore + >>> import matplotlib.pyplot as plt + + >>> rng = np.random.default_rng() + >>> mu, sigma = 3., 1. # mean and standard deviation + >>> x = rng.lognormal(mu, sigma, size=500) + + Display the histogram of the samples: + + >>> fig, ax = plt.subplots() + >>> ax.hist(x, 50) + >>> plt.show() + + Display the histogram of the samples standardized by the classical zscore. + Distribution is rescaled but its shape is unchanged. + + >>> fig, ax = plt.subplots() + >>> ax.hist(zscore(x), 50) + >>> plt.show() + + Demonstrate that the distribution of geometric zscores is rescaled and + quasinormal: + + >>> fig, ax = plt.subplots() + >>> ax.hist(gzscore(x), 50) + >>> plt.show() + + """ + xp = array_namespace(a) + a = _convert_common_float(a, xp=xp) + log = ma.log if isinstance(a, ma.MaskedArray) else xp.log + return zscore(log(a), axis=axis, ddof=ddof, nan_policy=nan_policy) + + +def zmap(scores, compare, axis=0, ddof=0, nan_policy='propagate'): + """ + Calculate the relative z-scores. + + Return an array of z-scores, i.e., scores that are standardized to + zero mean and unit variance, where mean and variance are calculated + from the comparison array. + + Parameters + ---------- + scores : array_like + The input for which z-scores are calculated. + compare : array_like + The input from which the mean and standard deviation of the + normalization are taken; assumed to have the same dimension as + `scores`. + axis : int or None, optional + Axis over which mean and variance of `compare` are calculated. + Default is 0. If None, compute over the whole array `scores`. + ddof : int, optional + Degrees of freedom correction in the calculation of the + standard deviation. Default is 0. + nan_policy : {'propagate', 'raise', 'omit'}, optional + Defines how to handle the occurrence of nans in `compare`. + 'propagate' returns nan, 'raise' raises an exception, 'omit' + performs the calculations ignoring nan values. Default is + 'propagate'. Note that when the value is 'omit', nans in `scores` + also propagate to the output, but they do not affect the z-scores + computed for the non-nan values. + + Returns + ------- + zscore : array_like + Z-scores, in the same shape as `scores`. + + Notes + ----- + This function preserves ndarray subclasses, and works also with + matrices and masked arrays (it uses `asanyarray` instead of + `asarray` for parameters). + + Examples + -------- + >>> from scipy.stats import zmap + >>> a = [0.5, 2.0, 2.5, 3] + >>> b = [0, 1, 2, 3, 4] + >>> zmap(a, b) + array([-1.06066017, 0. , 0.35355339, 0.70710678]) + + """ + # The docstring explicitly states that it preserves subclasses. + # Let's table deprecating that and just get the array API version + # working. + + like_zscore = (scores is compare) + xp = array_namespace(scores, compare) + scores, compare = _convert_common_float(scores, compare, xp=xp) + + with warnings.catch_warnings(): + if like_zscore: # zscore should not emit SmallSampleWarning + warnings.simplefilter('ignore', SmallSampleWarning) + + mn = _xp_mean(compare, axis=axis, keepdims=True, nan_policy=nan_policy) + std = _xp_var(compare, axis=axis, correction=ddof, + keepdims=True, nan_policy=nan_policy)**0.5 + + with np.errstate(invalid='ignore', divide='ignore'): + z = _demean(scores, mn, axis, xp=xp, precision_warning=False) / std + + # If we know that scores and compare are identical, we can infer that + # some slices should have NaNs. + if like_zscore: + eps = xp.finfo(z.dtype).eps + zero = std <= xp.abs(eps * mn) + zero = xp.broadcast_to(zero, z.shape) + z[zero] = xp.nan + + return z + + +def gstd(a, axis=0, ddof=1): + r""" + Calculate the geometric standard deviation of an array. + + The geometric standard deviation describes the spread of a set of numbers + where the geometric mean is preferred. It is a multiplicative factor, and + so a dimensionless quantity. + + It is defined as the exponential of the standard deviation of the + natural logarithms of the observations. + + Parameters + ---------- + a : array_like + An array containing finite, strictly positive, real numbers. + + .. deprecated:: 1.14.0 + Support for masked array input was deprecated in + SciPy 1.14.0 and will be removed in version 1.16.0. + + axis : int, tuple or None, optional + Axis along which to operate. Default is 0. If None, compute over + the whole array `a`. + ddof : int, optional + Degree of freedom correction in the calculation of the + geometric standard deviation. Default is 1. + + Returns + ------- + gstd : ndarray or float + An array of the geometric standard deviation. If `axis` is None or `a` + is a 1d array a float is returned. + + See Also + -------- + gmean : Geometric mean + numpy.std : Standard deviation + gzscore : Geometric standard score + + Notes + ----- + Mathematically, the sample geometric standard deviation :math:`s_G` can be + defined in terms of the natural logarithms of the observations + :math:`y_i = \log(x_i)`: + + .. math:: + + s_G = \exp(s), \quad s = \sqrt{\frac{1}{n - d} \sum_{i=1}^n (y_i - \bar y)^2} + + where :math:`n` is the number of observations, :math:`d` is the adjustment `ddof` + to the degrees of freedom, and :math:`\bar y` denotes the mean of the natural + logarithms of the observations. Note that the default ``ddof=1`` is different from + the default value used by similar functions, such as `numpy.std` and `numpy.var`. + + When an observation is infinite, the geometric standard deviation is + NaN (undefined). Non-positive observations will also produce NaNs in the + output because the *natural* logarithm (as opposed to the *complex* + logarithm) is defined and finite only for positive reals. + The geometric standard deviation is sometimes confused with the exponential + of the standard deviation, ``exp(std(a))``. Instead, the geometric standard + deviation is ``exp(std(log(a)))``. + + References + ---------- + .. [1] "Geometric standard deviation", *Wikipedia*, + https://en.wikipedia.org/wiki/Geometric_standard_deviation. + .. [2] Kirkwood, T. B., "Geometric means and measures of dispersion", + Biometrics, vol. 35, pp. 908-909, 1979 + + Examples + -------- + Find the geometric standard deviation of a log-normally distributed sample. + Note that the standard deviation of the distribution is one; on a + log scale this evaluates to approximately ``exp(1)``. + + >>> import numpy as np + >>> from scipy.stats import gstd + >>> rng = np.random.default_rng() + >>> sample = rng.lognormal(mean=0, sigma=1, size=1000) + >>> gstd(sample) + 2.810010162475324 + + Compute the geometric standard deviation of a multidimensional array and + of a given axis. + + >>> a = np.arange(1, 25).reshape(2, 3, 4) + >>> gstd(a, axis=None) + 2.2944076136018947 + >>> gstd(a, axis=2) + array([[1.82424757, 1.22436866, 1.13183117], + [1.09348306, 1.07244798, 1.05914985]]) + >>> gstd(a, axis=(1,2)) + array([2.12939215, 1.22120169]) + + """ + a = np.asanyarray(a) + if isinstance(a, ma.MaskedArray): + message = ("`gstd` support for masked array input was deprecated in " + "SciPy 1.14.0 and will be removed in version 1.16.0.") + warnings.warn(message, DeprecationWarning, stacklevel=2) + log = ma.log + else: + log = np.log + + with np.errstate(invalid='ignore', divide='ignore'): + res = np.exp(np.std(log(a), axis=axis, ddof=ddof)) + + if (a <= 0).any(): + message = ("The geometric standard deviation is only defined if all elements " + "are greater than or equal to zero; otherwise, the result is NaN.") + warnings.warn(message, RuntimeWarning, stacklevel=2) + + return res + +# Private dictionary initialized only once at module level +# See https://en.wikipedia.org/wiki/Robust_measures_of_scale +_scale_conversions = {'normal': special.erfinv(0.5) * 2.0 * math.sqrt(2.0)} + + +@_axis_nan_policy_factory( + lambda x: x, result_to_tuple=lambda x: (x,), n_outputs=1, + default_axis=None, override={'nan_propagation': False} +) +def iqr(x, axis=None, rng=(25, 75), scale=1.0, nan_policy='propagate', + interpolation='linear', keepdims=False): + r""" + Compute the interquartile range of the data along the specified axis. + + The interquartile range (IQR) is the difference between the 75th and + 25th percentile of the data. It is a measure of the dispersion + similar to standard deviation or variance, but is much more robust + against outliers [2]_. + + The ``rng`` parameter allows this function to compute other + percentile ranges than the actual IQR. For example, setting + ``rng=(0, 100)`` is equivalent to `numpy.ptp`. + + The IQR of an empty array is `np.nan`. + + .. versionadded:: 0.18.0 + + Parameters + ---------- + x : array_like + Input array or object that can be converted to an array. + axis : int or sequence of int, optional + Axis along which the range is computed. The default is to + compute the IQR for the entire array. + rng : Two-element sequence containing floats in range of [0,100] optional + Percentiles over which to compute the range. Each must be + between 0 and 100, inclusive. The default is the true IQR: + ``(25, 75)``. The order of the elements is not important. + scale : scalar or str or array_like of reals, optional + The numerical value of scale will be divided out of the final + result. The following string value is also recognized: + + * 'normal' : Scale by + :math:`2 \sqrt{2} erf^{-1}(\frac{1}{2}) \approx 1.349`. + + The default is 1.0. + Array-like `scale` of real dtype is also allowed, as long + as it broadcasts correctly to the output such that + ``out / scale`` is a valid operation. The output dimensions + depend on the input array, `x`, the `axis` argument, and the + `keepdims` flag. + nan_policy : {'propagate', 'raise', 'omit'}, optional + Defines how to handle when input contains nan. + The following options are available (default is 'propagate'): + + * 'propagate': returns nan + * 'raise': throws an error + * 'omit': performs the calculations ignoring nan values + interpolation : str, optional + + Specifies the interpolation method to use when the percentile + boundaries lie between two data points ``i`` and ``j``. + The following options are available (default is 'linear'): + + * 'linear': ``i + (j - i)*fraction``, where ``fraction`` is the + fractional part of the index surrounded by ``i`` and ``j``. + * 'lower': ``i``. + * 'higher': ``j``. + * 'nearest': ``i`` or ``j`` whichever is nearest. + * 'midpoint': ``(i + j)/2``. + + For NumPy >= 1.22.0, the additional options provided by the ``method`` + keyword of `numpy.percentile` are also valid. + + keepdims : bool, optional + If this is set to True, the reduced axes are left in the + result as dimensions with size one. With this option, the result + will broadcast correctly against the original array `x`. + + Returns + ------- + iqr : scalar or ndarray + If ``axis=None``, a scalar is returned. If the input contains + integers or floats of smaller precision than ``np.float64``, then the + output data-type is ``np.float64``. Otherwise, the output data-type is + the same as that of the input. + + See Also + -------- + numpy.std, numpy.var + + References + ---------- + .. [1] "Interquartile range" https://en.wikipedia.org/wiki/Interquartile_range + .. [2] "Robust measures of scale" https://en.wikipedia.org/wiki/Robust_measures_of_scale + .. [3] "Quantile" https://en.wikipedia.org/wiki/Quantile + + Examples + -------- + >>> import numpy as np + >>> from scipy.stats import iqr + >>> x = np.array([[10, 7, 4], [3, 2, 1]]) + >>> x + array([[10, 7, 4], + [ 3, 2, 1]]) + >>> iqr(x) + 4.0 + >>> iqr(x, axis=0) + array([ 3.5, 2.5, 1.5]) + >>> iqr(x, axis=1) + array([ 3., 1.]) + >>> iqr(x, axis=1, keepdims=True) + array([[ 3.], + [ 1.]]) + + """ + x = asarray(x) + + # This check prevents percentile from raising an error later. Also, it is + # consistent with `np.var` and `np.std`. + if not x.size: + return _get_nan(x) + + # An error may be raised here, so fail-fast, before doing lengthy + # computations, even though `scale` is not used until later + if isinstance(scale, str): + scale_key = scale.lower() + if scale_key not in _scale_conversions: + raise ValueError(f"{scale} not a valid scale for `iqr`") + scale = _scale_conversions[scale_key] + + # Select the percentile function to use based on nans and policy + contains_nan, nan_policy = _contains_nan(x, nan_policy) + + if contains_nan and nan_policy == 'omit': + percentile_func = np.nanpercentile + else: + percentile_func = np.percentile + + if len(rng) != 2: + raise TypeError("quantile range must be two element sequence") + + if np.isnan(rng).any(): + raise ValueError("range must not contain NaNs") + + rng = sorted(rng) + pct = percentile_func(x, rng, axis=axis, method=interpolation, + keepdims=keepdims) + out = np.subtract(pct[1], pct[0]) + + if scale != 1.0: + out /= scale + + return out + + +def _mad_1d(x, center, nan_policy): + # Median absolute deviation for 1-d array x. + # This is a helper function for `median_abs_deviation`; it assumes its + # arguments have been validated already. In particular, x must be a + # 1-d numpy array, center must be callable, and if nan_policy is not + # 'propagate', it is assumed to be 'omit', because 'raise' is handled + # in `median_abs_deviation`. + # No warning is generated if x is empty or all nan. + isnan = np.isnan(x) + if isnan.any(): + if nan_policy == 'propagate': + return np.nan + x = x[~isnan] + if x.size == 0: + # MAD of an empty array is nan. + return np.nan + # Edge cases have been handled, so do the basic MAD calculation. + med = center(x) + mad = np.median(np.abs(x - med)) + return mad + + +def median_abs_deviation(x, axis=0, center=np.median, scale=1.0, + nan_policy='propagate'): + r""" + Compute the median absolute deviation of the data along the given axis. + + The median absolute deviation (MAD, [1]_) computes the median over the + absolute deviations from the median. It is a measure of dispersion + similar to the standard deviation but more robust to outliers [2]_. + + The MAD of an empty array is ``np.nan``. + + .. versionadded:: 1.5.0 + + Parameters + ---------- + x : array_like + Input array or object that can be converted to an array. + axis : int or None, optional + Axis along which the range is computed. Default is 0. If None, compute + the MAD over the entire array. + center : callable, optional + A function that will return the central value. The default is to use + np.median. Any user defined function used will need to have the + function signature ``func(arr, axis)``. + scale : scalar or str, optional + The numerical value of scale will be divided out of the final + result. The default is 1.0. The string "normal" is also accepted, + and results in `scale` being the inverse of the standard normal + quantile function at 0.75, which is approximately 0.67449. + Array-like scale is also allowed, as long as it broadcasts correctly + to the output such that ``out / scale`` is a valid operation. The + output dimensions depend on the input array, `x`, and the `axis` + argument. + nan_policy : {'propagate', 'raise', 'omit'}, optional + Defines how to handle when input contains nan. + The following options are available (default is 'propagate'): + + * 'propagate': returns nan + * 'raise': throws an error + * 'omit': performs the calculations ignoring nan values + + Returns + ------- + mad : scalar or ndarray + If ``axis=None``, a scalar is returned. If the input contains + integers or floats of smaller precision than ``np.float64``, then the + output data-type is ``np.float64``. Otherwise, the output data-type is + the same as that of the input. + + See Also + -------- + numpy.std, numpy.var, numpy.median, scipy.stats.iqr, scipy.stats.tmean, + scipy.stats.tstd, scipy.stats.tvar + + Notes + ----- + The `center` argument only affects the calculation of the central value + around which the MAD is calculated. That is, passing in ``center=np.mean`` + will calculate the MAD around the mean - it will not calculate the *mean* + absolute deviation. + + The input array may contain `inf`, but if `center` returns `inf`, the + corresponding MAD for that data will be `nan`. + + References + ---------- + .. [1] "Median absolute deviation", + https://en.wikipedia.org/wiki/Median_absolute_deviation + .. [2] "Robust measures of scale", + https://en.wikipedia.org/wiki/Robust_measures_of_scale + + Examples + -------- + When comparing the behavior of `median_abs_deviation` with ``np.std``, + the latter is affected when we change a single value of an array to have an + outlier value while the MAD hardly changes: + + >>> import numpy as np + >>> from scipy import stats + >>> x = stats.norm.rvs(size=100, scale=1, random_state=123456) + >>> x.std() + 0.9973906394005013 + >>> stats.median_abs_deviation(x) + 0.82832610097857 + >>> x[0] = 345.6 + >>> x.std() + 34.42304872314415 + >>> stats.median_abs_deviation(x) + 0.8323442311590675 + + Axis handling example: + + >>> x = np.array([[10, 7, 4], [3, 2, 1]]) + >>> x + array([[10, 7, 4], + [ 3, 2, 1]]) + >>> stats.median_abs_deviation(x) + array([3.5, 2.5, 1.5]) + >>> stats.median_abs_deviation(x, axis=None) + 2.0 + + Scale normal example: + + >>> x = stats.norm.rvs(size=1000000, scale=2, random_state=123456) + >>> stats.median_abs_deviation(x) + 1.3487398527041636 + >>> stats.median_abs_deviation(x, scale='normal') + 1.9996446978061115 + + """ + if not callable(center): + raise TypeError("The argument 'center' must be callable. The given " + f"value {repr(center)} is not callable.") + + # An error may be raised here, so fail-fast, before doing lengthy + # computations, even though `scale` is not used until later + if isinstance(scale, str): + if scale.lower() == 'normal': + scale = 0.6744897501960817 # special.ndtri(0.75) + else: + raise ValueError(f"{scale} is not a valid scale value.") + + x = asarray(x) + + # Consistent with `np.var` and `np.std`. + if not x.size: + if axis is None: + return np.nan + nan_shape = tuple(item for i, item in enumerate(x.shape) if i != axis) + if nan_shape == (): + # Return nan, not array(nan) + return np.nan + return np.full(nan_shape, np.nan) + + contains_nan, nan_policy = _contains_nan(x, nan_policy) + + if contains_nan: + if axis is None: + mad = _mad_1d(x.ravel(), center, nan_policy) + else: + mad = np.apply_along_axis(_mad_1d, axis, x, center, nan_policy) + else: + if axis is None: + med = center(x, axis=None) + mad = np.median(np.abs(x - med)) + else: + # Wrap the call to center() in expand_dims() so it acts like + # keepdims=True was used. + med = np.expand_dims(center(x, axis=axis), axis) + mad = np.median(np.abs(x - med), axis=axis) + + return mad / scale + + +##################################### +# TRIMMING FUNCTIONS # +##################################### + + +SigmaclipResult = namedtuple('SigmaclipResult', ('clipped', 'lower', 'upper')) + + +def sigmaclip(a, low=4., high=4.): + """Perform iterative sigma-clipping of array elements. + + Starting from the full sample, all elements outside the critical range are + removed, i.e. all elements of the input array `c` that satisfy either of + the following conditions:: + + c < mean(c) - std(c)*low + c > mean(c) + std(c)*high + + The iteration continues with the updated sample until no + elements are outside the (updated) range. + + Parameters + ---------- + a : array_like + Data array, will be raveled if not 1-D. + low : float, optional + Lower bound factor of sigma clipping. Default is 4. + high : float, optional + Upper bound factor of sigma clipping. Default is 4. + + Returns + ------- + clipped : ndarray + Input array with clipped elements removed. + lower : float + Lower threshold value use for clipping. + upper : float + Upper threshold value use for clipping. + + Examples + -------- + >>> import numpy as np + >>> from scipy.stats import sigmaclip + >>> a = np.concatenate((np.linspace(9.5, 10.5, 31), + ... np.linspace(0, 20, 5))) + >>> fact = 1.5 + >>> c, low, upp = sigmaclip(a, fact, fact) + >>> c + array([ 9.96666667, 10. , 10.03333333, 10. ]) + >>> c.var(), c.std() + (0.00055555555555555165, 0.023570226039551501) + >>> low, c.mean() - fact*c.std(), c.min() + (9.9646446609406727, 9.9646446609406727, 9.9666666666666668) + >>> upp, c.mean() + fact*c.std(), c.max() + (10.035355339059327, 10.035355339059327, 10.033333333333333) + + >>> a = np.concatenate((np.linspace(9.5, 10.5, 11), + ... np.linspace(-100, -50, 3))) + >>> c, low, upp = sigmaclip(a, 1.8, 1.8) + >>> (c == np.linspace(9.5, 10.5, 11)).all() + True + + """ + c = np.asarray(a).ravel() + delta = 1 + while delta: + c_std = c.std() + c_mean = c.mean() + size = c.size + critlower = c_mean - c_std * low + critupper = c_mean + c_std * high + c = c[(c >= critlower) & (c <= critupper)] + delta = size - c.size + + return SigmaclipResult(c, critlower, critupper) + + +def trimboth(a, proportiontocut, axis=0): + """Slice off a proportion of items from both ends of an array. + + Slice off the passed proportion of items from both ends of the passed + array (i.e., with `proportiontocut` = 0.1, slices leftmost 10% **and** + rightmost 10% of scores). The trimmed values are the lowest and + highest ones. + Slice off less if proportion results in a non-integer slice index (i.e. + conservatively slices off `proportiontocut`). + + Parameters + ---------- + a : array_like + Data to trim. + proportiontocut : float + Proportion (in range 0-1) of total data set to trim of each end. + axis : int or None, optional + Axis along which to trim data. Default is 0. If None, compute over + the whole array `a`. + + Returns + ------- + out : ndarray + Trimmed version of array `a`. The order of the trimmed content + is undefined. + + See Also + -------- + trim_mean + + Examples + -------- + Create an array of 10 values and trim 10% of those values from each end: + + >>> import numpy as np + >>> from scipy import stats + >>> a = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] + >>> stats.trimboth(a, 0.1) + array([1, 3, 2, 4, 5, 6, 7, 8]) + + Note that the elements of the input array are trimmed by value, but the + output array is not necessarily sorted. + + The proportion to trim is rounded down to the nearest integer. For + instance, trimming 25% of the values from each end of an array of 10 + values will return an array of 6 values: + + >>> b = np.arange(10) + >>> stats.trimboth(b, 1/4).shape + (6,) + + Multidimensional arrays can be trimmed along any axis or across the entire + array: + + >>> c = [2, 4, 6, 8, 0, 1, 3, 5, 7, 9] + >>> d = np.array([a, b, c]) + >>> stats.trimboth(d, 0.4, axis=0).shape + (1, 10) + >>> stats.trimboth(d, 0.4, axis=1).shape + (3, 2) + >>> stats.trimboth(d, 0.4, axis=None).shape + (6,) + + """ + a = np.asarray(a) + + if a.size == 0: + return a + + if axis is None: + a = a.ravel() + axis = 0 + + nobs = a.shape[axis] + lowercut = int(proportiontocut * nobs) + uppercut = nobs - lowercut + if (lowercut >= uppercut): + raise ValueError("Proportion too big.") + + atmp = np.partition(a, (lowercut, uppercut - 1), axis) + + sl = [slice(None)] * atmp.ndim + sl[axis] = slice(lowercut, uppercut) + return atmp[tuple(sl)] + + +def trim1(a, proportiontocut, tail='right', axis=0): + """Slice off a proportion from ONE end of the passed array distribution. + + If `proportiontocut` = 0.1, slices off 'leftmost' or 'rightmost' + 10% of scores. The lowest or highest values are trimmed (depending on + the tail). + Slice off less if proportion results in a non-integer slice index + (i.e. conservatively slices off `proportiontocut` ). + + Parameters + ---------- + a : array_like + Input array. + proportiontocut : float + Fraction to cut off of 'left' or 'right' of distribution. + tail : {'left', 'right'}, optional + Defaults to 'right'. + axis : int or None, optional + Axis along which to trim data. Default is 0. If None, compute over + the whole array `a`. + + Returns + ------- + trim1 : ndarray + Trimmed version of array `a`. The order of the trimmed content is + undefined. + + Examples + -------- + Create an array of 10 values and trim 20% of its lowest values: + + >>> import numpy as np + >>> from scipy import stats + >>> a = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] + >>> stats.trim1(a, 0.2, 'left') + array([2, 4, 3, 5, 6, 7, 8, 9]) + + Note that the elements of the input array are trimmed by value, but the + output array is not necessarily sorted. + + The proportion to trim is rounded down to the nearest integer. For + instance, trimming 25% of the values from an array of 10 values will + return an array of 8 values: + + >>> b = np.arange(10) + >>> stats.trim1(b, 1/4).shape + (8,) + + Multidimensional arrays can be trimmed along any axis or across the entire + array: + + >>> c = [2, 4, 6, 8, 0, 1, 3, 5, 7, 9] + >>> d = np.array([a, b, c]) + >>> stats.trim1(d, 0.8, axis=0).shape + (1, 10) + >>> stats.trim1(d, 0.8, axis=1).shape + (3, 2) + >>> stats.trim1(d, 0.8, axis=None).shape + (6,) + + """ + a = np.asarray(a) + if axis is None: + a = a.ravel() + axis = 0 + + nobs = a.shape[axis] + + # avoid possible corner case + if proportiontocut >= 1: + return [] + + if tail.lower() == 'right': + lowercut = 0 + uppercut = nobs - int(proportiontocut * nobs) + + elif tail.lower() == 'left': + lowercut = int(proportiontocut * nobs) + uppercut = nobs + + atmp = np.partition(a, (lowercut, uppercut - 1), axis) + + sl = [slice(None)] * atmp.ndim + sl[axis] = slice(lowercut, uppercut) + return atmp[tuple(sl)] + + +def trim_mean(a, proportiontocut, axis=0): + """Return mean of array after trimming a specified fraction of extreme values + + Removes the specified proportion of elements from *each* end of the + sorted array, then computes the mean of the remaining elements. + + Parameters + ---------- + a : array_like + Input array. + proportiontocut : float + Fraction of the most positive and most negative elements to remove. + When the specified proportion does not result in an integer number of + elements, the number of elements to trim is rounded down. + axis : int or None, default: 0 + Axis along which the trimmed means are computed. + If None, compute over the raveled array. + + Returns + ------- + trim_mean : ndarray + Mean of trimmed array. + + See Also + -------- + trimboth : Remove a proportion of elements from each end of an array. + tmean : Compute the mean after trimming values outside specified limits. + + Notes + ----- + For 1-D array `a`, `trim_mean` is approximately equivalent to the following + calculation:: + + import numpy as np + a = np.sort(a) + m = int(proportiontocut * len(a)) + np.mean(a[m: len(a) - m]) + + Examples + -------- + >>> import numpy as np + >>> from scipy import stats + >>> x = [1, 2, 3, 5] + >>> stats.trim_mean(x, 0.25) + 2.5 + + When the specified proportion does not result in an integer number of + elements, the number of elements to trim is rounded down. + + >>> stats.trim_mean(x, 0.24999) == np.mean(x) + True + + Use `axis` to specify the axis along which the calculation is performed. + + >>> x2 = [[1, 2, 3, 5], + ... [10, 20, 30, 50]] + >>> stats.trim_mean(x2, 0.25) + array([ 5.5, 11. , 16.5, 27.5]) + >>> stats.trim_mean(x2, 0.25, axis=1) + array([ 2.5, 25. ]) + + """ + a = np.asarray(a) + + if a.size == 0: + return np.nan + + if axis is None: + a = a.ravel() + axis = 0 + + nobs = a.shape[axis] + lowercut = int(proportiontocut * nobs) + uppercut = nobs - lowercut + if (lowercut > uppercut): + raise ValueError("Proportion too big.") + + atmp = np.partition(a, (lowercut, uppercut - 1), axis) + + sl = [slice(None)] * atmp.ndim + sl[axis] = slice(lowercut, uppercut) + return np.mean(atmp[tuple(sl)], axis=axis) + + +F_onewayResult = namedtuple('F_onewayResult', ('statistic', 'pvalue')) + + +def _create_f_oneway_nan_result(shape, axis, samples): + """ + This is a helper function for f_oneway for creating the return values + in certain degenerate conditions. It creates return values that are + all nan with the appropriate shape for the given `shape` and `axis`. + """ + axis = normalize_axis_index(axis, len(shape)) + shp = shape[:axis] + shape[axis+1:] + f = np.full(shp, fill_value=_get_nan(*samples)) + prob = f.copy() + return F_onewayResult(f[()], prob[()]) + + +def _first(arr, axis): + """Return arr[..., 0:1, ...] where 0:1 is in the `axis` position.""" + return np.take_along_axis(arr, np.array(0, ndmin=arr.ndim), axis) + + +def _f_oneway_is_too_small(samples, kwargs=None, axis=-1): + message = f"At least two samples are required; got {len(samples)}." + if len(samples) < 2: + raise TypeError(message) + + # Check this after forming alldata, so shape errors are detected + # and reported before checking for 0 length inputs. + if any(sample.shape[axis] == 0 for sample in samples): + return True + + # Must have at least one group with length greater than 1. + if all(sample.shape[axis] == 1 for sample in samples): + msg = ('all input arrays have length 1. f_oneway requires that at ' + 'least one input has length greater than 1.') + warnings.warn(SmallSampleWarning(msg), stacklevel=2) + return True + + return False + + +@_axis_nan_policy_factory( + F_onewayResult, n_samples=None, too_small=_f_oneway_is_too_small) +def f_oneway(*samples, axis=0): + """Perform one-way ANOVA. + + The one-way ANOVA tests the null hypothesis that two or more groups have + the same population mean. The test is applied to samples from two or + more groups, possibly with differing sizes. + + Parameters + ---------- + sample1, sample2, ... : array_like + The sample measurements for each group. There must be at least + two arguments. If the arrays are multidimensional, then all the + dimensions of the array must be the same except for `axis`. + axis : int, optional + Axis of the input arrays along which the test is applied. + Default is 0. + + Returns + ------- + statistic : float + The computed F statistic of the test. + pvalue : float + The associated p-value from the F distribution. + + Warns + ----- + `~scipy.stats.ConstantInputWarning` + Emitted if all values within each of the input arrays are identical. + In this case the F statistic is either infinite or isn't defined, + so ``np.inf`` or ``np.nan`` is returned. + + RuntimeWarning + Emitted if the length of any input array is 0, or if all the input + arrays have length 1. ``np.nan`` is returned for the F statistic + and the p-value in these cases. + + Notes + ----- + The ANOVA test has important assumptions that must be satisfied in order + for the associated p-value to be valid. + + 1. The samples are independent. + 2. Each sample is from a normally distributed population. + 3. The population standard deviations of the groups are all equal. This + property is known as homoscedasticity. + + If these assumptions are not true for a given set of data, it may still + be possible to use the Kruskal-Wallis H-test (`scipy.stats.kruskal`) or + the Alexander-Govern test (`scipy.stats.alexandergovern`) although with + some loss of power. + + The length of each group must be at least one, and there must be at + least one group with length greater than one. If these conditions + are not satisfied, a warning is generated and (``np.nan``, ``np.nan``) + is returned. + + If all values in each group are identical, and there exist at least two + groups with different values, the function generates a warning and + returns (``np.inf``, 0). + + If all values in all groups are the same, function generates a warning + and returns (``np.nan``, ``np.nan``). + + The algorithm is from Heiman [2]_, pp.394-7. + + References + ---------- + .. [1] R. Lowry, "Concepts and Applications of Inferential Statistics", + Chapter 14, 2014, http://vassarstats.net/textbook/ + + .. [2] G.W. Heiman, "Understanding research methods and statistics: An + integrated introduction for psychology", Houghton, Mifflin and + Company, 2001. + + .. [3] G.H. McDonald, "Handbook of Biological Statistics", One-way ANOVA. + http://www.biostathandbook.com/onewayanova.html + + Examples + -------- + >>> import numpy as np + >>> from scipy.stats import f_oneway + + Here are some data [3]_ on a shell measurement (the length of the anterior + adductor muscle scar, standardized by dividing by length) in the mussel + Mytilus trossulus from five locations: Tillamook, Oregon; Newport, Oregon; + Petersburg, Alaska; Magadan, Russia; and Tvarminne, Finland, taken from a + much larger data set used in McDonald et al. (1991). + + >>> tillamook = [0.0571, 0.0813, 0.0831, 0.0976, 0.0817, 0.0859, 0.0735, + ... 0.0659, 0.0923, 0.0836] + >>> newport = [0.0873, 0.0662, 0.0672, 0.0819, 0.0749, 0.0649, 0.0835, + ... 0.0725] + >>> petersburg = [0.0974, 0.1352, 0.0817, 0.1016, 0.0968, 0.1064, 0.105] + >>> magadan = [0.1033, 0.0915, 0.0781, 0.0685, 0.0677, 0.0697, 0.0764, + ... 0.0689] + >>> tvarminne = [0.0703, 0.1026, 0.0956, 0.0973, 0.1039, 0.1045] + >>> f_oneway(tillamook, newport, petersburg, magadan, tvarminne) + F_onewayResult(statistic=7.121019471642447, pvalue=0.0002812242314534544) + + `f_oneway` accepts multidimensional input arrays. When the inputs + are multidimensional and `axis` is not given, the test is performed + along the first axis of the input arrays. For the following data, the + test is performed three times, once for each column. + + >>> a = np.array([[9.87, 9.03, 6.81], + ... [7.18, 8.35, 7.00], + ... [8.39, 7.58, 7.68], + ... [7.45, 6.33, 9.35], + ... [6.41, 7.10, 9.33], + ... [8.00, 8.24, 8.44]]) + >>> b = np.array([[6.35, 7.30, 7.16], + ... [6.65, 6.68, 7.63], + ... [5.72, 7.73, 6.72], + ... [7.01, 9.19, 7.41], + ... [7.75, 7.87, 8.30], + ... [6.90, 7.97, 6.97]]) + >>> c = np.array([[3.31, 8.77, 1.01], + ... [8.25, 3.24, 3.62], + ... [6.32, 8.81, 5.19], + ... [7.48, 8.83, 8.91], + ... [8.59, 6.01, 6.07], + ... [3.07, 9.72, 7.48]]) + >>> F = f_oneway(a, b, c) + >>> F.statistic + array([1.75676344, 0.03701228, 3.76439349]) + >>> F.pvalue + array([0.20630784, 0.96375203, 0.04733157]) + + """ + if len(samples) < 2: + raise TypeError('at least two inputs are required;' + f' got {len(samples)}.') + + # ANOVA on N groups, each in its own array + num_groups = len(samples) + + # We haven't explicitly validated axis, but if it is bad, this call of + # np.concatenate will raise np.exceptions.AxisError. The call will raise + # ValueError if the dimensions of all the arrays, except the axis + # dimension, are not the same. + alldata = np.concatenate(samples, axis=axis) + bign = alldata.shape[axis] + + # Check if the inputs are too small + if _f_oneway_is_too_small(samples): + return _create_f_oneway_nan_result(alldata.shape, axis, samples) + + # Check if all values within each group are identical, and if the common + # value in at least one group is different from that in another group. + # Based on https://github.com/scipy/scipy/issues/11669 + + # If axis=0, say, and the groups have shape (n0, ...), (n1, ...), ..., + # then is_const is a boolean array with shape (num_groups, ...). + # It is True if the values within the groups along the axis slice are + # identical. In the typical case where each input array is 1-d, is_const is + # a 1-d array with length num_groups. + is_const = np.concatenate( + [(_first(sample, axis) == sample).all(axis=axis, + keepdims=True) + for sample in samples], + axis=axis + ) + + # all_const is a boolean array with shape (...) (see previous comment). + # It is True if the values within each group along the axis slice are + # the same (e.g. [[3, 3, 3], [5, 5, 5, 5], [4, 4, 4]]). + all_const = is_const.all(axis=axis) + if all_const.any(): + msg = ("Each of the input arrays is constant; " + "the F statistic is not defined or infinite") + warnings.warn(stats.ConstantInputWarning(msg), stacklevel=2) + + # all_same_const is True if all the values in the groups along the axis=0 + # slice are the same (e.g. [[3, 3, 3], [3, 3, 3, 3], [3, 3, 3]]). + all_same_const = (_first(alldata, axis) == alldata).all(axis=axis) + + # Determine the mean of the data, and subtract that from all inputs to a + # variance (via sum_of_sq / sq_of_sum) calculation. Variance is invariant + # to a shift in location, and centering all data around zero vastly + # improves numerical stability. + offset = alldata.mean(axis=axis, keepdims=True) + alldata = alldata - offset + + normalized_ss = _square_of_sums(alldata, axis=axis) / bign + + sstot = _sum_of_squares(alldata, axis=axis) - normalized_ss + + ssbn = 0 + for sample in samples: + smo_ss = _square_of_sums(sample - offset, axis=axis) + ssbn = ssbn + smo_ss / sample.shape[axis] + + # Naming: variables ending in bn/b are for "between treatments", wn/w are + # for "within treatments" + ssbn = ssbn - normalized_ss + sswn = sstot - ssbn + dfbn = num_groups - 1 + dfwn = bign - num_groups + msb = ssbn / dfbn + msw = sswn / dfwn + with np.errstate(divide='ignore', invalid='ignore'): + f = msb / msw + + prob = special.fdtrc(dfbn, dfwn, f) # equivalent to stats.f.sf + + # Fix any f values that should be inf or nan because the corresponding + # inputs were constant. + if np.isscalar(f): + if all_same_const: + f = np.nan + prob = np.nan + elif all_const: + f = np.inf + prob = 0.0 + else: + f[all_const] = np.inf + prob[all_const] = 0.0 + f[all_same_const] = np.nan + prob[all_same_const] = np.nan + + return F_onewayResult(f, prob) + + +@dataclass +class AlexanderGovernResult: + statistic: float + pvalue: float + + +@_axis_nan_policy_factory( + AlexanderGovernResult, n_samples=None, + result_to_tuple=lambda x: (x.statistic, x.pvalue), + too_small=1 +) +def alexandergovern(*samples, nan_policy='propagate', axis=0): + """Performs the Alexander Govern test. + + The Alexander-Govern approximation tests the equality of k independent + means in the face of heterogeneity of variance. The test is applied to + samples from two or more groups, possibly with differing sizes. + + Parameters + ---------- + sample1, sample2, ... : array_like + The sample measurements for each group. There must be at least + two samples, and each sample must contain at least two observations. + nan_policy : {'propagate', 'raise', 'omit'}, optional + Defines how to handle when input contains nan. + The following options are available (default is 'propagate'): + + * 'propagate': returns nan + * 'raise': throws an error + * 'omit': performs the calculations ignoring nan values + + Returns + ------- + res : AlexanderGovernResult + An object with attributes: + + statistic : float + The computed A statistic of the test. + pvalue : float + The associated p-value from the chi-squared distribution. + + Warns + ----- + `~scipy.stats.ConstantInputWarning` + Raised if an input is a constant array. The statistic is not defined + in this case, so ``np.nan`` is returned. + + See Also + -------- + f_oneway : one-way ANOVA + + Notes + ----- + The use of this test relies on several assumptions. + + 1. The samples are independent. + 2. Each sample is from a normally distributed population. + 3. Unlike `f_oneway`, this test does not assume on homoscedasticity, + instead relaxing the assumption of equal variances. + + Input samples must be finite, one dimensional, and with size greater than + one. + + References + ---------- + .. [1] Alexander, Ralph A., and Diane M. Govern. "A New and Simpler + Approximation for ANOVA under Variance Heterogeneity." Journal + of Educational Statistics, vol. 19, no. 2, 1994, pp. 91-101. + JSTOR, www.jstor.org/stable/1165140. Accessed 12 Sept. 2020. + + Examples + -------- + >>> from scipy.stats import alexandergovern + + Here are some data on annual percentage rate of interest charged on + new car loans at nine of the largest banks in four American cities + taken from the National Institute of Standards and Technology's + ANOVA dataset. + + We use `alexandergovern` to test the null hypothesis that all cities + have the same mean APR against the alternative that the cities do not + all have the same mean APR. We decide that a significance level of 5% + is required to reject the null hypothesis in favor of the alternative. + + >>> atlanta = [13.75, 13.75, 13.5, 13.5, 13.0, 13.0, 13.0, 12.75, 12.5] + >>> chicago = [14.25, 13.0, 12.75, 12.5, 12.5, 12.4, 12.3, 11.9, 11.9] + >>> houston = [14.0, 14.0, 13.51, 13.5, 13.5, 13.25, 13.0, 12.5, 12.5] + >>> memphis = [15.0, 14.0, 13.75, 13.59, 13.25, 12.97, 12.5, 12.25, + ... 11.89] + >>> alexandergovern(atlanta, chicago, houston, memphis) + AlexanderGovernResult(statistic=4.65087071883494, + pvalue=0.19922132490385214) + + The p-value is 0.1992, indicating a nearly 20% chance of observing + such an extreme value of the test statistic under the null hypothesis. + This exceeds 5%, so we do not reject the null hypothesis in favor of + the alternative. + + """ + samples = _alexandergovern_input_validation(samples, nan_policy, axis) + + # The following formula numbers reference the equation described on + # page 92 by Alexander, Govern. Formulas 5, 6, and 7 describe other + # tests that serve as the basis for equation (8) but are not needed + # to perform the test. + + # precalculate mean and length of each sample + lengths = [sample.shape[-1] for sample in samples] + means = np.asarray([_xp_mean(sample, axis=-1) for sample in samples]) + + # (1) determine standard error of the mean for each sample + se2 = [(_xp_var(sample, correction=1, axis=-1) / length) + for sample, length in zip(samples, lengths)] + standard_errors_squared = np.asarray(se2) + standard_errors = standard_errors_squared**0.5 + + # Special case: statistic is NaN when variance is zero + eps = np.finfo(standard_errors.dtype).eps + zero = standard_errors <= np.abs(eps * means) + NaN = np.asarray(np.nan, dtype=standard_errors.dtype) + standard_errors = np.where(zero, NaN, standard_errors) + + # (2) define a weight for each sample + inv_sq_se = 1 / standard_errors_squared + weights = inv_sq_se / np.sum(inv_sq_se, axis=0, keepdims=True) + + # (3) determine variance-weighted estimate of the common mean + var_w = np.sum(weights * means, axis=0, keepdims=True) + + # (4) determine one-sample t statistic for each group + t_stats = _demean(means, var_w, axis=0, xp=np) / standard_errors + + # calculate parameters to be used in transformation + v = np.asarray(lengths) - 1 + # align along 0th axis, which corresponds with separate samples + v = np.reshape(v, (-1,) + (1,)*(t_stats.ndim-1)) + a = v - .5 + b = 48 * a**2 + c = (a * np.log(1 + (t_stats ** 2)/v))**.5 + + # (8) perform a normalizing transformation on t statistic + z = (c + ((c**3 + 3*c)/b) - + ((4*c**7 + 33*c**5 + 240*c**3 + 855*c) / + (b**2*10 + 8*b*c**4 + 1000*b))) + + # (9) calculate statistic + A = np.sum(z**2, axis=0) + + # "[the p value is determined from] central chi-square random deviates + # with k - 1 degrees of freedom". Alexander, Govern (94) + df = len(samples) - 1 + chi2 = _SimpleChi2(df) + p = _get_pvalue(A, chi2, alternative='greater', symmetric=False, xp=np) + return AlexanderGovernResult(A, p) + + +def _alexandergovern_input_validation(samples, nan_policy, axis): + if len(samples) < 2: + raise TypeError(f"2 or more inputs required, got {len(samples)}") + + for sample in samples: + if sample.shape[axis] <= 1: + raise ValueError("Input sample size must be greater than one.") + + samples = [np.moveaxis(sample, axis, -1) for sample in samples] + + return samples + + +def _pearsonr_fisher_ci(r, n, confidence_level, alternative): + """ + Compute the confidence interval for Pearson's R. + + Fisher's transformation is used to compute the confidence interval + (https://en.wikipedia.org/wiki/Fisher_transformation). + """ + xp = array_namespace(r) + + with np.errstate(divide='ignore'): + zr = xp.atanh(r) + + ones = xp.ones_like(r) + n = xp.asarray(n, dtype=r.dtype) + confidence_level = xp.asarray(confidence_level, dtype=r.dtype) + if n > 3: + se = xp.sqrt(1 / (n - 3)) + if alternative == "two-sided": + h = special.ndtri(0.5 + confidence_level/2) + zlo = zr - h*se + zhi = zr + h*se + rlo = xp.tanh(zlo) + rhi = xp.tanh(zhi) + elif alternative == "less": + h = special.ndtri(confidence_level) + zhi = zr + h*se + rhi = xp.tanh(zhi) + rlo = -ones + else: + # alternative == "greater": + h = special.ndtri(confidence_level) + zlo = zr - h*se + rlo = xp.tanh(zlo) + rhi = ones + else: + rlo, rhi = -ones, ones + + rlo = rlo[()] if rlo.ndim == 0 else rlo + rhi = rhi[()] if rhi.ndim == 0 else rhi + return ConfidenceInterval(low=rlo, high=rhi) + + +def _pearsonr_bootstrap_ci(confidence_level, method, x, y, alternative, axis): + """ + Compute the confidence interval for Pearson's R using the bootstrap. + """ + def statistic(x, y, axis): + statistic, _ = pearsonr(x, y, axis=axis) + return statistic + + res = bootstrap((x, y), statistic, confidence_level=confidence_level, axis=axis, + paired=True, alternative=alternative, **method._asdict()) + # for one-sided confidence intervals, bootstrap gives +/- inf on one side + res.confidence_interval = np.clip(res.confidence_interval, -1, 1) + + return ConfidenceInterval(*res.confidence_interval) + + +ConfidenceInterval = namedtuple('ConfidenceInterval', ['low', 'high']) + +PearsonRResultBase = _make_tuple_bunch('PearsonRResultBase', + ['statistic', 'pvalue'], []) + + +class PearsonRResult(PearsonRResultBase): + """ + Result of `scipy.stats.pearsonr` + + Attributes + ---------- + statistic : float + Pearson product-moment correlation coefficient. + pvalue : float + The p-value associated with the chosen alternative. + + Methods + ------- + confidence_interval + Computes the confidence interval of the correlation + coefficient `statistic` for the given confidence level. + + """ + def __init__(self, statistic, pvalue, alternative, n, x, y, axis): + super().__init__(statistic, pvalue) + self._alternative = alternative + self._n = n + self._x = x + self._y = y + self._axis = axis + + # add alias for consistency with other correlation functions + self.correlation = statistic + + def confidence_interval(self, confidence_level=0.95, method=None): + """ + The confidence interval for the correlation coefficient. + + Compute the confidence interval for the correlation coefficient + ``statistic`` with the given confidence level. + + If `method` is not provided, + The confidence interval is computed using the Fisher transformation + F(r) = arctanh(r) [1]_. When the sample pairs are drawn from a + bivariate normal distribution, F(r) approximately follows a normal + distribution with standard error ``1/sqrt(n - 3)``, where ``n`` is the + length of the original samples along the calculation axis. When + ``n <= 3``, this approximation does not yield a finite, real standard + error, so we define the confidence interval to be -1 to 1. + + If `method` is an instance of `BootstrapMethod`, the confidence + interval is computed using `scipy.stats.bootstrap` with the provided + configuration options and other appropriate settings. In some cases, + confidence limits may be NaN due to a degenerate resample, and this is + typical for very small samples (~6 observations). + + Parameters + ---------- + confidence_level : float + The confidence level for the calculation of the correlation + coefficient confidence interval. Default is 0.95. + + method : BootstrapMethod, optional + Defines the method used to compute the confidence interval. See + method description for details. + + .. versionadded:: 1.11.0 + + Returns + ------- + ci : namedtuple + The confidence interval is returned in a ``namedtuple`` with + fields `low` and `high`. + + References + ---------- + .. [1] "Pearson correlation coefficient", Wikipedia, + https://en.wikipedia.org/wiki/Pearson_correlation_coefficient + """ + if isinstance(method, BootstrapMethod): + xp = array_namespace(self._x) + message = ('`method` must be `None` if `pearsonr` ' + 'arguments were not NumPy arrays.') + if not is_numpy(xp): + raise ValueError(message) + + ci = _pearsonr_bootstrap_ci(confidence_level, method, self._x, self._y, + self._alternative, self._axis) + elif method is None: + ci = _pearsonr_fisher_ci(self.statistic, self._n, confidence_level, + self._alternative) + else: + message = ('`method` must be an instance of `BootstrapMethod` ' + 'or None.') + raise ValueError(message) + return ci + + +def pearsonr(x, y, *, alternative='two-sided', method=None, axis=0): + r""" + Pearson correlation coefficient and p-value for testing non-correlation. + + The Pearson correlation coefficient [1]_ measures the linear relationship + between two datasets. Like other correlation + coefficients, this one varies between -1 and +1 with 0 implying no + correlation. Correlations of -1 or +1 imply an exact linear relationship. + Positive correlations imply that as x increases, so does y. Negative + correlations imply that as x increases, y decreases. + + This function also performs a test of the null hypothesis that the + distributions underlying the samples are uncorrelated and normally + distributed. (See Kowalski [3]_ + for a discussion of the effects of non-normality of the input on the + distribution of the correlation coefficient.) + The p-value roughly indicates the probability of an uncorrelated system + producing datasets that have a Pearson correlation at least as extreme + as the one computed from these datasets. + + Parameters + ---------- + x : array_like + Input array. + y : array_like + Input array. + axis : int or None, default + Axis along which to perform the calculation. Default is 0. + If None, ravel both arrays before performing the calculation. + + .. versionadded:: 1.13.0 + alternative : {'two-sided', 'greater', 'less'}, optional + Defines the alternative hypothesis. Default is 'two-sided'. + The following options are available: + + * 'two-sided': the correlation is nonzero + * 'less': the correlation is negative (less than zero) + * 'greater': the correlation is positive (greater than zero) + + .. versionadded:: 1.9.0 + method : ResamplingMethod, optional + Defines the method used to compute the p-value. If `method` is an + instance of `PermutationMethod`/`MonteCarloMethod`, the p-value is + computed using + `scipy.stats.permutation_test`/`scipy.stats.monte_carlo_test` with the + provided configuration options and other appropriate settings. + Otherwise, the p-value is computed as documented in the notes. + + .. versionadded:: 1.11.0 + + Returns + ------- + result : `~scipy.stats._result_classes.PearsonRResult` + An object with the following attributes: + + statistic : float + Pearson product-moment correlation coefficient. + pvalue : float + The p-value associated with the chosen alternative. + + The object has the following method: + + confidence_interval(confidence_level, method) + This computes the confidence interval of the correlation + coefficient `statistic` for the given confidence level. + The confidence interval is returned in a ``namedtuple`` with + fields `low` and `high`. If `method` is not provided, the + confidence interval is computed using the Fisher transformation + [1]_. If `method` is an instance of `BootstrapMethod`, the + confidence interval is computed using `scipy.stats.bootstrap` with + the provided configuration options and other appropriate settings. + In some cases, confidence limits may be NaN due to a degenerate + resample, and this is typical for very small samples (~6 + observations). + + Raises + ------ + ValueError + If `x` and `y` do not have length at least 2. + + Warns + ----- + `~scipy.stats.ConstantInputWarning` + Raised if an input is a constant array. The correlation coefficient + is not defined in this case, so ``np.nan`` is returned. + + `~scipy.stats.NearConstantInputWarning` + Raised if an input is "nearly" constant. The array ``x`` is considered + nearly constant if ``norm(x - mean(x)) < 1e-13 * abs(mean(x))``. + Numerical errors in the calculation ``x - mean(x)`` in this case might + result in an inaccurate calculation of r. + + See Also + -------- + spearmanr : Spearman rank-order correlation coefficient. + kendalltau : Kendall's tau, a correlation measure for ordinal data. + + Notes + ----- + The correlation coefficient is calculated as follows: + + .. math:: + + r = \frac{\sum (x - m_x) (y - m_y)} + {\sqrt{\sum (x - m_x)^2 \sum (y - m_y)^2}} + + where :math:`m_x` is the mean of the vector x and :math:`m_y` is + the mean of the vector y. + + Under the assumption that x and y are drawn from + independent normal distributions (so the population correlation coefficient + is 0), the probability density function of the sample correlation + coefficient r is ([1]_, [2]_): + + .. math:: + f(r) = \frac{{(1-r^2)}^{n/2-2}}{\mathrm{B}(\frac{1}{2},\frac{n}{2}-1)} + + where n is the number of samples, and B is the beta function. This + is sometimes referred to as the exact distribution of r. This is + the distribution that is used in `pearsonr` to compute the p-value when + the `method` parameter is left at its default value (None). + The distribution is a beta distribution on the interval [-1, 1], + with equal shape parameters a = b = n/2 - 1. In terms of SciPy's + implementation of the beta distribution, the distribution of r is:: + + dist = scipy.stats.beta(n/2 - 1, n/2 - 1, loc=-1, scale=2) + + The default p-value returned by `pearsonr` is a two-sided p-value. For a + given sample with correlation coefficient r, the p-value is + the probability that abs(r') of a random sample x' and y' drawn from + the population with zero correlation would be greater than or equal + to abs(r). In terms of the object ``dist`` shown above, the p-value + for a given r and length n can be computed as:: + + p = 2*dist.cdf(-abs(r)) + + When n is 2, the above continuous distribution is not well-defined. + One can interpret the limit of the beta distribution as the shape + parameters a and b approach a = b = 0 as a discrete distribution with + equal probability masses at r = 1 and r = -1. More directly, one + can observe that, given the data x = [x1, x2] and y = [y1, y2], and + assuming x1 != x2 and y1 != y2, the only possible values for r are 1 + and -1. Because abs(r') for any sample x' and y' with length 2 will + be 1, the two-sided p-value for a sample of length 2 is always 1. + + For backwards compatibility, the object that is returned also behaves + like a tuple of length two that holds the statistic and the p-value. + + References + ---------- + .. [1] "Pearson correlation coefficient", Wikipedia, + https://en.wikipedia.org/wiki/Pearson_correlation_coefficient + .. [2] Student, "Probable error of a correlation coefficient", + Biometrika, Volume 6, Issue 2-3, 1 September 1908, pp. 302-310. + .. [3] C. J. Kowalski, "On the Effects of Non-Normality on the Distribution + of the Sample Product-Moment Correlation Coefficient" + Journal of the Royal Statistical Society. Series C (Applied + Statistics), Vol. 21, No. 1 (1972), pp. 1-12. + + Examples + -------- + >>> import numpy as np + >>> from scipy import stats + >>> x, y = [1, 2, 3, 4, 5, 6, 7], [10, 9, 2.5, 6, 4, 3, 2] + >>> res = stats.pearsonr(x, y) + >>> res + PearsonRResult(statistic=-0.828503883588428, pvalue=0.021280260007523286) + + To perform an exact permutation version of the test: + + >>> rng = np.random.default_rng(7796654889291491997) + >>> method = stats.PermutationMethod(n_resamples=np.inf, random_state=rng) + >>> stats.pearsonr(x, y, method=method) + PearsonRResult(statistic=-0.828503883588428, pvalue=0.028174603174603175) + + To perform the test under the null hypothesis that the data were drawn from + *uniform* distributions: + + >>> method = stats.MonteCarloMethod(rvs=(rng.uniform, rng.uniform)) + >>> stats.pearsonr(x, y, method=method) + PearsonRResult(statistic=-0.828503883588428, pvalue=0.0188) + + To produce an asymptotic 90% confidence interval: + + >>> res.confidence_interval(confidence_level=0.9) + ConfidenceInterval(low=-0.9644331982722841, high=-0.3460237473272273) + + And for a bootstrap confidence interval: + + >>> method = stats.BootstrapMethod(method='BCa', rng=rng) + >>> res.confidence_interval(confidence_level=0.9, method=method) + ConfidenceInterval(low=-0.9983163756488651, high=-0.22771001702132443) # may vary + + If N-dimensional arrays are provided, multiple tests are performed in a + single call according to the same conventions as most `scipy.stats` functions: + + >>> rng = np.random.default_rng(2348246935601934321) + >>> x = rng.standard_normal((8, 15)) + >>> y = rng.standard_normal((8, 15)) + >>> stats.pearsonr(x, y, axis=0).statistic.shape # between corresponding columns + (15,) + >>> stats.pearsonr(x, y, axis=1).statistic.shape # between corresponding rows + (8,) + + To perform all pairwise comparisons between slices of the arrays, + use standard NumPy broadcasting techniques. For instance, to compute the + correlation between all pairs of rows: + + >>> stats.pearsonr(x[:, np.newaxis, :], y, axis=-1).statistic.shape + (8, 8) + + There is a linear dependence between x and y if y = a + b*x + e, where + a,b are constants and e is a random error term, assumed to be independent + of x. For simplicity, assume that x is standard normal, a=0, b=1 and let + e follow a normal distribution with mean zero and standard deviation s>0. + + >>> rng = np.random.default_rng() + >>> s = 0.5 + >>> x = stats.norm.rvs(size=500, random_state=rng) + >>> e = stats.norm.rvs(scale=s, size=500, random_state=rng) + >>> y = x + e + >>> stats.pearsonr(x, y).statistic + 0.9001942438244763 + + This should be close to the exact value given by + + >>> 1/np.sqrt(1 + s**2) + 0.8944271909999159 + + For s=0.5, we observe a high level of correlation. In general, a large + variance of the noise reduces the correlation, while the correlation + approaches one as the variance of the error goes to zero. + + It is important to keep in mind that no correlation does not imply + independence unless (x, y) is jointly normal. Correlation can even be zero + when there is a very simple dependence structure: if X follows a + standard normal distribution, let y = abs(x). Note that the correlation + between x and y is zero. Indeed, since the expectation of x is zero, + cov(x, y) = E[x*y]. By definition, this equals E[x*abs(x)] which is zero + by symmetry. The following lines of code illustrate this observation: + + >>> y = np.abs(x) + >>> stats.pearsonr(x, y) + PearsonRResult(statistic=-0.05444919272687482, pvalue=0.22422294836207743) + + A non-zero correlation coefficient can be misleading. For example, if X has + a standard normal distribution, define y = x if x < 0 and y = 0 otherwise. + A simple calculation shows that corr(x, y) = sqrt(2/Pi) = 0.797..., + implying a high level of correlation: + + >>> y = np.where(x < 0, x, 0) + >>> stats.pearsonr(x, y) + PearsonRResult(statistic=0.861985781588, pvalue=4.813432002751103e-149) + + This is unintuitive since there is no dependence of x and y if x is larger + than zero which happens in about half of the cases if we sample x and y. + + """ + xp = array_namespace(x, y) + x = xp.asarray(x) + y = xp.asarray(y) + + if not is_numpy(xp) and method is not None: + method = 'invalid' + + if axis is None: + x = xp.reshape(x, (-1,)) + y = xp.reshape(y, (-1,)) + axis = -1 + + axis_int = int(axis) + if axis_int != axis: + raise ValueError('`axis` must be an integer.') + axis = axis_int + + n = x.shape[axis] + if n != y.shape[axis]: + raise ValueError('`x` and `y` must have the same length along `axis`.') + + if n < 2: + raise ValueError('`x` and `y` must have length at least 2.') + + try: + x, y = xp.broadcast_arrays(x, y) + except (ValueError, RuntimeError) as e: + message = '`x` and `y` must be broadcastable.' + raise ValueError(message) from e + + # `moveaxis` only recently added to array API, so it's not yey available in + # array_api_strict. Replace with e.g. `xp.moveaxis(x, axis, -1)` when available. + x = xp_moveaxis_to_end(x, axis, xp=xp) + y = xp_moveaxis_to_end(y, axis, xp=xp) + axis = -1 + + dtype = xp.result_type(x.dtype, y.dtype) + if xp.isdtype(dtype, "integral"): + dtype = xp.asarray(1.).dtype + + if xp.isdtype(dtype, "complex floating"): + raise ValueError('This function does not support complex data') + + x = xp.astype(x, dtype, copy=False) + y = xp.astype(y, dtype, copy=False) + threshold = xp.finfo(dtype).eps ** 0.75 + + # If an input is constant, the correlation coefficient is not defined. + const_x = xp.all(x == x[..., 0:1], axis=-1) + const_y = xp.all(y == y[..., 0:1], axis=-1) + const_xy = const_x | const_y + if xp.any(const_xy): + msg = ("An input array is constant; the correlation coefficient " + "is not defined.") + warnings.warn(stats.ConstantInputWarning(msg), stacklevel=2) + + if isinstance(method, PermutationMethod): + def statistic(y, axis): + statistic, _ = pearsonr(x, y, axis=axis, alternative=alternative) + return statistic + + res = permutation_test((y,), statistic, permutation_type='pairings', + axis=axis, alternative=alternative, **method._asdict()) + + return PearsonRResult(statistic=res.statistic, pvalue=res.pvalue, n=n, + alternative=alternative, x=x, y=y, axis=axis) + elif isinstance(method, MonteCarloMethod): + def statistic(x, y, axis): + statistic, _ = pearsonr(x, y, axis=axis, alternative=alternative) + return statistic + + # `monte_carlo_test` accepts an `rvs` tuple of callables, not an `rng` + # If the user specified an `rng`, replace it with the appropriate callables + method = method._asdict() + if (rng := method.pop('rng', None)) is not None: # goo-goo g'joob + rng = np.random.default_rng(rng) + method['rvs'] = rng.normal, rng.normal + + res = monte_carlo_test((x, y,), statistic=statistic, axis=axis, + alternative=alternative, **method) + + return PearsonRResult(statistic=res.statistic, pvalue=res.pvalue, n=n, + alternative=alternative, x=x, y=y, axis=axis) + elif method == 'invalid': + message = '`method` must be `None` if arguments are not NumPy arrays.' + raise ValueError(message) + elif method is not None: + message = ('`method` must be an instance of `PermutationMethod`,' + '`MonteCarloMethod`, or None.') + raise ValueError(message) + + xmean = xp.mean(x, axis=axis, keepdims=True) + ymean = xp.mean(y, axis=axis, keepdims=True) + xm = x - xmean + ym = y - ymean + + # scipy.linalg.norm(xm) avoids premature overflow when xm is e.g. + # [-5e210, 5e210, 3e200, -3e200] + # but not when `axis` is provided, so scale manually. scipy.linalg.norm + # also raises an error with NaN input rather than returning NaN, so + # use np.linalg.norm. + xmax = xp.max(xp.abs(xm), axis=axis, keepdims=True) + ymax = xp.max(xp.abs(ym), axis=axis, keepdims=True) + with np.errstate(invalid='ignore', divide='ignore'): + normxm = xmax * xp_vector_norm(xm/xmax, axis=axis, keepdims=True) + normym = ymax * xp_vector_norm(ym/ymax, axis=axis, keepdims=True) + + nconst_x = xp.any(normxm < threshold*xp.abs(xmean), axis=axis) + nconst_y = xp.any(normym < threshold*xp.abs(ymean), axis=axis) + nconst_xy = nconst_x | nconst_y + if xp.any(nconst_xy & (~const_xy)): + # If all the values in x (likewise y) are very close to the mean, + # the loss of precision that occurs in the subtraction xm = x - xmean + # might result in large errors in r. + msg = ("An input array is nearly constant; the computed " + "correlation coefficient may be inaccurate.") + warnings.warn(stats.NearConstantInputWarning(msg), stacklevel=2) + + with np.errstate(invalid='ignore', divide='ignore'): + r = xp.sum(xm/normxm * ym/normym, axis=axis) + + # Presumably, if abs(r) > 1, then it is only some small artifact of + # floating point arithmetic. + one = xp.asarray(1, dtype=dtype) + r = xp.asarray(xp.clip(r, -one, one)) + r[const_xy] = xp.nan + + # Make sure we return exact 1.0 or -1.0 values for n == 2 case as promised + # in the docs. + if n == 2: + r = xp.round(r) + one = xp.asarray(1, dtype=dtype) + pvalue = xp.where(xp.asarray(xp.isnan(r)), xp.nan*one, one) + else: + # As explained in the docstring, the distribution of `r` under the null + # hypothesis is the beta distribution on (-1, 1) with a = b = n/2 - 1. + ab = xp.asarray(n/2 - 1) + dist = _SimpleBeta(ab, ab, loc=-1, scale=2) + pvalue = _get_pvalue(r, dist, alternative, xp=xp) + + r = r[()] if r.ndim == 0 else r + pvalue = pvalue[()] if pvalue.ndim == 0 else pvalue + return PearsonRResult(statistic=r, pvalue=pvalue, n=n, + alternative=alternative, x=x, y=y, axis=axis) + + +def fisher_exact(table, alternative=None, *, method=None): + """Perform a Fisher exact test on a contingency table. + + For a 2x2 table, + the null hypothesis is that the true odds ratio of the populations + underlying the observations is one, and the observations were sampled + from these populations under a condition: the marginals of the + resulting table must equal those of the observed table. + The statistic is the unconditional maximum likelihood estimate of the odds + ratio, and the p-value is the probability under the null hypothesis of + obtaining a table at least as extreme as the one that was actually + observed. + + For other table sizes, or if `method` is provided, the null hypothesis + is that the rows and columns of the tables have fixed sums and are + independent; i.e., the table was sampled from a `scipy.stats.random_table` + distribution with the observed marginals. The statistic is the + probability mass of this distribution evaluated at `table`, and the + p-value is the percentage of the population of tables with statistic at + least as extreme (small) as that of `table`. There is only one alternative + hypothesis available: the rows and columns are not independent. + + There are other possible choices of statistic and two-sided + p-value definition associated with Fisher's exact test; please see the + Notes for more information. + + Parameters + ---------- + table : array_like of ints + A contingency table. Elements must be non-negative integers. + alternative : {'two-sided', 'less', 'greater'}, optional + Defines the alternative hypothesis for 2x2 tables; unused for other + table sizes. + The following options are available (default is 'two-sided'): + + * 'two-sided': the odds ratio of the underlying population is not one + * 'less': the odds ratio of the underlying population is less than one + * 'greater': the odds ratio of the underlying population is greater + than one + + See the Notes for more details. + + method : ResamplingMethod, optional + Defines the method used to compute the p-value. + If `method` is an instance of `PermutationMethod`/`MonteCarloMethod`, + the p-value is computed using + `scipy.stats.permutation_test`/`scipy.stats.monte_carlo_test` with the + provided configuration options and other appropriate settings. + Note that if `method` is an instance of `MonteCarloMethod`, the ``rvs`` + attribute must be left unspecified; Monte Carlo samples are always drawn + using the ``rvs`` method of `scipy.stats.random_table`. + Otherwise, the p-value is computed as documented in the notes. + + .. versionadded:: 1.15.0 + + Returns + ------- + res : SignificanceResult + An object containing attributes: + + statistic : float + For a 2x2 table with default `method`, this is the odds ratio - the + prior odds ratio not a posterior estimate. In all other cases, this + is the probability density of obtaining the observed table under the + null hypothesis of independence with marginals fixed. + pvalue : float + The probability under the null hypothesis of obtaining a + table at least as extreme as the one that was actually observed. + + Raises + ------ + ValueError + If `table` is not two-dimensional or has negative entries. + + See Also + -------- + chi2_contingency : Chi-square test of independence of variables in a + contingency table. This can be used as an alternative to + `fisher_exact` when the numbers in the table are large. + contingency.odds_ratio : Compute the odds ratio (sample or conditional + MLE) for a 2x2 contingency table. + barnard_exact : Barnard's exact test, which is a more powerful alternative + than Fisher's exact test for 2x2 contingency tables. + boschloo_exact : Boschloo's exact test, which is a more powerful + alternative than Fisher's exact test for 2x2 contingency tables. + :ref:`hypothesis_fisher_exact` : Extended example + + Notes + ----- + *Null hypothesis and p-values* + + The null hypothesis is that the true odds ratio of the populations + underlying the observations is one, and the observations were sampled at + random from these populations under a condition: the marginals of the + resulting table must equal those of the observed table. Equivalently, + the null hypothesis is that the input table is from the hypergeometric + distribution with parameters (as used in `hypergeom`) + ``M = a + b + c + d``, ``n = a + b`` and ``N = a + c``, where the + input table is ``[[a, b], [c, d]]``. This distribution has support + ``max(0, N + n - M) <= x <= min(N, n)``, or, in terms of the values + in the input table, ``min(0, a - d) <= x <= a + min(b, c)``. ``x`` + can be interpreted as the upper-left element of a 2x2 table, so the + tables in the distribution have form:: + + [ x n - x ] + [N - x M - (n + N) + x] + + For example, if:: + + table = [6 2] + [1 4] + + then the support is ``2 <= x <= 7``, and the tables in the distribution + are:: + + [2 6] [3 5] [4 4] [5 3] [6 2] [7 1] + [5 0] [4 1] [3 2] [2 3] [1 4] [0 5] + + The probability of each table is given by the hypergeometric distribution + ``hypergeom.pmf(x, M, n, N)``. For this example, these are (rounded to + three significant digits):: + + x 2 3 4 5 6 7 + p 0.0163 0.163 0.408 0.326 0.0816 0.00466 + + These can be computed with:: + + >>> import numpy as np + >>> from scipy.stats import hypergeom + >>> table = np.array([[6, 2], [1, 4]]) + >>> M = table.sum() + >>> n = table[0].sum() + >>> N = table[:, 0].sum() + >>> start, end = hypergeom.support(M, n, N) + >>> hypergeom.pmf(np.arange(start, end+1), M, n, N) + array([0.01631702, 0.16317016, 0.40792541, 0.32634033, 0.08158508, + 0.004662 ]) + + The two-sided p-value is the probability that, under the null hypothesis, + a random table would have a probability equal to or less than the + probability of the input table. For our example, the probability of + the input table (where ``x = 6``) is 0.0816. The x values where the + probability does not exceed this are 2, 6 and 7, so the two-sided p-value + is ``0.0163 + 0.0816 + 0.00466 ~= 0.10256``:: + + >>> from scipy.stats import fisher_exact + >>> res = fisher_exact(table, alternative='two-sided') + >>> res.pvalue + 0.10256410256410257 + + The one-sided p-value for ``alternative='greater'`` is the probability + that a random table has ``x >= a``, which in our example is ``x >= 6``, + or ``0.0816 + 0.00466 ~= 0.08626``:: + + >>> res = fisher_exact(table, alternative='greater') + >>> res.pvalue + 0.08624708624708627 + + This is equivalent to computing the survival function of the + distribution at ``x = 5`` (one less than ``x`` from the input table, + because we want to include the probability of ``x = 6`` in the sum):: + + >>> hypergeom.sf(5, M, n, N) + 0.08624708624708627 + + For ``alternative='less'``, the one-sided p-value is the probability + that a random table has ``x <= a``, (i.e. ``x <= 6`` in our example), + or ``0.0163 + 0.163 + 0.408 + 0.326 + 0.0816 ~= 0.9949``:: + + >>> res = fisher_exact(table, alternative='less') + >>> res.pvalue + 0.9953379953379957 + + This is equivalent to computing the cumulative distribution function + of the distribution at ``x = 6``: + + >>> hypergeom.cdf(6, M, n, N) + 0.9953379953379957 + + *Odds ratio* + + The calculated odds ratio is different from the value computed by the + R function ``fisher.test``. This implementation returns the "sample" + or "unconditional" maximum likelihood estimate, while ``fisher.test`` + in R uses the conditional maximum likelihood estimate. To compute the + conditional maximum likelihood estimate of the odds ratio, use + `scipy.stats.contingency.odds_ratio`. + + References + ---------- + .. [1] Fisher, Sir Ronald A, "The Design of Experiments: + Mathematics of a Lady Tasting Tea." ISBN 978-0-486-41151-4, 1935. + .. [2] "Fisher's exact test", + https://en.wikipedia.org/wiki/Fisher's_exact_test + + Examples + -------- + + >>> from scipy.stats import fisher_exact + >>> res = fisher_exact([[8, 2], [1, 5]]) + >>> res.statistic + 20.0 + >>> res.pvalue + 0.034965034965034975 + + For tables with shape other than ``(2, 2)``, provide an instance of + `scipy.stats.MonteCarloMethod` or `scipy.stats.PermutationMethod` for the + `method` parameter: + + >>> import numpy as np + >>> from scipy.stats import MonteCarloMethod + >>> rng = np.random.default_rng(4507195762371367) + >>> method = MonteCarloMethod(rng=rng) + >>> fisher_exact([[8, 2, 3], [1, 5, 4]], method=method) + SignificanceResult(statistic=np.float64(0.005782), pvalue=np.float64(0.0603)) + + For a more detailed example, see :ref:`hypothesis_fisher_exact`. + """ + hypergeom = distributions.hypergeom + # int32 is not enough for the algorithm + c = np.asarray(table, dtype=np.int64) + if not c.ndim == 2: + raise ValueError("The input `table` must have two dimensions.") + + if np.any(c < 0): + raise ValueError("All values in `table` must be nonnegative.") + + if not c.shape == (2, 2) or method is not None: + return _fisher_exact_rxc(c, alternative, method) + alternative = 'two-sided' if alternative is None else alternative + + if 0 in c.sum(axis=0) or 0 in c.sum(axis=1): + # If both values in a row or column are zero, the p-value is 1 and + # the odds ratio is NaN. + return SignificanceResult(np.nan, 1.0) + + if c[1, 0] > 0 and c[0, 1] > 0: + oddsratio = c[0, 0] * c[1, 1] / (c[1, 0] * c[0, 1]) + else: + oddsratio = np.inf + + n1 = c[0, 0] + c[0, 1] + n2 = c[1, 0] + c[1, 1] + n = c[0, 0] + c[1, 0] + + def pmf(x): + return hypergeom.pmf(x, n1 + n2, n1, n) + + if alternative == 'less': + pvalue = hypergeom.cdf(c[0, 0], n1 + n2, n1, n) + elif alternative == 'greater': + # Same formula as the 'less' case, but with the second column. + pvalue = hypergeom.cdf(c[0, 1], n1 + n2, n1, c[0, 1] + c[1, 1]) + elif alternative == 'two-sided': + mode = int((n + 1) * (n1 + 1) / (n1 + n2 + 2)) + pexact = hypergeom.pmf(c[0, 0], n1 + n2, n1, n) + pmode = hypergeom.pmf(mode, n1 + n2, n1, n) + + epsilon = 1e-14 + gamma = 1 + epsilon + + if np.abs(pexact - pmode) / np.maximum(pexact, pmode) <= epsilon: + return SignificanceResult(oddsratio, 1.) + + elif c[0, 0] < mode: + plower = hypergeom.cdf(c[0, 0], n1 + n2, n1, n) + if hypergeom.pmf(n, n1 + n2, n1, n) > pexact * gamma: + return SignificanceResult(oddsratio, plower) + + guess = _binary_search(lambda x: -pmf(x), -pexact * gamma, mode, n) + pvalue = plower + hypergeom.sf(guess, n1 + n2, n1, n) + else: + pupper = hypergeom.sf(c[0, 0] - 1, n1 + n2, n1, n) + if hypergeom.pmf(0, n1 + n2, n1, n) > pexact * gamma: + return SignificanceResult(oddsratio, pupper) + + guess = _binary_search(pmf, pexact * gamma, 0, mode) + pvalue = pupper + hypergeom.cdf(guess, n1 + n2, n1, n) + else: + msg = "`alternative` should be one of {'two-sided', 'less', 'greater'}" + raise ValueError(msg) + + pvalue = min(pvalue, 1.0) + + return SignificanceResult(oddsratio, pvalue) + + +def _fisher_exact_rxc(table, alternative, method): + if alternative is not None: + message = ('`alternative` must be the default (None) unless ' + '`table` has shape `(2, 2)` and `method is None`.') + raise ValueError(message) + + if table.size == 0: + raise ValueError("`table` must have at least one row and one column.") + + if table.shape[0] == 1 or table.shape[1] == 1 or np.all(table == 0): + # Only one such table with those marginals + return SignificanceResult(1.0, 1.0) + + if method is None: + method = stats.MonteCarloMethod() + + if isinstance(method, stats.PermutationMethod): + res = _fisher_exact_permutation_method(table, method) + elif isinstance(method, stats.MonteCarloMethod): + res = _fisher_exact_monte_carlo_method(table, method) + else: + message = (f'`{method=}` not recognized; if provided, `method` must be an ' + 'instance of `PermutationMethod` or `MonteCarloMethod`.') + raise ValueError(message) + + return SignificanceResult(np.clip(res.statistic, None, 1.0), res.pvalue) + + +def _fisher_exact_permutation_method(table, method): + x, y = _untabulate(table) + colsums = np.sum(table, axis=0) + rowsums = np.sum(table, axis=1) + X = stats.random_table(rowsums, colsums) + + # `permutation_test` with `permutation_type='pairings' permutes the order of `x`, + # which pairs observations in `x` with different observations in `y`. + def statistic(x): + # crosstab the resample and compute the statistic + table = stats.contingency.crosstab(x, y)[1] + return X.pmf(table) + + # tables with *smaller* probability mass are considered to be more extreme + return stats.permutation_test((x,), statistic, permutation_type='pairings', + alternative='less', **method._asdict()) + + +def _fisher_exact_monte_carlo_method(table, method): + method = method._asdict() + + if method.pop('rvs', None) is not None: + message = ('If the `method` argument of `fisher_exact` is an ' + 'instance of `MonteCarloMethod`, its `rvs` attribute ' + 'must be unspecified. Use the `MonteCarloMethod` `rng` argument ' + 'to control the random state.') + raise ValueError(message) + rng = np.random.default_rng(method.pop('rng', None)) + + # `random_table.rvs` produces random contingency tables with the given marginals + # under the null hypothesis of independence + shape = table.shape + colsums = np.sum(table, axis=0) + rowsums = np.sum(table, axis=1) + totsum = np.sum(table) + X = stats.random_table(rowsums, colsums, seed=rng) + + def rvs(size): + n_resamples = size[0] + return X.rvs(size=n_resamples).reshape(size) + + # axis signals to `monte_carlo_test` that statistic is vectorized, but we know + # how it will pass the table(s), so we don't need to use `axis` explicitly. + def statistic(table, axis): + shape_ = (-1,) + shape if table.size > totsum else shape + return X.pmf(table.reshape(shape_)) + + # tables with *smaller* probability mass are considered to be more extreme + return stats.monte_carlo_test(table.ravel(), rvs, statistic, + alternative='less', **method) + + +def _untabulate(table): + # converts a contingency table to paired samples indicating the + # correspondence between row and column indices + r, c = table.shape + x, y = [], [] + for i in range(r): + for j in range(c): + x.append([i] * table[i, j]) + y.append([j] * table[i, j]) + return np.concatenate(x), np.concatenate(y) + + +def spearmanr(a, b=None, axis=0, nan_policy='propagate', + alternative='two-sided'): + r"""Calculate a Spearman correlation coefficient with associated p-value. + + The Spearman rank-order correlation coefficient is a nonparametric measure + of the monotonicity of the relationship between two datasets. + Like other correlation coefficients, + this one varies between -1 and +1 with 0 implying no correlation. + Correlations of -1 or +1 imply an exact monotonic relationship. Positive + correlations imply that as x increases, so does y. Negative correlations + imply that as x increases, y decreases. + + The p-value roughly indicates the probability of an uncorrelated system + producing datasets that have a Spearman correlation at least as extreme + as the one computed from these datasets. Although calculation of the + p-value does not make strong assumptions about the distributions underlying + the samples, it is only accurate for very large samples (>500 + observations). For smaller sample sizes, consider a permutation test (see + Examples section below). + + Parameters + ---------- + a, b : 1D or 2D array_like, b is optional + One or two 1-D or 2-D arrays containing multiple variables and + observations. When these are 1-D, each represents a vector of + observations of a single variable. For the behavior in the 2-D case, + see under ``axis``, below. + Both arrays need to have the same length in the ``axis`` dimension. + axis : int or None, optional + If axis=0 (default), then each column represents a variable, with + observations in the rows. If axis=1, the relationship is transposed: + each row represents a variable, while the columns contain observations. + If axis=None, then both arrays will be raveled. + nan_policy : {'propagate', 'raise', 'omit'}, optional + Defines how to handle when input contains nan. + The following options are available (default is 'propagate'): + + * 'propagate': returns nan + * 'raise': throws an error + * 'omit': performs the calculations ignoring nan values + + alternative : {'two-sided', 'less', 'greater'}, optional + Defines the alternative hypothesis. Default is 'two-sided'. + The following options are available: + + * 'two-sided': the correlation is nonzero + * 'less': the correlation is negative (less than zero) + * 'greater': the correlation is positive (greater than zero) + + .. versionadded:: 1.7.0 + + Returns + ------- + res : SignificanceResult + An object containing attributes: + + statistic : float or ndarray (2-D square) + Spearman correlation matrix or correlation coefficient (if only 2 + variables are given as parameters). Correlation matrix is square + with length equal to total number of variables (columns or rows) in + ``a`` and ``b`` combined. + pvalue : float + The p-value for a hypothesis test whose null hypothesis + is that two samples have no ordinal correlation. See + `alternative` above for alternative hypotheses. `pvalue` has the + same shape as `statistic`. + + Raises + ------ + ValueError + If `axis` is not 0, 1 or None, or if the number of dimensions of `a` + is greater than 2, or if `b` is None and the number of dimensions of + `a` is less than 2. + + Warns + ----- + `~scipy.stats.ConstantInputWarning` + Raised if an input is a constant array. The correlation coefficient + is not defined in this case, so ``np.nan`` is returned. + + See Also + -------- + :ref:`hypothesis_spearmanr` : Extended example + + References + ---------- + .. [1] Zwillinger, D. and Kokoska, S. (2000). CRC Standard + Probability and Statistics Tables and Formulae. Chapman & Hall: New + York. 2000. + Section 14.7 + .. [2] Kendall, M. G. and Stuart, A. (1973). + The Advanced Theory of Statistics, Volume 2: Inference and Relationship. + Griffin. 1973. + Section 31.18 + + Examples + -------- + + >>> import numpy as np + >>> from scipy import stats + >>> res = stats.spearmanr([1, 2, 3, 4, 5], [5, 6, 7, 8, 7]) + >>> res.statistic + 0.8207826816681233 + >>> res.pvalue + 0.08858700531354381 + + >>> rng = np.random.default_rng() + >>> x2n = rng.standard_normal((100, 2)) + >>> y2n = rng.standard_normal((100, 2)) + >>> res = stats.spearmanr(x2n) + >>> res.statistic, res.pvalue + (-0.07960396039603959, 0.4311168705769747) + + >>> res = stats.spearmanr(x2n[:, 0], x2n[:, 1]) + >>> res.statistic, res.pvalue + (-0.07960396039603959, 0.4311168705769747) + + >>> res = stats.spearmanr(x2n, y2n) + >>> res.statistic + array([[ 1. , -0.07960396, -0.08314431, 0.09662166], + [-0.07960396, 1. , -0.14448245, 0.16738074], + [-0.08314431, -0.14448245, 1. , 0.03234323], + [ 0.09662166, 0.16738074, 0.03234323, 1. ]]) + >>> res.pvalue + array([[0. , 0.43111687, 0.41084066, 0.33891628], + [0.43111687, 0. , 0.15151618, 0.09600687], + [0.41084066, 0.15151618, 0. , 0.74938561], + [0.33891628, 0.09600687, 0.74938561, 0. ]]) + + >>> res = stats.spearmanr(x2n.T, y2n.T, axis=1) + >>> res.statistic + array([[ 1. , -0.07960396, -0.08314431, 0.09662166], + [-0.07960396, 1. , -0.14448245, 0.16738074], + [-0.08314431, -0.14448245, 1. , 0.03234323], + [ 0.09662166, 0.16738074, 0.03234323, 1. ]]) + + >>> res = stats.spearmanr(x2n, y2n, axis=None) + >>> res.statistic, res.pvalue + (0.044981624540613524, 0.5270803651336189) + + >>> res = stats.spearmanr(x2n.ravel(), y2n.ravel()) + >>> res.statistic, res.pvalue + (0.044981624540613524, 0.5270803651336189) + + >>> rng = np.random.default_rng() + >>> xint = rng.integers(10, size=(100, 2)) + >>> res = stats.spearmanr(xint) + >>> res.statistic, res.pvalue + (0.09800224850707953, 0.3320271757932076) + + For small samples, consider performing a permutation test instead of + relying on the asymptotic p-value. Note that to calculate the null + distribution of the statistic (for all possibly pairings between + observations in sample ``x`` and ``y``), only one of the two inputs needs + to be permuted. + + >>> x = [1.76405235, 0.40015721, 0.97873798, + ... 2.2408932, 1.86755799, -0.97727788] + >>> y = [2.71414076, 0.2488, 0.87551913, + ... 2.6514917, 2.01160156, 0.47699563] + + >>> def statistic(x): # permute only `x` + ... return stats.spearmanr(x, y).statistic + >>> res_exact = stats.permutation_test((x,), statistic, + ... permutation_type='pairings') + >>> res_asymptotic = stats.spearmanr(x, y) + >>> res_exact.pvalue, res_asymptotic.pvalue # asymptotic pvalue is too low + (0.10277777777777777, 0.07239650145772594) + + For a more detailed example, see :ref:`hypothesis_spearmanr`. + """ + if axis is not None and axis > 1: + raise ValueError("spearmanr only handles 1-D or 2-D arrays, " + f"supplied axis argument {axis}, please use only " + "values 0, 1 or None for axis") + + a, axisout = _chk_asarray(a, axis) + if a.ndim > 2: + raise ValueError("spearmanr only handles 1-D or 2-D arrays") + + if b is None: + if a.ndim < 2: + raise ValueError("`spearmanr` needs at least 2 " + "variables to compare") + else: + # Concatenate a and b, so that we now only have to handle the case + # of a 2-D `a`. + b, _ = _chk_asarray(b, axis) + if axisout == 0: + a = np.column_stack((a, b)) + else: + a = np.vstack((a, b)) + + n_vars = a.shape[1 - axisout] + n_obs = a.shape[axisout] + if n_obs <= 1: + # Handle empty arrays or single observations. + res = SignificanceResult(np.nan, np.nan) + res.correlation = np.nan + return res + + warn_msg = ("An input array is constant; the correlation coefficient " + "is not defined.") + if axisout == 0: + if (a[:, 0][0] == a[:, 0]).all() or (a[:, 1][0] == a[:, 1]).all(): + # If an input is constant, the correlation coefficient + # is not defined. + warnings.warn(stats.ConstantInputWarning(warn_msg), stacklevel=2) + res = SignificanceResult(np.nan, np.nan) + res.correlation = np.nan + return res + else: # case when axisout == 1 b/c a is 2 dim only + if (a[0, :][0] == a[0, :]).all() or (a[1, :][0] == a[1, :]).all(): + # If an input is constant, the correlation coefficient + # is not defined. + warnings.warn(stats.ConstantInputWarning(warn_msg), stacklevel=2) + res = SignificanceResult(np.nan, np.nan) + res.correlation = np.nan + return res + + a_contains_nan, nan_policy = _contains_nan(a, nan_policy) + variable_has_nan = np.zeros(n_vars, dtype=bool) + if a_contains_nan: + if nan_policy == 'omit': + return mstats_basic.spearmanr(a, axis=axis, nan_policy=nan_policy, + alternative=alternative) + elif nan_policy == 'propagate': + if a.ndim == 1 or n_vars <= 2: + res = SignificanceResult(np.nan, np.nan) + res.correlation = np.nan + return res + else: + # Keep track of variables with NaNs, set the outputs to NaN + # only for those variables + variable_has_nan = np.isnan(a).any(axis=axisout) + + a_ranked = np.apply_along_axis(rankdata, axisout, a) + rs = np.corrcoef(a_ranked, rowvar=axisout) + dof = n_obs - 2 # degrees of freedom + + # rs can have elements equal to 1, so avoid zero division warnings + with np.errstate(divide='ignore'): + # clip the small negative values possibly caused by rounding + # errors before taking the square root + t = rs * np.sqrt((dof/((rs+1.0)*(1.0-rs))).clip(0)) + + dist = _SimpleStudentT(dof) + prob = _get_pvalue(t, dist, alternative, xp=np) + + # For backwards compatibility, return scalars when comparing 2 columns + if rs.shape == (2, 2): + res = SignificanceResult(rs[1, 0], prob[1, 0]) + res.correlation = rs[1, 0] + return res + else: + rs[variable_has_nan, :] = np.nan + rs[:, variable_has_nan] = np.nan + res = SignificanceResult(rs[()], prob[()]) + res.correlation = rs + return res + + +def pointbiserialr(x, y): + r"""Calculate a point biserial correlation coefficient and its p-value. + + The point biserial correlation is used to measure the relationship + between a binary variable, x, and a continuous variable, y. Like other + correlation coefficients, this one varies between -1 and +1 with 0 + implying no correlation. Correlations of -1 or +1 imply a determinative + relationship. + + This function may be computed using a shortcut formula but produces the + same result as `pearsonr`. + + Parameters + ---------- + x : array_like of bools + Input array. + y : array_like + Input array. + + Returns + ------- + res: SignificanceResult + An object containing attributes: + + statistic : float + The R value. + pvalue : float + The two-sided p-value. + + Notes + ----- + `pointbiserialr` uses a t-test with ``n-1`` degrees of freedom. + It is equivalent to `pearsonr`. + + The value of the point-biserial correlation can be calculated from: + + .. math:: + + r_{pb} = \frac{\overline{Y_1} - \overline{Y_0}} + {s_y} + \sqrt{\frac{N_0 N_1} + {N (N - 1)}} + + Where :math:`\overline{Y_{0}}` and :math:`\overline{Y_{1}}` are means + of the metric observations coded 0 and 1 respectively; :math:`N_{0}` and + :math:`N_{1}` are number of observations coded 0 and 1 respectively; + :math:`N` is the total number of observations and :math:`s_{y}` is the + standard deviation of all the metric observations. + + A value of :math:`r_{pb}` that is significantly different from zero is + completely equivalent to a significant difference in means between the two + groups. Thus, an independent groups t Test with :math:`N-2` degrees of + freedom may be used to test whether :math:`r_{pb}` is nonzero. The + relation between the t-statistic for comparing two independent groups and + :math:`r_{pb}` is given by: + + .. math:: + + t = \sqrt{N - 2}\frac{r_{pb}}{\sqrt{1 - r^{2}_{pb}}} + + References + ---------- + .. [1] J. Lev, "The Point Biserial Coefficient of Correlation", Ann. Math. + Statist., Vol. 20, no.1, pp. 125-126, 1949. + + .. [2] R.F. Tate, "Correlation Between a Discrete and a Continuous + Variable. Point-Biserial Correlation.", Ann. Math. Statist., Vol. 25, + np. 3, pp. 603-607, 1954. + + .. [3] D. Kornbrot "Point Biserial Correlation", In Wiley StatsRef: + Statistics Reference Online (eds N. Balakrishnan, et al.), 2014. + :doi:`10.1002/9781118445112.stat06227` + + Examples + -------- + >>> import numpy as np + >>> from scipy import stats + >>> a = np.array([0, 0, 0, 1, 1, 1, 1]) + >>> b = np.arange(7) + >>> stats.pointbiserialr(a, b) + (0.8660254037844386, 0.011724811003954652) + >>> stats.pearsonr(a, b) + (0.86602540378443871, 0.011724811003954626) + >>> np.corrcoef(a, b) + array([[ 1. , 0.8660254], + [ 0.8660254, 1. ]]) + + """ + rpb, prob = pearsonr(x, y) + # create result object with alias for backward compatibility + res = SignificanceResult(rpb, prob) + res.correlation = rpb + return res + + +def kendalltau(x, y, *, nan_policy='propagate', + method='auto', variant='b', alternative='two-sided'): + r"""Calculate Kendall's tau, a correlation measure for ordinal data. + + Kendall's tau is a measure of the correspondence between two rankings. + Values close to 1 indicate strong agreement, and values close to -1 + indicate strong disagreement. This implements two variants of Kendall's + tau: tau-b (the default) and tau-c (also known as Stuart's tau-c). These + differ only in how they are normalized to lie within the range -1 to 1; + the hypothesis tests (their p-values) are identical. Kendall's original + tau-a is not implemented separately because both tau-b and tau-c reduce + to tau-a in the absence of ties. + + Parameters + ---------- + x, y : array_like + Arrays of rankings, of the same shape. If arrays are not 1-D, they + will be flattened to 1-D. + nan_policy : {'propagate', 'raise', 'omit'}, optional + Defines how to handle when input contains nan. + The following options are available (default is 'propagate'): + + * 'propagate': returns nan + * 'raise': throws an error + * 'omit': performs the calculations ignoring nan values + + method : {'auto', 'asymptotic', 'exact'}, optional + Defines which method is used to calculate the p-value [5]_. + The following options are available (default is 'auto'): + + * 'auto': selects the appropriate method based on a trade-off + between speed and accuracy + * 'asymptotic': uses a normal approximation valid for large samples + * 'exact': computes the exact p-value, but can only be used if no ties + are present. As the sample size increases, the 'exact' computation + time may grow and the result may lose some precision. + + variant : {'b', 'c'}, optional + Defines which variant of Kendall's tau is returned. Default is 'b'. + alternative : {'two-sided', 'less', 'greater'}, optional + Defines the alternative hypothesis. Default is 'two-sided'. + The following options are available: + + * 'two-sided': the rank correlation is nonzero + * 'less': the rank correlation is negative (less than zero) + * 'greater': the rank correlation is positive (greater than zero) + + Returns + ------- + res : SignificanceResult + An object containing attributes: + + statistic : float + The tau statistic. + pvalue : float + The p-value for a hypothesis test whose null hypothesis is + an absence of association, tau = 0. + + Raises + ------ + ValueError + If `nan_policy` is 'omit' and `variant` is not 'b' or + if `method` is 'exact' and there are ties between `x` and `y`. + + See Also + -------- + spearmanr : Calculates a Spearman rank-order correlation coefficient. + theilslopes : Computes the Theil-Sen estimator for a set of points (x, y). + weightedtau : Computes a weighted version of Kendall's tau. + :ref:`hypothesis_kendalltau` : Extended example + + Notes + ----- + The definition of Kendall's tau that is used is [2]_:: + + tau_b = (P - Q) / sqrt((P + Q + T) * (P + Q + U)) + + tau_c = 2 (P - Q) / (n**2 * (m - 1) / m) + + where P is the number of concordant pairs, Q the number of discordant + pairs, T the number of ties only in `x`, and U the number of ties only in + `y`. If a tie occurs for the same pair in both `x` and `y`, it is not + added to either T or U. n is the total number of samples, and m is the + number of unique values in either `x` or `y`, whichever is smaller. + + References + ---------- + .. [1] Maurice G. Kendall, "A New Measure of Rank Correlation", Biometrika + Vol. 30, No. 1/2, pp. 81-93, 1938. + .. [2] Maurice G. Kendall, "The treatment of ties in ranking problems", + Biometrika Vol. 33, No. 3, pp. 239-251. 1945. + .. [3] Gottfried E. Noether, "Elements of Nonparametric Statistics", John + Wiley & Sons, 1967. + .. [4] Peter M. Fenwick, "A new data structure for cumulative frequency + tables", Software: Practice and Experience, Vol. 24, No. 3, + pp. 327-336, 1994. + .. [5] Maurice G. Kendall, "Rank Correlation Methods" (4th Edition), + Charles Griffin & Co., 1970. + + Examples + -------- + + >>> from scipy import stats + >>> x1 = [12, 2, 1, 12, 2] + >>> x2 = [1, 4, 7, 1, 0] + >>> res = stats.kendalltau(x1, x2) + >>> res.statistic + -0.47140452079103173 + >>> res.pvalue + 0.2827454599327748 + + For a more detailed example, see :ref:`hypothesis_kendalltau`. + """ + x = np.asarray(x).ravel() + y = np.asarray(y).ravel() + + if x.size != y.size: + raise ValueError("All inputs to `kendalltau` must be of the same " + f"size, found x-size {x.size} and y-size {y.size}") + elif not x.size or not y.size: + # Return NaN if arrays are empty + res = SignificanceResult(np.nan, np.nan) + res.correlation = np.nan + return res + + # check both x and y + cnx, npx = _contains_nan(x, nan_policy) + cny, npy = _contains_nan(y, nan_policy) + contains_nan = cnx or cny + if npx == 'omit' or npy == 'omit': + nan_policy = 'omit' + + if contains_nan and nan_policy == 'propagate': + res = SignificanceResult(np.nan, np.nan) + res.correlation = np.nan + return res + + elif contains_nan and nan_policy == 'omit': + x = ma.masked_invalid(x) + y = ma.masked_invalid(y) + if variant == 'b': + return mstats_basic.kendalltau(x, y, method=method, use_ties=True, + alternative=alternative) + else: + message = ("nan_policy='omit' is currently compatible only with " + "variant='b'.") + raise ValueError(message) + + def count_rank_tie(ranks): + cnt = np.bincount(ranks).astype('int64', copy=False) + cnt = cnt[cnt > 1] + # Python ints to avoid overflow down the line + return (int((cnt * (cnt - 1) // 2).sum()), + int((cnt * (cnt - 1.) * (cnt - 2)).sum()), + int((cnt * (cnt - 1.) * (2*cnt + 5)).sum())) + + size = x.size + perm = np.argsort(y) # sort on y and convert y to dense ranks + x, y = x[perm], y[perm] + y = np.r_[True, y[1:] != y[:-1]].cumsum(dtype=np.intp) + + # stable sort on x and convert x to dense ranks + perm = np.argsort(x, kind='mergesort') + x, y = x[perm], y[perm] + x = np.r_[True, x[1:] != x[:-1]].cumsum(dtype=np.intp) + + dis = _kendall_dis(x, y) # discordant pairs + + obs = np.r_[True, (x[1:] != x[:-1]) | (y[1:] != y[:-1]), True] + cnt = np.diff(np.nonzero(obs)[0]).astype('int64', copy=False) + + ntie = int((cnt * (cnt - 1) // 2).sum()) # joint ties + xtie, x0, x1 = count_rank_tie(x) # ties in x, stats + ytie, y0, y1 = count_rank_tie(y) # ties in y, stats + + tot = (size * (size - 1)) // 2 + + if xtie == tot or ytie == tot: + res = SignificanceResult(np.nan, np.nan) + res.correlation = np.nan + return res + + # Note that tot = con + dis + (xtie - ntie) + (ytie - ntie) + ntie + # = con + dis + xtie + ytie - ntie + con_minus_dis = tot - xtie - ytie + ntie - 2 * dis + if variant == 'b': + tau = con_minus_dis / np.sqrt(tot - xtie) / np.sqrt(tot - ytie) + elif variant == 'c': + minclasses = min(len(set(x)), len(set(y))) + tau = 2*con_minus_dis / (size**2 * (minclasses-1)/minclasses) + else: + raise ValueError(f"Unknown variant of the method chosen: {variant}. " + "variant must be 'b' or 'c'.") + + # Limit range to fix computational errors + tau = np.minimum(1., max(-1., tau)) + + # The p-value calculation is the same for all variants since the p-value + # depends only on con_minus_dis. + if method == 'exact' and (xtie != 0 or ytie != 0): + raise ValueError("Ties found, exact method cannot be used.") + + if method == 'auto': + if (xtie == 0 and ytie == 0) and (size <= 33 or + min(dis, tot-dis) <= 1): + method = 'exact' + else: + method = 'asymptotic' + + if xtie == 0 and ytie == 0 and method == 'exact': + pvalue = mstats_basic._kendall_p_exact(size, tot-dis, alternative) + elif method == 'asymptotic': + # con_minus_dis is approx normally distributed with this variance [3]_ + m = size * (size - 1.) + var = ((m * (2*size + 5) - x1 - y1) / 18 + + (2 * xtie * ytie) / m + x0 * y0 / (9 * m * (size - 2))) + z = con_minus_dis / np.sqrt(var) + pvalue = _get_pvalue(z, _SimpleNormal(), alternative, xp=np) + else: + raise ValueError(f"Unknown method {method} specified. Use 'auto', " + "'exact' or 'asymptotic'.") + + # create result object with alias for backward compatibility + res = SignificanceResult(tau[()], pvalue[()]) + res.correlation = tau[()] + return res + + +def weightedtau(x, y, rank=True, weigher=None, additive=True): + r"""Compute a weighted version of Kendall's :math:`\tau`. + + The weighted :math:`\tau` is a weighted version of Kendall's + :math:`\tau` in which exchanges of high weight are more influential than + exchanges of low weight. The default parameters compute the additive + hyperbolic version of the index, :math:`\tau_\mathrm h`, which has + been shown to provide the best balance between important and + unimportant elements [1]_. + + The weighting is defined by means of a rank array, which assigns a + nonnegative rank to each element (higher importance ranks being + associated with smaller values, e.g., 0 is the highest possible rank), + and a weigher function, which assigns a weight based on the rank to + each element. The weight of an exchange is then the sum or the product + of the weights of the ranks of the exchanged elements. The default + parameters compute :math:`\tau_\mathrm h`: an exchange between + elements with rank :math:`r` and :math:`s` (starting from zero) has + weight :math:`1/(r+1) + 1/(s+1)`. + + Specifying a rank array is meaningful only if you have in mind an + external criterion of importance. If, as it usually happens, you do + not have in mind a specific rank, the weighted :math:`\tau` is + defined by averaging the values obtained using the decreasing + lexicographical rank by (`x`, `y`) and by (`y`, `x`). This is the + behavior with default parameters. Note that the convention used + here for ranking (lower values imply higher importance) is opposite + to that used by other SciPy statistical functions. + + Parameters + ---------- + x, y : array_like + Arrays of scores, of the same shape. If arrays are not 1-D, they will + be flattened to 1-D. + rank : array_like of ints or bool, optional + A nonnegative rank assigned to each element. If it is None, the + decreasing lexicographical rank by (`x`, `y`) will be used: elements of + higher rank will be those with larger `x`-values, using `y`-values to + break ties (in particular, swapping `x` and `y` will give a different + result). If it is False, the element indices will be used + directly as ranks. The default is True, in which case this + function returns the average of the values obtained using the + decreasing lexicographical rank by (`x`, `y`) and by (`y`, `x`). + weigher : callable, optional + The weigher function. Must map nonnegative integers (zero + representing the most important element) to a nonnegative weight. + The default, None, provides hyperbolic weighing, that is, + rank :math:`r` is mapped to weight :math:`1/(r+1)`. + additive : bool, optional + If True, the weight of an exchange is computed by adding the + weights of the ranks of the exchanged elements; otherwise, the weights + are multiplied. The default is True. + + Returns + ------- + res: SignificanceResult + An object containing attributes: + + statistic : float + The weighted :math:`\tau` correlation index. + pvalue : float + Presently ``np.nan``, as the null distribution of the statistic is + unknown (even in the additive hyperbolic case). + + See Also + -------- + kendalltau : Calculates Kendall's tau. + spearmanr : Calculates a Spearman rank-order correlation coefficient. + theilslopes : Computes the Theil-Sen estimator for a set of points (x, y). + + Notes + ----- + This function uses an :math:`O(n \log n)`, mergesort-based algorithm + [1]_ that is a weighted extension of Knight's algorithm for Kendall's + :math:`\tau` [2]_. It can compute Shieh's weighted :math:`\tau` [3]_ + between rankings without ties (i.e., permutations) by setting + `additive` and `rank` to False, as the definition given in [1]_ is a + generalization of Shieh's. + + NaNs are considered the smallest possible score. + + .. versionadded:: 0.19.0 + + References + ---------- + .. [1] Sebastiano Vigna, "A weighted correlation index for rankings with + ties", Proceedings of the 24th international conference on World + Wide Web, pp. 1166-1176, ACM, 2015. + .. [2] W.R. Knight, "A Computer Method for Calculating Kendall's Tau with + Ungrouped Data", Journal of the American Statistical Association, + Vol. 61, No. 314, Part 1, pp. 436-439, 1966. + .. [3] Grace S. Shieh. "A weighted Kendall's tau statistic", Statistics & + Probability Letters, Vol. 39, No. 1, pp. 17-24, 1998. + + Examples + -------- + >>> import numpy as np + >>> from scipy import stats + >>> x = [12, 2, 1, 12, 2] + >>> y = [1, 4, 7, 1, 0] + >>> res = stats.weightedtau(x, y) + >>> res.statistic + -0.56694968153682723 + >>> res.pvalue + nan + >>> res = stats.weightedtau(x, y, additive=False) + >>> res.statistic + -0.62205716951801038 + + NaNs are considered the smallest possible score: + + >>> x = [12, 2, 1, 12, 2] + >>> y = [1, 4, 7, 1, np.nan] + >>> res = stats.weightedtau(x, y) + >>> res.statistic + -0.56694968153682723 + + This is exactly Kendall's tau: + + >>> x = [12, 2, 1, 12, 2] + >>> y = [1, 4, 7, 1, 0] + >>> res = stats.weightedtau(x, y, weigher=lambda x: 1) + >>> res.statistic + -0.47140452079103173 + + >>> x = [12, 2, 1, 12, 2] + >>> y = [1, 4, 7, 1, 0] + >>> stats.weightedtau(x, y, rank=None) + SignificanceResult(statistic=-0.4157652301037516, pvalue=nan) + >>> stats.weightedtau(y, x, rank=None) + SignificanceResult(statistic=-0.7181341329699028, pvalue=nan) + + """ + x = np.asarray(x).ravel() + y = np.asarray(y).ravel() + + if x.size != y.size: + raise ValueError("All inputs to `weightedtau` must be " + "of the same size, " + f"found x-size {x.size} and y-size {y.size}") + if not x.size: + # Return NaN if arrays are empty + res = SignificanceResult(np.nan, np.nan) + res.correlation = np.nan + return res + + # If there are NaNs we apply _toint64() + if np.isnan(np.sum(x)): + x = _toint64(x) + if np.isnan(np.sum(y)): + y = _toint64(y) + + # Reduce to ranks unsupported types + if x.dtype != y.dtype: + if x.dtype != np.int64: + x = _toint64(x) + if y.dtype != np.int64: + y = _toint64(y) + else: + if x.dtype not in (np.int32, np.int64, np.float32, np.float64): + x = _toint64(x) + y = _toint64(y) + + if rank is True: + tau = ( + _weightedrankedtau(x, y, None, weigher, additive) + + _weightedrankedtau(y, x, None, weigher, additive) + ) / 2 + res = SignificanceResult(tau, np.nan) + res.correlation = tau + return res + + if rank is False: + rank = np.arange(x.size, dtype=np.intp) + elif rank is not None: + rank = np.asarray(rank).ravel() + if rank.size != x.size: + raise ValueError( + "All inputs to `weightedtau` must be of the same size, " + f"found x-size {x.size} and rank-size {rank.size}" + ) + + tau = _weightedrankedtau(x, y, rank, weigher, additive) + res = SignificanceResult(tau, np.nan) + res.correlation = tau + return res + + +##################################### +# INFERENTIAL STATISTICS # +##################################### + +TtestResultBase = _make_tuple_bunch('TtestResultBase', + ['statistic', 'pvalue'], ['df']) + + +class TtestResult(TtestResultBase): + """ + Result of a t-test. + + See the documentation of the particular t-test function for more + information about the definition of the statistic and meaning of + the confidence interval. + + Attributes + ---------- + statistic : float or array + The t-statistic of the sample. + pvalue : float or array + The p-value associated with the given alternative. + df : float or array + The number of degrees of freedom used in calculation of the + t-statistic; this is one less than the size of the sample + (``a.shape[axis]-1`` if there are no masked elements or omitted NaNs). + + Methods + ------- + confidence_interval + Computes a confidence interval around the population statistic + for the given confidence level. + The confidence interval is returned in a ``namedtuple`` with + fields `low` and `high`. + + """ + + def __init__(self, statistic, pvalue, df, # public + alternative, standard_error, estimate, # private + statistic_np=None, xp=None): # private + super().__init__(statistic, pvalue, df=df) + self._alternative = alternative + self._standard_error = standard_error # denominator of t-statistic + self._estimate = estimate # point estimate of sample mean + self._statistic_np = statistic if statistic_np is None else statistic_np + self._dtype = statistic.dtype + self._xp = array_namespace(statistic, pvalue) if xp is None else xp + + + def confidence_interval(self, confidence_level=0.95): + """ + Parameters + ---------- + confidence_level : float + The confidence level for the calculation of the population mean + confidence interval. Default is 0.95. + + Returns + ------- + ci : namedtuple + The confidence interval is returned in a ``namedtuple`` with + fields `low` and `high`. + + """ + low, high = _t_confidence_interval(self.df, self._statistic_np, + confidence_level, self._alternative, + self._dtype, self._xp) + low = low * self._standard_error + self._estimate + high = high * self._standard_error + self._estimate + return ConfidenceInterval(low=low, high=high) + + +def pack_TtestResult(statistic, pvalue, df, alternative, standard_error, + estimate): + # this could be any number of dimensions (including 0d), but there is + # at most one unique non-NaN value + alternative = np.atleast_1d(alternative) # can't index 0D object + alternative = alternative[np.isfinite(alternative)] + alternative = alternative[0] if alternative.size else np.nan + return TtestResult(statistic, pvalue, df=df, alternative=alternative, + standard_error=standard_error, estimate=estimate) + + +def unpack_TtestResult(res): + return (res.statistic, res.pvalue, res.df, res._alternative, + res._standard_error, res._estimate) + + +@_axis_nan_policy_factory(pack_TtestResult, default_axis=0, n_samples=2, + result_to_tuple=unpack_TtestResult, n_outputs=6) +# nan_policy handled by `_axis_nan_policy`, but needs to be left +# in signature to preserve use as a positional argument +def ttest_1samp(a, popmean, axis=0, nan_policy="propagate", alternative="two-sided"): + """Calculate the T-test for the mean of ONE group of scores. + + This is a test for the null hypothesis that the expected value + (mean) of a sample of independent observations `a` is equal to the given + population mean, `popmean`. + + Parameters + ---------- + a : array_like + Sample observations. + popmean : float or array_like + Expected value in null hypothesis. If array_like, then its length along + `axis` must equal 1, and it must otherwise be broadcastable with `a`. + axis : int or None, optional + Axis along which to compute test; default is 0. If None, compute over + the whole array `a`. + nan_policy : {'propagate', 'raise', 'omit'}, optional + Defines how to handle when input contains nan. + The following options are available (default is 'propagate'): + + * 'propagate': returns nan + * 'raise': throws an error + * 'omit': performs the calculations ignoring nan values + + alternative : {'two-sided', 'less', 'greater'}, optional + Defines the alternative hypothesis. + The following options are available (default is 'two-sided'): + + * 'two-sided': the mean of the underlying distribution of the sample + is different than the given population mean (`popmean`) + * 'less': the mean of the underlying distribution of the sample is + less than the given population mean (`popmean`) + * 'greater': the mean of the underlying distribution of the sample is + greater than the given population mean (`popmean`) + + Returns + ------- + result : `~scipy.stats._result_classes.TtestResult` + An object with the following attributes: + + statistic : float or array + The t-statistic. + pvalue : float or array + The p-value associated with the given alternative. + df : float or array + The number of degrees of freedom used in calculation of the + t-statistic; this is one less than the size of the sample + (``a.shape[axis]``). + + .. versionadded:: 1.10.0 + + The object also has the following method: + + confidence_interval(confidence_level=0.95) + Computes a confidence interval around the population + mean for the given confidence level. + The confidence interval is returned in a ``namedtuple`` with + fields `low` and `high`. + + .. versionadded:: 1.10.0 + + Notes + ----- + The statistic is calculated as ``(np.mean(a) - popmean)/se``, where + ``se`` is the standard error. Therefore, the statistic will be positive + when the sample mean is greater than the population mean and negative when + the sample mean is less than the population mean. + + Examples + -------- + Suppose we wish to test the null hypothesis that the mean of a population + is equal to 0.5. We choose a confidence level of 99%; that is, we will + reject the null hypothesis in favor of the alternative if the p-value is + less than 0.01. + + When testing random variates from the standard uniform distribution, which + has a mean of 0.5, we expect the data to be consistent with the null + hypothesis most of the time. + + >>> import numpy as np + >>> from scipy import stats + >>> rng = np.random.default_rng() + >>> rvs = stats.uniform.rvs(size=50, random_state=rng) + >>> stats.ttest_1samp(rvs, popmean=0.5) + TtestResult(statistic=2.456308468440, pvalue=0.017628209047638, df=49) + + As expected, the p-value of 0.017 is not below our threshold of 0.01, so + we cannot reject the null hypothesis. + + When testing data from the standard *normal* distribution, which has a mean + of 0, we would expect the null hypothesis to be rejected. + + >>> rvs = stats.norm.rvs(size=50, random_state=rng) + >>> stats.ttest_1samp(rvs, popmean=0.5) + TtestResult(statistic=-7.433605518875, pvalue=1.416760157221e-09, df=49) + + Indeed, the p-value is lower than our threshold of 0.01, so we reject the + null hypothesis in favor of the default "two-sided" alternative: the mean + of the population is *not* equal to 0.5. + + However, suppose we were to test the null hypothesis against the + one-sided alternative that the mean of the population is *greater* than + 0.5. Since the mean of the standard normal is less than 0.5, we would not + expect the null hypothesis to be rejected. + + >>> stats.ttest_1samp(rvs, popmean=0.5, alternative='greater') + TtestResult(statistic=-7.433605518875, pvalue=0.99999999929, df=49) + + Unsurprisingly, with a p-value greater than our threshold, we would not + reject the null hypothesis. + + Note that when working with a confidence level of 99%, a true null + hypothesis will be rejected approximately 1% of the time. + + >>> rvs = stats.uniform.rvs(size=(100, 50), random_state=rng) + >>> res = stats.ttest_1samp(rvs, popmean=0.5, axis=1) + >>> np.sum(res.pvalue < 0.01) + 1 + + Indeed, even though all 100 samples above were drawn from the standard + uniform distribution, which *does* have a population mean of 0.5, we would + mistakenly reject the null hypothesis for one of them. + + `ttest_1samp` can also compute a confidence interval around the population + mean. + + >>> rvs = stats.norm.rvs(size=50, random_state=rng) + >>> res = stats.ttest_1samp(rvs, popmean=0) + >>> ci = res.confidence_interval(confidence_level=0.95) + >>> ci + ConfidenceInterval(low=-0.3193887540880017, high=0.2898583388980972) + + The bounds of the 95% confidence interval are the + minimum and maximum values of the parameter `popmean` for which the + p-value of the test would be 0.05. + + >>> res = stats.ttest_1samp(rvs, popmean=ci.low) + >>> np.testing.assert_allclose(res.pvalue, 0.05) + >>> res = stats.ttest_1samp(rvs, popmean=ci.high) + >>> np.testing.assert_allclose(res.pvalue, 0.05) + + Under certain assumptions about the population from which a sample + is drawn, the confidence interval with confidence level 95% is expected + to contain the true population mean in 95% of sample replications. + + >>> rvs = stats.norm.rvs(size=(50, 1000), loc=1, random_state=rng) + >>> res = stats.ttest_1samp(rvs, popmean=0) + >>> ci = res.confidence_interval() + >>> contains_pop_mean = (ci.low < 1) & (ci.high > 1) + >>> contains_pop_mean.sum() + 953 + + """ + xp = array_namespace(a) + a, axis = _chk_asarray(a, axis, xp=xp) + + n = a.shape[axis] + df = n - 1 + + if n == 0: + # This is really only needed for *testing* _axis_nan_policy decorator + # It won't happen when the decorator is used. + NaN = _get_nan(a) + return TtestResult(NaN, NaN, df=NaN, alternative=NaN, + standard_error=NaN, estimate=NaN) + + mean = xp.mean(a, axis=axis) + try: + popmean = xp.asarray(popmean) + popmean = xp.squeeze(popmean, axis=axis) if popmean.ndim > 0 else popmean + except ValueError as e: + raise ValueError("`popmean.shape[axis]` must equal 1.") from e + d = mean - popmean + v = _var(a, axis=axis, ddof=1) + denom = xp.sqrt(v / n) + + with np.errstate(divide='ignore', invalid='ignore'): + t = xp.divide(d, denom) + t = t[()] if t.ndim == 0 else t + + dist = _SimpleStudentT(xp.asarray(df, dtype=t.dtype)) + prob = _get_pvalue(t, dist, alternative, xp=xp) + prob = prob[()] if prob.ndim == 0 else prob + + # when nan_policy='omit', `df` can be different for different axis-slices + df = xp.broadcast_to(xp.asarray(df), t.shape) + df = df[()] if df.ndim == 0 else df + # _axis_nan_policy decorator doesn't play well with strings + alternative_num = {"less": -1, "two-sided": 0, "greater": 1}[alternative] + return TtestResult(t, prob, df=df, alternative=alternative_num, + standard_error=denom, estimate=mean, + statistic_np=xp.asarray(t), xp=xp) + + +def _t_confidence_interval(df, t, confidence_level, alternative, dtype=None, xp=None): + # Input validation on `alternative` is already done + # We just need IV on confidence_level + dtype = t.dtype if dtype is None else dtype + xp = array_namespace(t) if xp is None else xp + + # stdtrit not dispatched yet; use NumPy + df, t = np.asarray(df), np.asarray(t) + + if confidence_level < 0 or confidence_level > 1: + message = "`confidence_level` must be a number between 0 and 1." + raise ValueError(message) + + if alternative < 0: # 'less' + p = confidence_level + low, high = np.broadcast_arrays(-np.inf, special.stdtrit(df, p)) + elif alternative > 0: # 'greater' + p = 1 - confidence_level + low, high = np.broadcast_arrays(special.stdtrit(df, p), np.inf) + elif alternative == 0: # 'two-sided' + tail_probability = (1 - confidence_level)/2 + p = tail_probability, 1-tail_probability + # axis of p must be the zeroth and orthogonal to all the rest + p = np.reshape(p, [2] + [1]*np.asarray(df).ndim) + low, high = special.stdtrit(df, p) + else: # alternative is NaN when input is empty (see _axis_nan_policy) + p, nans = np.broadcast_arrays(t, np.nan) + low, high = nans, nans + + low = xp.asarray(low, dtype=dtype) + low = low[()] if low.ndim == 0 else low + high = xp.asarray(high, dtype=dtype) + high = high[()] if high.ndim == 0 else high + return low, high + + +def _ttest_ind_from_stats(mean1, mean2, denom, df, alternative, xp=None): + xp = array_namespace(mean1, mean2, denom) if xp is None else xp + + d = mean1 - mean2 + with np.errstate(divide='ignore', invalid='ignore'): + t = xp.divide(d, denom) + + t_np = np.asarray(t) + df_np = np.asarray(df) + prob = _get_pvalue(t_np, distributions.t(df_np), alternative, xp=np) + prob = xp.asarray(prob, dtype=t.dtype) + + t = t[()] if t.ndim == 0 else t + prob = prob[()] if prob.ndim == 0 else prob + return t, prob + + +def _unequal_var_ttest_denom(v1, n1, v2, n2, xp=None): + xp = array_namespace(v1, v2) if xp is None else xp + vn1 = v1 / n1 + vn2 = v2 / n2 + with np.errstate(divide='ignore', invalid='ignore'): + df = (vn1 + vn2)**2 / (vn1**2 / (n1 - 1) + vn2**2 / (n2 - 1)) + + # If df is undefined, variances are zero (assumes n1 > 0 & n2 > 0). + # Hence it doesn't matter what df is as long as it's not NaN. + df = xp.where(xp.isnan(df), xp.asarray(1.), df) + denom = xp.sqrt(vn1 + vn2) + return df, denom + + +def _equal_var_ttest_denom(v1, n1, v2, n2, xp=None): + xp = array_namespace(v1, v2) if xp is None else xp + + # If there is a single observation in one sample, this formula for pooled + # variance breaks down because the variance of that sample is undefined. + # The pooled variance is still defined, though, because the (n-1) in the + # numerator should cancel with the (n-1) in the denominator, leaving only + # the sum of squared differences from the mean: zero. + zero = xp.asarray(0.) + v1 = xp.where(xp.asarray(n1 == 1), zero, v1) + v2 = xp.where(xp.asarray(n2 == 1), zero, v2) + + df = n1 + n2 - 2.0 + svar = ((n1 - 1) * v1 + (n2 - 1) * v2) / df + denom = xp.sqrt(svar * (1.0 / n1 + 1.0 / n2)) + return df, denom + + +Ttest_indResult = namedtuple('Ttest_indResult', ('statistic', 'pvalue')) + + +def ttest_ind_from_stats(mean1, std1, nobs1, mean2, std2, nobs2, + equal_var=True, alternative="two-sided"): + r""" + T-test for means of two independent samples from descriptive statistics. + + This is a test for the null hypothesis that two independent + samples have identical average (expected) values. + + Parameters + ---------- + mean1 : array_like + The mean(s) of sample 1. + std1 : array_like + The corrected sample standard deviation of sample 1 (i.e. ``ddof=1``). + nobs1 : array_like + The number(s) of observations of sample 1. + mean2 : array_like + The mean(s) of sample 2. + std2 : array_like + The corrected sample standard deviation of sample 2 (i.e. ``ddof=1``). + nobs2 : array_like + The number(s) of observations of sample 2. + equal_var : bool, optional + If True (default), perform a standard independent 2 sample test + that assumes equal population variances [1]_. + If False, perform Welch's t-test, which does not assume equal + population variance [2]_. + alternative : {'two-sided', 'less', 'greater'}, optional + Defines the alternative hypothesis. + The following options are available (default is 'two-sided'): + + * 'two-sided': the means of the distributions are unequal. + * 'less': the mean of the first distribution is less than the + mean of the second distribution. + * 'greater': the mean of the first distribution is greater than the + mean of the second distribution. + + .. versionadded:: 1.6.0 + + Returns + ------- + statistic : float or array + The calculated t-statistics. + pvalue : float or array + The two-tailed p-value. + + See Also + -------- + scipy.stats.ttest_ind + + Notes + ----- + The statistic is calculated as ``(mean1 - mean2)/se``, where ``se`` is the + standard error. Therefore, the statistic will be positive when `mean1` is + greater than `mean2` and negative when `mean1` is less than `mean2`. + + This method does not check whether any of the elements of `std1` or `std2` + are negative. If any elements of the `std1` or `std2` parameters are + negative in a call to this method, this method will return the same result + as if it were passed ``numpy.abs(std1)`` and ``numpy.abs(std2)``, + respectively, instead; no exceptions or warnings will be emitted. + + References + ---------- + .. [1] https://en.wikipedia.org/wiki/T-test#Independent_two-sample_t-test + + .. [2] https://en.wikipedia.org/wiki/Welch%27s_t-test + + Examples + -------- + Suppose we have the summary data for two samples, as follows (with the + Sample Variance being the corrected sample variance):: + + Sample Sample + Size Mean Variance + Sample 1 13 15.0 87.5 + Sample 2 11 12.0 39.0 + + Apply the t-test to this data (with the assumption that the population + variances are equal): + + >>> import numpy as np + >>> from scipy.stats import ttest_ind_from_stats + >>> ttest_ind_from_stats(mean1=15.0, std1=np.sqrt(87.5), nobs1=13, + ... mean2=12.0, std2=np.sqrt(39.0), nobs2=11) + Ttest_indResult(statistic=0.9051358093310269, pvalue=0.3751996797581487) + + For comparison, here is the data from which those summary statistics + were taken. With this data, we can compute the same result using + `scipy.stats.ttest_ind`: + + >>> a = np.array([1, 3, 4, 6, 11, 13, 15, 19, 22, 24, 25, 26, 26]) + >>> b = np.array([2, 4, 6, 9, 11, 13, 14, 15, 18, 19, 21]) + >>> from scipy.stats import ttest_ind + >>> ttest_ind(a, b) + TtestResult(statistic=0.905135809331027, + pvalue=0.3751996797581486, + df=22.0) + + Suppose we instead have binary data and would like to apply a t-test to + compare the proportion of 1s in two independent groups:: + + Number of Sample Sample + Size ones Mean Variance + Sample 1 150 30 0.2 0.161073 + Sample 2 200 45 0.225 0.175251 + + The sample mean :math:`\hat{p}` is the proportion of ones in the sample + and the variance for a binary observation is estimated by + :math:`\hat{p}(1-\hat{p})`. + + >>> ttest_ind_from_stats(mean1=0.2, std1=np.sqrt(0.161073), nobs1=150, + ... mean2=0.225, std2=np.sqrt(0.175251), nobs2=200) + Ttest_indResult(statistic=-0.5627187905196761, pvalue=0.5739887114209541) + + For comparison, we could compute the t statistic and p-value using + arrays of 0s and 1s and `scipy.stat.ttest_ind`, as above. + + >>> group1 = np.array([1]*30 + [0]*(150-30)) + >>> group2 = np.array([1]*45 + [0]*(200-45)) + >>> ttest_ind(group1, group2) + TtestResult(statistic=-0.5627179589855622, + pvalue=0.573989277115258, + df=348.0) + + """ + xp = array_namespace(mean1, std1, mean2, std2) + + mean1 = xp.asarray(mean1) + std1 = xp.asarray(std1) + mean2 = xp.asarray(mean2) + std2 = xp.asarray(std2) + + if equal_var: + df, denom = _equal_var_ttest_denom(std1**2, nobs1, std2**2, nobs2, xp=xp) + else: + df, denom = _unequal_var_ttest_denom(std1**2, nobs1, std2**2, nobs2, xp=xp) + + res = _ttest_ind_from_stats(mean1, mean2, denom, df, alternative) + return Ttest_indResult(*res) + + +_ttest_ind_dep_msg = "Use ``method`` to perform a permutation test." +@_deprecate_positional_args(version='1.17.0', + deprecated_args={'permutations', 'random_state'}, + custom_message=_ttest_ind_dep_msg) +@_axis_nan_policy_factory(pack_TtestResult, default_axis=0, n_samples=2, + result_to_tuple=unpack_TtestResult, n_outputs=6) +def ttest_ind(a, b, *, axis=0, equal_var=True, nan_policy='propagate', + permutations=None, random_state=None, alternative="two-sided", + trim=0, method=None): + """ + Calculate the T-test for the means of *two independent* samples of scores. + + This is a test for the null hypothesis that 2 independent samples + have identical average (expected) values. This test assumes that the + populations have identical variances by default. + + Parameters + ---------- + a, b : array_like + The arrays must have the same shape, except in the dimension + corresponding to `axis` (the first, by default). + axis : int or None, optional + Axis along which to compute test. If None, compute over the whole + arrays, `a`, and `b`. + equal_var : bool, optional + If True (default), perform a standard independent 2 sample test + that assumes equal population variances [1]_. + If False, perform Welch's t-test, which does not assume equal + population variance [2]_. + + .. versionadded:: 0.11.0 + + nan_policy : {'propagate', 'raise', 'omit'}, optional + Defines how to handle when input contains nan. + The following options are available (default is 'propagate'): + + * 'propagate': returns nan + * 'raise': throws an error + * 'omit': performs the calculations ignoring nan values + + The 'omit' option is not currently available for permutation tests or + one-sided asymptotic tests. + + permutations : non-negative int, np.inf, or None (default), optional + If 0 or None (default), use the t-distribution to calculate p-values. + Otherwise, `permutations` is the number of random permutations that + will be used to estimate p-values using a permutation test. If + `permutations` equals or exceeds the number of distinct partitions of + the pooled data, an exact test is performed instead (i.e. each + distinct partition is used exactly once). See Notes for details. + + .. deprecated:: 1.17.0 + `permutations` is deprecated and will be removed in SciPy 1.7.0. + Use the `n_resamples` argument of `PermutationMethod`, instead, + and pass the instance as the `method` argument. + + random_state : {None, int, `numpy.random.Generator`, + `numpy.random.RandomState`}, optional + + If `seed` is None (or `np.random`), the `numpy.random.RandomState` + singleton is used. + If `seed` is an int, a new ``RandomState`` instance is used, + seeded with `seed`. + If `seed` is already a ``Generator`` or ``RandomState`` instance then + that instance is used. + + Pseudorandom number generator state used to generate permutations + (used only when `permutations` is not None). + + .. deprecated:: 1.17.0 + `random_state` is deprecated and will be removed in SciPy 1.7.0. + Use the `rng` argument of `PermutationMethod`, instead, + and pass the instance as the `method` argument. + + alternative : {'two-sided', 'less', 'greater'}, optional + Defines the alternative hypothesis. + The following options are available (default is 'two-sided'): + + * 'two-sided': the means of the distributions underlying the samples + are unequal. + * 'less': the mean of the distribution underlying the first sample + is less than the mean of the distribution underlying the second + sample. + * 'greater': the mean of the distribution underlying the first + sample is greater than the mean of the distribution underlying + the second sample. + + trim : float, optional + If nonzero, performs a trimmed (Yuen's) t-test. + Defines the fraction of elements to be trimmed from each end of the + input samples. If 0 (default), no elements will be trimmed from either + side. The number of trimmed elements from each tail is the floor of the + trim times the number of elements. Valid range is [0, .5). + method : ResamplingMethod, optional + Defines the method used to compute the p-value. If `method` is an + instance of `PermutationMethod`/`MonteCarloMethod`, the p-value is + computed using + `scipy.stats.permutation_test`/`scipy.stats.monte_carlo_test` with the + provided configuration options and other appropriate settings. + Otherwise, the p-value is computed by comparing the test statistic + against a theoretical t-distribution. + + .. versionadded:: 1.15.0 + + Returns + ------- + result : `~scipy.stats._result_classes.TtestResult` + An object with the following attributes: + + statistic : float or ndarray + The t-statistic. + pvalue : float or ndarray + The p-value associated with the given alternative. + df : float or ndarray + The number of degrees of freedom used in calculation of the + t-statistic. This is always NaN for a permutation t-test. + + .. versionadded:: 1.11.0 + + The object also has the following method: + + confidence_interval(confidence_level=0.95) + Computes a confidence interval around the difference in + population means for the given confidence level. + The confidence interval is returned in a ``namedtuple`` with + fields ``low`` and ``high``. + When a permutation t-test is performed, the confidence interval + is not computed, and fields ``low`` and ``high`` contain NaN. + + .. versionadded:: 1.11.0 + + Notes + ----- + Suppose we observe two independent samples, e.g. flower petal lengths, and + we are considering whether the two samples were drawn from the same + population (e.g. the same species of flower or two species with similar + petal characteristics) or two different populations. + + The t-test quantifies the difference between the arithmetic means + of the two samples. The p-value quantifies the probability of observing + as or more extreme values assuming the null hypothesis, that the + samples are drawn from populations with the same population means, is true. + A p-value larger than a chosen threshold (e.g. 5% or 1%) indicates that + our observation is not so unlikely to have occurred by chance. Therefore, + we do not reject the null hypothesis of equal population means. + If the p-value is smaller than our threshold, then we have evidence + against the null hypothesis of equal population means. + + By default, the p-value is determined by comparing the t-statistic of the + observed data against a theoretical t-distribution. + + (In the following, note that the argument `permutations` itself is + deprecated, but a nearly identical test may be performed by creating + an instance of `scipy.stats.PermutationMethod` with ``n_resamples=permutuations`` + and passing it as the `method` argument.) + When ``1 < permutations < binom(n, k)``, where + + * ``k`` is the number of observations in `a`, + * ``n`` is the total number of observations in `a` and `b`, and + * ``binom(n, k)`` is the binomial coefficient (``n`` choose ``k``), + + the data are pooled (concatenated), randomly assigned to either group `a` + or `b`, and the t-statistic is calculated. This process is performed + repeatedly (`permutation` times), generating a distribution of the + t-statistic under the null hypothesis, and the t-statistic of the observed + data is compared to this distribution to determine the p-value. + Specifically, the p-value reported is the "achieved significance level" + (ASL) as defined in 4.4 of [3]_. Note that there are other ways of + estimating p-values using randomized permutation tests; for other + options, see the more general `permutation_test`. + + When ``permutations >= binom(n, k)``, an exact test is performed: the data + are partitioned between the groups in each distinct way exactly once. + + The permutation test can be computationally expensive and not necessarily + more accurate than the analytical test, but it does not make strong + assumptions about the shape of the underlying distribution. + + Use of trimming is commonly referred to as the trimmed t-test. At times + called Yuen's t-test, this is an extension of Welch's t-test, with the + difference being the use of winsorized means in calculation of the variance + and the trimmed sample size in calculation of the statistic. Trimming is + recommended if the underlying distribution is long-tailed or contaminated + with outliers [4]_. + + The statistic is calculated as ``(np.mean(a) - np.mean(b))/se``, where + ``se`` is the standard error. Therefore, the statistic will be positive + when the sample mean of `a` is greater than the sample mean of `b` and + negative when the sample mean of `a` is less than the sample mean of + `b`. + + References + ---------- + .. [1] https://en.wikipedia.org/wiki/T-test#Independent_two-sample_t-test + + .. [2] https://en.wikipedia.org/wiki/Welch%27s_t-test + + .. [3] B. Efron and T. Hastie. Computer Age Statistical Inference. (2016). + + .. [4] Yuen, Karen K. "The Two-Sample Trimmed t for Unequal Population + Variances." Biometrika, vol. 61, no. 1, 1974, pp. 165-170. JSTOR, + www.jstor.org/stable/2334299. Accessed 30 Mar. 2021. + + .. [5] Yuen, Karen K., and W. J. Dixon. "The Approximate Behaviour and + Performance of the Two-Sample Trimmed t." Biometrika, vol. 60, + no. 2, 1973, pp. 369-374. JSTOR, www.jstor.org/stable/2334550. + Accessed 30 Mar. 2021. + + Examples + -------- + >>> import numpy as np + >>> from scipy import stats + >>> rng = np.random.default_rng() + + Test with sample with identical means: + + >>> rvs1 = stats.norm.rvs(loc=5, scale=10, size=500, random_state=rng) + >>> rvs2 = stats.norm.rvs(loc=5, scale=10, size=500, random_state=rng) + >>> stats.ttest_ind(rvs1, rvs2) + TtestResult(statistic=-0.4390847099199348, + pvalue=0.6606952038870015, + df=998.0) + >>> stats.ttest_ind(rvs1, rvs2, equal_var=False) + TtestResult(statistic=-0.4390847099199348, + pvalue=0.6606952553131064, + df=997.4602304121448) + + `ttest_ind` underestimates p for unequal variances: + + >>> rvs3 = stats.norm.rvs(loc=5, scale=20, size=500, random_state=rng) + >>> stats.ttest_ind(rvs1, rvs3) + TtestResult(statistic=-1.6370984482905417, + pvalue=0.1019251574705033, + df=998.0) + >>> stats.ttest_ind(rvs1, rvs3, equal_var=False) + TtestResult(statistic=-1.637098448290542, + pvalue=0.10202110497954867, + df=765.1098655246868) + + When ``n1 != n2``, the equal variance t-statistic is no longer equal to the + unequal variance t-statistic: + + >>> rvs4 = stats.norm.rvs(loc=5, scale=20, size=100, random_state=rng) + >>> stats.ttest_ind(rvs1, rvs4) + TtestResult(statistic=-1.9481646859513422, + pvalue=0.05186270935842703, + df=598.0) + >>> stats.ttest_ind(rvs1, rvs4, equal_var=False) + TtestResult(statistic=-1.3146566100751664, + pvalue=0.1913495266513811, + df=110.41349083985212) + + T-test with different means, variance, and n: + + >>> rvs5 = stats.norm.rvs(loc=8, scale=20, size=100, random_state=rng) + >>> stats.ttest_ind(rvs1, rvs5) + TtestResult(statistic=-2.8415950600298774, + pvalue=0.0046418707568707885, + df=598.0) + >>> stats.ttest_ind(rvs1, rvs5, equal_var=False) + TtestResult(statistic=-1.8686598649188084, + pvalue=0.06434714193919686, + df=109.32167496550137) + + Take these two samples, one of which has an extreme tail. + + >>> a = (56, 128.6, 12, 123.8, 64.34, 78, 763.3) + >>> b = (1.1, 2.9, 4.2) + + Use the `trim` keyword to perform a trimmed (Yuen) t-test. For example, + using 20% trimming, ``trim=.2``, the test will reduce the impact of one + (``np.floor(trim*len(a))``) element from each tail of sample `a`. It will + have no effect on sample `b` because ``np.floor(trim*len(b))`` is 0. + + >>> stats.ttest_ind(a, b, trim=.2) + TtestResult(statistic=3.4463884028073513, + pvalue=0.01369338726499547, + df=6.0) + """ + xp = array_namespace(a, b) + + default_float = xp.asarray(1.).dtype + if xp.isdtype(a.dtype, 'integral'): + a = xp.astype(a, default_float) + if xp.isdtype(b.dtype, 'integral'): + b = xp.astype(b, default_float) + + if not (0 <= trim < .5): + raise ValueError("Trimming percentage should be 0 <= `trim` < .5.") + + if not isinstance(method, PermutationMethod | MonteCarloMethod | None): + message = ("`method` must be an instance of `PermutationMethod`, an instance " + "of `MonteCarloMethod`, or None (default).") + raise ValueError(message) + + if not is_numpy(xp) and method is not None: + message = "Use of resampling methods is compatible only with NumPy arrays." + raise NotImplementedError(message) + + result_shape = _broadcast_array_shapes_remove_axis((a, b), axis=axis) + NaN = xp.full(result_shape, _get_nan(a, b, xp=xp)) + NaN = NaN[()] if NaN.ndim == 0 else NaN + if xp_size(a) == 0 or xp_size(b) == 0: + return TtestResult(NaN, NaN, df=NaN, alternative=NaN, + standard_error=NaN, estimate=NaN) + + alternative_nums = {"less": -1, "two-sided": 0, "greater": 1} + + # This probably should be deprecated and replaced with a `method` argument + if permutations is not None and permutations != 0: + message = "Use of `permutations` is compatible only with NumPy arrays." + if not is_numpy(xp): + raise NotImplementedError(message) + + message = "Use of `permutations` is incompatible with with use of `trim`." + if trim != 0: + raise NotImplementedError(message) + + t, prob = _permutation_ttest(a, b, permutations=permutations, + axis=axis, equal_var=equal_var, + nan_policy=nan_policy, + random_state=random_state, + alternative=alternative) + df, denom, estimate = NaN, NaN, NaN + + # _axis_nan_policy decorator doesn't play well with strings + return TtestResult(t, prob, df=df, alternative=alternative_nums[alternative], + standard_error=denom, estimate=estimate) + + n1 = xp.asarray(a.shape[axis], dtype=a.dtype) + n2 = xp.asarray(b.shape[axis], dtype=b.dtype) + + if trim == 0: + with np.errstate(divide='ignore', invalid='ignore'): + v1 = _var(a, axis, ddof=1, xp=xp) + v2 = _var(b, axis, ddof=1, xp=xp) + + m1 = xp.mean(a, axis=axis) + m2 = xp.mean(b, axis=axis) + else: + message = "Use of `trim` is compatible only with NumPy arrays." + if not is_numpy(xp): + raise NotImplementedError(message) + + v1, m1, n1 = _ttest_trim_var_mean_len(a, trim, axis) + v2, m2, n2 = _ttest_trim_var_mean_len(b, trim, axis) + + if equal_var: + df, denom = _equal_var_ttest_denom(v1, n1, v2, n2, xp=xp) + else: + df, denom = _unequal_var_ttest_denom(v1, n1, v2, n2, xp=xp) + + if method is None: + t, prob = _ttest_ind_from_stats(m1, m2, denom, df, alternative) + else: + # nan_policy is taken care of by axis_nan_policy decorator + ttest_kwargs = dict(equal_var=equal_var, trim=trim) + t, prob = _ttest_resampling(a, b, axis, alternative, ttest_kwargs, method) + + # when nan_policy='omit', `df` can be different for different axis-slices + df = xp.broadcast_to(df, t.shape) + df = df[()] if df.ndim ==0 else df + estimate = m1 - m2 + + return TtestResult(t, prob, df=df, alternative=alternative_nums[alternative], + standard_error=denom, estimate=estimate) + + +def _ttest_resampling(x, y, axis, alternative, ttest_kwargs, method): + def statistic(x, y, axis): + return ttest_ind(x, y, axis=axis, **ttest_kwargs).statistic + + test = (permutation_test if isinstance(method, PermutationMethod) + else monte_carlo_test) + method = method._asdict() + + if test is monte_carlo_test: + # `monte_carlo_test` accepts an `rvs` tuple of callables, not an `rng` + # If the user specified an `rng`, replace it with the default callables + if (rng := method.pop('rng', None)) is not None: + rng = np.random.default_rng(rng) + method['rvs'] = rng.normal, rng.normal + + res = test((x, y,), statistic=statistic, axis=axis, + alternative=alternative, **method) + + return res.statistic, res.pvalue + + +def _ttest_trim_var_mean_len(a, trim, axis): + """Variance, mean, and length of winsorized input along specified axis""" + # for use with `ttest_ind` when trimming. + # further calculations in this test assume that the inputs are sorted. + # From [4] Section 1 "Let x_1, ..., x_n be n ordered observations..." + a = np.sort(a, axis=axis) + + # `g` is the number of elements to be replaced on each tail, converted + # from a percentage amount of trimming + n = a.shape[axis] + g = int(n * trim) + + # Calculate the Winsorized variance of the input samples according to + # specified `g` + v = _calculate_winsorized_variance(a, g, axis) + + # the total number of elements in the trimmed samples + n -= 2 * g + + # calculate the g-times trimmed mean, as defined in [4] (1-1) + m = trim_mean(a, trim, axis=axis) + return v, m, n + + +def _calculate_winsorized_variance(a, g, axis): + """Calculates g-times winsorized variance along specified axis""" + # it is expected that the input `a` is sorted along the correct axis + if g == 0: + return _var(a, ddof=1, axis=axis) + # move the intended axis to the end that way it is easier to manipulate + a_win = np.moveaxis(a, axis, -1) + + # save where NaNs are for later use. + nans_indices = np.any(np.isnan(a_win), axis=-1) + + # Winsorization and variance calculation are done in one step in [4] + # (1-3), but here winsorization is done first; replace the left and + # right sides with the repeating value. This can be see in effect in ( + # 1-3) in [4], where the leftmost and rightmost tails are replaced with + # `(g + 1) * x_{g + 1}` on the left and `(g + 1) * x_{n - g}` on the + # right. Zero-indexing turns `g + 1` to `g`, and `n - g` to `- g - 1` in + # array indexing. + a_win[..., :g] = a_win[..., [g]] + a_win[..., -g:] = a_win[..., [-g - 1]] + + # Determine the variance. In [4], the degrees of freedom is expressed as + # `h - 1`, where `h = n - 2g` (unnumbered equations in Section 1, end of + # page 369, beginning of page 370). This is converted to NumPy's format, + # `n - ddof` for use with `np.var`. The result is converted to an + # array to accommodate indexing later. + var_win = np.asarray(_var(a_win, ddof=(2 * g + 1), axis=-1)) + + # with `nan_policy='propagate'`, NaNs may be completely trimmed out + # because they were sorted into the tail of the array. In these cases, + # replace computed variances with `np.nan`. + var_win[nans_indices] = np.nan + return var_win + + +def _permutation_distribution_t(data, permutations, size_a, equal_var, + random_state=None): + """Generation permutation distribution of t statistic""" + + random_state = check_random_state(random_state) + + # prepare permutation indices + size = data.shape[-1] + # number of distinct combinations + n_max = special.comb(size, size_a) + + if permutations < n_max: + perm_generator = (random_state.permutation(size) + for i in range(permutations)) + else: + permutations = n_max + perm_generator = (np.concatenate(z) + for z in _all_partitions(size_a, size-size_a)) + + t_stat = [] + for indices in _batch_generator(perm_generator, batch=50): + # get one batch from perm_generator at a time as a list + indices = np.array(indices) + # generate permutations + data_perm = data[..., indices] + # move axis indexing permutations to position 0 to broadcast + # nicely with t_stat_observed, which doesn't have this dimension + data_perm = np.moveaxis(data_perm, -2, 0) + + a = data_perm[..., :size_a] + b = data_perm[..., size_a:] + t_stat.append(_calc_t_stat(a, b, equal_var)) + + t_stat = np.concatenate(t_stat, axis=0) + + return t_stat, permutations, n_max + + +def _calc_t_stat(a, b, equal_var, axis=-1): + """Calculate the t statistic along the given dimension.""" + na = a.shape[axis] + nb = b.shape[axis] + avg_a = np.mean(a, axis=axis) + avg_b = np.mean(b, axis=axis) + var_a = _var(a, axis=axis, ddof=1) + var_b = _var(b, axis=axis, ddof=1) + + if not equal_var: + _, denom = _unequal_var_ttest_denom(var_a, na, var_b, nb) + else: + _, denom = _equal_var_ttest_denom(var_a, na, var_b, nb) + + return (avg_a-avg_b)/denom + + +def _permutation_ttest(a, b, permutations, axis=0, equal_var=True, + nan_policy='propagate', random_state=None, + alternative="two-sided"): + """ + Calculates the T-test for the means of TWO INDEPENDENT samples of scores + using permutation methods. + + This test is similar to `stats.ttest_ind`, except it doesn't rely on an + approximate normality assumption since it uses a permutation test. + This function is only called from ttest_ind when permutations is not None. + + Parameters + ---------- + a, b : array_like + The arrays must be broadcastable, except along the dimension + corresponding to `axis` (the zeroth, by default). + axis : int, optional + The axis over which to operate on a and b. + permutations : int, optional + Number of permutations used to calculate p-value. If greater than or + equal to the number of distinct permutations, perform an exact test. + equal_var : bool, optional + If False, an equal variance (Welch's) t-test is conducted. Otherwise, + an ordinary t-test is conducted. + random_state : {None, int, `numpy.random.Generator`}, optional + If `seed` is None the `numpy.random.Generator` singleton is used. + If `seed` is an int, a new ``Generator`` instance is used, + seeded with `seed`. + If `seed` is already a ``Generator`` instance then that instance is + used. + Pseudorandom number generator state used for generating random + permutations. + + Returns + ------- + statistic : float or array + The calculated t-statistic. + pvalue : float or array + The p-value. + + """ + if permutations < 0 or (np.isfinite(permutations) and + int(permutations) != permutations): + raise ValueError("Permutations must be a non-negative integer.") + + random_state = check_random_state(random_state) + + t_stat_observed = _calc_t_stat(a, b, equal_var, axis=axis) + + na = a.shape[axis] + mat = _broadcast_concatenate((a, b), axis=axis) + mat = np.moveaxis(mat, axis, -1) + + t_stat, permutations, n_max = _permutation_distribution_t( + mat, permutations, size_a=na, equal_var=equal_var, + random_state=random_state) + + compare = {"less": np.less_equal, + "greater": np.greater_equal, + "two-sided": lambda x, y: (x <= -np.abs(y)) | (x >= np.abs(y))} + + # Calculate the p-values + cmps = compare[alternative](t_stat, t_stat_observed) + # Randomized test p-value calculation should use biased estimate; see e.g. + # https://www.degruyter.com/document/doi/10.2202/1544-6115.1585/ + adjustment = 1 if n_max > permutations else 0 + pvalues = (cmps.sum(axis=0) + adjustment) / (permutations + adjustment) + + # nans propagate naturally in statistic calculation, but need to be + # propagated manually into pvalues + if nan_policy == 'propagate' and np.isnan(t_stat_observed).any(): + if np.ndim(pvalues) == 0: + pvalues = np.float64(np.nan) + else: + pvalues[np.isnan(t_stat_observed)] = np.nan + + return (t_stat_observed, pvalues) + + +def _get_len(a, axis, msg): + try: + n = a.shape[axis] + except IndexError: + raise AxisError(axis, a.ndim, msg) from None + return n + + +@_axis_nan_policy_factory(pack_TtestResult, default_axis=0, n_samples=2, + result_to_tuple=unpack_TtestResult, n_outputs=6, + paired=True) +def ttest_rel(a, b, axis=0, nan_policy='propagate', alternative="two-sided"): + """Calculate the t-test on TWO RELATED samples of scores, a and b. + + This is a test for the null hypothesis that two related or + repeated samples have identical average (expected) values. + + Parameters + ---------- + a, b : array_like + The arrays must have the same shape. + axis : int or None, optional + Axis along which to compute test. If None, compute over the whole + arrays, `a`, and `b`. + nan_policy : {'propagate', 'raise', 'omit'}, optional + Defines how to handle when input contains nan. + The following options are available (default is 'propagate'): + + * 'propagate': returns nan + * 'raise': throws an error + * 'omit': performs the calculations ignoring nan values + alternative : {'two-sided', 'less', 'greater'}, optional + Defines the alternative hypothesis. + The following options are available (default is 'two-sided'): + + * 'two-sided': the means of the distributions underlying the samples + are unequal. + * 'less': the mean of the distribution underlying the first sample + is less than the mean of the distribution underlying the second + sample. + * 'greater': the mean of the distribution underlying the first + sample is greater than the mean of the distribution underlying + the second sample. + + .. versionadded:: 1.6.0 + + Returns + ------- + result : `~scipy.stats._result_classes.TtestResult` + An object with the following attributes: + + statistic : float or array + The t-statistic. + pvalue : float or array + The p-value associated with the given alternative. + df : float or array + The number of degrees of freedom used in calculation of the + t-statistic; this is one less than the size of the sample + (``a.shape[axis]``). + + .. versionadded:: 1.10.0 + + The object also has the following method: + + confidence_interval(confidence_level=0.95) + Computes a confidence interval around the difference in + population means for the given confidence level. + The confidence interval is returned in a ``namedtuple`` with + fields `low` and `high`. + + .. versionadded:: 1.10.0 + + Notes + ----- + Examples for use are scores of the same set of student in + different exams, or repeated sampling from the same units. The + test measures whether the average score differs significantly + across samples (e.g. exams). If we observe a large p-value, for + example greater than 0.05 or 0.1 then we cannot reject the null + hypothesis of identical average scores. If the p-value is smaller + than the threshold, e.g. 1%, 5% or 10%, then we reject the null + hypothesis of equal averages. Small p-values are associated with + large t-statistics. + + The t-statistic is calculated as ``np.mean(a - b)/se``, where ``se`` is the + standard error. Therefore, the t-statistic will be positive when the sample + mean of ``a - b`` is greater than zero and negative when the sample mean of + ``a - b`` is less than zero. + + References + ---------- + https://en.wikipedia.org/wiki/T-test#Dependent_t-test_for_paired_samples + + Examples + -------- + >>> import numpy as np + >>> from scipy import stats + >>> rng = np.random.default_rng() + + >>> rvs1 = stats.norm.rvs(loc=5, scale=10, size=500, random_state=rng) + >>> rvs2 = (stats.norm.rvs(loc=5, scale=10, size=500, random_state=rng) + ... + stats.norm.rvs(scale=0.2, size=500, random_state=rng)) + >>> stats.ttest_rel(rvs1, rvs2) + TtestResult(statistic=-0.4549717054410304, pvalue=0.6493274702088672, df=499) + >>> rvs3 = (stats.norm.rvs(loc=8, scale=10, size=500, random_state=rng) + ... + stats.norm.rvs(scale=0.2, size=500, random_state=rng)) + >>> stats.ttest_rel(rvs1, rvs3) + TtestResult(statistic=-5.879467544540889, pvalue=7.540777129099917e-09, df=499) + + """ + return ttest_1samp(a - b, popmean=0, axis=axis, alternative=alternative, + _no_deco=True) + + +# Map from names to lambda_ values used in power_divergence(). +_power_div_lambda_names = { + "pearson": 1, + "log-likelihood": 0, + "freeman-tukey": -0.5, + "mod-log-likelihood": -1, + "neyman": -2, + "cressie-read": 2/3, +} + + +def _m_count(a, *, axis, xp): + """Count the number of non-masked elements of an array. + + This function behaves like `np.ma.count`, but is much faster + for ndarrays. + """ + if hasattr(a, 'count'): + num = a.count(axis=axis) + if isinstance(num, np.ndarray) and num.ndim == 0: + # In some cases, the `count` method returns a scalar array (e.g. + # np.array(3)), but we want a plain integer. + num = int(num) + else: + if axis is None: + num = xp_size(a) + else: + num = a.shape[axis] + return num + + +def _m_broadcast_to(a, shape, *, xp): + if np.ma.isMaskedArray(a): + return np.ma.masked_array(np.broadcast_to(a, shape), + mask=np.broadcast_to(a.mask, shape)) + return xp.broadcast_to(a, shape) + + +def _m_sum(a, *, axis, preserve_mask, xp): + if np.ma.isMaskedArray(a): + sum = a.sum(axis) + return sum if preserve_mask else np.asarray(sum) + return xp.sum(a, axis=axis) + + +def _m_mean(a, *, axis, keepdims, xp): + if np.ma.isMaskedArray(a): + return np.asarray(a.mean(axis=axis, keepdims=keepdims)) + return xp.mean(a, axis=axis, keepdims=keepdims) + + +Power_divergenceResult = namedtuple('Power_divergenceResult', + ('statistic', 'pvalue')) + + +def power_divergence(f_obs, f_exp=None, ddof=0, axis=0, lambda_=None): + """Cressie-Read power divergence statistic and goodness of fit test. + + This function tests the null hypothesis that the categorical data + has the given frequencies, using the Cressie-Read power divergence + statistic. + + Parameters + ---------- + f_obs : array_like + Observed frequencies in each category. + + .. deprecated:: 1.14.0 + Support for masked array input was deprecated in + SciPy 1.14.0 and will be removed in version 1.16.0. + + f_exp : array_like, optional + Expected frequencies in each category. By default the categories are + assumed to be equally likely. + + .. deprecated:: 1.14.0 + Support for masked array input was deprecated in + SciPy 1.14.0 and will be removed in version 1.16.0. + + ddof : int, optional + "Delta degrees of freedom": adjustment to the degrees of freedom + for the p-value. The p-value is computed using a chi-squared + distribution with ``k - 1 - ddof`` degrees of freedom, where `k` + is the number of observed frequencies. The default value of `ddof` + is 0. + axis : int or None, optional + The axis of the broadcast result of `f_obs` and `f_exp` along which to + apply the test. If axis is None, all values in `f_obs` are treated + as a single data set. Default is 0. + lambda_ : float or str, optional + The power in the Cressie-Read power divergence statistic. The default + is 1. For convenience, `lambda_` may be assigned one of the following + strings, in which case the corresponding numerical value is used: + + * ``"pearson"`` (value 1) + Pearson's chi-squared statistic. In this case, the function is + equivalent to `chisquare`. + * ``"log-likelihood"`` (value 0) + Log-likelihood ratio. Also known as the G-test [3]_. + * ``"freeman-tukey"`` (value -1/2) + Freeman-Tukey statistic. + * ``"mod-log-likelihood"`` (value -1) + Modified log-likelihood ratio. + * ``"neyman"`` (value -2) + Neyman's statistic. + * ``"cressie-read"`` (value 2/3) + The power recommended in [5]_. + + Returns + ------- + res: Power_divergenceResult + An object containing attributes: + + statistic : float or ndarray + The Cressie-Read power divergence test statistic. The value is + a float if `axis` is None or if` `f_obs` and `f_exp` are 1-D. + pvalue : float or ndarray + The p-value of the test. The value is a float if `ddof` and the + return value `stat` are scalars. + + See Also + -------- + chisquare + + Notes + ----- + This test is invalid when the observed or expected frequencies in each + category are too small. A typical rule is that all of the observed + and expected frequencies should be at least 5. + + Also, the sum of the observed and expected frequencies must be the same + for the test to be valid; `power_divergence` raises an error if the sums + do not agree within a relative tolerance of ``eps**0.5``, where ``eps`` + is the precision of the input dtype. + + When `lambda_` is less than zero, the formula for the statistic involves + dividing by `f_obs`, so a warning or error may be generated if any value + in `f_obs` is 0. + + Similarly, a warning or error may be generated if any value in `f_exp` is + zero when `lambda_` >= 0. + + The default degrees of freedom, k-1, are for the case when no parameters + of the distribution are estimated. If p parameters are estimated by + efficient maximum likelihood then the correct degrees of freedom are + k-1-p. If the parameters are estimated in a different way, then the + dof can be between k-1-p and k-1. However, it is also possible that + the asymptotic distribution is not a chisquare, in which case this + test is not appropriate. + + References + ---------- + .. [1] Lowry, Richard. "Concepts and Applications of Inferential + Statistics". Chapter 8. + https://web.archive.org/web/20171015035606/http://faculty.vassar.edu/lowry/ch8pt1.html + .. [2] "Chi-squared test", https://en.wikipedia.org/wiki/Chi-squared_test + .. [3] "G-test", https://en.wikipedia.org/wiki/G-test + .. [4] Sokal, R. R. and Rohlf, F. J. "Biometry: the principles and + practice of statistics in biological research", New York: Freeman + (1981) + .. [5] Cressie, N. and Read, T. R. C., "Multinomial Goodness-of-Fit + Tests", J. Royal Stat. Soc. Series B, Vol. 46, No. 3 (1984), + pp. 440-464. + + Examples + -------- + (See `chisquare` for more examples.) + + When just `f_obs` is given, it is assumed that the expected frequencies + are uniform and given by the mean of the observed frequencies. Here we + perform a G-test (i.e. use the log-likelihood ratio statistic): + + >>> import numpy as np + >>> from scipy.stats import power_divergence + >>> power_divergence([16, 18, 16, 14, 12, 12], lambda_='log-likelihood') + (2.006573162632538, 0.84823476779463769) + + The expected frequencies can be given with the `f_exp` argument: + + >>> power_divergence([16, 18, 16, 14, 12, 12], + ... f_exp=[16, 16, 16, 16, 16, 8], + ... lambda_='log-likelihood') + (3.3281031458963746, 0.6495419288047497) + + When `f_obs` is 2-D, by default the test is applied to each column. + + >>> obs = np.array([[16, 18, 16, 14, 12, 12], [32, 24, 16, 28, 20, 24]]).T + >>> obs.shape + (6, 2) + >>> power_divergence(obs, lambda_="log-likelihood") + (array([ 2.00657316, 6.77634498]), array([ 0.84823477, 0.23781225])) + + By setting ``axis=None``, the test is applied to all data in the array, + which is equivalent to applying the test to the flattened array. + + >>> power_divergence(obs, axis=None) + (23.31034482758621, 0.015975692534127565) + >>> power_divergence(obs.ravel()) + (23.31034482758621, 0.015975692534127565) + + `ddof` is the change to make to the default degrees of freedom. + + >>> power_divergence([16, 18, 16, 14, 12, 12], ddof=1) + (2.0, 0.73575888234288467) + + The calculation of the p-values is done by broadcasting the + test statistic with `ddof`. + + >>> power_divergence([16, 18, 16, 14, 12, 12], ddof=[0,1,2]) + (2.0, array([ 0.84914504, 0.73575888, 0.5724067 ])) + + `f_obs` and `f_exp` are also broadcast. In the following, `f_obs` has + shape (6,) and `f_exp` has shape (2, 6), so the result of broadcasting + `f_obs` and `f_exp` has shape (2, 6). To compute the desired chi-squared + statistics, we must use ``axis=1``: + + >>> power_divergence([16, 18, 16, 14, 12, 12], + ... f_exp=[[16, 16, 16, 16, 16, 8], + ... [8, 20, 20, 16, 12, 12]], + ... axis=1) + (array([ 3.5 , 9.25]), array([ 0.62338763, 0.09949846])) + + """ + return _power_divergence(f_obs, f_exp=f_exp, ddof=ddof, axis=axis, lambda_=lambda_) + + +def _power_divergence(f_obs, f_exp, ddof, axis, lambda_, sum_check=True): + xp = array_namespace(f_obs) + default_float = xp.asarray(1.).dtype + + # Convert the input argument `lambda_` to a numerical value. + if isinstance(lambda_, str): + if lambda_ not in _power_div_lambda_names: + names = repr(list(_power_div_lambda_names.keys()))[1:-1] + raise ValueError(f"invalid string for lambda_: {lambda_!r}. " + f"Valid strings are {names}") + lambda_ = _power_div_lambda_names[lambda_] + elif lambda_ is None: + lambda_ = 1 + + def warn_masked(arg): + if isinstance(arg, ma.MaskedArray): + message = ( + "`power_divergence` and `chisquare` support for masked array input was " + "deprecated in SciPy 1.14.0 and will be removed in version 1.16.0.") + warnings.warn(message, DeprecationWarning, stacklevel=2) + + warn_masked(f_obs) + f_obs = f_obs if np.ma.isMaskedArray(f_obs) else xp.asarray(f_obs) + dtype = default_float if xp.isdtype(f_obs.dtype, 'integral') else f_obs.dtype + f_obs = (f_obs.astype(dtype) if np.ma.isMaskedArray(f_obs) + else xp.asarray(f_obs, dtype=dtype)) + f_obs_float = (f_obs.astype(np.float64) if hasattr(f_obs, 'mask') + else xp.asarray(f_obs, dtype=xp.float64)) + + if f_exp is not None: + warn_masked(f_exp) + f_exp = f_exp if np.ma.isMaskedArray(f_obs) else xp.asarray(f_exp) + dtype = default_float if xp.isdtype(f_exp.dtype, 'integral') else f_exp.dtype + f_exp = (f_exp.astype(dtype) if np.ma.isMaskedArray(f_exp) + else xp.asarray(f_exp, dtype=dtype)) + + bshape = _broadcast_shapes((f_obs_float.shape, f_exp.shape)) + f_obs_float = _m_broadcast_to(f_obs_float, bshape, xp=xp) + f_exp = _m_broadcast_to(f_exp, bshape, xp=xp) + + if sum_check: + dtype_res = xp.result_type(f_obs.dtype, f_exp.dtype) + rtol = xp.finfo(dtype_res).eps**0.5 # to pass existing tests + with np.errstate(invalid='ignore'): + f_obs_sum = _m_sum(f_obs_float, axis=axis, preserve_mask=False, xp=xp) + f_exp_sum = _m_sum(f_exp, axis=axis, preserve_mask=False, xp=xp) + relative_diff = (xp.abs(f_obs_sum - f_exp_sum) / + xp.minimum(f_obs_sum, f_exp_sum)) + diff_gt_tol = xp.any(relative_diff > rtol, axis=None) + if diff_gt_tol: + msg = (f"For each axis slice, the sum of the observed " + f"frequencies must agree with the sum of the " + f"expected frequencies to a relative tolerance " + f"of {rtol}, but the percent differences are:\n" + f"{relative_diff}") + raise ValueError(msg) + + else: + # Ignore 'invalid' errors so the edge case of a data set with length 0 + # is handled without spurious warnings. + with np.errstate(invalid='ignore'): + f_exp = _m_mean(f_obs, axis=axis, keepdims=True, xp=xp) + + # `terms` is the array of terms that are summed along `axis` to create + # the test statistic. We use some specialized code for a few special + # cases of lambda_. + if lambda_ == 1: + # Pearson's chi-squared statistic + terms = (f_obs - f_exp)**2 / f_exp + elif lambda_ == 0: + # Log-likelihood ratio (i.e. G-test) + terms = 2.0 * special.xlogy(f_obs, f_obs / f_exp) + elif lambda_ == -1: + # Modified log-likelihood ratio + terms = 2.0 * special.xlogy(f_exp, f_exp / f_obs) + else: + # General Cressie-Read power divergence. + terms = f_obs * ((f_obs / f_exp)**lambda_ - 1) + terms /= 0.5 * lambda_ * (lambda_ + 1) + + stat = _m_sum(terms, axis=axis, preserve_mask=True, xp=xp) + + num_obs = _m_count(terms, axis=axis, xp=xp) + ddof = xp.asarray(ddof) + + df = xp.asarray(num_obs - 1 - ddof) + chi2 = _SimpleChi2(df) + pvalue = _get_pvalue(stat, chi2 , alternative='greater', symmetric=False, xp=xp) + + stat = stat[()] if stat.ndim == 0 else stat + pvalue = pvalue[()] if pvalue.ndim == 0 else pvalue + + return Power_divergenceResult(stat, pvalue) + + +def chisquare(f_obs, f_exp=None, ddof=0, axis=0, *, sum_check=True): + """Perform Pearson's chi-squared test. + + Pearson's chi-squared test [1]_ is a goodness-of-fit test for a multinomial + distribution with given probabilities; that is, it assesses the null hypothesis + that the observed frequencies (counts) are obtained by independent + sampling of *N* observations from a categorical distribution with given + expected frequencies. + + Parameters + ---------- + f_obs : array_like + Observed frequencies in each category. + f_exp : array_like, optional + Expected frequencies in each category. By default, the categories are + assumed to be equally likely. + ddof : int, optional + "Delta degrees of freedom": adjustment to the degrees of freedom + for the p-value. The p-value is computed using a chi-squared + distribution with ``k - 1 - ddof`` degrees of freedom, where ``k`` + is the number of categories. The default value of `ddof` is 0. + axis : int or None, optional + The axis of the broadcast result of `f_obs` and `f_exp` along which to + apply the test. If axis is None, all values in `f_obs` are treated + as a single data set. Default is 0. + sum_check : bool, optional + Whether to perform a check that ``sum(f_obs) - sum(f_exp) == 0``. If True, + (default) raise an error when the relative difference exceeds the square root + of the precision of the data type. See Notes for rationale and possible + exceptions. + + Returns + ------- + res: Power_divergenceResult + An object containing attributes: + + statistic : float or ndarray + The chi-squared test statistic. The value is a float if `axis` is + None or `f_obs` and `f_exp` are 1-D. + pvalue : float or ndarray + The p-value of the test. The value is a float if `ddof` and the + result attribute `statistic` are scalars. + + See Also + -------- + scipy.stats.power_divergence + scipy.stats.fisher_exact : Fisher exact test on a 2x2 contingency table. + scipy.stats.barnard_exact : An unconditional exact test. An alternative + to chi-squared test for small sample sizes. + :ref:`hypothesis_chisquare` : Extended example + + Notes + ----- + This test is invalid when the observed or expected frequencies in each + category are too small. A typical rule is that all of the observed + and expected frequencies should be at least 5. According to [2]_, the + total number of observations is recommended to be greater than 13, + otherwise exact tests (such as Barnard's Exact test) should be used + because they do not overreject. + + The default degrees of freedom, k-1, are for the case when no parameters + of the distribution are estimated. If p parameters are estimated by + efficient maximum likelihood then the correct degrees of freedom are + k-1-p. If the parameters are estimated in a different way, then the + dof can be between k-1-p and k-1. However, it is also possible that + the asymptotic distribution is not chi-square, in which case this test + is not appropriate. + + For Pearson's chi-squared test, the total observed and expected counts must match + for the p-value to accurately reflect the probability of observing such an extreme + value of the statistic under the null hypothesis. + This function may be used to perform other statistical tests that do not require + the total counts to be equal. For instance, to test the null hypothesis that + ``f_obs[i]`` is Poisson-distributed with expectation ``f_exp[i]``, set ``ddof=-1`` + and ``sum_check=False``. This test follows from the fact that a Poisson random + variable with mean and variance ``f_exp[i]`` is approximately normal with the + same mean and variance; the chi-squared statistic standardizes, squares, and sums + the observations; and the sum of ``n`` squared standard normal variables follows + the chi-squared distribution with ``n`` degrees of freedom. + + References + ---------- + .. [1] "Pearson's chi-squared test". + *Wikipedia*. https://en.wikipedia.org/wiki/Pearson%27s_chi-squared_test + .. [2] Pearson, Karl. "On the criterion that a given system of deviations from the probable + in the case of a correlated system of variables is such that it can be reasonably + supposed to have arisen from random sampling", Philosophical Magazine. Series 5. 50 + (1900), pp. 157-175. + + Examples + -------- + When only the mandatory `f_obs` argument is given, it is assumed that the + expected frequencies are uniform and given by the mean of the observed + frequencies: + + >>> import numpy as np + >>> from scipy.stats import chisquare + >>> chisquare([16, 18, 16, 14, 12, 12]) + Power_divergenceResult(statistic=2.0, pvalue=0.84914503608460956) + + The optional `f_exp` argument gives the expected frequencies. + + >>> chisquare([16, 18, 16, 14, 12, 12], f_exp=[16, 16, 16, 16, 16, 8]) + Power_divergenceResult(statistic=3.5, pvalue=0.62338762774958223) + + When `f_obs` is 2-D, by default the test is applied to each column. + + >>> obs = np.array([[16, 18, 16, 14, 12, 12], [32, 24, 16, 28, 20, 24]]).T + >>> obs.shape + (6, 2) + >>> chisquare(obs) + Power_divergenceResult(statistic=array([2. , 6.66666667]), pvalue=array([0.84914504, 0.24663415])) + + By setting ``axis=None``, the test is applied to all data in the array, + which is equivalent to applying the test to the flattened array. + + >>> chisquare(obs, axis=None) + Power_divergenceResult(statistic=23.31034482758621, pvalue=0.015975692534127565) + >>> chisquare(obs.ravel()) + Power_divergenceResult(statistic=23.310344827586206, pvalue=0.01597569253412758) + + `ddof` is the change to make to the default degrees of freedom. + + >>> chisquare([16, 18, 16, 14, 12, 12], ddof=1) + Power_divergenceResult(statistic=2.0, pvalue=0.7357588823428847) + + The calculation of the p-values is done by broadcasting the + chi-squared statistic with `ddof`. + + >>> chisquare([16, 18, 16, 14, 12, 12], ddof=[0, 1, 2]) + Power_divergenceResult(statistic=2.0, pvalue=array([0.84914504, 0.73575888, 0.5724067 ])) + + `f_obs` and `f_exp` are also broadcast. In the following, `f_obs` has + shape (6,) and `f_exp` has shape (2, 6), so the result of broadcasting + `f_obs` and `f_exp` has shape (2, 6). To compute the desired chi-squared + statistics, we use ``axis=1``: + + >>> chisquare([16, 18, 16, 14, 12, 12], + ... f_exp=[[16, 16, 16, 16, 16, 8], [8, 20, 20, 16, 12, 12]], + ... axis=1) + Power_divergenceResult(statistic=array([3.5 , 9.25]), pvalue=array([0.62338763, 0.09949846])) + + For a more detailed example, see :ref:`hypothesis_chisquare`. + """ # noqa: E501 + return _power_divergence(f_obs, f_exp=f_exp, ddof=ddof, axis=axis, + lambda_="pearson", sum_check=sum_check) + + +KstestResult = _make_tuple_bunch('KstestResult', ['statistic', 'pvalue'], + ['statistic_location', 'statistic_sign']) + + +def _compute_dplus(cdfvals, x): + """Computes D+ as used in the Kolmogorov-Smirnov test. + + Parameters + ---------- + cdfvals : array_like + Sorted array of CDF values between 0 and 1 + x: array_like + Sorted array of the stochastic variable itself + + Returns + ------- + res: Pair with the following elements: + - The maximum distance of the CDF values below Uniform(0, 1). + - The location at which the maximum is reached. + + """ + n = len(cdfvals) + dplus = (np.arange(1.0, n + 1) / n - cdfvals) + amax = dplus.argmax() + loc_max = x[amax] + return (dplus[amax], loc_max) + + +def _compute_dminus(cdfvals, x): + """Computes D- as used in the Kolmogorov-Smirnov test. + + Parameters + ---------- + cdfvals : array_like + Sorted array of CDF values between 0 and 1 + x: array_like + Sorted array of the stochastic variable itself + + Returns + ------- + res: Pair with the following elements: + - Maximum distance of the CDF values above Uniform(0, 1) + - The location at which the maximum is reached. + """ + n = len(cdfvals) + dminus = (cdfvals - np.arange(0.0, n)/n) + amax = dminus.argmax() + loc_max = x[amax] + return (dminus[amax], loc_max) + + +def _tuple_to_KstestResult(statistic, pvalue, + statistic_location, statistic_sign): + return KstestResult(statistic, pvalue, + statistic_location=statistic_location, + statistic_sign=statistic_sign) + + +def _KstestResult_to_tuple(res): + return *res, res.statistic_location, res.statistic_sign + + +@_axis_nan_policy_factory(_tuple_to_KstestResult, n_samples=1, n_outputs=4, + result_to_tuple=_KstestResult_to_tuple) +@_rename_parameter("mode", "method") +def ks_1samp(x, cdf, args=(), alternative='two-sided', method='auto'): + """ + Performs the one-sample Kolmogorov-Smirnov test for goodness of fit. + + This test compares the underlying distribution F(x) of a sample + against a given continuous distribution G(x). See Notes for a description + of the available null and alternative hypotheses. + + Parameters + ---------- + x : array_like + a 1-D array of observations of iid random variables. + cdf : callable + callable used to calculate the cdf. + args : tuple, sequence, optional + Distribution parameters, used with `cdf`. + alternative : {'two-sided', 'less', 'greater'}, optional + Defines the null and alternative hypotheses. Default is 'two-sided'. + Please see explanations in the Notes below. + method : {'auto', 'exact', 'approx', 'asymp'}, optional + Defines the distribution used for calculating the p-value. + The following options are available (default is 'auto'): + + * 'auto' : selects one of the other options. + * 'exact' : uses the exact distribution of test statistic. + * 'approx' : approximates the two-sided probability with twice + the one-sided probability + * 'asymp': uses asymptotic distribution of test statistic + + Returns + ------- + res: KstestResult + An object containing attributes: + + statistic : float + KS test statistic, either D+, D-, or D (the maximum of the two) + pvalue : float + One-tailed or two-tailed p-value. + statistic_location : float + Value of `x` corresponding with the KS statistic; i.e., the + distance between the empirical distribution function and the + hypothesized cumulative distribution function is measured at this + observation. + statistic_sign : int + +1 if the KS statistic is the maximum positive difference between + the empirical distribution function and the hypothesized cumulative + distribution function (D+); -1 if the KS statistic is the maximum + negative difference (D-). + + + See Also + -------- + ks_2samp, kstest + + Notes + ----- + There are three options for the null and corresponding alternative + hypothesis that can be selected using the `alternative` parameter. + + - `two-sided`: The null hypothesis is that the two distributions are + identical, F(x)=G(x) for all x; the alternative is that they are not + identical. + + - `less`: The null hypothesis is that F(x) >= G(x) for all x; the + alternative is that F(x) < G(x) for at least one x. + + - `greater`: The null hypothesis is that F(x) <= G(x) for all x; the + alternative is that F(x) > G(x) for at least one x. + + Note that the alternative hypotheses describe the *CDFs* of the + underlying distributions, not the observed values. For example, + suppose x1 ~ F and x2 ~ G. If F(x) > G(x) for all x, the values in + x1 tend to be less than those in x2. + + Examples + -------- + Suppose we wish to test the null hypothesis that a sample is distributed + according to the standard normal. + We choose a confidence level of 95%; that is, we will reject the null + hypothesis in favor of the alternative if the p-value is less than 0.05. + + When testing uniformly distributed data, we would expect the + null hypothesis to be rejected. + + >>> import numpy as np + >>> from scipy import stats + >>> rng = np.random.default_rng() + >>> stats.ks_1samp(stats.uniform.rvs(size=100, random_state=rng), + ... stats.norm.cdf) + KstestResult(statistic=0.5001899973268688, + pvalue=1.1616392184763533e-23, + statistic_location=0.00047625268963724654, + statistic_sign=-1) + + Indeed, the p-value is lower than our threshold of 0.05, so we reject the + null hypothesis in favor of the default "two-sided" alternative: the data + are *not* distributed according to the standard normal. + + When testing random variates from the standard normal distribution, we + expect the data to be consistent with the null hypothesis most of the time. + + >>> x = stats.norm.rvs(size=100, random_state=rng) + >>> stats.ks_1samp(x, stats.norm.cdf) + KstestResult(statistic=0.05345882212970396, + pvalue=0.9227159037744717, + statistic_location=-1.2451343873745018, + statistic_sign=1) + + As expected, the p-value of 0.92 is not below our threshold of 0.05, so + we cannot reject the null hypothesis. + + Suppose, however, that the random variates are distributed according to + a normal distribution that is shifted toward greater values. In this case, + the cumulative density function (CDF) of the underlying distribution tends + to be *less* than the CDF of the standard normal. Therefore, we would + expect the null hypothesis to be rejected with ``alternative='less'``: + + >>> x = stats.norm.rvs(size=100, loc=0.5, random_state=rng) + >>> stats.ks_1samp(x, stats.norm.cdf, alternative='less') + KstestResult(statistic=0.17482387821055168, + pvalue=0.001913921057766743, + statistic_location=0.3713830565352756, + statistic_sign=-1) + + and indeed, with p-value smaller than our threshold, we reject the null + hypothesis in favor of the alternative. + + """ + mode = method + + alternative = {'t': 'two-sided', 'g': 'greater', 'l': 'less'}.get( + alternative.lower()[0], alternative) + if alternative not in ['two-sided', 'greater', 'less']: + raise ValueError(f"Unexpected value {alternative=}") + + N = len(x) + x = np.sort(x) + cdfvals = cdf(x, *args) + np_one = np.int8(1) + + if alternative == 'greater': + Dplus, d_location = _compute_dplus(cdfvals, x) + return KstestResult(Dplus, distributions.ksone.sf(Dplus, N), + statistic_location=d_location, + statistic_sign=np_one) + + if alternative == 'less': + Dminus, d_location = _compute_dminus(cdfvals, x) + return KstestResult(Dminus, distributions.ksone.sf(Dminus, N), + statistic_location=d_location, + statistic_sign=-np_one) + + # alternative == 'two-sided': + Dplus, dplus_location = _compute_dplus(cdfvals, x) + Dminus, dminus_location = _compute_dminus(cdfvals, x) + if Dplus > Dminus: + D = Dplus + d_location = dplus_location + d_sign = np_one + else: + D = Dminus + d_location = dminus_location + d_sign = -np_one + + if mode == 'auto': # Always select exact + mode = 'exact' + if mode == 'exact': + prob = distributions.kstwo.sf(D, N) + elif mode == 'asymp': + prob = distributions.kstwobign.sf(D * np.sqrt(N)) + else: + # mode == 'approx' + prob = 2 * distributions.ksone.sf(D, N) + prob = np.clip(prob, 0, 1) + return KstestResult(D, prob, + statistic_location=d_location, + statistic_sign=d_sign) + + +Ks_2sampResult = KstestResult + + +def _compute_prob_outside_square(n, h): + """ + Compute the proportion of paths that pass outside the two diagonal lines. + + Parameters + ---------- + n : integer + n > 0 + h : integer + 0 <= h <= n + + Returns + ------- + p : float + The proportion of paths that pass outside the lines x-y = +/-h. + + """ + # Compute Pr(D_{n,n} >= h/n) + # Prob = 2 * ( binom(2n, n-h) - binom(2n, n-2a) + binom(2n, n-3a) - ... ) + # / binom(2n, n) + # This formulation exhibits subtractive cancellation. + # Instead divide each term by binom(2n, n), then factor common terms + # and use a Horner-like algorithm + # P = 2 * A0 * (1 - A1*(1 - A2*(1 - A3*(1 - A4*(...))))) + + P = 0.0 + k = int(np.floor(n / h)) + while k >= 0: + p1 = 1.0 + # Each of the Ai terms has numerator and denominator with + # h simple terms. + for j in range(h): + p1 = (n - k * h - j) * p1 / (n + k * h + j + 1) + P = p1 * (1.0 - P) + k -= 1 + return 2 * P + + +def _count_paths_outside_method(m, n, g, h): + """Count the number of paths that pass outside the specified diagonal. + + Parameters + ---------- + m : integer + m > 0 + n : integer + n > 0 + g : integer + g is greatest common divisor of m and n + h : integer + 0 <= h <= lcm(m,n) + + Returns + ------- + p : float + The number of paths that go low. + The calculation may overflow - check for a finite answer. + + Notes + ----- + Count the integer lattice paths from (0, 0) to (m, n), which at some + point (x, y) along the path, satisfy: + m*y <= n*x - h*g + The paths make steps of size +1 in either positive x or positive y + directions. + + We generally follow Hodges' treatment of Drion/Gnedenko/Korolyuk. + Hodges, J.L. Jr., + "The Significance Probability of the Smirnov Two-Sample Test," + Arkiv fiur Matematik, 3, No. 43 (1958), 469-86. + + """ + # Compute #paths which stay lower than x/m-y/n = h/lcm(m,n) + # B(x, y) = #{paths from (0,0) to (x,y) without + # previously crossing the boundary} + # = binom(x, y) - #{paths which already reached the boundary} + # Multiply by the number of path extensions going from (x, y) to (m, n) + # Sum. + + # Probability is symmetrical in m, n. Computation below assumes m >= n. + if m < n: + m, n = n, m + mg = m // g + ng = n // g + + # Not every x needs to be considered. + # xj holds the list of x values to be checked. + # Wherever n*x/m + ng*h crosses an integer + lxj = n + (mg-h)//mg + xj = [(h + mg * j + ng-1)//ng for j in range(lxj)] + # B is an array just holding a few values of B(x,y), the ones needed. + # B[j] == B(x_j, j) + if lxj == 0: + return special.binom(m + n, n) + B = np.zeros(lxj) + B[0] = 1 + # Compute the B(x, y) terms + for j in range(1, lxj): + Bj = special.binom(xj[j] + j, j) + for i in range(j): + bin = special.binom(xj[j] - xj[i] + j - i, j-i) + Bj -= bin * B[i] + B[j] = Bj + # Compute the number of path extensions... + num_paths = 0 + for j in range(lxj): + bin = special.binom((m-xj[j]) + (n - j), n-j) + term = B[j] * bin + num_paths += term + return num_paths + + +def _attempt_exact_2kssamp(n1, n2, g, d, alternative): + """Attempts to compute the exact 2sample probability. + + n1, n2 are the sample sizes + g is the gcd(n1, n2) + d is the computed max difference in ECDFs + + Returns (success, d, probability) + """ + lcm = (n1 // g) * n2 + h = int(np.round(d * lcm)) + d = h * 1.0 / lcm + if h == 0: + return True, d, 1.0 + saw_fp_error, prob = False, np.nan + try: + with np.errstate(invalid="raise", over="raise"): + if alternative == 'two-sided': + if n1 == n2: + prob = _compute_prob_outside_square(n1, h) + else: + prob = _compute_outer_prob_inside_method(n1, n2, g, h) + else: + if n1 == n2: + # prob = binom(2n, n-h) / binom(2n, n) + # Evaluating in that form incurs roundoff errors + # from special.binom. Instead calculate directly + jrange = np.arange(h) + prob = np.prod((n1 - jrange) / (n1 + jrange + 1.0)) + else: + with np.errstate(over='raise'): + num_paths = _count_paths_outside_method(n1, n2, g, h) + bin = special.binom(n1 + n2, n1) + if num_paths > bin or np.isinf(bin): + saw_fp_error = True + else: + prob = num_paths / bin + + except (FloatingPointError, OverflowError): + saw_fp_error = True + + if saw_fp_error: + return False, d, np.nan + if not (0 <= prob <= 1): + return False, d, prob + return True, d, prob + + +@_axis_nan_policy_factory(_tuple_to_KstestResult, n_samples=2, n_outputs=4, + result_to_tuple=_KstestResult_to_tuple) +@_rename_parameter("mode", "method") +def ks_2samp(data1, data2, alternative='two-sided', method='auto'): + """ + Performs the two-sample Kolmogorov-Smirnov test for goodness of fit. + + This test compares the underlying continuous distributions F(x) and G(x) + of two independent samples. See Notes for a description of the available + null and alternative hypotheses. + + Parameters + ---------- + data1, data2 : array_like, 1-Dimensional + Two arrays of sample observations assumed to be drawn from a continuous + distribution, sample sizes can be different. + alternative : {'two-sided', 'less', 'greater'}, optional + Defines the null and alternative hypotheses. Default is 'two-sided'. + Please see explanations in the Notes below. + method : {'auto', 'exact', 'asymp'}, optional + Defines the method used for calculating the p-value. + The following options are available (default is 'auto'): + + * 'auto' : use 'exact' for small size arrays, 'asymp' for large + * 'exact' : use exact distribution of test statistic + * 'asymp' : use asymptotic distribution of test statistic + + Returns + ------- + res: KstestResult + An object containing attributes: + + statistic : float + KS test statistic. + pvalue : float + One-tailed or two-tailed p-value. + statistic_location : float + Value from `data1` or `data2` corresponding with the KS statistic; + i.e., the distance between the empirical distribution functions is + measured at this observation. + statistic_sign : int + +1 if the empirical distribution function of `data1` exceeds + the empirical distribution function of `data2` at + `statistic_location`, otherwise -1. + + See Also + -------- + kstest, ks_1samp, epps_singleton_2samp, anderson_ksamp + + Notes + ----- + There are three options for the null and corresponding alternative + hypothesis that can be selected using the `alternative` parameter. + + - `less`: The null hypothesis is that F(x) >= G(x) for all x; the + alternative is that F(x) < G(x) for at least one x. The statistic + is the magnitude of the minimum (most negative) difference between the + empirical distribution functions of the samples. + + - `greater`: The null hypothesis is that F(x) <= G(x) for all x; the + alternative is that F(x) > G(x) for at least one x. The statistic + is the maximum (most positive) difference between the empirical + distribution functions of the samples. + + - `two-sided`: The null hypothesis is that the two distributions are + identical, F(x)=G(x) for all x; the alternative is that they are not + identical. The statistic is the maximum absolute difference between the + empirical distribution functions of the samples. + + Note that the alternative hypotheses describe the *CDFs* of the + underlying distributions, not the observed values of the data. For example, + suppose x1 ~ F and x2 ~ G. If F(x) > G(x) for all x, the values in + x1 tend to be less than those in x2. + + If the KS statistic is large, then the p-value will be small, and this may + be taken as evidence against the null hypothesis in favor of the + alternative. + + If ``method='exact'``, `ks_2samp` attempts to compute an exact p-value, + that is, the probability under the null hypothesis of obtaining a test + statistic value as extreme as the value computed from the data. + If ``method='asymp'``, the asymptotic Kolmogorov-Smirnov distribution is + used to compute an approximate p-value. + If ``method='auto'``, an exact p-value computation is attempted if both + sample sizes are less than 10000; otherwise, the asymptotic method is used. + In any case, if an exact p-value calculation is attempted and fails, a + warning will be emitted, and the asymptotic p-value will be returned. + + The 'two-sided' 'exact' computation computes the complementary probability + and then subtracts from 1. As such, the minimum probability it can return + is about 1e-16. While the algorithm itself is exact, numerical + errors may accumulate for large sample sizes. It is most suited to + situations in which one of the sample sizes is only a few thousand. + + We generally follow Hodges' treatment of Drion/Gnedenko/Korolyuk [1]_. + + References + ---------- + .. [1] Hodges, J.L. Jr., "The Significance Probability of the Smirnov + Two-Sample Test," Arkiv fiur Matematik, 3, No. 43 (1958), 469-486. + + Examples + -------- + Suppose we wish to test the null hypothesis that two samples were drawn + from the same distribution. + We choose a confidence level of 95%; that is, we will reject the null + hypothesis in favor of the alternative if the p-value is less than 0.05. + + If the first sample were drawn from a uniform distribution and the second + were drawn from the standard normal, we would expect the null hypothesis + to be rejected. + + >>> import numpy as np + >>> from scipy import stats + >>> rng = np.random.default_rng() + >>> sample1 = stats.uniform.rvs(size=100, random_state=rng) + >>> sample2 = stats.norm.rvs(size=110, random_state=rng) + >>> stats.ks_2samp(sample1, sample2) + KstestResult(statistic=0.5454545454545454, + pvalue=7.37417839555191e-15, + statistic_location=-0.014071496412861274, + statistic_sign=-1) + + + Indeed, the p-value is lower than our threshold of 0.05, so we reject the + null hypothesis in favor of the default "two-sided" alternative: the data + were *not* drawn from the same distribution. + + When both samples are drawn from the same distribution, we expect the data + to be consistent with the null hypothesis most of the time. + + >>> sample1 = stats.norm.rvs(size=105, random_state=rng) + >>> sample2 = stats.norm.rvs(size=95, random_state=rng) + >>> stats.ks_2samp(sample1, sample2) + KstestResult(statistic=0.10927318295739348, + pvalue=0.5438289009927495, + statistic_location=-0.1670157701848795, + statistic_sign=-1) + + As expected, the p-value of 0.54 is not below our threshold of 0.05, so + we cannot reject the null hypothesis. + + Suppose, however, that the first sample were drawn from + a normal distribution shifted toward greater values. In this case, + the cumulative density function (CDF) of the underlying distribution tends + to be *less* than the CDF underlying the second sample. Therefore, we would + expect the null hypothesis to be rejected with ``alternative='less'``: + + >>> sample1 = stats.norm.rvs(size=105, loc=0.5, random_state=rng) + >>> stats.ks_2samp(sample1, sample2, alternative='less') + KstestResult(statistic=0.4055137844611529, + pvalue=3.5474563068855554e-08, + statistic_location=-0.13249370614972575, + statistic_sign=-1) + + and indeed, with p-value smaller than our threshold, we reject the null + hypothesis in favor of the alternative. + + """ + mode = method + + if mode not in ['auto', 'exact', 'asymp']: + raise ValueError(f'Invalid value for mode: {mode}') + alternative = {'t': 'two-sided', 'g': 'greater', 'l': 'less'}.get( + alternative.lower()[0], alternative) + if alternative not in ['two-sided', 'less', 'greater']: + raise ValueError(f'Invalid value for alternative: {alternative}') + MAX_AUTO_N = 10000 # 'auto' will attempt to be exact if n1,n2 <= MAX_AUTO_N + if np.ma.is_masked(data1): + data1 = data1.compressed() + if np.ma.is_masked(data2): + data2 = data2.compressed() + data1 = np.sort(data1) + data2 = np.sort(data2) + n1 = data1.shape[0] + n2 = data2.shape[0] + if min(n1, n2) == 0: + raise ValueError('Data passed to ks_2samp must not be empty') + + data_all = np.concatenate([data1, data2]) + # using searchsorted solves equal data problem + cdf1 = np.searchsorted(data1, data_all, side='right') / n1 + cdf2 = np.searchsorted(data2, data_all, side='right') / n2 + cddiffs = cdf1 - cdf2 + + # Identify the location of the statistic + argminS = np.argmin(cddiffs) + argmaxS = np.argmax(cddiffs) + loc_minS = data_all[argminS] + loc_maxS = data_all[argmaxS] + + # Ensure sign of minS is not negative. + minS = np.clip(-cddiffs[argminS], 0, 1) + maxS = cddiffs[argmaxS] + + if alternative == 'less' or (alternative == 'two-sided' and minS > maxS): + d = minS + d_location = loc_minS + d_sign = -1 + else: + d = maxS + d_location = loc_maxS + d_sign = 1 + g = gcd(n1, n2) + n1g = n1 // g + n2g = n2 // g + prob = -np.inf + if mode == 'auto': + mode = 'exact' if max(n1, n2) <= MAX_AUTO_N else 'asymp' + elif mode == 'exact': + # If lcm(n1, n2) is too big, switch from exact to asymp + if n1g >= np.iinfo(np.int32).max / n2g: + mode = 'asymp' + warnings.warn( + f"Exact ks_2samp calculation not possible with samples sizes " + f"{n1} and {n2}. Switching to 'asymp'.", RuntimeWarning, + stacklevel=3) + + if mode == 'exact': + success, d, prob = _attempt_exact_2kssamp(n1, n2, g, d, alternative) + if not success: + mode = 'asymp' + warnings.warn(f"ks_2samp: Exact calculation unsuccessful. " + f"Switching to method={mode}.", RuntimeWarning, + stacklevel=3) + + if mode == 'asymp': + # The product n1*n2 is large. Use Smirnov's asymptotic formula. + # Ensure float to avoid overflow in multiplication + # sorted because the one-sided formula is not symmetric in n1, n2 + m, n = sorted([float(n1), float(n2)], reverse=True) + en = m * n / (m + n) + if alternative == 'two-sided': + prob = distributions.kstwo.sf(d, np.round(en)) + else: + z = np.sqrt(en) * d + # Use Hodges' suggested approximation Eqn 5.3 + # Requires m to be the larger of (n1, n2) + expt = -2 * z**2 - 2 * z * (m + 2*n)/np.sqrt(m*n*(m+n))/3.0 + prob = np.exp(expt) + + prob = np.clip(prob, 0, 1) + # Currently, `d` is a Python float. We want it to be a NumPy type, so + # float64 is appropriate. An enhancement would be for `d` to respect the + # dtype of the input. + return KstestResult(np.float64(d), prob, statistic_location=d_location, + statistic_sign=np.int8(d_sign)) + + +def _parse_kstest_args(data1, data2, args, N): + # kstest allows many different variations of arguments. + # Pull out the parsing into a separate function + # (xvals, yvals, ) # 2sample + # (xvals, cdf function,..) + # (xvals, name of distribution, ...) + # (name of distribution, name of distribution, ...) + + # Returns xvals, yvals, cdf + # where cdf is a cdf function, or None + # and yvals is either an array_like of values, or None + # and xvals is array_like. + rvsfunc, cdf = None, None + if isinstance(data1, str): + rvsfunc = getattr(distributions, data1).rvs + elif callable(data1): + rvsfunc = data1 + + if isinstance(data2, str): + cdf = getattr(distributions, data2).cdf + data2 = None + elif callable(data2): + cdf = data2 + data2 = None + + data1 = np.sort(rvsfunc(*args, size=N) if rvsfunc else data1) + return data1, data2, cdf + + +def _kstest_n_samples(kwargs): + cdf = kwargs['cdf'] + return 1 if (isinstance(cdf, str) or callable(cdf)) else 2 + + +@_axis_nan_policy_factory(_tuple_to_KstestResult, n_samples=_kstest_n_samples, + n_outputs=4, result_to_tuple=_KstestResult_to_tuple) +@_rename_parameter("mode", "method") +def kstest(rvs, cdf, args=(), N=20, alternative='two-sided', method='auto'): + """ + Performs the (one-sample or two-sample) Kolmogorov-Smirnov test for + goodness of fit. + + The one-sample test compares the underlying distribution F(x) of a sample + against a given distribution G(x). The two-sample test compares the + underlying distributions of two independent samples. Both tests are valid + only for continuous distributions. + + Parameters + ---------- + rvs : str, array_like, or callable + If an array, it should be a 1-D array of observations of random + variables. + If a callable, it should be a function to generate random variables; + it is required to have a keyword argument `size`. + If a string, it should be the name of a distribution in `scipy.stats`, + which will be used to generate random variables. + cdf : str, array_like or callable + If array_like, it should be a 1-D array of observations of random + variables, and the two-sample test is performed + (and rvs must be array_like). + If a callable, that callable is used to calculate the cdf. + If a string, it should be the name of a distribution in `scipy.stats`, + which will be used as the cdf function. + args : tuple, sequence, optional + Distribution parameters, used if `rvs` or `cdf` are strings or + callables. + N : int, optional + Sample size if `rvs` is string or callable. Default is 20. + alternative : {'two-sided', 'less', 'greater'}, optional + Defines the null and alternative hypotheses. Default is 'two-sided'. + Please see explanations in the Notes below. + method : {'auto', 'exact', 'approx', 'asymp'}, optional + Defines the distribution used for calculating the p-value. + The following options are available (default is 'auto'): + + * 'auto' : selects one of the other options. + * 'exact' : uses the exact distribution of test statistic. + * 'approx' : approximates the two-sided probability with twice the + one-sided probability + * 'asymp': uses asymptotic distribution of test statistic + + Returns + ------- + res: KstestResult + An object containing attributes: + + statistic : float + KS test statistic, either D+, D-, or D (the maximum of the two) + pvalue : float + One-tailed or two-tailed p-value. + statistic_location : float + In a one-sample test, this is the value of `rvs` + corresponding with the KS statistic; i.e., the distance between + the empirical distribution function and the hypothesized cumulative + distribution function is measured at this observation. + + In a two-sample test, this is the value from `rvs` or `cdf` + corresponding with the KS statistic; i.e., the distance between + the empirical distribution functions is measured at this + observation. + statistic_sign : int + In a one-sample test, this is +1 if the KS statistic is the + maximum positive difference between the empirical distribution + function and the hypothesized cumulative distribution function + (D+); it is -1 if the KS statistic is the maximum negative + difference (D-). + + In a two-sample test, this is +1 if the empirical distribution + function of `rvs` exceeds the empirical distribution + function of `cdf` at `statistic_location`, otherwise -1. + + See Also + -------- + ks_1samp, ks_2samp + + Notes + ----- + There are three options for the null and corresponding alternative + hypothesis that can be selected using the `alternative` parameter. + + - `two-sided`: The null hypothesis is that the two distributions are + identical, F(x)=G(x) for all x; the alternative is that they are not + identical. + + - `less`: The null hypothesis is that F(x) >= G(x) for all x; the + alternative is that F(x) < G(x) for at least one x. + + - `greater`: The null hypothesis is that F(x) <= G(x) for all x; the + alternative is that F(x) > G(x) for at least one x. + + Note that the alternative hypotheses describe the *CDFs* of the + underlying distributions, not the observed values. For example, + suppose x1 ~ F and x2 ~ G. If F(x) > G(x) for all x, the values in + x1 tend to be less than those in x2. + + + Examples + -------- + Suppose we wish to test the null hypothesis that a sample is distributed + according to the standard normal. + We choose a confidence level of 95%; that is, we will reject the null + hypothesis in favor of the alternative if the p-value is less than 0.05. + + When testing uniformly distributed data, we would expect the + null hypothesis to be rejected. + + >>> import numpy as np + >>> from scipy import stats + >>> rng = np.random.default_rng() + >>> stats.kstest(stats.uniform.rvs(size=100, random_state=rng), + ... stats.norm.cdf) + KstestResult(statistic=0.5001899973268688, + pvalue=1.1616392184763533e-23, + statistic_location=0.00047625268963724654, + statistic_sign=-1) + + Indeed, the p-value is lower than our threshold of 0.05, so we reject the + null hypothesis in favor of the default "two-sided" alternative: the data + are *not* distributed according to the standard normal. + + When testing random variates from the standard normal distribution, we + expect the data to be consistent with the null hypothesis most of the time. + + >>> x = stats.norm.rvs(size=100, random_state=rng) + >>> stats.kstest(x, stats.norm.cdf) + KstestResult(statistic=0.05345882212970396, + pvalue=0.9227159037744717, + statistic_location=-1.2451343873745018, + statistic_sign=1) + + + As expected, the p-value of 0.92 is not below our threshold of 0.05, so + we cannot reject the null hypothesis. + + Suppose, however, that the random variates are distributed according to + a normal distribution that is shifted toward greater values. In this case, + the cumulative density function (CDF) of the underlying distribution tends + to be *less* than the CDF of the standard normal. Therefore, we would + expect the null hypothesis to be rejected with ``alternative='less'``: + + >>> x = stats.norm.rvs(size=100, loc=0.5, random_state=rng) + >>> stats.kstest(x, stats.norm.cdf, alternative='less') + KstestResult(statistic=0.17482387821055168, + pvalue=0.001913921057766743, + statistic_location=0.3713830565352756, + statistic_sign=-1) + + and indeed, with p-value smaller than our threshold, we reject the null + hypothesis in favor of the alternative. + + For convenience, the previous test can be performed using the name of the + distribution as the second argument. + + >>> stats.kstest(x, "norm", alternative='less') + KstestResult(statistic=0.17482387821055168, + pvalue=0.001913921057766743, + statistic_location=0.3713830565352756, + statistic_sign=-1) + + The examples above have all been one-sample tests identical to those + performed by `ks_1samp`. Note that `kstest` can also perform two-sample + tests identical to those performed by `ks_2samp`. For example, when two + samples are drawn from the same distribution, we expect the data to be + consistent with the null hypothesis most of the time. + + >>> sample1 = stats.laplace.rvs(size=105, random_state=rng) + >>> sample2 = stats.laplace.rvs(size=95, random_state=rng) + >>> stats.kstest(sample1, sample2) + KstestResult(statistic=0.11779448621553884, + pvalue=0.4494256912629795, + statistic_location=0.6138814275424155, + statistic_sign=1) + + As expected, the p-value of 0.45 is not below our threshold of 0.05, so + we cannot reject the null hypothesis. + + """ + # to not break compatibility with existing code + if alternative == 'two_sided': + alternative = 'two-sided' + if alternative not in ['two-sided', 'greater', 'less']: + raise ValueError(f"Unexpected alternative: {alternative}") + xvals, yvals, cdf = _parse_kstest_args(rvs, cdf, args, N) + if cdf: + return ks_1samp(xvals, cdf, args=args, alternative=alternative, + method=method, _no_deco=True) + return ks_2samp(xvals, yvals, alternative=alternative, method=method, + _no_deco=True) + + +def tiecorrect(rankvals): + """Tie correction factor for Mann-Whitney U and Kruskal-Wallis H tests. + + Parameters + ---------- + rankvals : array_like + A 1-D sequence of ranks. Typically this will be the array + returned by `~scipy.stats.rankdata`. + + Returns + ------- + factor : float + Correction factor for U or H. + + See Also + -------- + rankdata : Assign ranks to the data + mannwhitneyu : Mann-Whitney rank test + kruskal : Kruskal-Wallis H test + + References + ---------- + .. [1] Siegel, S. (1956) Nonparametric Statistics for the Behavioral + Sciences. New York: McGraw-Hill. + + Examples + -------- + >>> from scipy.stats import tiecorrect, rankdata + >>> tiecorrect([1, 2.5, 2.5, 4]) + 0.9 + >>> ranks = rankdata([1, 3, 2, 4, 5, 7, 2, 8, 4]) + >>> ranks + array([ 1. , 4. , 2.5, 5.5, 7. , 8. , 2.5, 9. , 5.5]) + >>> tiecorrect(ranks) + 0.9833333333333333 + + """ + arr = np.sort(rankvals) + idx = np.nonzero(np.r_[True, arr[1:] != arr[:-1], True])[0] + cnt = np.diff(idx).astype(np.float64) + + size = np.float64(arr.size) + return 1.0 if size < 2 else 1.0 - (cnt**3 - cnt).sum() / (size**3 - size) + + +RanksumsResult = namedtuple('RanksumsResult', ('statistic', 'pvalue')) + + +@_axis_nan_policy_factory(RanksumsResult, n_samples=2) +def ranksums(x, y, alternative='two-sided'): + """Compute the Wilcoxon rank-sum statistic for two samples. + + The Wilcoxon rank-sum test tests the null hypothesis that two sets + of measurements are drawn from the same distribution. The alternative + hypothesis is that values in one sample are more likely to be + larger than the values in the other sample. + + This test should be used to compare two samples from continuous + distributions. It does not handle ties between measurements + in x and y. For tie-handling and an optional continuity correction + see `scipy.stats.mannwhitneyu`. + + Parameters + ---------- + x,y : array_like + The data from the two samples. + alternative : {'two-sided', 'less', 'greater'}, optional + Defines the alternative hypothesis. Default is 'two-sided'. + The following options are available: + + * 'two-sided': one of the distributions (underlying `x` or `y`) is + stochastically greater than the other. + * 'less': the distribution underlying `x` is stochastically less + than the distribution underlying `y`. + * 'greater': the distribution underlying `x` is stochastically greater + than the distribution underlying `y`. + + .. versionadded:: 1.7.0 + + Returns + ------- + statistic : float + The test statistic under the large-sample approximation that the + rank sum statistic is normally distributed. + pvalue : float + The p-value of the test. + + References + ---------- + .. [1] https://en.wikipedia.org/wiki/Wilcoxon_rank-sum_test + + Examples + -------- + We can test the hypothesis that two independent unequal-sized samples are + drawn from the same distribution with computing the Wilcoxon rank-sum + statistic. + + >>> import numpy as np + >>> from scipy.stats import ranksums + >>> rng = np.random.default_rng() + >>> sample1 = rng.uniform(-1, 1, 200) + >>> sample2 = rng.uniform(-0.5, 1.5, 300) # a shifted distribution + >>> ranksums(sample1, sample2) + RanksumsResult(statistic=-7.887059, + pvalue=3.09390448e-15) # may vary + >>> ranksums(sample1, sample2, alternative='less') + RanksumsResult(statistic=-7.750585297581713, + pvalue=4.573497606342543e-15) # may vary + >>> ranksums(sample1, sample2, alternative='greater') + RanksumsResult(statistic=-7.750585297581713, + pvalue=0.9999999999999954) # may vary + + The p-value of less than ``0.05`` indicates that this test rejects the + hypothesis at the 5% significance level. + + """ + x, y = map(np.asarray, (x, y)) + n1 = len(x) + n2 = len(y) + alldata = np.concatenate((x, y)) + ranked = rankdata(alldata) + x = ranked[:n1] + s = np.sum(x, axis=0) + expected = n1 * (n1+n2+1) / 2.0 + z = (s - expected) / np.sqrt(n1*n2*(n1+n2+1)/12.0) + pvalue = _get_pvalue(z, _SimpleNormal(), alternative, xp=np) + + return RanksumsResult(z[()], pvalue[()]) + + +KruskalResult = namedtuple('KruskalResult', ('statistic', 'pvalue')) + + +@_axis_nan_policy_factory(KruskalResult, n_samples=None) +def kruskal(*samples, nan_policy='propagate'): + """Compute the Kruskal-Wallis H-test for independent samples. + + The Kruskal-Wallis H-test tests the null hypothesis that the population + median of all of the groups are equal. It is a non-parametric version of + ANOVA. The test works on 2 or more independent samples, which may have + different sizes. Note that rejecting the null hypothesis does not + indicate which of the groups differs. Post hoc comparisons between + groups are required to determine which groups are different. + + Parameters + ---------- + sample1, sample2, ... : array_like + Two or more arrays with the sample measurements can be given as + arguments. Samples must be one-dimensional. + nan_policy : {'propagate', 'raise', 'omit'}, optional + Defines how to handle when input contains nan. + The following options are available (default is 'propagate'): + + * 'propagate': returns nan + * 'raise': throws an error + * 'omit': performs the calculations ignoring nan values + + Returns + ------- + statistic : float + The Kruskal-Wallis H statistic, corrected for ties. + pvalue : float + The p-value for the test using the assumption that H has a chi + square distribution. The p-value returned is the survival function of + the chi square distribution evaluated at H. + + See Also + -------- + f_oneway : 1-way ANOVA. + mannwhitneyu : Mann-Whitney rank test on two samples. + friedmanchisquare : Friedman test for repeated measurements. + + Notes + ----- + Due to the assumption that H has a chi square distribution, the number + of samples in each group must not be too small. A typical rule is + that each sample must have at least 5 measurements. + + References + ---------- + .. [1] W. H. Kruskal & W. W. Wallis, "Use of Ranks in + One-Criterion Variance Analysis", Journal of the American Statistical + Association, Vol. 47, Issue 260, pp. 583-621, 1952. + .. [2] https://en.wikipedia.org/wiki/Kruskal-Wallis_one-way_analysis_of_variance + + Examples + -------- + >>> from scipy import stats + >>> x = [1, 3, 5, 7, 9] + >>> y = [2, 4, 6, 8, 10] + >>> stats.kruskal(x, y) + KruskalResult(statistic=0.2727272727272734, pvalue=0.6015081344405895) + + >>> x = [1, 1, 1] + >>> y = [2, 2, 2] + >>> z = [2, 2] + >>> stats.kruskal(x, y, z) + KruskalResult(statistic=7.0, pvalue=0.0301973834223185) + + """ + samples = list(map(np.asarray, samples)) + + num_groups = len(samples) + if num_groups < 2: + raise ValueError("Need at least two groups in stats.kruskal()") + + n = np.asarray(list(map(len, samples))) + + alldata = np.concatenate(samples) + ranked = rankdata(alldata) + ties = tiecorrect(ranked) + if ties == 0: + raise ValueError('All numbers are identical in kruskal') + + # Compute sum^2/n for each group and sum + j = np.insert(np.cumsum(n), 0, 0) + ssbn = 0 + for i in range(num_groups): + ssbn += _square_of_sums(ranked[j[i]:j[i+1]]) / n[i] + + totaln = np.sum(n, dtype=float) + h = 12.0 / (totaln * (totaln + 1)) * ssbn - 3 * (totaln + 1) + df = num_groups - 1 + h /= ties + + chi2 = _SimpleChi2(df) + pvalue = _get_pvalue(h, chi2, alternative='greater', symmetric=False, xp=np) + return KruskalResult(h, pvalue) + + +FriedmanchisquareResult = namedtuple('FriedmanchisquareResult', + ('statistic', 'pvalue')) + + +@_axis_nan_policy_factory(FriedmanchisquareResult, n_samples=None, paired=True) +def friedmanchisquare(*samples): + """Compute the Friedman test for repeated samples. + + The Friedman test tests the null hypothesis that repeated samples of + the same individuals have the same distribution. It is often used + to test for consistency among samples obtained in different ways. + For example, if two sampling techniques are used on the same set of + individuals, the Friedman test can be used to determine if the two + sampling techniques are consistent. + + Parameters + ---------- + sample1, sample2, sample3... : array_like + Arrays of observations. All of the arrays must have the same number + of elements. At least three samples must be given. + + Returns + ------- + statistic : float + The test statistic, correcting for ties. + pvalue : float + The associated p-value assuming that the test statistic has a chi + squared distribution. + + See Also + -------- + :ref:`hypothesis_friedmanchisquare` : Extended example + + Notes + ----- + Due to the assumption that the test statistic has a chi squared + distribution, the p-value is only reliable for n > 10 and more than + 6 repeated samples. + + References + ---------- + .. [1] https://en.wikipedia.org/wiki/Friedman_test + .. [2] Demsar, J. (2006). Statistical comparisons of classifiers over + multiple data sets. Journal of Machine Learning Research, 7, 1-30. + + Examples + -------- + + >>> import numpy as np + >>> rng = np.random.default_rng(seed=18) + >>> x = rng.random((6, 10)) + >>> from scipy.stats import friedmanchisquare + >>> res = friedmanchisquare(x[0], x[1], x[2], x[3], x[4], x[5]) + >>> res.statistic, res.pvalue + (11.428571428571416, 0.043514520866727614) + + The p-value is less than 0.05; however, as noted above, the results may not + be reliable since we have a small number of repeated samples. + + For a more detailed example, see :ref:`hypothesis_friedmanchisquare`. + """ + k = len(samples) + if k < 3: + raise ValueError('At least 3 sets of samples must be given ' + f'for Friedman test, got {k}.') + + n = len(samples[0]) + for i in range(1, k): + if len(samples[i]) != n: + raise ValueError('Unequal N in friedmanchisquare. Aborting.') + + # Rank data + data = np.vstack(samples).T + data = data.astype(float) + for i in range(len(data)): + data[i] = rankdata(data[i]) + + # Handle ties + ties = 0 + for d in data: + _, repnum = _find_repeats(np.array(d, dtype=np.float64)) + for t in repnum: + ties += t * (t*t - 1) + c = 1 - ties / (k*(k*k - 1)*n) + + ssbn = np.sum(data.sum(axis=0)**2) + statistic = (12.0 / (k*n*(k+1)) * ssbn - 3*n*(k+1)) / c + + chi2 = _SimpleChi2(k - 1) + pvalue = _get_pvalue(statistic, chi2, alternative='greater', symmetric=False, xp=np) + return FriedmanchisquareResult(statistic, pvalue) + + +BrunnerMunzelResult = namedtuple('BrunnerMunzelResult', + ('statistic', 'pvalue')) + + +@_axis_nan_policy_factory(BrunnerMunzelResult, n_samples=2) +def brunnermunzel(x, y, alternative="two-sided", distribution="t", + nan_policy='propagate'): + """Compute the Brunner-Munzel test on samples x and y. + + The Brunner-Munzel test is a nonparametric test of the null hypothesis that + when values are taken one by one from each group, the probabilities of + getting large values in both groups are equal. + Unlike the Wilcoxon-Mann-Whitney's U test, this does not require the + assumption of equivariance of two groups. Note that this does not assume + the distributions are same. This test works on two independent samples, + which may have different sizes. + + Parameters + ---------- + x, y : array_like + Array of samples, should be one-dimensional. + alternative : {'two-sided', 'less', 'greater'}, optional + Defines the alternative hypothesis. + The following options are available (default is 'two-sided'): + + * 'two-sided' + * 'less': one-sided + * 'greater': one-sided + distribution : {'t', 'normal'}, optional + Defines how to get the p-value. + The following options are available (default is 't'): + + * 't': get the p-value by t-distribution + * 'normal': get the p-value by standard normal distribution. + nan_policy : {'propagate', 'raise', 'omit'}, optional + Defines how to handle when input contains nan. + The following options are available (default is 'propagate'): + + * 'propagate': returns nan + * 'raise': throws an error + * 'omit': performs the calculations ignoring nan values + + Returns + ------- + statistic : float + The Brunner-Munzer W statistic. + pvalue : float + p-value assuming an t distribution. One-sided or + two-sided, depending on the choice of `alternative` and `distribution`. + + See Also + -------- + mannwhitneyu : Mann-Whitney rank test on two samples. + + Notes + ----- + Brunner and Munzel recommended to estimate the p-value by t-distribution + when the size of data is 50 or less. If the size is lower than 10, it would + be better to use permuted Brunner Munzel test (see [2]_). + + References + ---------- + .. [1] Brunner, E. and Munzel, U. "The nonparametric Benhrens-Fisher + problem: Asymptotic theory and a small-sample approximation". + Biometrical Journal. Vol. 42(2000): 17-25. + .. [2] Neubert, K. and Brunner, E. "A studentized permutation test for the + non-parametric Behrens-Fisher problem". Computational Statistics and + Data Analysis. Vol. 51(2007): 5192-5204. + + Examples + -------- + >>> from scipy import stats + >>> x1 = [1,2,1,1,1,1,1,1,1,1,2,4,1,1] + >>> x2 = [3,3,4,3,1,2,3,1,1,5,4] + >>> w, p_value = stats.brunnermunzel(x1, x2) + >>> w + 3.1374674823029505 + >>> p_value + 0.0057862086661515377 + + """ + nx = len(x) + ny = len(y) + + rankc = rankdata(np.concatenate((x, y))) + rankcx = rankc[0:nx] + rankcy = rankc[nx:nx+ny] + rankcx_mean = np.mean(rankcx) + rankcy_mean = np.mean(rankcy) + rankx = rankdata(x) + ranky = rankdata(y) + rankx_mean = np.mean(rankx) + ranky_mean = np.mean(ranky) + + Sx = np.sum(np.power(rankcx - rankx - rankcx_mean + rankx_mean, 2.0)) + Sx /= nx - 1 + Sy = np.sum(np.power(rankcy - ranky - rankcy_mean + ranky_mean, 2.0)) + Sy /= ny - 1 + + wbfn = nx * ny * (rankcy_mean - rankcx_mean) + wbfn /= (nx + ny) * np.sqrt(nx * Sx + ny * Sy) + + if distribution == "t": + df_numer = np.power(nx * Sx + ny * Sy, 2.0) + df_denom = np.power(nx * Sx, 2.0) / (nx - 1) + df_denom += np.power(ny * Sy, 2.0) / (ny - 1) + df = df_numer / df_denom + + if (df_numer == 0) and (df_denom == 0): + message = ("p-value cannot be estimated with `distribution='t' " + "because degrees of freedom parameter is undefined " + "(0/0). Try using `distribution='normal'") + warnings.warn(message, RuntimeWarning, stacklevel=2) + + distribution = _SimpleStudentT(df) + elif distribution == "normal": + distribution = _SimpleNormal() + else: + raise ValueError( + "distribution should be 't' or 'normal'") + + p = _get_pvalue(-wbfn, distribution, alternative, xp=np) + + return BrunnerMunzelResult(wbfn, p) + + +@_axis_nan_policy_factory(SignificanceResult, kwd_samples=['weights'], paired=True) +def combine_pvalues(pvalues, method='fisher', weights=None, *, axis=0): + """ + Combine p-values from independent tests that bear upon the same hypothesis. + + These methods are intended only for combining p-values from hypothesis + tests based upon continuous distributions. + + Each method assumes that under the null hypothesis, the p-values are + sampled independently and uniformly from the interval [0, 1]. A test + statistic (different for each method) is computed and a combined + p-value is calculated based upon the distribution of this test statistic + under the null hypothesis. + + Parameters + ---------- + pvalues : array_like + Array of p-values assumed to come from independent tests based on + continuous distributions. + method : {'fisher', 'pearson', 'tippett', 'stouffer', 'mudholkar_george'} + + Name of method to use to combine p-values. + + The available methods are (see Notes for details): + + * 'fisher': Fisher's method (Fisher's combined probability test) + * 'pearson': Pearson's method + * 'mudholkar_george': Mudholkar's and George's method + * 'tippett': Tippett's method + * 'stouffer': Stouffer's Z-score method + weights : array_like, optional + Optional array of weights used only for Stouffer's Z-score method. + Ignored by other methods. + + Returns + ------- + res : SignificanceResult + An object containing attributes: + + statistic : float + The statistic calculated by the specified method. + pvalue : float + The combined p-value. + + Examples + -------- + Suppose we wish to combine p-values from four independent tests + of the same null hypothesis using Fisher's method (default). + + >>> from scipy.stats import combine_pvalues + >>> pvalues = [0.1, 0.05, 0.02, 0.3] + >>> combine_pvalues(pvalues) + SignificanceResult(statistic=20.828626352604235, pvalue=0.007616871850449092) + + When the individual p-values carry different weights, consider Stouffer's + method. + + >>> weights = [1, 2, 3, 4] + >>> res = combine_pvalues(pvalues, method='stouffer', weights=weights) + >>> res.pvalue + 0.009578891494533616 + + Notes + ----- + If this function is applied to tests with a discrete statistics such as + any rank test or contingency-table test, it will yield systematically + wrong results, e.g. Fisher's method will systematically overestimate the + p-value [1]_. This problem becomes less severe for large sample sizes + when the discrete distributions become approximately continuous. + + The differences between the methods can be best illustrated by their + statistics and what aspects of a combination of p-values they emphasise + when considering significance [2]_. For example, methods emphasising large + p-values are more sensitive to strong false and true negatives; conversely + methods focussing on small p-values are sensitive to positives. + + * The statistics of Fisher's method (also known as Fisher's combined + probability test) [3]_ is :math:`-2\\sum_i \\log(p_i)`, which is + equivalent (as a test statistics) to the product of individual p-values: + :math:`\\prod_i p_i`. Under the null hypothesis, this statistics follows + a :math:`\\chi^2` distribution. This method emphasises small p-values. + * Pearson's method uses :math:`-2\\sum_i\\log(1-p_i)`, which is equivalent + to :math:`\\prod_i \\frac{1}{1-p_i}` [2]_. + It thus emphasises large p-values. + * Mudholkar and George compromise between Fisher's and Pearson's method by + averaging their statistics [4]_. Their method emphasises extreme + p-values, both close to 1 and 0. + * Stouffer's method [5]_ uses Z-scores and the statistic: + :math:`\\sum_i \\Phi^{-1} (p_i)`, where :math:`\\Phi` is the CDF of the + standard normal distribution. The advantage of this method is that it is + straightforward to introduce weights, which can make Stouffer's method + more powerful than Fisher's method when the p-values are from studies + of different size [6]_ [7]_. + * Tippett's method uses the smallest p-value as a statistic. + (Mind that this minimum is not the combined p-value.) + + Fisher's method may be extended to combine p-values from dependent tests + [8]_. Extensions such as Brown's method and Kost's method are not currently + implemented. + + .. versionadded:: 0.15.0 + + References + ---------- + .. [1] Kincaid, W. M., "The Combination of Tests Based on Discrete + Distributions." Journal of the American Statistical Association 57, + no. 297 (1962), 10-19. + .. [2] Heard, N. and Rubin-Delanchey, P. "Choosing between methods of + combining p-values." Biometrika 105.1 (2018): 239-246. + .. [3] https://en.wikipedia.org/wiki/Fisher%27s_method + .. [4] George, E. O., and G. S. Mudholkar. "On the convolution of logistic + random variables." Metrika 30.1 (1983): 1-13. + .. [5] https://en.wikipedia.org/wiki/Fisher%27s_method#Relation_to_Stouffer.27s_Z-score_method + .. [6] Whitlock, M. C. "Combining probability from independent tests: the + weighted Z-method is superior to Fisher's approach." Journal of + Evolutionary Biology 18, no. 5 (2005): 1368-1373. + .. [7] Zaykin, Dmitri V. "Optimally weighted Z-test is a powerful method + for combining probabilities in meta-analysis." Journal of + Evolutionary Biology 24, no. 8 (2011): 1836-1841. + .. [8] https://en.wikipedia.org/wiki/Extensions_of_Fisher%27s_method + + """ + xp = array_namespace(pvalues) + pvalues = xp.asarray(pvalues) + if xp_size(pvalues) == 0: + # This is really only needed for *testing* _axis_nan_policy decorator + # It won't happen when the decorator is used. + NaN = _get_nan(pvalues) + return SignificanceResult(NaN, NaN) + + n = pvalues.shape[axis] + # used to convert Python scalar to the right dtype + one = xp.asarray(1, dtype=pvalues.dtype) + + if method == 'fisher': + statistic = -2 * xp.sum(xp.log(pvalues), axis=axis) + chi2 = _SimpleChi2(2*n*one) + pval = _get_pvalue(statistic, chi2, alternative='greater', + symmetric=False, xp=xp) + elif method == 'pearson': + statistic = 2 * xp.sum(xp.log1p(-pvalues), axis=axis) + chi2 = _SimpleChi2(2*n*one) + pval = _get_pvalue(-statistic, chi2, alternative='less', symmetric=False, xp=xp) + elif method == 'mudholkar_george': + normalizing_factor = math.sqrt(3/n)/xp.pi + statistic = (-xp.sum(xp.log(pvalues), axis=axis) + + xp.sum(xp.log1p(-pvalues), axis=axis)) + nu = 5*n + 4 + approx_factor = math.sqrt(nu / (nu - 2)) + t = _SimpleStudentT(nu*one) + pval = _get_pvalue(statistic * normalizing_factor * approx_factor, t, + alternative="greater", xp=xp) + elif method == 'tippett': + statistic = xp.min(pvalues, axis=axis) + beta = _SimpleBeta(one, n*one) + pval = _get_pvalue(statistic, beta, alternative='less', symmetric=False, xp=xp) + elif method == 'stouffer': + if weights is None: + weights = xp.ones_like(pvalues, dtype=pvalues.dtype) + elif weights.shape[axis] != n: + raise ValueError("pvalues and weights must be of the same " + "length along `axis`.") + + norm = _SimpleNormal() + Zi = norm.isf(pvalues) + # could use `einsum` or clever `matmul` for performance, + # but this is the most readable + statistic = (xp.sum(weights * Zi, axis=axis) + / xp_vector_norm(weights, axis=axis)) + pval = _get_pvalue(statistic, norm, alternative="greater", xp=xp) + + else: + raise ValueError( + f"Invalid method {method!r}. Valid methods are 'fisher', " + "'pearson', 'mudholkar_george', 'tippett', and 'stouffer'" + ) + + return SignificanceResult(statistic, pval) + + +@dataclass +class QuantileTestResult: + r""" + Result of `scipy.stats.quantile_test`. + + Attributes + ---------- + statistic: float + The statistic used to calculate the p-value; either ``T1``, the + number of observations less than or equal to the hypothesized quantile, + or ``T2``, the number of observations strictly less than the + hypothesized quantile. Two test statistics are required to handle the + possibility the data was generated from a discrete or mixed + distribution. + + statistic_type : int + ``1`` or ``2`` depending on which of ``T1`` or ``T2`` was used to + calculate the p-value respectively. ``T1`` corresponds to the + ``"greater"`` alternative hypothesis and ``T2`` to the ``"less"``. For + the ``"two-sided"`` case, the statistic type that leads to smallest + p-value is used. For significant tests, ``statistic_type = 1`` means + there is evidence that the population quantile is significantly greater + than the hypothesized value and ``statistic_type = 2`` means there is + evidence that it is significantly less than the hypothesized value. + + pvalue : float + The p-value of the hypothesis test. + """ + statistic: float + statistic_type: int + pvalue: float + _alternative: list[str] = field(repr=False) + _x : np.ndarray = field(repr=False) + _p : float = field(repr=False) + + def confidence_interval(self, confidence_level=0.95): + """ + Compute the confidence interval of the quantile. + + Parameters + ---------- + confidence_level : float, default: 0.95 + Confidence level for the computed confidence interval + of the quantile. Default is 0.95. + + Returns + ------- + ci : ``ConfidenceInterval`` object + The object has attributes ``low`` and ``high`` that hold the + lower and upper bounds of the confidence interval. + + Examples + -------- + >>> import numpy as np + >>> import scipy.stats as stats + >>> p = 0.75 # quantile of interest + >>> q = 0 # hypothesized value of the quantile + >>> x = np.exp(np.arange(0, 1.01, 0.01)) + >>> res = stats.quantile_test(x, q=q, p=p, alternative='less') + >>> lb, ub = res.confidence_interval() + >>> lb, ub + (-inf, 2.293318740264183) + >>> res = stats.quantile_test(x, q=q, p=p, alternative='two-sided') + >>> lb, ub = res.confidence_interval(0.9) + >>> lb, ub + (1.9542373206359396, 2.293318740264183) + """ + + alternative = self._alternative + p = self._p + x = np.sort(self._x) + n = len(x) + bd = stats.binom(n, p) + + if confidence_level <= 0 or confidence_level >= 1: + message = "`confidence_level` must be a number between 0 and 1." + raise ValueError(message) + + low_index = np.nan + high_index = np.nan + + if alternative == 'less': + p = 1 - confidence_level + low = -np.inf + high_index = int(bd.isf(p)) + high = x[high_index] if high_index < n else np.nan + elif alternative == 'greater': + p = 1 - confidence_level + low_index = int(bd.ppf(p)) - 1 + low = x[low_index] if low_index >= 0 else np.nan + high = np.inf + elif alternative == 'two-sided': + p = (1 - confidence_level) / 2 + low_index = int(bd.ppf(p)) - 1 + low = x[low_index] if low_index >= 0 else np.nan + high_index = int(bd.isf(p)) + high = x[high_index] if high_index < n else np.nan + + return ConfidenceInterval(low, high) + + +def quantile_test_iv(x, q, p, alternative): + + x = np.atleast_1d(x) + message = '`x` must be a one-dimensional array of numbers.' + if x.ndim != 1 or not np.issubdtype(x.dtype, np.number): + raise ValueError(message) + + q = np.array(q)[()] + message = "`q` must be a scalar." + if q.ndim != 0 or not np.issubdtype(q.dtype, np.number): + raise ValueError(message) + + p = np.array(p)[()] + message = "`p` must be a float strictly between 0 and 1." + if p.ndim != 0 or p >= 1 or p <= 0: + raise ValueError(message) + + alternatives = {'two-sided', 'less', 'greater'} + message = f"`alternative` must be one of {alternatives}" + if alternative not in alternatives: + raise ValueError(message) + + return x, q, p, alternative + + +def quantile_test(x, *, q=0, p=0.5, alternative='two-sided'): + r""" + Perform a quantile test and compute a confidence interval of the quantile. + + This function tests the null hypothesis that `q` is the value of the + quantile associated with probability `p` of the population underlying + sample `x`. For example, with default parameters, it tests that the + median of the population underlying `x` is zero. The function returns an + object including the test statistic, a p-value, and a method for computing + the confidence interval around the quantile. + + Parameters + ---------- + x : array_like + A one-dimensional sample. + q : float, default: 0 + The hypothesized value of the quantile. + p : float, default: 0.5 + The probability associated with the quantile; i.e. the proportion of + the population less than `q` is `p`. Must be strictly between 0 and + 1. + alternative : {'two-sided', 'less', 'greater'}, optional + Defines the alternative hypothesis. + The following options are available (default is 'two-sided'): + + * 'two-sided': the quantile associated with the probability `p` + is not `q`. + * 'less': the quantile associated with the probability `p` is less + than `q`. + * 'greater': the quantile associated with the probability `p` is + greater than `q`. + + Returns + ------- + result : QuantileTestResult + An object with the following attributes: + + statistic : float + One of two test statistics that may be used in the quantile test. + The first test statistic, ``T1``, is the proportion of samples in + `x` that are less than or equal to the hypothesized quantile + `q`. The second test statistic, ``T2``, is the proportion of + samples in `x` that are strictly less than the hypothesized + quantile `q`. + + When ``alternative = 'greater'``, ``T1`` is used to calculate the + p-value and ``statistic`` is set to ``T1``. + + When ``alternative = 'less'``, ``T2`` is used to calculate the + p-value and ``statistic`` is set to ``T2``. + + When ``alternative = 'two-sided'``, both ``T1`` and ``T2`` are + considered, and the one that leads to the smallest p-value is used. + + statistic_type : int + Either `1` or `2` depending on which of ``T1`` or ``T2`` was + used to calculate the p-value. + + pvalue : float + The p-value associated with the given alternative. + + The object also has the following method: + + confidence_interval(confidence_level=0.95) + Computes a confidence interval around the the + population quantile associated with the probability `p`. The + confidence interval is returned in a ``namedtuple`` with + fields `low` and `high`. Values are `nan` when there are + not enough observations to compute the confidence interval at + the desired confidence. + + Notes + ----- + This test and its method for computing confidence intervals are + non-parametric. They are valid if and only if the observations are i.i.d. + + The implementation of the test follows Conover [1]_. Two test statistics + are considered. + + ``T1``: The number of observations in `x` less than or equal to `q`. + + ``T1 = (x <= q).sum()`` + + ``T2``: The number of observations in `x` strictly less than `q`. + + ``T2 = (x < q).sum()`` + + The use of two test statistics is necessary to handle the possibility that + `x` was generated from a discrete or mixed distribution. + + The null hypothesis for the test is: + + H0: The :math:`p^{\mathrm{th}}` population quantile is `q`. + + and the null distribution for each test statistic is + :math:`\mathrm{binom}\left(n, p\right)`. When ``alternative='less'``, + the alternative hypothesis is: + + H1: The :math:`p^{\mathrm{th}}` population quantile is less than `q`. + + and the p-value is the probability that the binomial random variable + + .. math:: + Y \sim \mathrm{binom}\left(n, p\right) + + is greater than or equal to the observed value ``T2``. + + When ``alternative='greater'``, the alternative hypothesis is: + + H1: The :math:`p^{\mathrm{th}}` population quantile is greater than `q` + + and the p-value is the probability that the binomial random variable Y + is less than or equal to the observed value ``T1``. + + When ``alternative='two-sided'``, the alternative hypothesis is + + H1: `q` is not the :math:`p^{\mathrm{th}}` population quantile. + + and the p-value is twice the smaller of the p-values for the ``'less'`` + and ``'greater'`` cases. Both of these p-values can exceed 0.5 for the same + data, so the value is clipped into the interval :math:`[0, 1]`. + + The approach for confidence intervals is attributed to Thompson [2]_ and + later proven to be applicable to any set of i.i.d. samples [3]_. The + computation is based on the observation that the probability of a quantile + :math:`q` to be larger than any observations :math:`x_m (1\leq m \leq N)` + can be computed as + + .. math:: + + \mathbb{P}(x_m \leq q) = 1 - \sum_{k=0}^{m-1} \binom{N}{k} + q^k(1-q)^{N-k} + + By default, confidence intervals are computed for a 95% confidence level. + A common interpretation of a 95% confidence intervals is that if i.i.d. + samples are drawn repeatedly from the same population and confidence + intervals are formed each time, the confidence interval will contain the + true value of the specified quantile in approximately 95% of trials. + + A similar function is available in the QuantileNPCI R package [4]_. The + foundation is the same, but it computes the confidence interval bounds by + doing interpolations between the sample values, whereas this function uses + only sample values as bounds. Thus, ``quantile_test.confidence_interval`` + returns more conservative intervals (i.e., larger). + + The same computation of confidence intervals for quantiles is included in + the confintr package [5]_. + + Two-sided confidence intervals are not guaranteed to be optimal; i.e., + there may exist a tighter interval that may contain the quantile of + interest with probability larger than the confidence level. + Without further assumption on the samples (e.g., the nature of the + underlying distribution), the one-sided intervals are optimally tight. + + References + ---------- + .. [1] W. J. Conover. Practical Nonparametric Statistics, 3rd Ed. 1999. + .. [2] W. R. Thompson, "On Confidence Ranges for the Median and Other + Expectation Distributions for Populations of Unknown Distribution + Form," The Annals of Mathematical Statistics, vol. 7, no. 3, + pp. 122-128, 1936, Accessed: Sep. 18, 2019. [Online]. Available: + https://www.jstor.org/stable/2957563. + .. [3] H. A. David and H. N. Nagaraja, "Order Statistics in Nonparametric + Inference" in Order Statistics, John Wiley & Sons, Ltd, 2005, pp. + 159-170. Available: + https://onlinelibrary.wiley.com/doi/10.1002/0471722162.ch7. + .. [4] N. Hutson, A. Hutson, L. Yan, "QuantileNPCI: Nonparametric + Confidence Intervals for Quantiles," R package, + https://cran.r-project.org/package=QuantileNPCI + .. [5] M. Mayer, "confintr: Confidence Intervals," R package, + https://cran.r-project.org/package=confintr + + + Examples + -------- + + Suppose we wish to test the null hypothesis that the median of a population + is equal to 0.5. We choose a confidence level of 99%; that is, we will + reject the null hypothesis in favor of the alternative if the p-value is + less than 0.01. + + When testing random variates from the standard uniform distribution, which + has a median of 0.5, we expect the data to be consistent with the null + hypothesis most of the time. + + >>> import numpy as np + >>> from scipy import stats + >>> rng = np.random.default_rng(6981396440634228121) + >>> rvs = stats.uniform.rvs(size=100, random_state=rng) + >>> stats.quantile_test(rvs, q=0.5, p=0.5) + QuantileTestResult(statistic=45, statistic_type=1, pvalue=0.36820161732669576) + + As expected, the p-value is not below our threshold of 0.01, so + we cannot reject the null hypothesis. + + When testing data from the standard *normal* distribution, which has a + median of 0, we would expect the null hypothesis to be rejected. + + >>> rvs = stats.norm.rvs(size=100, random_state=rng) + >>> stats.quantile_test(rvs, q=0.5, p=0.5) + QuantileTestResult(statistic=67, statistic_type=2, pvalue=0.0008737198369123724) + + Indeed, the p-value is lower than our threshold of 0.01, so we reject the + null hypothesis in favor of the default "two-sided" alternative: the median + of the population is *not* equal to 0.5. + + However, suppose we were to test the null hypothesis against the + one-sided alternative that the median of the population is *greater* than + 0.5. Since the median of the standard normal is less than 0.5, we would not + expect the null hypothesis to be rejected. + + >>> stats.quantile_test(rvs, q=0.5, p=0.5, alternative='greater') + QuantileTestResult(statistic=67, statistic_type=1, pvalue=0.9997956114162866) + + Unsurprisingly, with a p-value greater than our threshold, we would not + reject the null hypothesis in favor of the chosen alternative. + + The quantile test can be used for any quantile, not only the median. For + example, we can test whether the third quartile of the distribution + underlying the sample is greater than 0.6. + + >>> rvs = stats.uniform.rvs(size=100, random_state=rng) + >>> stats.quantile_test(rvs, q=0.6, p=0.75, alternative='greater') + QuantileTestResult(statistic=64, statistic_type=1, pvalue=0.00940696592998271) + + The p-value is lower than the threshold. We reject the null hypothesis in + favor of the alternative: the third quartile of the distribution underlying + our sample is greater than 0.6. + + `quantile_test` can also compute confidence intervals for any quantile. + + >>> rvs = stats.norm.rvs(size=100, random_state=rng) + >>> res = stats.quantile_test(rvs, q=0.6, p=0.75) + >>> ci = res.confidence_interval(confidence_level=0.95) + >>> ci + ConfidenceInterval(low=0.284491604437432, high=0.8912531024914844) + + When testing a one-sided alternative, the confidence interval contains + all observations such that if passed as `q`, the p-value of the + test would be greater than 0.05, and therefore the null hypothesis + would not be rejected. For example: + + >>> rvs.sort() + >>> q, p, alpha = 0.6, 0.75, 0.95 + >>> res = stats.quantile_test(rvs, q=q, p=p, alternative='less') + >>> ci = res.confidence_interval(confidence_level=alpha) + >>> for x in rvs[rvs <= ci.high]: + ... res = stats.quantile_test(rvs, q=x, p=p, alternative='less') + ... assert res.pvalue > 1-alpha + >>> for x in rvs[rvs > ci.high]: + ... res = stats.quantile_test(rvs, q=x, p=p, alternative='less') + ... assert res.pvalue < 1-alpha + + Also, if a 95% confidence interval is repeatedly generated for random + samples, the confidence interval will contain the true quantile value in + approximately 95% of replications. + + >>> dist = stats.rayleigh() # our "unknown" distribution + >>> p = 0.2 + >>> true_stat = dist.ppf(p) # the true value of the statistic + >>> n_trials = 1000 + >>> quantile_ci_contains_true_stat = 0 + >>> for i in range(n_trials): + ... data = dist.rvs(size=100, random_state=rng) + ... res = stats.quantile_test(data, p=p) + ... ci = res.confidence_interval(0.95) + ... if ci[0] < true_stat < ci[1]: + ... quantile_ci_contains_true_stat += 1 + >>> quantile_ci_contains_true_stat >= 950 + True + + This works with any distribution and any quantile, as long as the samples + are i.i.d. + """ + # Implementation carefully follows [1] 3.2 + # "H0: the p*th quantile of X is x*" + # To facilitate comparison with [1], we'll use variable names that + # best match Conover's notation + X, x_star, p_star, H1 = quantile_test_iv(x, q, p, alternative) + + # "We will use two test statistics in this test. Let T1 equal " + # "the number of observations less than or equal to x*, and " + # "let T2 equal the number of observations less than x*." + T1 = (X <= x_star).sum() + T2 = (X < x_star).sum() + + # "The null distribution of the test statistics T1 and T2 is " + # "the binomial distribution, with parameters n = sample size, and " + # "p = p* as given in the null hypothesis.... Y has the binomial " + # "distribution with parameters n and p*." + n = len(X) + Y = stats.binom(n=n, p=p_star) + + # "H1: the p* population quantile is less than x*" + if H1 == 'less': + # "The p-value is the probability that a binomial random variable Y " + # "is greater than *or equal to* the observed value of T2...using p=p*" + pvalue = Y.sf(T2-1) # Y.pmf(T2) + Y.sf(T2) + statistic = T2 + statistic_type = 2 + # "H1: the p* population quantile is greater than x*" + elif H1 == 'greater': + # "The p-value is the probability that a binomial random variable Y " + # "is less than or equal to the observed value of T1... using p = p*" + pvalue = Y.cdf(T1) + statistic = T1 + statistic_type = 1 + # "H1: x* is not the p*th population quantile" + elif H1 == 'two-sided': + # "The p-value is twice the smaller of the probabilities that a + # binomial random variable Y is less than or equal to the observed + # value of T1 or greater than or equal to the observed value of T2 + # using p=p*." + # Note: both one-sided p-values can exceed 0.5 for the same data, so + # `clip` + pvalues = [Y.cdf(T1), Y.sf(T2 - 1)] # [greater, less] + sorted_idx = np.argsort(pvalues) + pvalue = np.clip(2*pvalues[sorted_idx[0]], 0, 1) + if sorted_idx[0]: + statistic, statistic_type = T2, 2 + else: + statistic, statistic_type = T1, 1 + + return QuantileTestResult( + statistic=statistic, + statistic_type=statistic_type, + pvalue=pvalue, + _alternative=H1, + _x=X, + _p=p_star + ) + + +##################################### +# STATISTICAL DISTANCES # +##################################### + + +def wasserstein_distance_nd(u_values, v_values, u_weights=None, v_weights=None): + r""" + Compute the Wasserstein-1 distance between two N-D discrete distributions. + + The Wasserstein distance, also called the Earth mover's distance or the + optimal transport distance, is a similarity metric between two probability + distributions [1]_. In the discrete case, the Wasserstein distance can be + understood as the cost of an optimal transport plan to convert one + distribution into the other. The cost is calculated as the product of the + amount of probability mass being moved and the distance it is being moved. + A brief and intuitive introduction can be found at [2]_. + + .. versionadded:: 1.13.0 + + Parameters + ---------- + u_values : 2d array_like + A sample from a probability distribution or the support (set of all + possible values) of a probability distribution. Each element along + axis 0 is an observation or possible value, and axis 1 represents the + dimensionality of the distribution; i.e., each row is a vector + observation or possible value. + + v_values : 2d array_like + A sample from or the support of a second distribution. + + u_weights, v_weights : 1d array_like, optional + Weights or counts corresponding with the sample or probability masses + corresponding with the support values. Sum of elements must be positive + and finite. If unspecified, each value is assigned the same weight. + + Returns + ------- + distance : float + The computed distance between the distributions. + + Notes + ----- + Given two probability mass functions, :math:`u` + and :math:`v`, the first Wasserstein distance between the distributions + using the Euclidean norm is: + + .. math:: + + l_1 (u, v) = \inf_{\pi \in \Gamma (u, v)} \int \| x-y \|_2 \mathrm{d} \pi (x, y) + + where :math:`\Gamma (u, v)` is the set of (probability) distributions on + :math:`\mathbb{R}^n \times \mathbb{R}^n` whose marginals are :math:`u` and + :math:`v` on the first and second factors respectively. For a given value + :math:`x`, :math:`u(x)` gives the probability of :math:`u` at position + :math:`x`, and the same for :math:`v(x)`. + + This is also called the optimal transport problem or the Monge problem. + Let the finite point sets :math:`\{x_i\}` and :math:`\{y_j\}` denote + the support set of probability mass function :math:`u` and :math:`v` + respectively. The Monge problem can be expressed as follows, + + Let :math:`\Gamma` denote the transport plan, :math:`D` denote the + distance matrix and, + + .. math:: + + x = \text{vec}(\Gamma) \\ + c = \text{vec}(D) \\ + b = \begin{bmatrix} + u\\ + v\\ + \end{bmatrix} + + The :math:`\text{vec}()` function denotes the Vectorization function + that transforms a matrix into a column vector by vertically stacking + the columns of the matrix. + The transport plan :math:`\Gamma` is a matrix :math:`[\gamma_{ij}]` in + which :math:`\gamma_{ij}` is a positive value representing the amount of + probability mass transported from :math:`u(x_i)` to :math:`v(y_i)`. + Summing over the rows of :math:`\Gamma` should give the source distribution + :math:`u` : :math:`\sum_j \gamma_{ij} = u(x_i)` holds for all :math:`i` + and summing over the columns of :math:`\Gamma` should give the target + distribution :math:`v`: :math:`\sum_i \gamma_{ij} = v(y_j)` holds for all + :math:`j`. + The distance matrix :math:`D` is a matrix :math:`[d_{ij}]`, in which + :math:`d_{ij} = d(x_i, y_j)`. + + Given :math:`\Gamma`, :math:`D`, :math:`b`, the Monge problem can be + transformed into a linear programming problem by + taking :math:`A x = b` as constraints and :math:`z = c^T x` as minimization + target (sum of costs) , where matrix :math:`A` has the form + + .. math:: + + \begin{array} {rrrr|rrrr|r|rrrr} + 1 & 1 & \dots & 1 & 0 & 0 & \dots & 0 & \dots & 0 & 0 & \dots & + 0 \cr + 0 & 0 & \dots & 0 & 1 & 1 & \dots & 1 & \dots & 0 & 0 &\dots & + 0 \cr + \vdots & \vdots & \ddots & \vdots & \vdots & \vdots & \ddots + & \vdots & \vdots & \vdots & \vdots & \ddots & \vdots \cr + 0 & 0 & \dots & 0 & 0 & 0 & \dots & 0 & \dots & 1 & 1 & \dots & + 1 \cr \hline + + 1 & 0 & \dots & 0 & 1 & 0 & \dots & \dots & \dots & 1 & 0 & \dots & + 0 \cr + 0 & 1 & \dots & 0 & 0 & 1 & \dots & \dots & \dots & 0 & 1 & \dots & + 0 \cr + \vdots & \vdots & \ddots & \vdots & \vdots & \vdots & \ddots & + \vdots & \vdots & \vdots & \vdots & \ddots & \vdots \cr + 0 & 0 & \dots & 1 & 0 & 0 & \dots & 1 & \dots & 0 & 0 & \dots & 1 + \end{array} + + By solving the dual form of the above linear programming problem (with + solution :math:`y^*`), the Wasserstein distance :math:`l_1 (u, v)` can + be computed as :math:`b^T y^*`. + + The above solution is inspired by Vincent Herrmann's blog [3]_ . For a + more thorough explanation, see [4]_ . + + The input distributions can be empirical, therefore coming from samples + whose values are effectively inputs of the function, or they can be seen as + generalized functions, in which case they are weighted sums of Dirac delta + functions located at the specified values. + + References + ---------- + .. [1] "Wasserstein metric", + https://en.wikipedia.org/wiki/Wasserstein_metric + .. [2] Lili Weng, "What is Wasserstein distance?", Lil'log, + https://lilianweng.github.io/posts/2017-08-20-gan/#what-is-wasserstein-distance. + .. [3] Hermann, Vincent. "Wasserstein GAN and the Kantorovich-Rubinstein + Duality". https://vincentherrmann.github.io/blog/wasserstein/. + .. [4] Peyré, Gabriel, and Marco Cuturi. "Computational optimal + transport." Center for Research in Economics and Statistics + Working Papers 2017-86 (2017). + + See Also + -------- + wasserstein_distance: Compute the Wasserstein-1 distance between two + 1D discrete distributions. + + Examples + -------- + Compute the Wasserstein distance between two three-dimensional samples, + each with two observations. + + >>> from scipy.stats import wasserstein_distance_nd + >>> wasserstein_distance_nd([[0, 2, 3], [1, 2, 5]], [[3, 2, 3], [4, 2, 5]]) + 3.0 + + Compute the Wasserstein distance between two two-dimensional distributions + with three and two weighted observations, respectively. + + >>> wasserstein_distance_nd([[0, 2.75], [2, 209.3], [0, 0]], + ... [[0.2, 0.322], [4.5, 25.1808]], + ... [0.4, 5.2, 0.114], [0.8, 1.5]) + 174.15840245217169 + """ + m, n = len(u_values), len(v_values) + u_values = asarray(u_values) + v_values = asarray(v_values) + + if u_values.ndim > 2 or v_values.ndim > 2: + raise ValueError('Invalid input values. The inputs must have either ' + 'one or two dimensions.') + # if dimensions are not equal throw error + if u_values.ndim != v_values.ndim: + raise ValueError('Invalid input values. Dimensions of inputs must be ' + 'equal.') + # if data is 1D then call the cdf_distance function + if u_values.ndim == 1 and v_values.ndim == 1: + return _cdf_distance(1, u_values, v_values, u_weights, v_weights) + + u_values, u_weights = _validate_distribution(u_values, u_weights) + v_values, v_weights = _validate_distribution(v_values, v_weights) + # if number of columns is not equal throw error + if u_values.shape[1] != v_values.shape[1]: + raise ValueError('Invalid input values. If two-dimensional, ' + '`u_values` and `v_values` must have the same ' + 'number of columns.') + + # if data contains np.inf then return inf or nan + if np.any(np.isinf(u_values)) ^ np.any(np.isinf(v_values)): + return np.inf + elif np.any(np.isinf(u_values)) and np.any(np.isinf(v_values)): + return np.nan + + # create constraints + A_upper_part = sparse.block_diag((np.ones((1, n)), ) * m) + A_lower_part = sparse.hstack((sparse.eye(n), ) * m) + # sparse constraint matrix of size (m + n)*(m * n) + A = sparse.vstack((A_upper_part, A_lower_part)) + A = sparse.coo_array(A) + + # get cost matrix + D = distance_matrix(u_values, v_values, p=2) + cost = D.ravel() + + # create the minimization target + p_u = np.full(m, 1/m) if u_weights is None else u_weights/np.sum(u_weights) + p_v = np.full(n, 1/n) if v_weights is None else v_weights/np.sum(v_weights) + b = np.concatenate((p_u, p_v), axis=0) + + # solving LP + constraints = LinearConstraint(A=A.T, ub=cost) + opt_res = milp(c=-b, constraints=constraints, bounds=(-np.inf, np.inf)) + return -opt_res.fun + + +def wasserstein_distance(u_values, v_values, u_weights=None, v_weights=None): + r""" + Compute the Wasserstein-1 distance between two 1D discrete distributions. + + The Wasserstein distance, also called the Earth mover's distance or the + optimal transport distance, is a similarity metric between two probability + distributions [1]_. In the discrete case, the Wasserstein distance can be + understood as the cost of an optimal transport plan to convert one + distribution into the other. The cost is calculated as the product of the + amount of probability mass being moved and the distance it is being moved. + A brief and intuitive introduction can be found at [2]_. + + .. versionadded:: 1.0.0 + + Parameters + ---------- + u_values : 1d array_like + A sample from a probability distribution or the support (set of all + possible values) of a probability distribution. Each element is an + observation or possible value. + + v_values : 1d array_like + A sample from or the support of a second distribution. + + u_weights, v_weights : 1d array_like, optional + Weights or counts corresponding with the sample or probability masses + corresponding with the support values. Sum of elements must be positive + and finite. If unspecified, each value is assigned the same weight. + + Returns + ------- + distance : float + The computed distance between the distributions. + + Notes + ----- + Given two 1D probability mass functions, :math:`u` and :math:`v`, the first + Wasserstein distance between the distributions is: + + .. math:: + + l_1 (u, v) = \inf_{\pi \in \Gamma (u, v)} \int_{\mathbb{R} \times + \mathbb{R}} |x-y| \mathrm{d} \pi (x, y) + + where :math:`\Gamma (u, v)` is the set of (probability) distributions on + :math:`\mathbb{R} \times \mathbb{R}` whose marginals are :math:`u` and + :math:`v` on the first and second factors respectively. For a given value + :math:`x`, :math:`u(x)` gives the probability of :math:`u` at position + :math:`x`, and the same for :math:`v(x)`. + + If :math:`U` and :math:`V` are the respective CDFs of :math:`u` and + :math:`v`, this distance also equals to: + + .. math:: + + l_1(u, v) = \int_{-\infty}^{+\infty} |U-V| + + See [3]_ for a proof of the equivalence of both definitions. + + The input distributions can be empirical, therefore coming from samples + whose values are effectively inputs of the function, or they can be seen as + generalized functions, in which case they are weighted sums of Dirac delta + functions located at the specified values. + + References + ---------- + .. [1] "Wasserstein metric", https://en.wikipedia.org/wiki/Wasserstein_metric + .. [2] Lili Weng, "What is Wasserstein distance?", Lil'log, + https://lilianweng.github.io/posts/2017-08-20-gan/#what-is-wasserstein-distance. + .. [3] Ramdas, Garcia, Cuturi "On Wasserstein Two Sample Testing and Related + Families of Nonparametric Tests" (2015). :arXiv:`1509.02237`. + + See Also + -------- + wasserstein_distance_nd: Compute the Wasserstein-1 distance between two N-D + discrete distributions. + + Examples + -------- + >>> from scipy.stats import wasserstein_distance + >>> wasserstein_distance([0, 1, 3], [5, 6, 8]) + 5.0 + >>> wasserstein_distance([0, 1], [0, 1], [3, 1], [2, 2]) + 0.25 + >>> wasserstein_distance([3.4, 3.9, 7.5, 7.8], [4.5, 1.4], + ... [1.4, 0.9, 3.1, 7.2], [3.2, 3.5]) + 4.0781331438047861 + + """ + return _cdf_distance(1, u_values, v_values, u_weights, v_weights) + + +def energy_distance(u_values, v_values, u_weights=None, v_weights=None): + r"""Compute the energy distance between two 1D distributions. + + .. versionadded:: 1.0.0 + + Parameters + ---------- + u_values, v_values : array_like + Values observed in the (empirical) distribution. + u_weights, v_weights : array_like, optional + Weight for each value. If unspecified, each value is assigned the same + weight. + `u_weights` (resp. `v_weights`) must have the same length as + `u_values` (resp. `v_values`). If the weight sum differs from 1, it + must still be positive and finite so that the weights can be normalized + to sum to 1. + + Returns + ------- + distance : float + The computed distance between the distributions. + + Notes + ----- + The energy distance between two distributions :math:`u` and :math:`v`, whose + respective CDFs are :math:`U` and :math:`V`, equals to: + + .. math:: + + D(u, v) = \left( 2\mathbb E|X - Y| - \mathbb E|X - X'| - + \mathbb E|Y - Y'| \right)^{1/2} + + where :math:`X` and :math:`X'` (resp. :math:`Y` and :math:`Y'`) are + independent random variables whose probability distribution is :math:`u` + (resp. :math:`v`). + + Sometimes the square of this quantity is referred to as the "energy + distance" (e.g. in [2]_, [4]_), but as noted in [1]_ and [3]_, only the + definition above satisfies the axioms of a distance function (metric). + + As shown in [2]_, for one-dimensional real-valued variables, the energy + distance is linked to the non-distribution-free version of the Cramér-von + Mises distance: + + .. math:: + + D(u, v) = \sqrt{2} l_2(u, v) = \left( 2 \int_{-\infty}^{+\infty} (U-V)^2 + \right)^{1/2} + + Note that the common Cramér-von Mises criterion uses the distribution-free + version of the distance. See [2]_ (section 2), for more details about both + versions of the distance. + + The input distributions can be empirical, therefore coming from samples + whose values are effectively inputs of the function, or they can be seen as + generalized functions, in which case they are weighted sums of Dirac delta + functions located at the specified values. + + References + ---------- + .. [1] Rizzo, Szekely "Energy distance." Wiley Interdisciplinary Reviews: + Computational Statistics, 8(1):27-38 (2015). + .. [2] Szekely "E-statistics: The energy of statistical samples." Bowling + Green State University, Department of Mathematics and Statistics, + Technical Report 02-16 (2002). + .. [3] "Energy distance", https://en.wikipedia.org/wiki/Energy_distance + .. [4] Bellemare, Danihelka, Dabney, Mohamed, Lakshminarayanan, Hoyer, + Munos "The Cramer Distance as a Solution to Biased Wasserstein + Gradients" (2017). :arXiv:`1705.10743`. + + Examples + -------- + >>> from scipy.stats import energy_distance + >>> energy_distance([0], [2]) + 2.0000000000000004 + >>> energy_distance([0, 8], [0, 8], [3, 1], [2, 2]) + 1.0000000000000002 + >>> energy_distance([0.7, 7.4, 2.4, 6.8], [1.4, 8. ], + ... [2.1, 4.2, 7.4, 8. ], [7.6, 8.8]) + 0.88003340976158217 + + """ + return np.sqrt(2) * _cdf_distance(2, u_values, v_values, + u_weights, v_weights) + + +def _cdf_distance(p, u_values, v_values, u_weights=None, v_weights=None): + r""" + Compute, between two one-dimensional distributions :math:`u` and + :math:`v`, whose respective CDFs are :math:`U` and :math:`V`, the + statistical distance that is defined as: + + .. math:: + + l_p(u, v) = \left( \int_{-\infty}^{+\infty} |U-V|^p \right)^{1/p} + + p is a positive parameter; p = 1 gives the Wasserstein distance, p = 2 + gives the energy distance. + + Parameters + ---------- + u_values, v_values : array_like + Values observed in the (empirical) distribution. + u_weights, v_weights : array_like, optional + Weight for each value. If unspecified, each value is assigned the same + weight. + `u_weights` (resp. `v_weights`) must have the same length as + `u_values` (resp. `v_values`). If the weight sum differs from 1, it + must still be positive and finite so that the weights can be normalized + to sum to 1. + + Returns + ------- + distance : float + The computed distance between the distributions. + + Notes + ----- + The input distributions can be empirical, therefore coming from samples + whose values are effectively inputs of the function, or they can be seen as + generalized functions, in which case they are weighted sums of Dirac delta + functions located at the specified values. + + References + ---------- + .. [1] Bellemare, Danihelka, Dabney, Mohamed, Lakshminarayanan, Hoyer, + Munos "The Cramer Distance as a Solution to Biased Wasserstein + Gradients" (2017). :arXiv:`1705.10743`. + + """ + u_values, u_weights = _validate_distribution(u_values, u_weights) + v_values, v_weights = _validate_distribution(v_values, v_weights) + + u_sorter = np.argsort(u_values) + v_sorter = np.argsort(v_values) + + all_values = np.concatenate((u_values, v_values)) + all_values.sort(kind='mergesort') + + # Compute the differences between pairs of successive values of u and v. + deltas = np.diff(all_values) + + # Get the respective positions of the values of u and v among the values of + # both distributions. + u_cdf_indices = u_values[u_sorter].searchsorted(all_values[:-1], 'right') + v_cdf_indices = v_values[v_sorter].searchsorted(all_values[:-1], 'right') + + # Calculate the CDFs of u and v using their weights, if specified. + if u_weights is None: + u_cdf = u_cdf_indices / u_values.size + else: + u_sorted_cumweights = np.concatenate(([0], + np.cumsum(u_weights[u_sorter]))) + u_cdf = u_sorted_cumweights[u_cdf_indices] / u_sorted_cumweights[-1] + + if v_weights is None: + v_cdf = v_cdf_indices / v_values.size + else: + v_sorted_cumweights = np.concatenate(([0], + np.cumsum(v_weights[v_sorter]))) + v_cdf = v_sorted_cumweights[v_cdf_indices] / v_sorted_cumweights[-1] + + # Compute the value of the integral based on the CDFs. + # If p = 1 or p = 2, we avoid using np.power, which introduces an overhead + # of about 15%. + if p == 1: + return np.sum(np.multiply(np.abs(u_cdf - v_cdf), deltas)) + if p == 2: + return np.sqrt(np.sum(np.multiply(np.square(u_cdf - v_cdf), deltas))) + return np.power(np.sum(np.multiply(np.power(np.abs(u_cdf - v_cdf), p), + deltas)), 1/p) + + +def _validate_distribution(values, weights): + """ + Validate the values and weights from a distribution input of `cdf_distance` + and return them as ndarray objects. + + Parameters + ---------- + values : array_like + Values observed in the (empirical) distribution. + weights : array_like + Weight for each value. + + Returns + ------- + values : ndarray + Values as ndarray. + weights : ndarray + Weights as ndarray. + + """ + # Validate the value array. + values = np.asarray(values, dtype=float) + if len(values) == 0: + raise ValueError("Distribution can't be empty.") + + # Validate the weight array, if specified. + if weights is not None: + weights = np.asarray(weights, dtype=float) + if len(weights) != len(values): + raise ValueError('Value and weight array-likes for the same ' + 'empirical distribution must be of the same size.') + if np.any(weights < 0): + raise ValueError('All weights must be non-negative.') + if not 0 < np.sum(weights) < np.inf: + raise ValueError('Weight array-like sum must be positive and ' + 'finite. Set as None for an equal distribution of ' + 'weight.') + + return values, weights + + return values, None + + +##################################### +# SUPPORT FUNCTIONS # +##################################### + +RepeatedResults = namedtuple('RepeatedResults', ('values', 'counts')) + + +@_deprecated("`scipy.stats.find_repeats` is deprecated as of SciPy 1.15.0 " + "and will be removed in SciPy 1.17.0. Please use " + "`numpy.unique`/`numpy.unique_counts` instead.") +def find_repeats(arr): + """Find repeats and repeat counts. + + .. deprecated:: 1.15.0 + + This function is deprecated as of SciPy 1.15.0 and will be removed + in SciPy 1.17.0. Please use `numpy.unique` / `numpy.unique_counts` instead. + + Parameters + ---------- + arr : array_like + Input array. This is cast to float64. + + Returns + ------- + values : ndarray + The unique values from the (flattened) input that are repeated. + + counts : ndarray + Number of times the corresponding 'value' is repeated. + + Notes + ----- + In numpy >= 1.9 `numpy.unique` provides similar functionality. The main + difference is that `find_repeats` only returns repeated values. + + Examples + -------- + >>> from scipy import stats + >>> stats.find_repeats([2, 1, 2, 3, 2, 2, 5]) + RepeatedResults(values=array([2.]), counts=array([4])) + + >>> stats.find_repeats([[10, 20, 1, 2], [5, 5, 4, 4]]) + RepeatedResults(values=array([4., 5.]), counts=array([2, 2])) + + """ + # Note: always copies. + return RepeatedResults(*_find_repeats(np.array(arr, dtype=np.float64))) + + +def _sum_of_squares(a, axis=0): + """Square each element of the input array, and return the sum(s) of that. + + Parameters + ---------- + a : array_like + Input array. + axis : int or None, optional + Axis along which to calculate. Default is 0. If None, compute over + the whole array `a`. + + Returns + ------- + sum_of_squares : ndarray + The sum along the given axis for (a**2). + + See Also + -------- + _square_of_sums : The square(s) of the sum(s) (the opposite of + `_sum_of_squares`). + + """ + a, axis = _chk_asarray(a, axis) + return np.sum(a*a, axis) + + +def _square_of_sums(a, axis=0): + """Sum elements of the input array, and return the square(s) of that sum. + + Parameters + ---------- + a : array_like + Input array. + axis : int or None, optional + Axis along which to calculate. Default is 0. If None, compute over + the whole array `a`. + + Returns + ------- + square_of_sums : float or ndarray + The square of the sum over `axis`. + + See Also + -------- + _sum_of_squares : The sum of squares (the opposite of `square_of_sums`). + + """ + a, axis = _chk_asarray(a, axis) + s = np.sum(a, axis) + if not np.isscalar(s): + return s.astype(float) * s + else: + return float(s) * s + + +def rankdata(a, method='average', *, axis=None, nan_policy='propagate'): + """Assign ranks to data, dealing with ties appropriately. + + By default (``axis=None``), the data array is first flattened, and a flat + array of ranks is returned. Separately reshape the rank array to the + shape of the data array if desired (see Examples). + + Ranks begin at 1. The `method` argument controls how ranks are assigned + to equal values. See [1]_ for further discussion of ranking methods. + + Parameters + ---------- + a : array_like + The array of values to be ranked. + method : {'average', 'min', 'max', 'dense', 'ordinal'}, optional + The method used to assign ranks to tied elements. + The following methods are available (default is 'average'): + + * 'average': The average of the ranks that would have been assigned to + all the tied values is assigned to each value. + * 'min': The minimum of the ranks that would have been assigned to all + the tied values is assigned to each value. (This is also + referred to as "competition" ranking.) + * 'max': The maximum of the ranks that would have been assigned to all + the tied values is assigned to each value. + * 'dense': Like 'min', but the rank of the next highest element is + assigned the rank immediately after those assigned to the tied + elements. + * 'ordinal': All values are given a distinct rank, corresponding to + the order that the values occur in `a`. + axis : {None, int}, optional + Axis along which to perform the ranking. If ``None``, the data array + is first flattened. + nan_policy : {'propagate', 'omit', 'raise'}, optional + Defines how to handle when input contains nan. + The following options are available (default is 'propagate'): + + * 'propagate': propagates nans through the rank calculation + * 'omit': performs the calculations ignoring nan values + * 'raise': raises an error + + .. note:: + + When `nan_policy` is 'propagate', the output is an array of *all* + nans because ranks relative to nans in the input are undefined. + When `nan_policy` is 'omit', nans in `a` are ignored when ranking + the other values, and the corresponding locations of the output + are nan. + + .. versionadded:: 1.10 + + Returns + ------- + ranks : ndarray + An array of size equal to the size of `a`, containing rank + scores. + + References + ---------- + .. [1] "Ranking", https://en.wikipedia.org/wiki/Ranking + + Examples + -------- + >>> import numpy as np + >>> from scipy.stats import rankdata + >>> rankdata([0, 2, 3, 2]) + array([ 1. , 2.5, 4. , 2.5]) + >>> rankdata([0, 2, 3, 2], method='min') + array([ 1, 2, 4, 2]) + >>> rankdata([0, 2, 3, 2], method='max') + array([ 1, 3, 4, 3]) + >>> rankdata([0, 2, 3, 2], method='dense') + array([ 1, 2, 3, 2]) + >>> rankdata([0, 2, 3, 2], method='ordinal') + array([ 1, 2, 4, 3]) + >>> rankdata([[0, 2], [3, 2]]).reshape(2,2) + array([[1. , 2.5], + [4. , 2.5]]) + >>> rankdata([[0, 2, 2], [3, 2, 5]], axis=1) + array([[1. , 2.5, 2.5], + [2. , 1. , 3. ]]) + >>> rankdata([0, 2, 3, np.nan, -2, np.nan], nan_policy="propagate") + array([nan, nan, nan, nan, nan, nan]) + >>> rankdata([0, 2, 3, np.nan, -2, np.nan], nan_policy="omit") + array([ 2., 3., 4., nan, 1., nan]) + + """ + methods = ('average', 'min', 'max', 'dense', 'ordinal') + if method not in methods: + raise ValueError(f'unknown method "{method}"') + + x = np.asarray(a) + + if axis is None: + x = x.ravel() + axis = -1 + + if x.size == 0: + dtype = float if method == 'average' else np.dtype("long") + return np.empty(x.shape, dtype=dtype) + + contains_nan, nan_policy = _contains_nan(x, nan_policy) + + x = np.swapaxes(x, axis, -1) + ranks = _rankdata(x, method) + + if contains_nan: + i_nan = (np.isnan(x) if nan_policy == 'omit' + else np.isnan(x).any(axis=-1)) + ranks = ranks.astype(float, copy=False) + ranks[i_nan] = np.nan + + ranks = np.swapaxes(ranks, axis, -1) + return ranks + + +def _order_ranks(ranks, j): + # Reorder ascending order `ranks` according to `j` + ordered_ranks = np.empty(j.shape, dtype=ranks.dtype) + np.put_along_axis(ordered_ranks, j, ranks, axis=-1) + return ordered_ranks + + +def _rankdata(x, method, return_ties=False): + # Rank data `x` by desired `method`; `return_ties` if desired + shape = x.shape + + # Get sort order + kind = 'mergesort' if method == 'ordinal' else 'quicksort' + j = np.argsort(x, axis=-1, kind=kind) + ordinal_ranks = np.broadcast_to(np.arange(1, shape[-1]+1, dtype=int), shape) + + # Ordinal ranks is very easy because ties don't matter. We're done. + if method == 'ordinal': + return _order_ranks(ordinal_ranks, j) # never return ties + + # Sort array + y = np.take_along_axis(x, j, axis=-1) + # Logical indices of unique elements + i = np.concatenate([np.ones(shape[:-1] + (1,), dtype=np.bool_), + y[..., :-1] != y[..., 1:]], axis=-1) + + # Integer indices of unique elements + indices = np.arange(y.size)[i.ravel()] + # Counts of unique elements + counts = np.diff(indices, append=y.size) + + # Compute `'min'`, `'max'`, and `'mid'` ranks of unique elements + if method == 'min': + ranks = ordinal_ranks[i] + elif method == 'max': + ranks = ordinal_ranks[i] + counts - 1 + elif method == 'average': + ranks = ordinal_ranks[i] + (counts - 1)/2 + elif method == 'dense': + ranks = np.cumsum(i, axis=-1)[i] + + ranks = np.repeat(ranks, counts).reshape(shape) + ranks = _order_ranks(ranks, j) + + if return_ties: + # Tie information is returned in a format that is useful to functions that + # rely on this (private) function. Example: + # >>> x = np.asarray([3, 2, 1, 2, 2, 2, 1]) + # >>> _, t = _rankdata(x, 'average', return_ties=True) + # >>> t # array([2., 0., 4., 0., 0., 0., 1.]) # two 1s, four 2s, and one 3 + # Unlike ranks, tie counts are *not* reordered to correspond with the order of + # the input; e.g. the number of appearances of the lowest rank element comes + # first. This is a useful format because: + # - The shape of the result is the shape of the input. Different slices can + # have different numbers of tied elements but not result in a ragged array. + # - Functions that use `t` usually don't need to which each element of the + # original array is associated with each tie count; they perform a reduction + # over the tie counts onnly. The tie counts are naturally computed in a + # sorted order, so this does not unnecessarily reorder them. + # - One exception is `wilcoxon`, which needs the number of zeros. Zeros always + # have the lowest rank, so it is easy to find them at the zeroth index. + t = np.zeros(shape, dtype=float) + t[i] = counts + return ranks, t + return ranks + + +def expectile(a, alpha=0.5, *, weights=None): + r"""Compute the expectile at the specified level. + + Expectiles are a generalization of the expectation in the same way as + quantiles are a generalization of the median. The expectile at level + `alpha = 0.5` is the mean (average). See Notes for more details. + + Parameters + ---------- + a : array_like + Array containing numbers whose expectile is desired. + alpha : float, default: 0.5 + The level of the expectile; e.g., ``alpha=0.5`` gives the mean. + weights : array_like, optional + An array of weights associated with the values in `a`. + The `weights` must be broadcastable to the same shape as `a`. + Default is None, which gives each value a weight of 1.0. + An integer valued weight element acts like repeating the corresponding + observation in `a` that many times. See Notes for more details. + + Returns + ------- + expectile : ndarray + The empirical expectile at level `alpha`. + + See Also + -------- + numpy.mean : Arithmetic average + numpy.quantile : Quantile + + Notes + ----- + In general, the expectile at level :math:`\alpha` of a random variable + :math:`X` with cumulative distribution function (CDF) :math:`F` is given + by the unique solution :math:`t` of: + + .. math:: + + \alpha E((X - t)_+) = (1 - \alpha) E((t - X)_+) \,. + + Here, :math:`(x)_+ = \max(0, x)` is the positive part of :math:`x`. + This equation can be equivalently written as: + + .. math:: + + \alpha \int_t^\infty (x - t)\mathrm{d}F(x) + = (1 - \alpha) \int_{-\infty}^t (t - x)\mathrm{d}F(x) \,. + + The empirical expectile at level :math:`\alpha` (`alpha`) of a sample + :math:`a_i` (the array `a`) is defined by plugging in the empirical CDF of + `a`. Given sample or case weights :math:`w` (the array `weights`), it + reads :math:`F_a(x) = \frac{1}{\sum_i w_i} \sum_i w_i 1_{a_i \leq x}` + with indicator function :math:`1_{A}`. This leads to the definition of the + empirical expectile at level `alpha` as the unique solution :math:`t` of: + + .. math:: + + \alpha \sum_{i=1}^n w_i (a_i - t)_+ = + (1 - \alpha) \sum_{i=1}^n w_i (t - a_i)_+ \,. + + For :math:`\alpha=0.5`, this simplifies to the weighted average. + Furthermore, the larger :math:`\alpha`, the larger the value of the + expectile. + + As a final remark, the expectile at level :math:`\alpha` can also be + written as a minimization problem. One often used choice is + + .. math:: + + \operatorname{argmin}_t + E(\lvert 1_{t\geq X} - \alpha\rvert(t - X)^2) \,. + + References + ---------- + .. [1] W. K. Newey and J. L. Powell (1987), "Asymmetric Least Squares + Estimation and Testing," Econometrica, 55, 819-847. + .. [2] T. Gneiting (2009). "Making and Evaluating Point Forecasts," + Journal of the American Statistical Association, 106, 746 - 762. + :doi:`10.48550/arXiv.0912.0902` + + Examples + -------- + >>> import numpy as np + >>> from scipy.stats import expectile + >>> a = [1, 4, 2, -1] + >>> expectile(a, alpha=0.5) == np.mean(a) + True + >>> expectile(a, alpha=0.2) + 0.42857142857142855 + >>> expectile(a, alpha=0.8) + 2.5714285714285716 + >>> weights = [1, 3, 1, 1] + + """ + if alpha < 0 or alpha > 1: + raise ValueError( + "The expectile level alpha must be in the range [0, 1]." + ) + a = np.asarray(a) + + if weights is not None: + weights = np.broadcast_to(weights, a.shape) + + # This is the empirical equivalent of Eq. (13) with identification + # function from Table 9 (omitting a factor of 2) in [2] (their y is our + # data a, their x is our t) + def first_order(t): + return np.average(np.abs((a <= t) - alpha) * (t - a), weights=weights) + + if alpha >= 0.5: + x0 = np.average(a, weights=weights) + x1 = np.amax(a) + else: + x1 = np.average(a, weights=weights) + x0 = np.amin(a) + + if x0 == x1: + # a has a single unique element + return x0 + + # Note that the expectile is the unique solution, so no worries about + # finding a wrong root. + res = root_scalar(first_order, x0=x0, x1=x1) + return res.root + + +def _lmoment_iv(sample, order, axis, sorted, standardize): + # input validation/standardization for `lmoment` + sample = np.asarray(sample) + message = "`sample` must be an array of real numbers." + if np.issubdtype(sample.dtype, np.integer): + sample = sample.astype(np.float64) + if not np.issubdtype(sample.dtype, np.floating): + raise ValueError(message) + + message = "`order` must be a scalar or a non-empty array of positive integers." + order = np.arange(1, 5) if order is None else np.asarray(order) + if not np.issubdtype(order.dtype, np.integer) or np.any(order <= 0): + raise ValueError(message) + + axis = np.asarray(axis)[()] + message = "`axis` must be an integer." + if not np.issubdtype(axis.dtype, np.integer) or axis.ndim != 0: + raise ValueError(message) + + sorted = np.asarray(sorted)[()] + message = "`sorted` must be True or False." + if not np.issubdtype(sorted.dtype, np.bool_) or sorted.ndim != 0: + raise ValueError(message) + + standardize = np.asarray(standardize)[()] + message = "`standardize` must be True or False." + if not np.issubdtype(standardize.dtype, np.bool_) or standardize.ndim != 0: + raise ValueError(message) + + sample = np.moveaxis(sample, axis, -1) + sample = np.sort(sample, axis=-1) if not sorted else sample + + return sample, order, axis, sorted, standardize + + +def _br(x, *, r=0): + n = x.shape[-1] + x = np.expand_dims(x, axis=-2) + x = np.broadcast_to(x, x.shape[:-2] + (len(r), n)) + x = np.triu(x) + j = np.arange(n, dtype=x.dtype) + n = np.asarray(n, dtype=x.dtype)[()] + return (np.sum(special.binom(j, r[:, np.newaxis])*x, axis=-1) + / special.binom(n-1, r) / n) + + +def _prk(r, k): + # Writen to match [1] Equation 27 closely to facilitate review. + # This does not protect against overflow, so improvements to + # robustness would be a welcome follow-up. + return (-1)**(r-k)*special.binom(r, k)*special.binom(r+k, k) + + +@_axis_nan_policy_factory( # noqa: E302 + _moment_result_object, n_samples=1, result_to_tuple=_moment_tuple, + n_outputs=lambda kwds: _moment_outputs(kwds, [1, 2, 3, 4]) +) +def lmoment(sample, order=None, *, axis=0, sorted=False, standardize=True): + r"""Compute L-moments of a sample from a continuous distribution + + The L-moments of a probability distribution are summary statistics with + uses similar to those of conventional moments, but they are defined in + terms of the expected values of order statistics. + Sample L-moments are defined analogously to population L-moments, and + they can serve as estimators of population L-moments. They tend to be less + sensitive to extreme observations than conventional moments. + + Parameters + ---------- + sample : array_like + The real-valued sample whose L-moments are desired. + order : array_like, optional + The (positive integer) orders of the desired L-moments. + Must be a scalar or non-empty 1D array. Default is [1, 2, 3, 4]. + axis : int or None, default=0 + If an int, the axis of the input along which to compute the statistic. + The statistic of each axis-slice (e.g. row) of the input will appear + in a corresponding element of the output. If None, the input will be + raveled before computing the statistic. + sorted : bool, default=False + Whether `sample` is already sorted in increasing order along `axis`. + If False (default), `sample` will be sorted. + standardize : bool, default=True + Whether to return L-moment ratios for orders 3 and higher. + L-moment ratios are analogous to standardized conventional + moments: they are the non-standardized L-moments divided + by the L-moment of order 2. + + Returns + ------- + lmoments : ndarray + The sample L-moments of order `order`. + + See Also + -------- + moment + + References + ---------- + .. [1] D. Bilkova. "L-Moments and TL-Moments as an Alternative Tool of + Statistical Data Analysis". Journal of Applied Mathematics and + Physics. 2014. :doi:`10.4236/jamp.2014.210104` + .. [2] J. R. M. Hosking. "L-Moments: Analysis and Estimation of Distributions + Using Linear Combinations of Order Statistics". Journal of the Royal + Statistical Society. 1990. :doi:`10.1111/j.2517-6161.1990.tb01775.x` + .. [3] "L-moment". *Wikipedia*. https://en.wikipedia.org/wiki/L-moment. + + Examples + -------- + >>> import numpy as np + >>> from scipy import stats + >>> rng = np.random.default_rng(328458568356392) + >>> sample = rng.exponential(size=100000) + >>> stats.lmoment(sample) + array([1.00124272, 0.50111437, 0.3340092 , 0.16755338]) + + Note that the first four standardized population L-moments of the standard + exponential distribution are 1, 1/2, 1/3, and 1/6; the sample L-moments + provide reasonable estimates. + + """ + args = _lmoment_iv(sample, order, axis, sorted, standardize) + sample, order, axis, sorted, standardize = args + + n_moments = np.max(order) + k = np.arange(n_moments, dtype=sample.dtype) + prk = _prk(np.expand_dims(k, tuple(range(1, sample.ndim+1))), k) + bk = _br(sample, r=k) + + n = sample.shape[-1] + bk[..., n:] = 0 # remove NaNs due to n_moments > n + + lmoms = np.sum(prk * bk, axis=-1) + if standardize and n_moments > 2: + lmoms[2:] /= lmoms[1] + + lmoms[n:] = np.nan # add NaNs where appropriate + return lmoms[order-1] + + +LinregressResult = _make_tuple_bunch('LinregressResult', + ['slope', 'intercept', 'rvalue', + 'pvalue', 'stderr'], + extra_field_names=['intercept_stderr']) + + +def linregress(x, y=None, alternative='two-sided'): + """ + Calculate a linear least-squares regression for two sets of measurements. + + Parameters + ---------- + x, y : array_like + Two sets of measurements. Both arrays should have the same length N. If + only `x` is given (and ``y=None``), then it must be a two-dimensional + array where one dimension has length 2. The two sets of measurements + are then found by splitting the array along the length-2 dimension. In + the case where ``y=None`` and `x` is a 2xN array, ``linregress(x)`` is + equivalent to ``linregress(x[0], x[1])``. + + .. deprecated:: 1.14.0 + Inference of the two sets of measurements from a single argument `x` + is deprecated will result in an error in SciPy 1.16.0; the sets + must be specified separately as `x` and `y`. + alternative : {'two-sided', 'less', 'greater'}, optional + Defines the alternative hypothesis. Default is 'two-sided'. + The following options are available: + + * 'two-sided': the slope of the regression line is nonzero + * 'less': the slope of the regression line is less than zero + * 'greater': the slope of the regression line is greater than zero + + .. versionadded:: 1.7.0 + + Returns + ------- + result : ``LinregressResult`` instance + The return value is an object with the following attributes: + + slope : float + Slope of the regression line. + intercept : float + Intercept of the regression line. + rvalue : float + The Pearson correlation coefficient. The square of ``rvalue`` + is equal to the coefficient of determination. + pvalue : float + The p-value for a hypothesis test whose null hypothesis is + that the slope is zero, using Wald Test with t-distribution of + the test statistic. See `alternative` above for alternative + hypotheses. + stderr : float + Standard error of the estimated slope (gradient), under the + assumption of residual normality. + intercept_stderr : float + Standard error of the estimated intercept, under the assumption + of residual normality. + + See Also + -------- + scipy.optimize.curve_fit : + Use non-linear least squares to fit a function to data. + scipy.optimize.leastsq : + Minimize the sum of squares of a set of equations. + + Notes + ----- + For compatibility with older versions of SciPy, the return value acts + like a ``namedtuple`` of length 5, with fields ``slope``, ``intercept``, + ``rvalue``, ``pvalue`` and ``stderr``, so one can continue to write:: + + slope, intercept, r, p, se = linregress(x, y) + + With that style, however, the standard error of the intercept is not + available. To have access to all the computed values, including the + standard error of the intercept, use the return value as an object + with attributes, e.g.:: + + result = linregress(x, y) + print(result.intercept, result.intercept_stderr) + + Examples + -------- + >>> import numpy as np + >>> import matplotlib.pyplot as plt + >>> from scipy import stats + >>> rng = np.random.default_rng() + + Generate some data: + + >>> x = rng.random(10) + >>> y = 1.6*x + rng.random(10) + + Perform the linear regression: + + >>> res = stats.linregress(x, y) + + Coefficient of determination (R-squared): + + >>> print(f"R-squared: {res.rvalue**2:.6f}") + R-squared: 0.717533 + + Plot the data along with the fitted line: + + >>> plt.plot(x, y, 'o', label='original data') + >>> plt.plot(x, res.intercept + res.slope*x, 'r', label='fitted line') + >>> plt.legend() + >>> plt.show() + + Calculate 95% confidence interval on slope and intercept: + + >>> # Two-sided inverse Students t-distribution + >>> # p - probability, df - degrees of freedom + >>> from scipy.stats import t + >>> tinv = lambda p, df: abs(t.ppf(p/2, df)) + + >>> ts = tinv(0.05, len(x)-2) + >>> print(f"slope (95%): {res.slope:.6f} +/- {ts*res.stderr:.6f}") + slope (95%): 1.453392 +/- 0.743465 + >>> print(f"intercept (95%): {res.intercept:.6f}" + ... f" +/- {ts*res.intercept_stderr:.6f}") + intercept (95%): 0.616950 +/- 0.544475 + + """ + TINY = 1.0e-20 + if y is None: # x is a (2, N) or (N, 2) shaped array_like + message = ('Inference of the two sets of measurements from a single "' + 'argument `x` is deprecated will result in an error in "' + 'SciPy 1.16.0; the sets must be specified separately as "' + '`x` and `y`.') + warnings.warn(message, DeprecationWarning, stacklevel=2) + x = np.asarray(x) + if x.shape[0] == 2: + x, y = x + elif x.shape[1] == 2: + x, y = x.T + else: + raise ValueError("If only `x` is given as input, it has to " + "be of shape (2, N) or (N, 2); provided shape " + f"was {x.shape}.") + else: + x = np.asarray(x) + y = np.asarray(y) + + if x.size == 0 or y.size == 0: + raise ValueError("Inputs must not be empty.") + + if np.amax(x) == np.amin(x) and len(x) > 1: + raise ValueError("Cannot calculate a linear regression " + "if all x values are identical") + + n = len(x) + xmean = np.mean(x, None) + ymean = np.mean(y, None) + + # Average sums of square differences from the mean + # ssxm = mean( (x-mean(x))^2 ) + # ssxym = mean( (x-mean(x)) * (y-mean(y)) ) + ssxm, ssxym, _, ssym = np.cov(x, y, bias=1).flat + + # R-value + # r = ssxym / sqrt( ssxm * ssym ) + if ssxm == 0.0 or ssym == 0.0: + # If the denominator was going to be 0 + r = 0.0 + else: + r = ssxym / np.sqrt(ssxm * ssym) + # Test for numerical error propagation (make sure -1 < r < 1) + if r > 1.0: + r = 1.0 + elif r < -1.0: + r = -1.0 + + slope = ssxym / ssxm + intercept = ymean - slope*xmean + if n == 2: + # handle case when only two points are passed in + if y[0] == y[1]: + prob = 1.0 + else: + prob = 0.0 + slope_stderr = 0.0 + intercept_stderr = 0.0 + else: + df = n - 2 # Number of degrees of freedom + # n-2 degrees of freedom because 2 has been used up + # to estimate the mean and standard deviation + t = r * np.sqrt(df / ((1.0 - r + TINY)*(1.0 + r + TINY))) + + dist = _SimpleStudentT(df) + prob = _get_pvalue(t, dist, alternative, xp=np) + prob = prob[()] if prob.ndim == 0 else prob + + slope_stderr = np.sqrt((1 - r**2) * ssym / ssxm / df) + + # Also calculate the standard error of the intercept + # The following relationship is used: + # ssxm = mean( (x-mean(x))^2 ) + # = ssx - sx*sx + # = mean( x^2 ) - mean(x)^2 + intercept_stderr = slope_stderr * np.sqrt(ssxm + xmean**2) + + return LinregressResult(slope=slope, intercept=intercept, rvalue=r, + pvalue=prob, stderr=slope_stderr, + intercept_stderr=intercept_stderr) + + +def _xp_mean(x, /, *, axis=None, weights=None, keepdims=False, nan_policy='propagate', + dtype=None, xp=None): + r"""Compute the arithmetic mean along the specified axis. + + Parameters + ---------- + x : real array + Array containing real numbers whose mean is desired. + axis : int or tuple of ints, default: None + If an int or tuple of ints, the axis or axes of the input along which + to compute the statistic. The statistic of each axis-slice (e.g. row) + of the input will appear in a corresponding element of the output. + If ``None``, the input will be raveled before computing the statistic. + weights : real array, optional + If specified, an array of weights associated with the values in `x`; + otherwise ``1``. If `weights` and `x` do not have the same shape, the + arrays will be broadcasted before performing the calculation. See + Notes for details. + keepdims : boolean, optional + If this is set to ``True``, the axes which are reduced are left + in the result as dimensions with length one. With this option, + the result will broadcast correctly against the input array. + nan_policy : {'propagate', 'omit', 'raise'}, default: 'propagate' + Defines how to handle input NaNs. + + - ``propagate``: if a NaN is present in the axis slice (e.g. row) along + which the statistic is computed, the corresponding entry of the output + will be NaN. + - ``omit``: NaNs will be omitted when performing the calculation. + If insufficient data remains in the axis slice along which the + statistic is computed, the corresponding entry of the output will be + NaN. + - ``raise``: if a NaN is present, a ``ValueError`` will be raised. + + dtype : dtype, optional + Type to use in computing the mean. For integer inputs, the default is + the default float type of the array library; for floating point inputs, + the dtype is that of the input. + + Returns + ------- + out : array + The mean of each slice + + Notes + ----- + Let :math:`x_i` represent element :math:`i` of data `x` and let :math:`w_i` + represent the corresponding element of `weights` after broadcasting. Then the + (weighted) mean :math:`\bar{x}_w` is given by: + + .. math:: + + \bar{x}_w = \frac{ \sum_{i=0}^{n-1} w_i x_i } + { \sum_{i=0}^{n-1} w_i } + + where :math:`n` is the number of elements along a slice. Note that this simplifies + to the familiar :math:`(\sum_i x_i) / n` when the weights are all ``1`` (default). + + The behavior of this function with respect to weights is somewhat different + from that of `np.average`. For instance, + `np.average` raises an error when `axis` is not specified and the shapes of `x` + and the `weights` array are not the same; `xp_mean` simply broadcasts the two. + Also, `np.average` raises an error when weights sum to zero along a slice; + `xp_mean` computes the appropriate result. The intent is for this function's + interface to be consistent with the rest of `scipy.stats`. + + Note that according to the formula, including NaNs with zero weights is not + the same as *omitting* NaNs with ``nan_policy='omit'``; in the former case, + the NaNs will continue to propagate through the calculation whereas in the + latter case, the NaNs are excluded entirely. + + """ + # ensure that `x` and `weights` are array-API compatible arrays of identical shape + xp = array_namespace(x) if xp is None else xp + x = _asarray(x, dtype=dtype, subok=True) + weights = xp.asarray(weights, dtype=dtype) if weights is not None else weights + + # to ensure that this matches the behavior of decorated functions when one of the + # arguments has size zero, it's easiest to call a similar decorated function. + if is_numpy(xp) and (xp_size(x) == 0 + or (weights is not None and xp_size(weights) == 0)): + return gmean(x, weights=weights, axis=axis, keepdims=keepdims) + + x, weights = xp_broadcast_promote(x, weights, force_floating=True) + + # handle the special case of zero-sized arrays + message = (too_small_1d_not_omit if (x.ndim == 1 or axis is None) + else too_small_nd_not_omit) + if xp_size(x) == 0: + with warnings.catch_warnings(): + warnings.simplefilter("ignore") + res = xp.mean(x, axis=axis, keepdims=keepdims) + if xp_size(res) != 0: + warnings.warn(message, SmallSampleWarning, stacklevel=2) + return res + + contains_nan, _ = _contains_nan(x, nan_policy, xp_omit_okay=True, xp=xp) + if weights is not None: + contains_nan_w, _ = _contains_nan(weights, nan_policy, xp_omit_okay=True, xp=xp) + contains_nan = contains_nan | contains_nan_w + + # Handle `nan_policy='omit'` by giving zero weight to NaNs, whether they + # appear in `x` or `weights`. Emit warning if there is an all-NaN slice. + message = (too_small_1d_omit if (x.ndim == 1 or axis is None) + else too_small_nd_omit) + if contains_nan and nan_policy == 'omit': + nan_mask = xp.isnan(x) + if weights is not None: + nan_mask |= xp.isnan(weights) + if xp.any(xp.all(nan_mask, axis=axis)): + warnings.warn(message, SmallSampleWarning, stacklevel=2) + weights = xp.ones_like(x) if weights is None else weights + x = xp.where(nan_mask, xp.asarray(0, dtype=x.dtype), x) + weights = xp.where(nan_mask, xp.asarray(0, dtype=x.dtype), weights) + + # Perform the mean calculation itself + if weights is None: + return xp.mean(x, axis=axis, keepdims=keepdims) + + norm = xp.sum(weights, axis=axis) + wsum = xp.sum(x * weights, axis=axis) + with np.errstate(divide='ignore', invalid='ignore'): + res = wsum/norm + + # Respect `keepdims` and convert NumPy 0-D arrays to scalars + if keepdims: + + if axis is None: + final_shape = (1,) * len(x.shape) + else: + # axis can be a scalar or sequence + axes = (axis,) if not isinstance(axis, Sequence) else axis + final_shape = list(x.shape) + for i in axes: + final_shape[i] = 1 + + res = xp.reshape(res, final_shape) + + return res[()] if res.ndim == 0 else res + + +def _xp_var(x, /, *, axis=None, correction=0, keepdims=False, nan_policy='propagate', + dtype=None, xp=None): + # an array-api compatible function for variance with scipy.stats interface + # and features (e.g. `nan_policy`). + xp = array_namespace(x) if xp is None else xp + x = _asarray(x, subok=True) + + # use `_xp_mean` instead of `xp.var` for desired warning behavior + # it would be nice to combine this with `_var`, which uses `_moment` + # and therefore warns when precision is lost, but that does not support + # `axis` tuples or keepdims. Eventually, `_axis_nan_policy` will simplify + # `axis` tuples and implement `keepdims` for non-NumPy arrays; then it will + # be easy. + kwargs = dict(axis=axis, nan_policy=nan_policy, dtype=dtype, xp=xp) + mean = _xp_mean(x, keepdims=True, **kwargs) + x = _asarray(x, dtype=mean.dtype, subok=True) + x_mean = _demean(x, mean, axis, xp=xp) + x_mean_conj = (xp.conj(x_mean) if xp.isdtype(x_mean.dtype, 'complex floating') + else x_mean) # crossref data-apis/array-api#824 + var = _xp_mean(x_mean * x_mean_conj, keepdims=keepdims, **kwargs) + + if correction != 0: + if axis is None: + n = xp_size(x) + elif np.iterable(axis): # note: using NumPy on `axis` is OK + n = math.prod(x.shape[i] for i in axis) + else: + n = x.shape[axis] + # Or two lines with ternaries : ) + # axis = range(x.ndim) if axis is None else axis + # n = math.prod(x.shape[i] for i in axis) if iterable(axis) else x.shape[axis] + + n = xp.asarray(n, dtype=var.dtype) + + if nan_policy == 'omit': + nan_mask = xp.astype(xp.isnan(x), var.dtype) + n = n - xp.sum(nan_mask, axis=axis, keepdims=keepdims) + + # Produce NaNs silently when n - correction <= 0 + factor = _lazywhere(n-correction > 0, (n, n-correction), xp.divide, xp.nan) + var *= factor + + return var[()] if var.ndim == 0 else var + + +class _SimpleNormal: + # A very simple, array-API compatible normal distribution for use in + # hypothesis tests. May be replaced by new infrastructure Normal + # distribution in due time. + + def cdf(self, x): + return special.ndtr(x) + + def sf(self, x): + return special.ndtr(-x) + + def isf(self, x): + return -special.ndtri(x) + + +class _SimpleChi2: + # A very simple, array-API compatible chi-squared distribution for use in + # hypothesis tests. May be replaced by new infrastructure chi-squared + # distribution in due time. + def __init__(self, df): + self.df = df + + def cdf(self, x): + return special.chdtr(self.df, x) + + def sf(self, x): + return special.chdtrc(self.df, x) + + +class _SimpleBeta: + # A very simple, array-API compatible beta distribution for use in + # hypothesis tests. May be replaced by new infrastructure beta + # distribution in due time. + def __init__(self, a, b, *, loc=None, scale=None): + self.a = a + self.b = b + self.loc = loc + self.scale = scale + + def cdf(self, x): + if self.loc is not None or self.scale is not None: + loc = 0 if self.loc is None else self.loc + scale = 1 if self.scale is None else self.scale + return special.betainc(self.a, self.b, (x - loc)/scale) + return special.betainc(self.a, self.b, x) + + def sf(self, x): + if self.loc is not None or self.scale is not None: + loc = 0 if self.loc is None else self.loc + scale = 1 if self.scale is None else self.scale + return special.betaincc(self.a, self.b, (x - loc)/scale) + return special.betaincc(self.a, self.b, x) + + +class _SimpleStudentT: + # A very simple, array-API compatible t distribution for use in + # hypothesis tests. May be replaced by new infrastructure t + # distribution in due time. + def __init__(self, df): + self.df = df + + def cdf(self, t): + return special.stdtr(self.df, t) + + def sf(self, t): + return special.stdtr(self.df, -t) diff --git a/shared/package-files/01/01b9b3bc255605c78745f9917de27d13ac733904c52e4d14d730dfa5fdff31a3/blob b/shared/package-files/01/01b9b3bc255605c78745f9917de27d13ac733904c52e4d14d730dfa5fdff31a3/blob new file mode 100644 index 0000000000000000000000000000000000000000..09e9487d14dfa274356f1d1fb923ccff9685d05b --- /dev/null +++ b/shared/package-files/01/01b9b3bc255605c78745f9917de27d13ac733904c52e4d14d730dfa5fdff31a3/blob @@ -0,0 +1,195 @@ +StartFontMetrics 2.0 +Comment Creation Date: Thu Jun 21 22:23:44 1990 +Comment UniqueID 5000820 +FontName CMSY10 +EncodingScheme FontSpecific +FullName CMSY10 +FamilyName Computer Modern +Weight Medium +ItalicAngle -14.035 +IsFixedPitch false +Version 1.00 +Notice Copyright (c) 1997 American Mathematical Society. All Rights Reserved. +Comment Computer Modern fonts were designed by Donald E. Knuth +FontBBox -29 -960 1116 775 +CapHeight 683.333 +XHeight 430.556 +Ascender 694.444 +Descender -960 +Comment FontID CMSY +Comment DesignSize 10 (pts) +Comment CharacterCodingScheme TeX math symbols +Comment Space 0 0 0 +Comment ExtraSpace 0 +Comment Quad 1000 +Comment Num 676.508 393.732 443.731 +Comment Denom 685.951 344.841 +Comment Sup 412.892 362.892 288.889 +Comment Sub 150 247.217 +Comment Supdrop 386.108 +Comment Subdrop 50 +Comment Delim 2390 1010 +Comment Axisheight 250 +StartCharMetrics 129 +C 0 ; WX 777.778 ; N minus ; B 83 230 694 270 ; +C 1 ; WX 277.778 ; N periodcentered ; B 86 197 192 303 ; +C 2 ; WX 777.778 ; N multiply ; B 147 9 630 491 ; +C 3 ; WX 500 ; N asteriskmath ; B 65 34 434 465 ; +C 4 ; WX 777.778 ; N divide ; B 56 -30 722 530 ; +C 5 ; WX 500 ; N diamondmath ; B 11 11 489 489 ; +C 6 ; WX 777.778 ; N plusminus ; B 56 0 721 666 ; +C 7 ; WX 777.778 ; N minusplus ; B 56 -166 721 500 ; +C 8 ; WX 777.778 ; N circleplus ; B 56 -83 721 583 ; +C 9 ; WX 777.778 ; N circleminus ; B 56 -83 721 583 ; +C 10 ; WX 777.778 ; N circlemultiply ; B 56 -83 721 583 ; +C 11 ; WX 777.778 ; N circledivide ; B 56 -83 721 583 ; +C 12 ; WX 777.778 ; N circledot ; B 56 -83 721 583 ; +C 13 ; WX 1000 ; N circlecopyrt ; B 56 -216 943 716 ; +C 14 ; WX 500 ; N openbullet ; B 56 56 443 444 ; +C 15 ; WX 500 ; N bullet ; B 56 56 443 444 ; +C 16 ; WX 777.778 ; N equivasymptotic ; B 56 16 721 484 ; +C 17 ; WX 777.778 ; N equivalence ; B 56 36 721 464 ; +C 18 ; WX 777.778 ; N reflexsubset ; B 83 -137 694 636 ; +C 19 ; WX 777.778 ; N reflexsuperset ; B 83 -137 694 636 ; +C 20 ; WX 777.778 ; N lessequal ; B 83 -137 694 636 ; +C 21 ; WX 777.778 ; N greaterequal ; B 83 -137 694 636 ; +C 22 ; WX 777.778 ; N precedesequal ; B 83 -137 694 636 ; +C 23 ; WX 777.778 ; N followsequal ; B 83 -137 694 636 ; +C 24 ; WX 777.778 ; N similar ; B 56 133 721 367 ; +C 25 ; WX 777.778 ; N approxequal ; B 56 56 721 483 ; +C 26 ; WX 777.778 ; N propersubset ; B 83 -40 694 540 ; +C 27 ; WX 777.778 ; N propersuperset ; B 83 -40 694 540 ; +C 28 ; WX 1000 ; N lessmuch ; B 56 -66 943 566 ; +C 29 ; WX 1000 ; N greatermuch ; B 56 -66 943 566 ; +C 30 ; WX 777.778 ; N precedes ; B 83 -40 694 539 ; +C 31 ; WX 777.778 ; N follows ; B 83 -40 694 539 ; +C 32 ; WX 1000 ; N arrowleft ; B 57 72 943 428 ; +C 33 ; WX 1000 ; N arrowright ; B 56 72 942 428 ; +C 34 ; WX 500 ; N arrowup ; B 72 -194 428 693 ; +C 35 ; WX 500 ; N arrowdown ; B 72 -193 428 694 ; +C 36 ; WX 1000 ; N arrowboth ; B 57 72 942 428 ; +C 37 ; WX 1000 ; N arrownortheast ; B 56 -193 946 697 ; +C 38 ; WX 1000 ; N arrowsoutheast ; B 56 -197 946 693 ; +C 39 ; WX 777.778 ; N similarequal ; B 56 36 721 464 ; +C 40 ; WX 1000 ; N arrowdblleft ; B 57 -25 943 525 ; +C 41 ; WX 1000 ; N arrowdblright ; B 56 -25 942 525 ; +C 42 ; WX 611.111 ; N arrowdblup ; B 30 -194 580 694 ; +C 43 ; WX 611.111 ; N arrowdbldown ; B 30 -194 580 694 ; +C 44 ; WX 1000 ; N arrowdblboth ; B 35 -25 964 525 ; +C 45 ; WX 1000 ; N arrownorthwest ; B 53 -193 943 697 ; +C 46 ; WX 1000 ; N arrowsouthwest ; B 53 -197 943 693 ; +C 47 ; WX 777.778 ; N proportional ; B 56 -11 722 442 ; +C 48 ; WX 275 ; N prime ; B 29 45 262 559 ; +C 49 ; WX 1000 ; N infinity ; B 56 -11 943 442 ; +C 50 ; WX 666.667 ; N element ; B 83 -40 583 540 ; +C 51 ; WX 666.667 ; N owner ; B 83 -40 583 540 ; +C 52 ; WX 888.889 ; N triangle ; B 59 0 829 716 ; +C 53 ; WX 888.889 ; N triangleinv ; B 59 -216 829 500 ; +C 54 ; WX 0 ; N negationslash ; B 139 -216 638 716 ; +C 55 ; WX 0 ; N mapsto ; B 56 64 124 436 ; +C 56 ; WX 555.556 ; N universal ; B 0 -22 556 694 ; +C 57 ; WX 555.556 ; N existential ; B 56 0 499 694 ; +C 58 ; WX 666.667 ; N logicalnot ; B 56 89 610 356 ; +C 59 ; WX 500 ; N emptyset ; B 47 -78 452 772 ; +C 60 ; WX 722.222 ; N Rfractur ; B 46 -22 714 716 ; +C 61 ; WX 722.222 ; N Ifractur ; B 56 -11 693 705 ; +C 62 ; WX 777.778 ; N latticetop ; B 56 0 722 666 ; +C 63 ; WX 777.778 ; N perpendicular ; B 56 0 722 666 ; +C 64 ; WX 611.111 ; N aleph ; B 56 0 554 693 ; +C 65 ; WX 798.469 ; N A ; B 27 -50 798 722 ; +C 66 ; WX 656.808 ; N B ; B 30 -22 665 706 ; +C 67 ; WX 526.527 ; N C ; B 12 -24 534 705 ; +C 68 ; WX 771.391 ; N D ; B 20 0 766 683 ; +C 69 ; WX 527.778 ; N E ; B 28 -22 565 705 ; +C 70 ; WX 718.75 ; N F ; B 17 -33 829 683 ; +C 71 ; WX 594.864 ; N G ; B 44 -119 601 705 ; +C 72 ; WX 844.516 ; N H ; B 20 -47 818 683 ; +C 73 ; WX 544.513 ; N I ; B -24 0 635 683 ; +C 74 ; WX 677.778 ; N J ; B 47 -119 840 683 ; +C 75 ; WX 761.949 ; N K ; B 30 -22 733 705 ; +C 76 ; WX 689.723 ; N L ; B 31 -22 656 705 ; +C 77 ; WX 1200.9 ; N M ; B 27 -50 1116 705 ; +C 78 ; WX 820.489 ; N N ; B -29 -50 978 775 ; +C 79 ; WX 796.112 ; N O ; B 57 -22 777 705 ; +C 80 ; WX 695.558 ; N P ; B 20 -50 733 683 ; +C 81 ; WX 816.667 ; N Q ; B 113 -124 788 705 ; +C 82 ; WX 847.502 ; N R ; B 20 -22 837 683 ; +C 83 ; WX 605.556 ; N S ; B 18 -22 642 705 ; +C 84 ; WX 544.643 ; N T ; B 29 0 798 717 ; +C 85 ; WX 625.83 ; N U ; B -17 -28 688 683 ; +C 86 ; WX 612.781 ; N V ; B 35 -45 660 683 ; +C 87 ; WX 987.782 ; N W ; B 35 -45 1036 683 ; +C 88 ; WX 713.295 ; N X ; B 50 0 808 683 ; +C 89 ; WX 668.335 ; N Y ; B 31 -135 717 683 ; +C 90 ; WX 724.724 ; N Z ; B 37 0 767 683 ; +C 91 ; WX 666.667 ; N union ; B 56 -22 610 598 ; +C 92 ; WX 666.667 ; N intersection ; B 56 -22 610 598 ; +C 93 ; WX 666.667 ; N unionmulti ; B 56 -22 610 598 ; +C 94 ; WX 666.667 ; N logicaland ; B 56 -22 610 598 ; +C 95 ; WX 666.667 ; N logicalor ; B 56 -22 610 598 ; +C 96 ; WX 611.111 ; N turnstileleft ; B 56 0 554 694 ; +C 97 ; WX 611.111 ; N turnstileright ; B 56 0 554 694 ; +C 98 ; WX 444.444 ; N floorleft ; B 174 -250 422 750 ; +C 99 ; WX 444.444 ; N floorright ; B 21 -250 269 750 ; +C 100 ; WX 444.444 ; N ceilingleft ; B 174 -250 422 750 ; +C 101 ; WX 444.444 ; N ceilingright ; B 21 -250 269 750 ; +C 102 ; WX 500 ; N braceleft ; B 72 -250 427 750 ; +C 103 ; WX 500 ; N braceright ; B 72 -250 427 750 ; +C 104 ; WX 388.889 ; N angbracketleft ; B 110 -250 332 750 ; +C 105 ; WX 388.889 ; N angbracketright ; B 56 -250 278 750 ; +C 106 ; WX 277.778 ; N bar ; B 119 -250 159 750 ; +C 107 ; WX 500 ; N bardbl ; B 132 -250 367 750 ; +C 108 ; WX 500 ; N arrowbothv ; B 72 -272 428 772 ; +C 109 ; WX 611.111 ; N arrowdblbothv ; B 30 -272 580 772 ; +C 110 ; WX 500 ; N backslash ; B 56 -250 443 750 ; +C 111 ; WX 277.778 ; N wreathproduct ; B 56 -83 221 583 ; +C 112 ; WX 833.333 ; N radical ; B 73 -960 853 40 ; +C 113 ; WX 750 ; N coproduct ; B 36 0 713 683 ; +C 114 ; WX 833.333 ; N nabla ; B 47 -33 785 683 ; +C 115 ; WX 416.667 ; N integral ; B 56 -216 471 716 ; +C 116 ; WX 666.667 ; N unionsq ; B 61 0 605 598 ; +C 117 ; WX 666.667 ; N intersectionsq ; B 61 0 605 598 ; +C 118 ; WX 777.778 ; N subsetsqequal ; B 83 -137 714 636 ; +C 119 ; WX 777.778 ; N supersetsqequal ; B 63 -137 694 636 ; +C 120 ; WX 444.444 ; N section ; B 69 -205 374 705 ; +C 121 ; WX 444.444 ; N dagger ; B 56 -216 387 705 ; +C 122 ; WX 444.444 ; N daggerdbl ; B 56 -205 387 705 ; +C 123 ; WX 611.111 ; N paragraph ; B 56 -194 582 694 ; +C 124 ; WX 777.778 ; N club ; B 28 -130 750 727 ; +C 125 ; WX 777.778 ; N diamond ; B 56 -163 722 727 ; +C 126 ; WX 777.778 ; N heart ; B 56 -33 722 716 ; +C 127 ; WX 777.778 ; N spade ; B 56 -130 722 727 ; +C -1 ; WX 333.333 ; N space ; B 0 0 0 0 ; +EndCharMetrics +Comment The following are bogus kern pairs for TeX positioning of accents +StartKernData +StartKernPairs 26 +KPX A prime 194.444 +KPX B prime 138.889 +KPX C prime 138.889 +KPX D prime 83.333 +KPX E prime 111.111 +KPX F prime 111.111 +KPX G prime 111.111 +KPX H prime 111.111 +KPX I prime 27.778 +KPX J prime 166.667 +KPX K prime 55.556 +KPX L prime 138.889 +KPX M prime 138.889 +KPX N prime 83.333 +KPX O prime 111.111 +KPX P prime 83.333 +KPX Q prime 111.111 +KPX R prime 83.333 +KPX S prime 138.889 +KPX T prime 27.778 +KPX U prime 83.333 +KPX V prime 27.778 +KPX W prime 83.333 +KPX X prime 138.889 +KPX Y prime 83.333 +KPX Z prime 138.889 +EndKernPairs +EndKernData +EndFontMetrics diff --git a/shared/package-files/01/01ba4719c80b6fe911b091a7c05124b64eeece964e09c058ef8f9805daca546b/blob b/shared/package-files/01/01ba4719c80b6fe911b091a7c05124b64eeece964e09c058ef8f9805daca546b/blob new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/shared/package-files/01/01ba4719c80b6fe911b091a7c05124b64eeece964e09c058ef8f9805daca546b/blob @@ -0,0 +1 @@ + diff --git a/shared/package-files/01/01bb811b212e7c401fdb86fb7f2f09421749b463dd3fd5c42313d32407c0145a/blob b/shared/package-files/01/01bb811b212e7c401fdb86fb7f2f09421749b463dd3fd5c42313d32407c0145a/blob new file mode 100644 index 0000000000000000000000000000000000000000..9e05c63863a6fca5a24dfaa26e1fd9569dea9580 --- /dev/null +++ b/shared/package-files/01/01bb811b212e7c401fdb86fb7f2f09421749b463dd3fd5c42313d32407c0145a/blob @@ -0,0 +1,24 @@ +import pytest + +from numpy import array_api as xp + + +@pytest.mark.parametrize( + "x, indices, axis, expected", + [ + ([2, 3], [1, 1, 0], 0, [3, 3, 2]), + ([2, 3], [1, 1, 0], -1, [3, 3, 2]), + ([[2, 3]], [1], -1, [[3]]), + ([[2, 3]], [0, 0], 0, [[2, 3], [2, 3]]), + ], +) +def test_take_function(x, indices, axis, expected): + """ + Indices respect relative order of a descending stable-sort + + See https://github.com/numpy/numpy/issues/20778 + """ + x = xp.asarray(x) + indices = xp.asarray(indices) + out = xp.take(x, indices, axis=axis) + assert xp.all(out == xp.asarray(expected)) diff --git a/shared/package-files/01/01bdfe46f06e2a5e2a32d5a71876c64f6013fbb0558d051790cc84d31b48a119/blob b/shared/package-files/01/01bdfe46f06e2a5e2a32d5a71876c64f6013fbb0558d051790cc84d31b48a119/blob new file mode 100644 index 0000000000000000000000000000000000000000..b4ab5eeb802cf102965d66714757fc78e56f4b5d --- /dev/null +++ b/shared/package-files/01/01bdfe46f06e2a5e2a32d5a71876c64f6013fbb0558d051790cc84d31b48a119/blob @@ -0,0 +1,13 @@ +*** Fri, 26 Aug 2016 11:44:12 *** +TEST FOR GRANGER-CAUSALITY: +H0: "Dp" do not Granger-cause "R" + +Test statistic l = 1.2025 +pval-F( l; 3, 184) = 0.3103 + +TEST FOR INSTANTANEOUS CAUSALITY: +H0: No instantaneous causality between "Dp" and "R" + +Test statistic: c = 1.4168 +pval-Chi( c; 1) = 0.2339 + diff --git a/shared/package-files/01/01bed50be567307a84cd4f0c19e12514e746689501f6f7aacddc04edeeb59079/blob b/shared/package-files/01/01bed50be567307a84cd4f0c19e12514e746689501f6f7aacddc04edeeb59079/blob new file mode 100644 index 0000000000000000000000000000000000000000..9576edf838214a7b9224856e94428c514e7f3cd8 --- /dev/null +++ b/shared/package-files/01/01bed50be567307a84cd4f0c19e12514e746689501f6f7aacddc04edeeb59079/blob @@ -0,0 +1,1710 @@ +from __future__ import annotations + +import logging +import os +import traceback +from io import BytesIO, StringIO, UnsupportedOperation +from typing import TYPE_CHECKING, TypedDict, TypeVar, overload + +from fontTools.config import Config +from fontTools.misc import xmlWriter +from fontTools.misc.configTools import AbstractConfig +from fontTools.misc.loggingTools import deprecateArgument +from fontTools.misc.textTools import Tag, byteord, tostr +from fontTools.ttLib import TTLibError +from fontTools.ttLib.sfnt import SFNTReader, SFNTWriter +from fontTools.ttLib.ttGlyphSet import ( + _TTGlyph, # noqa: F401 + _TTGlyphSet, + _TTGlyphSetCFF, + _TTGlyphSetGlyf, + _TTGlyphSetVARC, +) + +if TYPE_CHECKING: + from collections.abc import Mapping, MutableMapping + from types import ModuleType, TracebackType + from typing import Any, BinaryIO, Literal, Sequence, TextIO + + from typing_extensions import Self, Unpack + + from fontTools.ttLib.tables import ( + B_A_S_E_, + C_B_D_T_, + C_B_L_C_, + C_F_F_, + C_F_F__2, + C_O_L_R_, + C_P_A_L_, + D_S_I_G_, + E_B_D_T_, + E_B_L_C_, + E_B_S_C_, + F_F_T_M_, + G_D_E_F_, + G_P_O_S_, + G_S_U_B_, + G_V_A_R_, + H_V_A_R_, + I_F_T_, + I_F_T_X_, + J_S_T_F_, + L_T_S_H_, + M_A_T_H_, + M_V_A_R_, + S_T_A_T_, + S_V_G_, + T_S_I__0, + T_S_I__1, + T_S_I__2, + T_S_I__3, + T_S_I__5, + T_S_I_B_, + T_S_I_C_, + T_S_I_D_, + T_S_I_J_, + T_S_I_P_, + T_S_I_S_, + T_S_I_V_, + T_T_F_A_, + V_A_R_C_, + V_D_M_X_, + V_O_R_G_, + V_V_A_R_, + D__e_b_g, + F__e_a_t, + G__l_a_t, + G__l_o_c, + O_S_2f_2, + S__i_l_f, + S__i_l_l, + _a_n_k_r, + _a_v_a_r, + _b_d_a_t, + _b_g_c_l, + _b_h_e_d, + _b_l_o_c, + _b_s_l_n, + _c_i_d_g, + _c_m_a_p, + _c_v_a_r, + _c_v_t, + _f_e_a_t, + _f_p_g_m, + _f_v_a_r, + _g_a_s_p, + _g_c_i_d, + _g_l_y_f, + _g_v_a_r, + _h_d_m_x, + _h_e_a_d, + _h_h_e_a, + _h_m_t_x, + _k_e_r_n, + _l_c_a_r, + _l_o_c_a, + _l_t_a_g, + _m_a_x_p, + _m_e_t_a, + _m_o_r_t, + _m_o_r_x, + _n_a_m_e, + _o_p_b_d, + _p_o_s_t, + _p_r_e_p, + _p_r_o_p, + _s_b_i_x, + _t_r_a_k, + _v_h_e_a, + _v_m_t_x, + ) + from fontTools.ttLib.tables.DefaultTable import DefaultTable + + _VT_co = TypeVar("_VT_co", covariant=True) # Value type covariant containers. + +log = logging.getLogger(__name__) + + +_NumberT = TypeVar("_NumberT", bound=float) + + +class TTFont(object): + """Represents a TrueType font. + + The object manages file input and output, and offers a convenient way of + accessing tables. Tables will be only decompiled when necessary, ie. when + they're actually accessed. This means that simple operations can be extremely fast. + + Example usage: + + .. code-block:: pycon + + >>> + >> from fontTools import ttLib + >> tt = ttLib.TTFont("afont.ttf") # Load an existing font file + >> tt['maxp'].numGlyphs + 242 + >> tt['OS/2'].achVendID + 'B&H\000' + >> tt['head'].unitsPerEm + 2048 + + For details of the objects returned when accessing each table, see the + :doc:`tables ` documentation. + To add a table to the font, use the :py:func:`newTable` function: + + .. code-block:: pycon + + >>> + >> os2 = newTable("OS/2") + >> os2.version = 4 + >> # set other attributes + >> font["OS/2"] = os2 + + TrueType fonts can also be serialized to and from XML format (see also the + :doc:`ttx ` binary): + + .. code-block:: pycon + + >> + >> tt.saveXML("afont.ttx") + Dumping 'LTSH' table... + Dumping 'OS/2' table... + [...] + + >> tt2 = ttLib.TTFont() # Create a new font object + >> tt2.importXML("afont.ttx") + >> tt2['maxp'].numGlyphs + 242 + + The TTFont object may be used as a context manager; this will cause the file + reader to be closed after the context ``with`` block is exited:: + + with TTFont(filename) as f: + # Do stuff + + Args: + file: When reading a font from disk, either a pathname pointing to a file, + or a readable file object. + res_name_or_index: If running on a Macintosh, either a sfnt resource name or + an sfnt resource index number. If the index number is zero, TTLib will + autodetect whether the file is a flat file or a suitcase. (If it is a suitcase, + only the first 'sfnt' resource will be read.) + sfntVersion (str): When constructing a font object from scratch, sets the four-byte + sfnt magic number to be used. Defaults to ``\0\1\0\0`` (TrueType). To create + an OpenType file, use ``OTTO``. + flavor (str): Set this to ``woff`` when creating a WOFF file or ``woff2`` for a WOFF2 + file. + checkChecksums (int): How checksum data should be treated. Default is 0 + (no checking). Set to 1 to check and warn on wrong checksums; set to 2 to + raise an exception if any wrong checksums are found. + recalcBBoxes (bool): If true (the default), recalculates ``glyf``, ``CFF ``, + ``head`` bounding box values and ``hhea``/``vhea`` min/max values on save. + Also compiles the glyphs on importing, which saves memory consumption and + time. + ignoreDecompileErrors (bool): If true, exceptions raised during table decompilation + will be ignored, and the binary data will be returned for those tables instead. + recalcTimestamp (bool): If true (the default), sets the ``modified`` timestamp in + the ``head`` table on save. + fontNumber (int): The index of the font in a TrueType Collection file. + lazy (bool): If lazy is set to True, many data structures are loaded lazily, upon + access only. If it is set to False, many data structures are loaded immediately. + The default is ``lazy=None`` which is somewhere in between. + """ + + tables: dict[Tag, DefaultTable | GlyphOrder] + reader: SFNTReader | None + sfntVersion: str + flavor: str | None + flavorData: Any | None + lazy: bool | None + recalcBBoxes: bool + recalcTimestamp: bool + ignoreDecompileErrors: bool + cfg: AbstractConfig + glyphOrder: list[str] + _reverseGlyphOrderDict: dict[str, int] + _tableCache: MutableMapping[tuple[Tag, bytes], DefaultTable] | None + disassembleInstructions: bool + bitmapGlyphDataFormat: str + # Deprecated attributes + verbose: bool | None + quiet: bool | None + + def __init__( + self, + file: str | os.PathLike[str] | BinaryIO | None = None, + res_name_or_index: str | int | None = None, + sfntVersion: str = "\000\001\000\000", + flavor: str | None = None, + checkChecksums: int = 0, + verbose: bool | None = None, # Deprecated + recalcBBoxes: bool = True, + allowVID: Any = NotImplemented, # Deprecated/Unused + ignoreDecompileErrors: bool = False, + recalcTimestamp: bool = True, + fontNumber: int = -1, + lazy: bool | None = None, + quiet: bool | None = None, # Deprecated + _tableCache: MutableMapping[tuple[Tag, bytes], DefaultTable] | None = None, + cfg: Mapping[str, Any] | AbstractConfig = {}, + ) -> None: + # Set deprecated attributes + for name in ("verbose", "quiet"): + val = locals().get(name) + if val is not None: + deprecateArgument(name, "configure logging instead") + setattr(self, name, val) + + self.lazy = lazy + self.recalcBBoxes = recalcBBoxes + self.recalcTimestamp = recalcTimestamp + self.tables = {} + self.reader = None + self.cfg = cfg.copy() if isinstance(cfg, AbstractConfig) else Config(cfg) + self.ignoreDecompileErrors = ignoreDecompileErrors + + if not file: + self.sfntVersion = sfntVersion + self.flavor = flavor + self.flavorData = None + return + seekable = True + if not hasattr(file, "read"): + if not isinstance(file, (str, os.PathLike)): + raise TypeError( + "fileOrPath must be a file path (str or PathLike) if it isn't an object with a `read` method." + ) + closeStream = True + # assume file is a string + if res_name_or_index is not None: + # see if it contains 'sfnt' resources in the resource or data fork + from . import macUtils + + if res_name_or_index == 0: + if macUtils.getSFNTResIndices(file): + # get the first available sfnt font. + file = macUtils.SFNTResourceReader(file, 1) + else: + file = open(file, "rb") + else: + file = macUtils.SFNTResourceReader(file, res_name_or_index) + else: + file = open(file, "rb") + else: + # assume "file" is a readable file object + assert not isinstance(file, (str, os.PathLike)) + closeStream = False + # SFNTReader wants the input file to be seekable. + # SpooledTemporaryFile has no seekable() on < 3.11, but still can seek: + # https://github.com/fonttools/fonttools/issues/3052 + if hasattr(file, "seekable"): + seekable = file.seekable() + elif hasattr(file, "seek"): + try: + file.seek(0) + except UnsupportedOperation: + seekable = False + + if not self.lazy: + # read input file in memory and wrap a stream around it to allow overwriting + if seekable: + file.seek(0) + tmp = BytesIO(file.read()) + if hasattr(file, "name"): + # save reference to input file name + tmp.name = file.name + if closeStream: + file.close() + file = tmp + elif not seekable: + raise TTLibError("Input file must be seekable when lazy=True") + self._tableCache = _tableCache + self.reader = SFNTReader(file, checkChecksums, fontNumber=fontNumber) + self.sfntVersion = self.reader.sfntVersion + self.flavor = self.reader.flavor + self.flavorData = self.reader.flavorData + + def __enter__(self) -> Self: + return self + + def __exit__( + self, + exc_type: type[BaseException] | None, + exc_value: BaseException | None, + traceback: TracebackType | None, + ) -> None: + self.close() + + def close(self) -> None: + """If we still have a reader object, close it.""" + if self.reader is not None: + self.reader.close() + self.reader = None + + def save( + self, file: str | os.PathLike[str] | BinaryIO, reorderTables: bool | None = True + ) -> None: + """Save the font to disk. + + Args: + file: Similarly to the constructor, can be either a pathname or a writable + binary file object. + reorderTables (Option[bool]): If true (the default), reorder the tables, + sorting them by tag (recommended by the OpenType specification). If + false, retain the original font order. If None, reorder by table + dependency (fastest). + """ + if not hasattr(file, "write"): + if self.lazy and self.reader.file.name == file: + raise TTLibError("Can't overwrite TTFont when 'lazy' attribute is True") + createStream = True + else: + # assume "file" is a writable file object + createStream = False + + tmp = BytesIO() + + writer_reordersTables = self._save(tmp) + + if not ( + reorderTables is None + or writer_reordersTables + or (reorderTables is False and self.reader is None) + ): + if reorderTables is False: + # sort tables using the original font's order + if self.reader is None: + raise TTLibError( + "The original table order is unavailable because there isn't a font to read it from." + ) + tableOrder = list(self.reader.keys()) + else: + # use the recommended order from the OpenType specification + tableOrder = None + tmp.flush() + tmp2 = BytesIO() + reorderFontTables(tmp, tmp2, tableOrder) + tmp.close() + tmp = tmp2 + + if createStream: + # "file" is a path + assert isinstance(file, (str, os.PathLike)) + with open(file, "wb") as file: + file.write(tmp.getvalue()) + else: + assert not isinstance(file, (str, os.PathLike)) + file.write(tmp.getvalue()) + + tmp.close() + + def _save( + self, + file: BinaryIO, + tableCache: MutableMapping[tuple[Tag, bytes], Any] | None = None, + ) -> bool: + """Internal function, to be shared by save() and TTCollection.save()""" + + if self.recalcTimestamp and "head" in self: + # make sure 'head' is loaded so the recalculation is actually done + self["head"] + + tags = self.keys() + tags.pop(0) # skip GlyphOrder tag + numTables = len(tags) + # write to a temporary stream to allow saving to unseekable streams + writer = SFNTWriter( + file, numTables, self.sfntVersion, self.flavor, self.flavorData + ) + + done = [] + for tag in tags: + self._writeTable(tag, writer, done, tableCache) + + writer.close() + + return writer.reordersTables() + + class XMLSavingOptions(TypedDict): + writeVersion: bool + quiet: bool | None + tables: Sequence[str | bytes] | None + skipTables: Sequence[str] | None + splitTables: bool + splitGlyphs: bool + disassembleInstructions: bool + bitmapGlyphDataFormat: str + + def saveXML( + self, + fileOrPath: str | os.PathLike[str] | BinaryIO | TextIO, + newlinestr: str = "\n", + **kwargs: Unpack[XMLSavingOptions], + ) -> None: + """Export the font as TTX (an XML-based text file), or as a series of text + files when splitTables is true. In the latter case, the 'fileOrPath' + argument should be a path to a directory. + The 'tables' argument must either be falsy (None or empty list, meaning + dump all tables) or a non-empty list of tables to dump. The 'skipTables' + argument may be a list of tables to skip, but only when 'tables' is falsy. + """ + + writer = xmlWriter.XMLWriter(fileOrPath, newlinestr=newlinestr) + self._saveXML(writer, **kwargs) + writer.close() + + def _saveXML( + self, + writer: xmlWriter.XMLWriter, + writeVersion: bool = True, + quiet: bool | None = None, # Deprecated + tables: Sequence[str | bytes] | None = None, + skipTables: Sequence[str] | None = None, + splitTables: bool = False, + splitGlyphs: bool = False, + disassembleInstructions: bool = True, + bitmapGlyphDataFormat: str = "raw", + ) -> None: + if quiet is not None: + deprecateArgument("quiet", "configure logging instead") + + self.disassembleInstructions = disassembleInstructions + self.bitmapGlyphDataFormat = bitmapGlyphDataFormat + if not tables: + tables = self.keys() + if skipTables: + tables = [tag for tag in tables if tag not in skipTables] + + if writeVersion: + from fontTools import version + + version = ".".join(version.split(".")[:2]) + writer.begintag( + "ttFont", + sfntVersion=repr(tostr(self.sfntVersion))[1:-1], + ttLibVersion=version, + ) + else: + writer.begintag("ttFont", sfntVersion=repr(tostr(self.sfntVersion))[1:-1]) + writer.newline() + + # always splitTables if splitGlyphs is enabled + splitTables = splitTables or splitGlyphs + + if not splitTables: + writer.newline() + else: + if writer.filename is None: + raise TTLibError( + "splitTables requires the file name to be a file system path, not a stream." + ) + path, ext = os.path.splitext(writer.filename) + + for tag in tables: + if splitTables: + tablePath = path + "." + tagToIdentifier(tag) + ext + tableWriter = xmlWriter.XMLWriter( + tablePath, newlinestr=writer.newlinestr + ) + tableWriter.begintag("ttFont", ttLibVersion=version) + tableWriter.newline() + tableWriter.newline() + writer.simpletag(tagToXML(tag), src=os.path.basename(tablePath)) + writer.newline() + else: + tableWriter = writer + self._tableToXML(tableWriter, tag, splitGlyphs=splitGlyphs) + if splitTables: + tableWriter.endtag("ttFont") + tableWriter.newline() + tableWriter.close() + writer.endtag("ttFont") + writer.newline() + + def _tableToXML( + self, + writer: xmlWriter.XMLWriter, + tag: str | bytes, + quiet: bool | None = None, + splitGlyphs: bool = False, + ) -> None: + if quiet is not None: + deprecateArgument("quiet", "configure logging instead") + if tag in self: + table = self[tag] + report = "Dumping '%s' table..." % tag + else: + report = "No '%s' table found." % tag + log.info(report) + if tag not in self: + return + xmlTag = tagToXML(tag) + attrs: dict[str, Any] = {} + if hasattr(table, "ERROR"): + attrs["ERROR"] = "decompilation error" + from .tables.DefaultTable import DefaultTable + + if table.__class__ == DefaultTable: + attrs["raw"] = True + writer.begintag(xmlTag, **attrs) + writer.newline() + if tag == "glyf": + table.toXML(writer, self, splitGlyphs=splitGlyphs) + else: + table.toXML(writer, self) + writer.endtag(xmlTag) + writer.newline() + writer.newline() + + def importXML( + self, fileOrPath: str | os.PathLike[str] | BinaryIO, quiet: bool | None = None + ) -> None: + """Import a TTX file (an XML-based text format), so as to recreate + a font object. + """ + if quiet is not None: + deprecateArgument("quiet", "configure logging instead") + + if "maxp" in self and "post" in self: + # Make sure the glyph order is loaded, as it otherwise gets + # lost if the XML doesn't contain the glyph order, yet does + # contain the table which was originally used to extract the + # glyph names from (ie. 'post', 'cmap' or 'CFF '). + self.getGlyphOrder() + + from fontTools.misc import xmlReader + + reader = xmlReader.XMLReader(fileOrPath, self) + reader.read() + + def isLoaded(self, tag: str | bytes) -> bool: + """Return true if the table identified by ``tag`` has been + decompiled and loaded into memory.""" + return tag in self.tables + + def has_key(self, tag: str | bytes) -> bool: + """Test if the table identified by ``tag`` is present in the font. + + As well as this method, ``tag in font`` can also be used to determine the + presence of the table.""" + if self.isLoaded(tag): + return True + elif self.reader and tag in self.reader: + return True + elif tag == "GlyphOrder": + return True + else: + return False + + __contains__ = has_key + + def keys(self) -> list[str]: + """Returns the list of tables in the font, along with the ``GlyphOrder`` pseudo-table.""" + keys = list(self.tables.keys()) + if self.reader: + for key in list(self.reader.keys()): + if key not in keys: + keys.append(key) + + if "GlyphOrder" in keys: + keys.remove("GlyphOrder") + keys = sortedTagList(keys) + return ["GlyphOrder"] + keys + + def ensureDecompiled(self, recurse: bool | None = None) -> None: + """Decompile all the tables, even if a TTFont was opened in 'lazy' mode.""" + for tag in self.keys(): + table = self[tag] + if recurse is None: + recurse = self.lazy is not False + if recurse and hasattr(table, "ensureDecompiled"): + table.ensureDecompiled(recurse=recurse) + self.lazy = False + + def __len__(self) -> int: + return len(list(self.keys())) + + @overload + def __getitem__(self, tag: Literal["BASE"]) -> B_A_S_E_.table_B_A_S_E_: ... + @overload + def __getitem__(self, tag: Literal["CBDT"]) -> C_B_D_T_.table_C_B_D_T_: ... + @overload + def __getitem__(self, tag: Literal["CBLC"]) -> C_B_L_C_.table_C_B_L_C_: ... + @overload + def __getitem__(self, tag: Literal["CFF "]) -> C_F_F_.table_C_F_F_: ... + @overload + def __getitem__(self, tag: Literal["CFF2"]) -> C_F_F__2.table_C_F_F__2: ... + @overload + def __getitem__(self, tag: Literal["COLR"]) -> C_O_L_R_.table_C_O_L_R_: ... + @overload + def __getitem__(self, tag: Literal["CPAL"]) -> C_P_A_L_.table_C_P_A_L_: ... + @overload + def __getitem__(self, tag: Literal["DSIG"]) -> D_S_I_G_.table_D_S_I_G_: ... + @overload + def __getitem__(self, tag: Literal["EBDT"]) -> E_B_D_T_.table_E_B_D_T_: ... + @overload + def __getitem__(self, tag: Literal["EBLC"]) -> E_B_L_C_.table_E_B_L_C_: ... + @overload + def __getitem__(self, tag: Literal["EBSC"]) -> E_B_S_C_.table_E_B_S_C_: ... + @overload + def __getitem__(self, tag: Literal["FFTM"]) -> F_F_T_M_.table_F_F_T_M_: ... + @overload + def __getitem__(self, tag: Literal["GDEF"]) -> G_D_E_F_.table_G_D_E_F_: ... + @overload + def __getitem__(self, tag: Literal["GPOS"]) -> G_P_O_S_.table_G_P_O_S_: ... + @overload + def __getitem__(self, tag: Literal["GSUB"]) -> G_S_U_B_.table_G_S_U_B_: ... + @overload + def __getitem__(self, tag: Literal["GVAR"]) -> G_V_A_R_.table_G_V_A_R_: ... + @overload + def __getitem__(self, tag: Literal["HVAR"]) -> H_V_A_R_.table_H_V_A_R_: ... + @overload + def __getitem__(self, tag: Literal["IFT "]) -> I_F_T_.table_I_F_T_: ... + @overload + def __getitem__(self, tag: Literal["IFTX"]) -> I_F_T_X_.table_I_F_T_X_: ... + @overload + def __getitem__(self, tag: Literal["JSTF"]) -> J_S_T_F_.table_J_S_T_F_: ... + @overload + def __getitem__(self, tag: Literal["LTSH"]) -> L_T_S_H_.table_L_T_S_H_: ... + @overload + def __getitem__(self, tag: Literal["MATH"]) -> M_A_T_H_.table_M_A_T_H_: ... + @overload + def __getitem__(self, tag: Literal["MVAR"]) -> M_V_A_R_.table_M_V_A_R_: ... + @overload + def __getitem__(self, tag: Literal["STAT"]) -> S_T_A_T_.table_S_T_A_T_: ... + @overload + def __getitem__(self, tag: Literal["SVG "]) -> S_V_G_.table_S_V_G_: ... + @overload + def __getitem__(self, tag: Literal["TSI0"]) -> T_S_I__0.table_T_S_I__0: ... + @overload + def __getitem__(self, tag: Literal["TSI1"]) -> T_S_I__1.table_T_S_I__1: ... + @overload + def __getitem__(self, tag: Literal["TSI2"]) -> T_S_I__2.table_T_S_I__2: ... + @overload + def __getitem__(self, tag: Literal["TSI3"]) -> T_S_I__3.table_T_S_I__3: ... + @overload + def __getitem__(self, tag: Literal["TSI5"]) -> T_S_I__5.table_T_S_I__5: ... + @overload + def __getitem__(self, tag: Literal["TSIB"]) -> T_S_I_B_.table_T_S_I_B_: ... + @overload + def __getitem__(self, tag: Literal["TSIC"]) -> T_S_I_C_.table_T_S_I_C_: ... + @overload + def __getitem__(self, tag: Literal["TSID"]) -> T_S_I_D_.table_T_S_I_D_: ... + @overload + def __getitem__(self, tag: Literal["TSIJ"]) -> T_S_I_J_.table_T_S_I_J_: ... + @overload + def __getitem__(self, tag: Literal["TSIP"]) -> T_S_I_P_.table_T_S_I_P_: ... + @overload + def __getitem__(self, tag: Literal["TSIS"]) -> T_S_I_S_.table_T_S_I_S_: ... + @overload + def __getitem__(self, tag: Literal["TSIV"]) -> T_S_I_V_.table_T_S_I_V_: ... + @overload + def __getitem__(self, tag: Literal["TTFA"]) -> T_T_F_A_.table_T_T_F_A_: ... + @overload + def __getitem__(self, tag: Literal["VARC"]) -> V_A_R_C_.table_V_A_R_C_: ... + @overload + def __getitem__(self, tag: Literal["VDMX"]) -> V_D_M_X_.table_V_D_M_X_: ... + @overload + def __getitem__(self, tag: Literal["VORG"]) -> V_O_R_G_.table_V_O_R_G_: ... + @overload + def __getitem__(self, tag: Literal["VVAR"]) -> V_V_A_R_.table_V_V_A_R_: ... + @overload + def __getitem__(self, tag: Literal["Debg"]) -> D__e_b_g.table_D__e_b_g: ... + @overload + def __getitem__(self, tag: Literal["Feat"]) -> F__e_a_t.table_F__e_a_t: ... + @overload + def __getitem__(self, tag: Literal["Glat"]) -> G__l_a_t.table_G__l_a_t: ... + @overload + def __getitem__(self, tag: Literal["Gloc"]) -> G__l_o_c.table_G__l_o_c: ... + @overload + def __getitem__(self, tag: Literal["OS/2"]) -> O_S_2f_2.table_O_S_2f_2: ... + @overload + def __getitem__(self, tag: Literal["Silf"]) -> S__i_l_f.table_S__i_l_f: ... + @overload + def __getitem__(self, tag: Literal["Sill"]) -> S__i_l_l.table_S__i_l_l: ... + @overload + def __getitem__(self, tag: Literal["ankr"]) -> _a_n_k_r.table__a_n_k_r: ... + @overload + def __getitem__(self, tag: Literal["avar"]) -> _a_v_a_r.table__a_v_a_r: ... + @overload + def __getitem__(self, tag: Literal["bsln"]) -> _b_s_l_n.table__b_s_l_n: ... + @overload + def __getitem__(self, tag: Literal["bdat"]) -> _b_d_a_t.table__b_d_a_t: ... + @overload + def __getitem__(self, tag: Literal["bhed"]) -> _b_h_e_d.table__b_h_e_d: ... + @overload + def __getitem__(self, tag: Literal["bgcl"]) -> _b_g_c_l.table__b_g_c_l: ... + @overload + def __getitem__(self, tag: Literal["bloc"]) -> _b_l_o_c.table__b_l_o_c: ... + @overload + def __getitem__(self, tag: Literal["cidg"]) -> _c_i_d_g.table__c_i_d_g: ... + @overload + def __getitem__(self, tag: Literal["cmap"]) -> _c_m_a_p.table__c_m_a_p: ... + @overload + def __getitem__(self, tag: Literal["cvar"]) -> _c_v_a_r.table__c_v_a_r: ... + @overload + def __getitem__(self, tag: Literal["cvt "]) -> _c_v_t.table__c_v_t: ... + @overload + def __getitem__(self, tag: Literal["feat"]) -> _f_e_a_t.table__f_e_a_t: ... + @overload + def __getitem__(self, tag: Literal["fpgm"]) -> _f_p_g_m.table__f_p_g_m: ... + @overload + def __getitem__(self, tag: Literal["fvar"]) -> _f_v_a_r.table__f_v_a_r: ... + @overload + def __getitem__(self, tag: Literal["gasp"]) -> _g_a_s_p.table__g_a_s_p: ... + @overload + def __getitem__(self, tag: Literal["gcid"]) -> _g_c_i_d.table__g_c_i_d: ... + @overload + def __getitem__(self, tag: Literal["glyf"]) -> _g_l_y_f.table__g_l_y_f: ... + @overload + def __getitem__(self, tag: Literal["gvar"]) -> _g_v_a_r.table__g_v_a_r: ... + @overload + def __getitem__(self, tag: Literal["hdmx"]) -> _h_d_m_x.table__h_d_m_x: ... + @overload + def __getitem__(self, tag: Literal["head"]) -> _h_e_a_d.table__h_e_a_d: ... + @overload + def __getitem__(self, tag: Literal["hhea"]) -> _h_h_e_a.table__h_h_e_a: ... + @overload + def __getitem__(self, tag: Literal["hmtx"]) -> _h_m_t_x.table__h_m_t_x: ... + @overload + def __getitem__(self, tag: Literal["kern"]) -> _k_e_r_n.table__k_e_r_n: ... + @overload + def __getitem__(self, tag: Literal["lcar"]) -> _l_c_a_r.table__l_c_a_r: ... + @overload + def __getitem__(self, tag: Literal["loca"]) -> _l_o_c_a.table__l_o_c_a: ... + @overload + def __getitem__(self, tag: Literal["ltag"]) -> _l_t_a_g.table__l_t_a_g: ... + @overload + def __getitem__(self, tag: Literal["maxp"]) -> _m_a_x_p.table__m_a_x_p: ... + @overload + def __getitem__(self, tag: Literal["meta"]) -> _m_e_t_a.table__m_e_t_a: ... + @overload + def __getitem__(self, tag: Literal["mort"]) -> _m_o_r_t.table__m_o_r_t: ... + @overload + def __getitem__(self, tag: Literal["morx"]) -> _m_o_r_x.table__m_o_r_x: ... + @overload + def __getitem__(self, tag: Literal["name"]) -> _n_a_m_e.table__n_a_m_e: ... + @overload + def __getitem__(self, tag: Literal["opbd"]) -> _o_p_b_d.table__o_p_b_d: ... + @overload + def __getitem__(self, tag: Literal["post"]) -> _p_o_s_t.table__p_o_s_t: ... + @overload + def __getitem__(self, tag: Literal["prep"]) -> _p_r_e_p.table__p_r_e_p: ... + @overload + def __getitem__(self, tag: Literal["prop"]) -> _p_r_o_p.table__p_r_o_p: ... + @overload + def __getitem__(self, tag: Literal["sbix"]) -> _s_b_i_x.table__s_b_i_x: ... + @overload + def __getitem__(self, tag: Literal["trak"]) -> _t_r_a_k.table__t_r_a_k: ... + @overload + def __getitem__(self, tag: Literal["vhea"]) -> _v_h_e_a.table__v_h_e_a: ... + @overload + def __getitem__(self, tag: Literal["vmtx"]) -> _v_m_t_x.table__v_m_t_x: ... + @overload + def __getitem__(self, tag: Literal["GlyphOrder"]) -> GlyphOrder: ... + @overload + def __getitem__(self, tag: str | bytes) -> DefaultTable | GlyphOrder: ... + + def __getitem__(self, tag: str | bytes) -> DefaultTable | GlyphOrder: + tag = Tag(tag) + table = self.tables.get(tag) + if table is None: + if tag == "GlyphOrder": + table = GlyphOrder(tag) + self.tables[tag] = table + elif self.reader is not None: + table = self._readTable(tag) + else: + raise KeyError("'%s' table not found" % tag) + return table + + def _readTable(self, tag: Tag) -> DefaultTable: + log.debug("Reading '%s' table from disk", tag) + assert self.reader is not None + data = self.reader[tag] + if self._tableCache is not None: + table = self._tableCache.get((tag, data)) + if table is not None: + return table + tableClass = getTableClass(tag) + table = tableClass(tag) + self.tables[tag] = table + log.debug("Decompiling '%s' table", tag) + try: + table.decompile(data, self) + except Exception: + if not self.ignoreDecompileErrors: + raise + # fall back to DefaultTable, retaining the binary table data + log.exception( + "An exception occurred during the decompilation of the '%s' table", tag + ) + from .tables.DefaultTable import DefaultTable + + file = StringIO() + traceback.print_exc(file=file) + table = DefaultTable(tag) + table.ERROR = file.getvalue() + self.tables[tag] = table + table.decompile(data, self) + if self._tableCache is not None: + self._tableCache[(tag, data)] = table + return table + + def __setitem__(self, tag: str | bytes, table: DefaultTable) -> None: + self.tables[Tag(tag)] = table + + def __delitem__(self, tag: str | bytes) -> None: + if tag not in self: + raise KeyError("'%s' table not found" % tag) + if tag in self.tables: + del self.tables[tag] + if self.reader and tag in self.reader: + del self.reader[tag] + + @overload + def get(self, tag: Literal["BASE"]) -> B_A_S_E_.table_B_A_S_E_ | None: ... + @overload + def get(self, tag: Literal["CBDT"]) -> C_B_D_T_.table_C_B_D_T_ | None: ... + @overload + def get(self, tag: Literal["CBLC"]) -> C_B_L_C_.table_C_B_L_C_ | None: ... + @overload + def get(self, tag: Literal["CFF "]) -> C_F_F_.table_C_F_F_ | None: ... + @overload + def get(self, tag: Literal["CFF2"]) -> C_F_F__2.table_C_F_F__2 | None: ... + @overload + def get(self, tag: Literal["COLR"]) -> C_O_L_R_.table_C_O_L_R_ | None: ... + @overload + def get(self, tag: Literal["CPAL"]) -> C_P_A_L_.table_C_P_A_L_ | None: ... + @overload + def get(self, tag: Literal["DSIG"]) -> D_S_I_G_.table_D_S_I_G_ | None: ... + @overload + def get(self, tag: Literal["EBDT"]) -> E_B_D_T_.table_E_B_D_T_ | None: ... + @overload + def get(self, tag: Literal["EBLC"]) -> E_B_L_C_.table_E_B_L_C_ | None: ... + @overload + def get(self, tag: Literal["EBSC"]) -> E_B_S_C_.table_E_B_S_C_ | None: ... + @overload + def get(self, tag: Literal["FFTM"]) -> F_F_T_M_.table_F_F_T_M_ | None: ... + @overload + def get(self, tag: Literal["GDEF"]) -> G_D_E_F_.table_G_D_E_F_ | None: ... + @overload + def get(self, tag: Literal["GPOS"]) -> G_P_O_S_.table_G_P_O_S_ | None: ... + @overload + def get(self, tag: Literal["GSUB"]) -> G_S_U_B_.table_G_S_U_B_ | None: ... + @overload + def get(self, tag: Literal["GVAR"]) -> G_V_A_R_.table_G_V_A_R_ | None: ... + @overload + def get(self, tag: Literal["HVAR"]) -> H_V_A_R_.table_H_V_A_R_ | None: ... + @overload + def get(self, tag: Literal["IFT "]) -> I_F_T_.table_I_F_T_ | None: ... + @overload + def get(self, tag: Literal["IFTX"]) -> I_F_T_X_.table_I_F_T_X_ | None: ... + @overload + def get(self, tag: Literal["JSTF"]) -> J_S_T_F_.table_J_S_T_F_ | None: ... + @overload + def get(self, tag: Literal["LTSH"]) -> L_T_S_H_.table_L_T_S_H_ | None: ... + @overload + def get(self, tag: Literal["MATH"]) -> M_A_T_H_.table_M_A_T_H_ | None: ... + @overload + def get(self, tag: Literal["MVAR"]) -> M_V_A_R_.table_M_V_A_R_ | None: ... + @overload + def get(self, tag: Literal["STAT"]) -> S_T_A_T_.table_S_T_A_T_ | None: ... + @overload + def get(self, tag: Literal["SVG "]) -> S_V_G_.table_S_V_G_ | None: ... + @overload + def get(self, tag: Literal["TSI0"]) -> T_S_I__0.table_T_S_I__0 | None: ... + @overload + def get(self, tag: Literal["TSI1"]) -> T_S_I__1.table_T_S_I__1 | None: ... + @overload + def get(self, tag: Literal["TSI2"]) -> T_S_I__2.table_T_S_I__2 | None: ... + @overload + def get(self, tag: Literal["TSI3"]) -> T_S_I__3.table_T_S_I__3 | None: ... + @overload + def get(self, tag: Literal["TSI5"]) -> T_S_I__5.table_T_S_I__5 | None: ... + @overload + def get(self, tag: Literal["TSIB"]) -> T_S_I_B_.table_T_S_I_B_ | None: ... + @overload + def get(self, tag: Literal["TSIC"]) -> T_S_I_C_.table_T_S_I_C_ | None: ... + @overload + def get(self, tag: Literal["TSID"]) -> T_S_I_D_.table_T_S_I_D_ | None: ... + @overload + def get(self, tag: Literal["TSIJ"]) -> T_S_I_J_.table_T_S_I_J_ | None: ... + @overload + def get(self, tag: Literal["TSIP"]) -> T_S_I_P_.table_T_S_I_P_ | None: ... + @overload + def get(self, tag: Literal["TSIS"]) -> T_S_I_S_.table_T_S_I_S_ | None: ... + @overload + def get(self, tag: Literal["TSIV"]) -> T_S_I_V_.table_T_S_I_V_ | None: ... + @overload + def get(self, tag: Literal["TTFA"]) -> T_T_F_A_.table_T_T_F_A_ | None: ... + @overload + def get(self, tag: Literal["VARC"]) -> V_A_R_C_.table_V_A_R_C_ | None: ... + @overload + def get(self, tag: Literal["VDMX"]) -> V_D_M_X_.table_V_D_M_X_ | None: ... + @overload + def get(self, tag: Literal["VORG"]) -> V_O_R_G_.table_V_O_R_G_ | None: ... + @overload + def get(self, tag: Literal["VVAR"]) -> V_V_A_R_.table_V_V_A_R_ | None: ... + @overload + def get(self, tag: Literal["Debg"]) -> D__e_b_g.table_D__e_b_g | None: ... + @overload + def get(self, tag: Literal["Feat"]) -> F__e_a_t.table_F__e_a_t | None: ... + @overload + def get(self, tag: Literal["Glat"]) -> G__l_a_t.table_G__l_a_t | None: ... + @overload + def get(self, tag: Literal["Gloc"]) -> G__l_o_c.table_G__l_o_c | None: ... + @overload + def get(self, tag: Literal["OS/2"]) -> O_S_2f_2.table_O_S_2f_2 | None: ... + @overload + def get(self, tag: Literal["Silf"]) -> S__i_l_f.table_S__i_l_f | None: ... + @overload + def get(self, tag: Literal["Sill"]) -> S__i_l_l.table_S__i_l_l | None: ... + @overload + def get(self, tag: Literal["ankr"]) -> _a_n_k_r.table__a_n_k_r | None: ... + @overload + def get(self, tag: Literal["avar"]) -> _a_v_a_r.table__a_v_a_r | None: ... + @overload + def get(self, tag: Literal["bsln"]) -> _b_s_l_n.table__b_s_l_n | None: ... + @overload + def get(self, tag: Literal["bgcl"]) -> _b_g_c_l.table__b_g_c_l | None: ... + @overload + def get(self, tag: Literal["cidg"]) -> _c_i_d_g.table__c_i_d_g | None: ... + @overload + def get(self, tag: Literal["cmap"]) -> _c_m_a_p.table__c_m_a_p | None: ... + @overload + def get(self, tag: Literal["cvar"]) -> _c_v_a_r.table__c_v_a_r | None: ... + @overload + def get(self, tag: Literal["cvt "]) -> _c_v_t.table__c_v_t | None: ... + @overload + def get(self, tag: Literal["feat"]) -> _f_e_a_t.table__f_e_a_t | None: ... + @overload + def get(self, tag: Literal["fpgm"]) -> _f_p_g_m.table__f_p_g_m | None: ... + @overload + def get(self, tag: Literal["fvar"]) -> _f_v_a_r.table__f_v_a_r | None: ... + @overload + def get(self, tag: Literal["gasp"]) -> _g_a_s_p.table__g_a_s_p | None: ... + @overload + def get(self, tag: Literal["gcid"]) -> _g_c_i_d.table__g_c_i_d | None: ... + @overload + def get(self, tag: Literal["glyf"]) -> _g_l_y_f.table__g_l_y_f | None: ... + @overload + def get(self, tag: Literal["gvar"]) -> _g_v_a_r.table__g_v_a_r | None: ... + @overload + def get(self, tag: Literal["hdmx"]) -> _h_d_m_x.table__h_d_m_x | None: ... + @overload + def get(self, tag: Literal["head"]) -> _h_e_a_d.table__h_e_a_d | None: ... + @overload + def get(self, tag: Literal["hhea"]) -> _h_h_e_a.table__h_h_e_a | None: ... + @overload + def get(self, tag: Literal["hmtx"]) -> _h_m_t_x.table__h_m_t_x | None: ... + @overload + def get(self, tag: Literal["kern"]) -> _k_e_r_n.table__k_e_r_n | None: ... + @overload + def get(self, tag: Literal["lcar"]) -> _l_c_a_r.table__l_c_a_r | None: ... + @overload + def get(self, tag: Literal["loca"]) -> _l_o_c_a.table__l_o_c_a | None: ... + @overload + def get(self, tag: Literal["ltag"]) -> _l_t_a_g.table__l_t_a_g | None: ... + @overload + def get(self, tag: Literal["maxp"]) -> _m_a_x_p.table__m_a_x_p | None: ... + @overload + def get(self, tag: Literal["meta"]) -> _m_e_t_a.table__m_e_t_a | None: ... + @overload + def get(self, tag: Literal["mort"]) -> _m_o_r_t.table__m_o_r_t | None: ... + @overload + def get(self, tag: Literal["morx"]) -> _m_o_r_x.table__m_o_r_x | None: ... + @overload + def get(self, tag: Literal["name"]) -> _n_a_m_e.table__n_a_m_e | None: ... + @overload + def get(self, tag: Literal["opbd"]) -> _o_p_b_d.table__o_p_b_d | None: ... + @overload + def get(self, tag: Literal["post"]) -> _p_o_s_t.table__p_o_s_t | None: ... + @overload + def get(self, tag: Literal["prep"]) -> _p_r_e_p.table__p_r_e_p | None: ... + @overload + def get(self, tag: Literal["prop"]) -> _p_r_o_p.table__p_r_o_p | None: ... + @overload + def get(self, tag: Literal["sbix"]) -> _s_b_i_x.table__s_b_i_x | None: ... + @overload + def get(self, tag: Literal["trak"]) -> _t_r_a_k.table__t_r_a_k | None: ... + @overload + def get(self, tag: Literal["vhea"]) -> _v_h_e_a.table__v_h_e_a | None: ... + @overload + def get(self, tag: Literal["vmtx"]) -> _v_m_t_x.table__v_m_t_x | None: ... + @overload + def get(self, tag: Literal["GlyphOrder"]) -> GlyphOrder: ... + @overload + def get(self, tag: str | bytes) -> DefaultTable | GlyphOrder | Any | None: ... + @overload + def get( + self, tag: str | bytes, default: _VT_co + ) -> DefaultTable | GlyphOrder | Any | _VT_co: ... + + def get( + self, tag: str | bytes, default: Any | None = None + ) -> DefaultTable | GlyphOrder | Any | None: + """Returns the table if it exists or (optionally) a default if it doesn't.""" + try: + return self[tag] + except KeyError: + return default + + def setGlyphOrder(self, glyphOrder: list[str]) -> None: + """Set the glyph order + + Args: + glyphOrder ([str]): List of glyph names in order. + """ + self.glyphOrder = glyphOrder + if hasattr(self, "_reverseGlyphOrderDict"): + del self._reverseGlyphOrderDict + if self.isLoaded("glyf"): + self["glyf"].setGlyphOrder(glyphOrder) + + def getGlyphOrder(self) -> list[str]: + """Returns a list of glyph names ordered by their position in the font.""" + try: + return self.glyphOrder + except AttributeError: + pass + if "CFF " in self: + cff = self["CFF "] + self.glyphOrder = cff.getGlyphOrder() + elif "post" in self: + # TrueType font + glyphOrder = self["post"].getGlyphOrder() + if glyphOrder is None: + # + # No names found in the 'post' table. + # Try to create glyph names from the unicode cmap (if available) + # in combination with the Adobe Glyph List (AGL). + # + self._getGlyphNamesFromCmap() + elif len(glyphOrder) < self["maxp"].numGlyphs: + # + # Not enough names found in the 'post' table. + # Can happen when 'post' format 1 is improperly used on a font that + # has more than 258 glyphs (the length of 'standardGlyphOrder'). + # + log.warning( + "Not enough names found in the 'post' table, generating them from cmap instead" + ) + self._getGlyphNamesFromCmap() + else: + self.glyphOrder = glyphOrder + else: + self._getGlyphNamesFromCmap() + return self.glyphOrder + + def _getGlyphNamesFromCmap(self) -> None: + # + # This is rather convoluted, but then again, it's an interesting problem: + # - we need to use the unicode values found in the cmap table to + # build glyph names (eg. because there is only a minimal post table, + # or none at all). + # - but the cmap parser also needs glyph names to work with... + # So here's what we do: + # - make up glyph names based on glyphID + # - load a temporary cmap table based on those names + # - extract the unicode values, build the "real" glyph names + # - unload the temporary cmap table + # + if self.isLoaded("cmap"): + # Bootstrapping: we're getting called by the cmap parser + # itself. This means self.tables['cmap'] contains a partially + # loaded cmap, making it impossible to get at a unicode + # subtable here. We remove the partially loaded cmap and + # restore it later. + # This only happens if the cmap table is loaded before any + # other table that does f.getGlyphOrder() or f.getGlyphName(). + cmapLoading = self.tables["cmap"] + del self.tables["cmap"] + else: + cmapLoading = None + # Make up glyph names based on glyphID, which will be used by the + # temporary cmap and by the real cmap in case we don't find a unicode + # cmap. + numGlyphs = int(self["maxp"].numGlyphs) + glyphOrder = ["glyph%.5d" % i for i in range(numGlyphs)] + glyphOrder[0] = ".notdef" + # Set the glyph order, so the cmap parser has something + # to work with (so we don't get called recursively). + self.glyphOrder = glyphOrder + + # Make up glyph names based on the reversed cmap table. Because some + # glyphs (eg. ligatures or alternates) may not be reachable via cmap, + # this naming table will usually not cover all glyphs in the font. + # If the font has no Unicode cmap table, reversecmap will be empty. + if "cmap" in self: + reversecmap = self["cmap"].buildReversedMin() + else: + reversecmap = {} + useCount = {} + for i, tempName in enumerate(glyphOrder): + if tempName in reversecmap: + # If a font maps both U+0041 LATIN CAPITAL LETTER A and + # U+0391 GREEK CAPITAL LETTER ALPHA to the same glyph, + # we prefer naming the glyph as "A". + glyphName = self._makeGlyphName(reversecmap[tempName]) + numUses = useCount[glyphName] = useCount.get(glyphName, 0) + 1 + if numUses > 1: + glyphName = "%s.alt%d" % (glyphName, numUses - 1) + glyphOrder[i] = glyphName + + if "cmap" in self: + # Delete the temporary cmap table from the cache, so it can + # be parsed again with the right names. + del self.tables["cmap"] + self.glyphOrder = glyphOrder + if cmapLoading: + # restore partially loaded cmap, so it can continue loading + # using the proper names. + self.tables["cmap"] = cmapLoading + + @staticmethod + def _makeGlyphName(codepoint: int) -> str: + from fontTools import agl # Adobe Glyph List + + if codepoint in agl.UV2AGL: + return agl.UV2AGL[codepoint] + elif codepoint <= 0xFFFF: + return "uni%04X" % codepoint + else: + return "u%X" % codepoint + + def getGlyphNames(self) -> list[str]: + """Get a list of glyph names, sorted alphabetically.""" + glyphNames = sorted(self.getGlyphOrder()) + return glyphNames + + def getGlyphNames2(self) -> list[str]: + """Get a list of glyph names, sorted alphabetically, + but not case sensitive. + """ + from fontTools.misc import textTools + + return textTools.caselessSort(self.getGlyphOrder()) + + def getGlyphName(self, glyphID: int) -> str: + """Returns the name for the glyph with the given ID. + + If no name is available, synthesises one with the form ``glyphXXXXX``` where + ```XXXXX`` is the zero-padded glyph ID. + """ + try: + return self.getGlyphOrder()[glyphID] + except IndexError: + return "glyph%.5d" % glyphID + + def getGlyphNameMany(self, lst: Sequence[int]) -> list[str]: + """Converts a list of glyph IDs into a list of glyph names.""" + glyphOrder = self.getGlyphOrder() + cnt = len(glyphOrder) + return [glyphOrder[gid] if gid < cnt else "glyph%.5d" % gid for gid in lst] + + def getGlyphID(self, glyphName: str) -> int: + """Returns the ID of the glyph with the given name.""" + try: + return self.getReverseGlyphMap()[glyphName] + except KeyError: + if glyphName[:5] == "glyph": + try: + return int(glyphName[5:]) + except (NameError, ValueError): + raise KeyError(glyphName) + raise + + def getGlyphIDMany(self, lst: Sequence[str]) -> list[int]: + """Converts a list of glyph names into a list of glyph IDs.""" + d = self.getReverseGlyphMap() + try: + return [d[glyphName] for glyphName in lst] + except KeyError: + getGlyphID = self.getGlyphID + return [getGlyphID(glyphName) for glyphName in lst] + + def getReverseGlyphMap(self, rebuild: bool = False) -> dict[str, int]: + """Returns a mapping of glyph names to glyph IDs.""" + if rebuild or not hasattr(self, "_reverseGlyphOrderDict"): + self._buildReverseGlyphOrderDict() + return self._reverseGlyphOrderDict + + def _buildReverseGlyphOrderDict(self) -> dict[str, int]: + self._reverseGlyphOrderDict = d = {} + for glyphID, glyphName in enumerate(self.getGlyphOrder()): + d[glyphName] = glyphID + return d + + def _writeTable( + self, + tag: str | bytes, + writer: SFNTWriter, + done: list[str | bytes], # Use list as original + tableCache: MutableMapping[tuple[Tag, bytes], DefaultTable] | None = None, + ) -> None: + """Internal helper function for self.save(). Keeps track of + inter-table dependencies. + """ + if tag in done: + return + tableClass = getTableClass(tag) + for masterTable in tableClass.dependencies: + if masterTable not in done: + if masterTable in self: + self._writeTable(masterTable, writer, done, tableCache) + else: + done.append(masterTable) + done.append(tag) + tabledata = self.getTableData(tag) + if tableCache is not None: + entry = tableCache.get((Tag(tag), tabledata)) + if entry is not None: + log.debug("reusing '%s' table", tag) + writer.setEntry(tag, entry) + return + log.debug("Writing '%s' table to disk", tag) + writer[tag] = tabledata + if tableCache is not None: + tableCache[(Tag(tag), tabledata)] = writer[tag] + + def getTableData(self, tag: str | bytes) -> bytes: + """Returns the binary representation of a table. + + If the table is currently loaded and in memory, the data is compiled to + binary and returned; if it is not currently loaded, the binary data is + read from the font file and returned. + """ + tag = Tag(tag) + if self.isLoaded(tag): + log.debug("Compiling '%s' table", tag) + return self.tables[tag].compile(self) + elif self.reader and tag in self.reader: + log.debug("Reading '%s' table from disk", tag) + return self.reader[tag] + else: + raise KeyError(tag) + + def getGlyphSet( + self, + preferCFF: bool = True, + location: Mapping[str, _NumberT] | None = None, + normalized: bool = False, + recalcBounds: bool = True, + ) -> _TTGlyphSet: + """Return a generic GlyphSet, which is a dict-like object + mapping glyph names to glyph objects. The returned glyph objects + have a ``.draw()`` method that supports the Pen protocol, and will + have an attribute named 'width'. + + If the font is CFF-based, the outlines will be taken from the ``CFF `` + or ``CFF2`` tables. Otherwise the outlines will be taken from the + ``glyf`` table. + + If the font contains both a ``CFF ``/``CFF2`` and a ``glyf`` table, you + can use the ``preferCFF`` argument to specify which one should be taken. + If the font contains both a ``CFF `` and a ``CFF2`` table, the latter is + taken. + + If the ``location`` parameter is set, it should be a dictionary mapping + four-letter variation tags to their float values, and the returned + glyph-set will represent an instance of a variable font at that + location. + + If the ``normalized`` variable is set to True, that location is + interpreted as in the normalized (-1..+1) space, otherwise it is in the + font's defined axes space. + """ + if location and "fvar" not in self: + location = None + if location and not normalized: + location = self.normalizeLocation(location) + glyphSet = None + if ("CFF " in self or "CFF2" in self) and (preferCFF or "glyf" not in self): + glyphSet = _TTGlyphSetCFF(self, location) + elif "glyf" in self: + glyphSet = _TTGlyphSetGlyf(self, location, recalcBounds=recalcBounds) + else: + raise TTLibError("Font contains no outlines") + if "VARC" in self: + glyphSet = _TTGlyphSetVARC(self, location, glyphSet) + return glyphSet + + def normalizeLocation(self, location: Mapping[str, float]) -> dict[str, float]: + """Normalize a ``location`` from the font's defined axes space (also + known as user space) into the normalized (-1..+1) space. It applies + ``avar`` mapping if the font contains an ``avar`` table. + + The ``location`` parameter should be a dictionary mapping four-letter + variation tags to their float values. + + Raises ``TTLibError`` if the font is not a variable font. + """ + from fontTools.varLib.models import normalizeLocation + + if "fvar" not in self: + raise TTLibError("Not a variable font") + + axes = self["fvar"].getAxes() + location = normalizeLocation(location, axes) + if "avar" in self: + location = self["avar"].renormalizeLocation(location, self) + return location + + def getBestCmap( + self, + cmapPreferences: Sequence[tuple[int, int]] = ( + (3, 10), + (0, 6), + (0, 4), + (3, 1), + (0, 3), + (0, 2), + (0, 1), + (0, 0), + ), + ) -> dict[int, str] | None: + """Returns the 'best' Unicode cmap dictionary available in the font + or ``None``, if no Unicode cmap subtable is available. + + By default it will search for the following (platformID, platEncID) + pairs in order:: + + (3, 10), # Windows Unicode full repertoire + (0, 6), # Unicode full repertoire (format 13 subtable) + (0, 4), # Unicode 2.0 full repertoire + (3, 1), # Windows Unicode BMP + (0, 3), # Unicode 2.0 BMP + (0, 2), # Unicode ISO/IEC 10646 + (0, 1), # Unicode 1.1 + (0, 0) # Unicode 1.0 + + This particular order matches what HarfBuzz uses to choose what + subtable to use by default. This order prefers the largest-repertoire + subtable, and among those, prefers the Windows-platform over the + Unicode-platform as the former has wider support. + + This order can be customized via the ``cmapPreferences`` argument. + """ + return self["cmap"].getBestCmap(cmapPreferences=cmapPreferences) + + def reorderGlyphs(self, new_glyph_order: list[str]) -> None: + from .reorderGlyphs import reorderGlyphs + + reorderGlyphs(self, new_glyph_order) + + +class GlyphOrder(object): + """A pseudo table. The glyph order isn't in the font as a separate + table, but it's nice to present it as such in the TTX format. + """ + + def __init__(self, tag: str | None = None) -> None: + pass + + def toXML(self, writer: xmlWriter.XMLWriter, ttFont: TTFont) -> None: + glyphOrder = ttFont.getGlyphOrder() + writer.comment( + "The 'id' attribute is only for humans; it is ignored when parsed." + ) + writer.newline() + for i, glyphName in enumerate(glyphOrder): + writer.simpletag("GlyphID", id=i, name=glyphName) + writer.newline() + + def fromXML( + self, name: str, attrs: dict[str, str], content: list[Any], ttFont: TTFont + ) -> None: + if not hasattr(self, "glyphOrder"): + self.glyphOrder = [] + if name == "GlyphID": + self.glyphOrder.append(attrs["name"]) + ttFont.setGlyphOrder(self.glyphOrder) + + +def getTableModule(tag: str | bytes) -> ModuleType | None: + """Fetch the packer/unpacker module for a table. + Return None when no module is found. + """ + from . import tables + + pyTag = tagToIdentifier(tag) + try: + __import__("fontTools.ttLib.tables." + pyTag) + except ImportError as err: + # If pyTag is found in the ImportError message, + # means table is not implemented. If it's not + # there, then some other module is missing, don't + # suppress the error. + if str(err).find(pyTag) >= 0: + return None + else: + raise err + else: + return getattr(tables, pyTag) + + +# Registry for custom table packer/unpacker classes. Keys are table +# tags, values are (moduleName, className) tuples. +# See registerCustomTableClass() and getCustomTableClass() +_customTableRegistry: dict[str | bytes, tuple[str, str]] = {} + + +def registerCustomTableClass( + tag: str | bytes, moduleName: str, className: str | None = None +) -> None: + """Register a custom packer/unpacker class for a table. + + The 'moduleName' must be an importable module. If no 'className' + is given, it is derived from the tag, for example it will be + ``table_C_U_S_T_`` for a 'CUST' tag. + + The registered table class should be a subclass of + :py:class:`fontTools.ttLib.tables.DefaultTable.DefaultTable` + """ + if className is None: + className = "table_" + tagToIdentifier(tag) + _customTableRegistry[tag] = (moduleName, className) + + +def unregisterCustomTableClass(tag: str | bytes) -> None: + """Unregister the custom packer/unpacker class for a table.""" + del _customTableRegistry[tag] + + +def getCustomTableClass(tag: str | bytes) -> type[DefaultTable] | None: + """Return the custom table class for tag, if one has been registered + with 'registerCustomTableClass()'. Else return None. + """ + if tag not in _customTableRegistry: + return None + import importlib + + moduleName, className = _customTableRegistry[tag] + module = importlib.import_module(moduleName) + return getattr(module, className) + + +def getTableClass(tag: str | bytes) -> type[DefaultTable]: + """Fetch the packer/unpacker class for a table.""" + tableClass = getCustomTableClass(tag) + if tableClass is not None: + return tableClass + module = getTableModule(tag) + if module is None: + from .tables.DefaultTable import DefaultTable + + return DefaultTable + pyTag = tagToIdentifier(tag) + tableClass = getattr(module, "table_" + pyTag) + return tableClass + + +def getClassTag(klass: type[DefaultTable]) -> str | bytes: + """Fetch the table tag for a class object.""" + name = klass.__name__ + assert name[:6] == "table_" + name = name[6:] # Chop 'table_' + return identifierToTag(name) + + +def newTable(tag: str | bytes) -> DefaultTable: + """Return a new instance of a table.""" + tableClass = getTableClass(tag) + return tableClass(tag) + + +def _escapechar(c: str) -> str: + """Helper function for tagToIdentifier()""" + import re + + if re.match("[a-z0-9]", c): + return "_" + c + elif re.match("[A-Z]", c): + return c + "_" + else: + return hex(byteord(c))[2:] + + +def tagToIdentifier(tag: str | bytes) -> str: + """Convert a table tag to a valid (but UGLY) python identifier, + as well as a filename that's guaranteed to be unique even on a + caseless file system. Each character is mapped to two characters. + Lowercase letters get an underscore before the letter, uppercase + letters get an underscore after the letter. Trailing spaces are + trimmed. Illegal characters are escaped as two hex bytes. If the + result starts with a number (as the result of a hex escape), an + extra underscore is prepended. Examples: + .. code-block:: pycon + + >>> + >> tagToIdentifier('glyf') + '_g_l_y_f' + >> tagToIdentifier('cvt ') + '_c_v_t' + >> tagToIdentifier('OS/2') + 'O_S_2f_2' + """ + import re + + tag = Tag(tag) + if tag == "GlyphOrder": + return tag + assert len(tag) == 4, "tag should be 4 characters long" + while len(tag) > 1 and tag[-1] == " ": + tag = tag[:-1] + ident = "" + for c in tag: + ident = ident + _escapechar(c) + if re.match("[0-9]", ident): + ident = "_" + ident + return ident + + +def identifierToTag(ident: str) -> str: + """the opposite of tagToIdentifier()""" + if ident == "GlyphOrder": + return ident + if len(ident) % 2 and ident[0] == "_": + ident = ident[1:] + assert not (len(ident) % 2) + tag = "" + for i in range(0, len(ident), 2): + if ident[i] == "_": + tag = tag + ident[i + 1] + elif ident[i + 1] == "_": + tag = tag + ident[i] + else: + # assume hex + tag = tag + chr(int(ident[i : i + 2], 16)) + # append trailing spaces + tag = tag + (4 - len(tag)) * " " + return Tag(tag) + + +def tagToXML(tag: str | bytes) -> str: + """Similarly to tagToIdentifier(), this converts a TT tag + to a valid XML element name. Since XML element names are + case sensitive, this is a fairly simple/readable translation. + """ + import re + + tag = Tag(tag) + if tag == "OS/2": + return "OS_2" + elif tag == "GlyphOrder": + return tag + if re.match("[A-Za-z_][A-Za-z_0-9]* *$", tag): + return tag.strip() + else: + return tagToIdentifier(tag) + + +def xmlToTag(tag: str) -> str: + """The opposite of tagToXML()""" + if tag == "OS_2": + return Tag("OS/2") + if len(tag) == 8: + return identifierToTag(tag) + else: + return Tag(tag + " " * (4 - len(tag))) + + +# Table order as recommended in the OpenType specification 1.4 +TTFTableOrder = [ + "head", + "hhea", + "maxp", + "OS/2", + "hmtx", + "LTSH", + "VDMX", + "hdmx", + "cmap", + "fpgm", + "prep", + "cvt ", + "loca", + "glyf", + "kern", + "name", + "post", + "gasp", + "PCLT", +] + +OTFTableOrder = ["head", "hhea", "maxp", "OS/2", "name", "cmap", "post", "CFF "] + + +def sortedTagList( + tagList: Sequence[str], tableOrder: Sequence[str] | None = None +) -> list[str]: + """Return a sorted copy of tagList, sorted according to the OpenType + specification, or according to a custom tableOrder. If given and not + None, tableOrder needs to be a list of tag names. + """ + tagList = sorted(tagList) + if tableOrder is None: + if "DSIG" in tagList: + # DSIG should be last (XXX spec reference?) + tagList.remove("DSIG") + tagList.append("DSIG") + if "CFF " in tagList: + tableOrder = OTFTableOrder + else: + tableOrder = TTFTableOrder + orderedTables = [] + for tag in tableOrder: + if tag in tagList: + orderedTables.append(tag) + tagList.remove(tag) + orderedTables.extend(tagList) + return orderedTables + + +def reorderFontTables( + inFile: BinaryIO, # Takes file-like object as per original + outFile: BinaryIO, # Takes file-like object + tableOrder: Sequence[str] | None = None, + checkChecksums: bool = False, # Keep param even if reader handles it +) -> None: + """Rewrite a font file, ordering the tables as recommended by the + OpenType specification 1.4. + """ + inFile.seek(0) + outFile.seek(0) + reader = SFNTReader(inFile, checkChecksums=checkChecksums) + writer = SFNTWriter( + outFile, + len(reader.tables), + reader.sfntVersion, + reader.flavor, + reader.flavorData, + ) + tables = list(reader.keys()) + for tag in sortedTagList(tables, tableOrder): + writer[tag] = reader[tag] + writer.close() + + +def maxPowerOfTwo(x: int) -> int: + """Return the highest exponent of two, so that + (2 ** exponent) <= x. Return 0 if x is 0. + """ + exponent = 0 + while x: + x = x >> 1 + exponent = exponent + 1 + return max(exponent - 1, 0) + + +def getSearchRange(n: int, itemSize: int = 16) -> tuple[int, int, int]: + """Calculate searchRange, entrySelector, rangeShift.""" + # itemSize defaults to 16, for backward compatibility + # with upstream fonttools. + exponent = maxPowerOfTwo(n) + searchRange = (2**exponent) * itemSize + entrySelector = exponent + rangeShift = max(0, n * itemSize - searchRange) + return searchRange, entrySelector, rangeShift diff --git a/shared/package-files/01/01c2261cdf5dba16370b8e1256aaaf0e06ff7b43877bacb4d48d592f44751cc9/blob b/shared/package-files/01/01c2261cdf5dba16370b8e1256aaaf0e06ff7b43877bacb4d48d592f44751cc9/blob new file mode 100644 index 0000000000000000000000000000000000000000..0aecca58c305a24bc153fec8d72f03c946b7e191 --- /dev/null +++ b/shared/package-files/01/01c2261cdf5dba16370b8e1256aaaf0e06ff7b43877bacb4d48d592f44751cc9/blob @@ -0,0 +1,801 @@ +from .module import Module +from .utils import _pair, _quadruple, _ntuple +from .. import functional as F + +from torch import Tensor +from ..common_types import _size_2_t, _size_4_t, _size_6_t +from typing import Sequence, Tuple + + +# TODO: grad_output size asserts in THNN + +__all__ = ['CircularPad1d', 'CircularPad2d', 'CircularPad3d', 'ConstantPad1d', 'ConstantPad2d', + 'ConstantPad3d', 'ReflectionPad1d', 'ReflectionPad2d', 'ReflectionPad3d', + 'ReplicationPad1d', 'ReplicationPad2d', 'ReplicationPad3d', 'ZeroPad1d', 'ZeroPad2d', 'ZeroPad3d'] + + +class _CircularPadNd(Module): + __constants__ = ['padding'] + padding: Sequence[int] + + def _check_input_dim(self, input): + raise NotImplementedError + + def forward(self, input: Tensor) -> Tensor: + self._check_input_dim(input) + return F.pad(input, self.padding, 'circular') + + def extra_repr(self) -> str: + return f'{self.padding}' + + +class CircularPad1d(_CircularPadNd): + r"""Pads the input tensor using circular padding of the input boundary. + + Tensor values at the beginning of the dimension are used to pad the end, + and values at the end are used to pad the beginning. If negative padding is + applied then the ends of the tensor get removed. + + For `N`-dimensional padding, use :func:`torch.nn.functional.pad()`. + + Args: + padding (int, tuple): the size of the padding. If is `int`, uses the same + padding in all boundaries. If a 2-`tuple`, uses + (:math:`\text{padding\_left}`, :math:`\text{padding\_right}`) + + Shape: + - Input: :math:`(C, W_{in})` or :math:`(N, C, W_{in})`. + - Output: :math:`(C, W_{out})` or :math:`(N, C, W_{out})`, where + + :math:`W_{out} = W_{in} + \text{padding\_left} + \text{padding\_right}` + + Examples:: + + >>> # xdoctest: +IGNORE_WANT("not sure why xdoctest is choking on this") + >>> m = nn.CircularPad1d(2) + >>> input = torch.arange(8, dtype=torch.float).reshape(1, 2, 4) + >>> input + tensor([[[0., 1., 2., 3.], + [4., 5., 6., 7.]]]) + >>> m(input) + tensor([[[2., 3., 0., 1., 2., 3., 0., 1.], + [6., 7., 4., 5., 6., 7., 4., 5.]]]) + >>> # using different paddings for different sides + >>> m = nn.CircularPad1d((3, 1)) + >>> m(input) + tensor([[[1., 2., 3., 0., 1., 2., 3., 0.], + [5., 6., 7., 4., 5., 6., 7., 4.]]]) + """ + + padding: Tuple[int, int] + + def __init__(self, padding: _size_2_t) -> None: + super().__init__() + self.padding = _pair(padding) + + def _check_input_dim(self, input): + if input.dim() != 2 and input.dim() != 3: + raise ValueError( + f"expected 2D or 3D input (got {input.dim()}D input)" + ) + + +class CircularPad2d(_CircularPadNd): + r"""Pads the input tensor using circular padding of the input boundary. + + Tensor values at the beginning of the dimension are used to pad the end, + and values at the end are used to pad the beginning. If negative padding is + applied then the ends of the tensor get removed. + + For `N`-dimensional padding, use :func:`torch.nn.functional.pad()`. + + Args: + padding (int, tuple): the size of the padding. If is `int`, uses the same + padding in all boundaries. If a 4-`tuple`, uses (:math:`\text{padding\_left}`, + :math:`\text{padding\_right}`, :math:`\text{padding\_top}`, :math:`\text{padding\_bottom}`) + + Shape: + - Input: :math:`(N, C, H_{in}, W_{in})` or :math:`(C, H_{in}, W_{in})`. + - Output: :math:`(N, C, H_{out}, W_{out})` or :math:`(C, H_{out}, W_{out})`, where + + :math:`H_{out} = H_{in} + \text{padding\_top} + \text{padding\_bottom}` + + :math:`W_{out} = W_{in} + \text{padding\_left} + \text{padding\_right}` + + Examples:: + + >>> m = nn.CircularPad2d(2) + >>> input = torch.arange(9, dtype=torch.float).reshape(1, 1, 3, 3) + >>> input + tensor([[[[0., 1., 2.], + [3., 4., 5.], + [6., 7., 8.]]]]) + >>> m(input) + tensor([[[[4., 5., 3., 4., 5., 3., 4.], + [7., 8., 6., 7., 8., 6., 7.], + [1., 2., 0., 1., 2., 0., 1.], + [4., 5., 3., 4., 5., 3., 4.], + [7., 8., 6., 7., 8., 6., 7.], + [1., 2., 0., 1., 2., 0., 1.], + [4., 5., 3., 4., 5., 3., 4.]]]]) + >>> # using different paddings for different sides + >>> m = nn.CircularPad2d((1, 1, 2, 0)) + >>> m(input) + tensor([[[[5., 3., 4., 5., 3.], + [8., 6., 7., 8., 6.], + [2., 0., 1., 2., 0.], + [5., 3., 4., 5., 3.], + [8., 6., 7., 8., 6.]]]]) + """ + + padding: Tuple[int, int, int, int] + + def __init__(self, padding: _size_4_t) -> None: + super().__init__() + self.padding = _quadruple(padding) + + def _check_input_dim(self, input): + if input.dim() != 3 and input.dim() != 4: + raise ValueError( + f"expected 3D or 4D input (got {input.dim()}D input)" + ) + + +class CircularPad3d(_CircularPadNd): + r"""Pads the input tensor using circular padding of the input boundary. + + Tensor values at the beginning of the dimension are used to pad the end, + and values at the end are used to pad the beginning. If negative padding is + applied then the ends of the tensor get removed. + + For `N`-dimensional padding, use :func:`torch.nn.functional.pad()`. + + Args: + padding (int, tuple): the size of the padding. If is `int`, uses the same + padding in all boundaries. If a 6-`tuple`, uses + (:math:`\text{padding\_left}`, :math:`\text{padding\_right}`, + :math:`\text{padding\_top}`, :math:`\text{padding\_bottom}`, + :math:`\text{padding\_front}`, :math:`\text{padding\_back}`) + + Shape: + - Input: :math:`(N, C, D_{in}, H_{in}, W_{in})` or :math:`(C, D_{in}, H_{in}, W_{in})`. + - Output: :math:`(N, C, D_{out}, H_{out}, W_{out})` or :math:`(C, D_{out}, H_{out}, W_{out})`, + where + + :math:`D_{out} = D_{in} + \text{padding\_front} + \text{padding\_back}` + + :math:`H_{out} = H_{in} + \text{padding\_top} + \text{padding\_bottom}` + + :math:`W_{out} = W_{in} + \text{padding\_left} + \text{padding\_right}` + + Examples:: + + >>> # xdoctest: +IGNORE_WANT("non-deterministic") + >>> m = nn.CircularPad3d(3) + >>> input = torch.randn(16, 3, 8, 320, 480) + >>> output = m(input) + >>> # using different paddings for different sides + >>> m = nn.CircularPad3d((3, 3, 6, 6, 1, 1)) + >>> output = m(input) + """ + + padding: Tuple[int, int, int, int, int, int] + + def __init__(self, padding: _size_6_t) -> None: + super().__init__() + self.padding = _ntuple(6)(padding) + + def _check_input_dim(self, input): + if input.dim() != 4 and input.dim() != 5: + raise ValueError( + f"expected 4D or 5D input (got {input.dim()}D input)" + ) + + +class _ConstantPadNd(Module): + __constants__ = ['padding', 'value'] + value: float + padding: Sequence[int] + + def __init__(self, value: float) -> None: + super().__init__() + self.value = value + + def forward(self, input: Tensor) -> Tensor: + return F.pad(input, self.padding, 'constant', self.value) + + def extra_repr(self) -> str: + return f'padding={self.padding}, value={self.value}' + + +class ConstantPad1d(_ConstantPadNd): + r"""Pads the input tensor boundaries with a constant value. + + For `N`-dimensional padding, use :func:`torch.nn.functional.pad()`. + + Args: + padding (int, tuple): the size of the padding. If is `int`, uses the same + padding in both boundaries. If a 2-`tuple`, uses + (:math:`\text{padding\_left}`, :math:`\text{padding\_right}`) + + Shape: + - Input: :math:`(C, W_{in})` or :math:`(N, C, W_{in})`. + - Output: :math:`(C, W_{out})` or :math:`(N, C, W_{out})`, where + + :math:`W_{out} = W_{in} + \text{padding\_left} + \text{padding\_right}` + + Examples:: + + >>> # xdoctest: +IGNORE_WANT("non-deterministic") + >>> m = nn.ConstantPad1d(2, 3.5) + >>> input = torch.randn(1, 2, 4) + >>> input + tensor([[[-1.0491, -0.7152, -0.0749, 0.8530], + [-1.3287, 1.8966, 0.1466, -0.2771]]]) + >>> m(input) + tensor([[[ 3.5000, 3.5000, -1.0491, -0.7152, -0.0749, 0.8530, 3.5000, + 3.5000], + [ 3.5000, 3.5000, -1.3287, 1.8966, 0.1466, -0.2771, 3.5000, + 3.5000]]]) + >>> m = nn.ConstantPad1d(2, 3.5) + >>> input = torch.randn(1, 2, 3) + >>> input + tensor([[[ 1.6616, 1.4523, -1.1255], + [-3.6372, 0.1182, -1.8652]]]) + >>> m(input) + tensor([[[ 3.5000, 3.5000, 1.6616, 1.4523, -1.1255, 3.5000, 3.5000], + [ 3.5000, 3.5000, -3.6372, 0.1182, -1.8652, 3.5000, 3.5000]]]) + >>> # using different paddings for different sides + >>> m = nn.ConstantPad1d((3, 1), 3.5) + >>> m(input) + tensor([[[ 3.5000, 3.5000, 3.5000, 1.6616, 1.4523, -1.1255, 3.5000], + [ 3.5000, 3.5000, 3.5000, -3.6372, 0.1182, -1.8652, 3.5000]]]) + """ + + padding: Tuple[int, int] + + def __init__(self, padding: _size_2_t, value: float): + super().__init__(value) + self.padding = _pair(padding) + + +class ConstantPad2d(_ConstantPadNd): + r"""Pads the input tensor boundaries with a constant value. + + For `N`-dimensional padding, use :func:`torch.nn.functional.pad()`. + + Args: + padding (int, tuple): the size of the padding. If is `int`, uses the same + padding in all boundaries. If a 4-`tuple`, uses (:math:`\text{padding\_left}`, + :math:`\text{padding\_right}`, :math:`\text{padding\_top}`, :math:`\text{padding\_bottom}`) + + Shape: + - Input: :math:`(N, C, H_{in}, W_{in})` or :math:`(C, H_{in}, W_{in})`. + - Output: :math:`(N, C, H_{out}, W_{out})` or :math:`(C, H_{out}, W_{out})`, where + + :math:`H_{out} = H_{in} + \text{padding\_top} + \text{padding\_bottom}` + + :math:`W_{out} = W_{in} + \text{padding\_left} + \text{padding\_right}` + + Examples:: + + >>> # xdoctest: +IGNORE_WANT("non-deterministic") + >>> m = nn.ConstantPad2d(2, 3.5) + >>> input = torch.randn(1, 2, 2) + >>> input + tensor([[[ 1.6585, 0.4320], + [-0.8701, -0.4649]]]) + >>> m(input) + tensor([[[ 3.5000, 3.5000, 3.5000, 3.5000, 3.5000, 3.5000], + [ 3.5000, 3.5000, 3.5000, 3.5000, 3.5000, 3.5000], + [ 3.5000, 3.5000, 1.6585, 0.4320, 3.5000, 3.5000], + [ 3.5000, 3.5000, -0.8701, -0.4649, 3.5000, 3.5000], + [ 3.5000, 3.5000, 3.5000, 3.5000, 3.5000, 3.5000], + [ 3.5000, 3.5000, 3.5000, 3.5000, 3.5000, 3.5000]]]) + >>> # using different paddings for different sides + >>> m = nn.ConstantPad2d((3, 0, 2, 1), 3.5) + >>> m(input) + tensor([[[ 3.5000, 3.5000, 3.5000, 3.5000, 3.5000], + [ 3.5000, 3.5000, 3.5000, 3.5000, 3.5000], + [ 3.5000, 3.5000, 3.5000, 1.6585, 0.4320], + [ 3.5000, 3.5000, 3.5000, -0.8701, -0.4649], + [ 3.5000, 3.5000, 3.5000, 3.5000, 3.5000]]]) + """ + + __constants__ = ['padding', 'value'] + padding: Tuple[int, int, int, int] + + def __init__(self, padding: _size_4_t, value: float) -> None: + super().__init__(value) + self.padding = _quadruple(padding) + + +class ConstantPad3d(_ConstantPadNd): + r"""Pads the input tensor boundaries with a constant value. + + For `N`-dimensional padding, use :func:`torch.nn.functional.pad()`. + + Args: + padding (int, tuple): the size of the padding. If is `int`, uses the same + padding in all boundaries. If a 6-`tuple`, uses + (:math:`\text{padding\_left}`, :math:`\text{padding\_right}`, + :math:`\text{padding\_top}`, :math:`\text{padding\_bottom}`, + :math:`\text{padding\_front}`, :math:`\text{padding\_back}`) + + Shape: + - Input: :math:`(N, C, D_{in}, H_{in}, W_{in})` or :math:`(C, D_{in}, H_{in}, W_{in})`. + - Output: :math:`(N, C, D_{out}, H_{out}, W_{out})` or + :math:`(C, D_{out}, H_{out}, W_{out})`, where + + :math:`D_{out} = D_{in} + \text{padding\_front} + \text{padding\_back}` + + :math:`H_{out} = H_{in} + \text{padding\_top} + \text{padding\_bottom}` + + :math:`W_{out} = W_{in} + \text{padding\_left} + \text{padding\_right}` + + Examples:: + + >>> m = nn.ConstantPad3d(3, 3.5) + >>> input = torch.randn(16, 3, 10, 20, 30) + >>> output = m(input) + >>> # using different paddings for different sides + >>> m = nn.ConstantPad3d((3, 3, 6, 6, 0, 1), 3.5) + >>> output = m(input) + """ + + padding: Tuple[int, int, int, int, int, int] + + def __init__(self, padding: _size_6_t, value: float) -> None: + super().__init__(value) + self.padding = _ntuple(6)(padding) + + +class _ReflectionPadNd(Module): + __constants__ = ['padding'] + padding: Sequence[int] + + def forward(self, input: Tensor) -> Tensor: + return F.pad(input, self.padding, 'reflect') + + def extra_repr(self) -> str: + return f'{self.padding}' + + +class ReflectionPad1d(_ReflectionPadNd): + r"""Pads the input tensor using the reflection of the input boundary. + + For `N`-dimensional padding, use :func:`torch.nn.functional.pad()`. + + Args: + padding (int, tuple): the size of the padding. If is `int`, uses the same + padding in all boundaries. If a 2-`tuple`, uses + (:math:`\text{padding\_left}`, :math:`\text{padding\_right}`) + + Shape: + - Input: :math:`(C, W_{in})` or :math:`(N, C, W_{in})`. + - Output: :math:`(C, W_{out})` or :math:`(N, C, W_{out})`, where + + :math:`W_{out} = W_{in} + \text{padding\_left} + \text{padding\_right}` + + Examples:: + + >>> m = nn.ReflectionPad1d(2) + >>> # xdoctest: +IGNORE_WANT("other tests seem to modify printing styles") + >>> input = torch.arange(8, dtype=torch.float).reshape(1, 2, 4) + >>> input + tensor([[[0., 1., 2., 3.], + [4., 5., 6., 7.]]]) + >>> m(input) + tensor([[[2., 1., 0., 1., 2., 3., 2., 1.], + [6., 5., 4., 5., 6., 7., 6., 5.]]]) + >>> # using different paddings for different sides + >>> m = nn.ReflectionPad1d((3, 1)) + >>> m(input) + tensor([[[3., 2., 1., 0., 1., 2., 3., 2.], + [7., 6., 5., 4., 5., 6., 7., 6.]]]) + """ + + padding: Tuple[int, int] + + def __init__(self, padding: _size_2_t) -> None: + super().__init__() + self.padding = _pair(padding) + + +class ReflectionPad2d(_ReflectionPadNd): + r"""Pads the input tensor using the reflection of the input boundary. + + For `N`-dimensional padding, use :func:`torch.nn.functional.pad()`. + + Args: + padding (int, tuple): the size of the padding. If is `int`, uses the same + padding in all boundaries. If a 4-`tuple`, uses (:math:`\text{padding\_left}`, + :math:`\text{padding\_right}`, :math:`\text{padding\_top}`, :math:`\text{padding\_bottom}`) + Note that padding size should be less than the corresponding input dimension. + + Shape: + - Input: :math:`(N, C, H_{in}, W_{in})` or :math:`(C, H_{in}, W_{in})`. + - Output: :math:`(N, C, H_{out}, W_{out})` or :math:`(C, H_{out}, W_{out})` where + + :math:`H_{out} = H_{in} + \text{padding\_top} + \text{padding\_bottom}` + + :math:`W_{out} = W_{in} + \text{padding\_left} + \text{padding\_right}` + + Examples:: + + >>> # xdoctest: +IGNORE_WANT("not sure why xdoctest is choking on this") + >>> m = nn.ReflectionPad2d(2) + >>> input = torch.arange(9, dtype=torch.float).reshape(1, 1, 3, 3) + >>> input + tensor([[[[0., 1., 2.], + [3., 4., 5.], + [6., 7., 8.]]]]) + >>> m(input) + tensor([[[[8., 7., 6., 7., 8., 7., 6.], + [5., 4., 3., 4., 5., 4., 3.], + [2., 1., 0., 1., 2., 1., 0.], + [5., 4., 3., 4., 5., 4., 3.], + [8., 7., 6., 7., 8., 7., 6.], + [5., 4., 3., 4., 5., 4., 3.], + [2., 1., 0., 1., 2., 1., 0.]]]]) + >>> # using different paddings for different sides + >>> m = nn.ReflectionPad2d((1, 1, 2, 0)) + >>> m(input) + tensor([[[[7., 6., 7., 8., 7.], + [4., 3., 4., 5., 4.], + [1., 0., 1., 2., 1.], + [4., 3., 4., 5., 4.], + [7., 6., 7., 8., 7.]]]]) + """ + + padding: Tuple[int, int, int, int] + + def __init__(self, padding: _size_4_t) -> None: + super().__init__() + self.padding = _quadruple(padding) + + +class ReflectionPad3d(_ReflectionPadNd): + r"""Pads the input tensor using the reflection of the input boundary. + + For `N`-dimensional padding, use :func:`torch.nn.functional.pad()`. + + Args: + padding (int, tuple): the size of the padding. If is `int`, uses the same + padding in all boundaries. If a 6-`tuple`, uses + (:math:`\text{padding\_left}`, :math:`\text{padding\_right}`, + :math:`\text{padding\_top}`, :math:`\text{padding\_bottom}`, + :math:`\text{padding\_front}`, :math:`\text{padding\_back}`) + + Shape: + - Input: :math:`(N, C, D_{in}, H_{in}, W_{in})` or :math:`(C, D_{in}, H_{in}, W_{in})`. + - Output: :math:`(N, C, D_{out}, H_{out}, W_{out})` or :math:`(C, D_{out}, H_{out}, W_{out})`, + where + + :math:`D_{out} = D_{in} + \text{padding\_front} + \text{padding\_back}` + + :math:`H_{out} = H_{in} + \text{padding\_top} + \text{padding\_bottom}` + + :math:`W_{out} = W_{in} + \text{padding\_left} + \text{padding\_right}` + + Examples:: + + >>> # xdoctest: +IGNORE_WANT("not sure why xdoctest is choking on this") + >>> m = nn.ReflectionPad3d(1) + >>> input = torch.arange(8, dtype=torch.float).reshape(1, 1, 2, 2, 2) + >>> m(input) + tensor([[[[[7., 6., 7., 6.], + [5., 4., 5., 4.], + [7., 6., 7., 6.], + [5., 4., 5., 4.]], + [[3., 2., 3., 2.], + [1., 0., 1., 0.], + [3., 2., 3., 2.], + [1., 0., 1., 0.]], + [[7., 6., 7., 6.], + [5., 4., 5., 4.], + [7., 6., 7., 6.], + [5., 4., 5., 4.]], + [[3., 2., 3., 2.], + [1., 0., 1., 0.], + [3., 2., 3., 2.], + [1., 0., 1., 0.]]]]]) + """ + + padding: Tuple[int, int, int, int, int, int] + + def __init__(self, padding: _size_6_t) -> None: + super().__init__() + self.padding = _ntuple(6)(padding) + + +class _ReplicationPadNd(Module): + __constants__ = ['padding'] + padding: Sequence[int] + + def forward(self, input: Tensor) -> Tensor: + return F.pad(input, self.padding, 'replicate') + + def extra_repr(self) -> str: + return f'{self.padding}' + + +class ReplicationPad1d(_ReplicationPadNd): + r"""Pads the input tensor using replication of the input boundary. + + For `N`-dimensional padding, use :func:`torch.nn.functional.pad()`. + + Args: + padding (int, tuple): the size of the padding. If is `int`, uses the same + padding in all boundaries. If a 2-`tuple`, uses + (:math:`\text{padding\_left}`, :math:`\text{padding\_right}`) + + Shape: + - Input: :math:`(C, W_{in})` or :math:`(N, C, W_{in})`. + - Output: :math:`(C, W_{out})` or :math:`(N, C, W_{out})`, where + + :math:`W_{out} = W_{in} + \text{padding\_left} + \text{padding\_right}` + + Examples:: + + >>> # xdoctest: +IGNORE_WANT("not sure why xdoctest is choking on this") + >>> m = nn.ReplicationPad1d(2) + >>> input = torch.arange(8, dtype=torch.float).reshape(1, 2, 4) + >>> input + tensor([[[0., 1., 2., 3.], + [4., 5., 6., 7.]]]) + >>> m(input) + tensor([[[0., 0., 0., 1., 2., 3., 3., 3.], + [4., 4., 4., 5., 6., 7., 7., 7.]]]) + >>> # using different paddings for different sides + >>> m = nn.ReplicationPad1d((3, 1)) + >>> m(input) + tensor([[[0., 0., 0., 0., 1., 2., 3., 3.], + [4., 4., 4., 4., 5., 6., 7., 7.]]]) + """ + + padding: Tuple[int, int] + + def __init__(self, padding: _size_2_t) -> None: + super().__init__() + self.padding = _pair(padding) + + +class ReplicationPad2d(_ReplicationPadNd): + r"""Pads the input tensor using replication of the input boundary. + + For `N`-dimensional padding, use :func:`torch.nn.functional.pad()`. + + Args: + padding (int, tuple): the size of the padding. If is `int`, uses the same + padding in all boundaries. If a 4-`tuple`, uses (:math:`\text{padding\_left}`, + :math:`\text{padding\_right}`, :math:`\text{padding\_top}`, :math:`\text{padding\_bottom}`) + + Shape: + - Input: :math:`(N, C, H_{in}, W_{in})` or :math:`(C, H_{in}, W_{in})`. + - Output: :math:`(N, C, H_{out}, W_{out})` or :math:`(C, H_{out}, W_{out})`, where + + :math:`H_{out} = H_{in} + \text{padding\_top} + \text{padding\_bottom}` + + :math:`W_{out} = W_{in} + \text{padding\_left} + \text{padding\_right}` + + Examples:: + + >>> m = nn.ReplicationPad2d(2) + >>> # xdoctest: +IGNORE_WANT("non-deterministic") + >>> input = torch.arange(9, dtype=torch.float).reshape(1, 1, 3, 3) + >>> input + tensor([[[[0., 1., 2.], + [3., 4., 5.], + [6., 7., 8.]]]]) + >>> m(input) + tensor([[[[0., 0., 0., 1., 2., 2., 2.], + [0., 0., 0., 1., 2., 2., 2.], + [0., 0., 0., 1., 2., 2., 2.], + [3., 3., 3., 4., 5., 5., 5.], + [6., 6., 6., 7., 8., 8., 8.], + [6., 6., 6., 7., 8., 8., 8.], + [6., 6., 6., 7., 8., 8., 8.]]]]) + >>> # using different paddings for different sides + >>> m = nn.ReplicationPad2d((1, 1, 2, 0)) + >>> m(input) + tensor([[[[0., 0., 1., 2., 2.], + [0., 0., 1., 2., 2.], + [0., 0., 1., 2., 2.], + [3., 3., 4., 5., 5.], + [6., 6., 7., 8., 8.]]]]) + """ + + padding: Tuple[int, int, int, int] + + def __init__(self, padding: _size_4_t) -> None: + super().__init__() + self.padding = _quadruple(padding) + + +class ReplicationPad3d(_ReplicationPadNd): + r"""Pads the input tensor using replication of the input boundary. + + For `N`-dimensional padding, use :func:`torch.nn.functional.pad()`. + + Args: + padding (int, tuple): the size of the padding. If is `int`, uses the same + padding in all boundaries. If a 6-`tuple`, uses + (:math:`\text{padding\_left}`, :math:`\text{padding\_right}`, + :math:`\text{padding\_top}`, :math:`\text{padding\_bottom}`, + :math:`\text{padding\_front}`, :math:`\text{padding\_back}`) + + Shape: + - Input: :math:`(N, C, D_{in}, H_{in}, W_{in})` or :math:`(C, D_{in}, H_{in}, W_{in})`. + - Output: :math:`(N, C, D_{out}, H_{out}, W_{out})` or :math:`(C, D_{out}, H_{out}, W_{out})`, + where + + :math:`D_{out} = D_{in} + \text{padding\_front} + \text{padding\_back}` + + :math:`H_{out} = H_{in} + \text{padding\_top} + \text{padding\_bottom}` + + :math:`W_{out} = W_{in} + \text{padding\_left} + \text{padding\_right}` + + Examples:: + + >>> # xdoctest: +IGNORE_WANT("non-deterministic") + >>> m = nn.ReplicationPad3d(3) + >>> input = torch.randn(16, 3, 8, 320, 480) + >>> output = m(input) + >>> # using different paddings for different sides + >>> m = nn.ReplicationPad3d((3, 3, 6, 6, 1, 1)) + >>> output = m(input) + """ + + padding: Tuple[int, int, int, int, int, int] + + def __init__(self, padding: _size_6_t) -> None: + super().__init__() + self.padding = _ntuple(6)(padding) + + +class ZeroPad1d(ConstantPad1d): + r"""Pads the input tensor boundaries with zero. + + For `N`-dimensional padding, use :func:`torch.nn.functional.pad()`. + + Args: + padding (int, tuple): the size of the padding. If is `int`, uses the same + padding in both boundaries. If a 2-`tuple`, uses + (:math:`\text{padding\_left}`, :math:`\text{padding\_right}`) + + Shape: + - Input: :math:`(C, W_{in})` or :math:`(N, C, W_{in})`. + - Output: :math:`(C, W_{out})` or :math:`(N, C, W_{out})`, where + + :math:`W_{out} = W_{in} + \text{padding\_left} + \text{padding\_right}` + + Examples:: + + >>> # xdoctest: +IGNORE_WANT("non-deterministic") + >>> m = nn.ZeroPad1d(2) + >>> input = torch.randn(1, 2, 4) + >>> input + tensor([[[-1.0491, -0.7152, -0.0749, 0.8530], + [-1.3287, 1.8966, 0.1466, -0.2771]]]) + >>> m(input) + tensor([[[ 0.0000, 0.0000, -1.0491, -0.7152, -0.0749, 0.8530, 0.0000, + 0.0000], + [ 0.0000, 0.0000, -1.3287, 1.8966, 0.1466, -0.2771, 0.0000, + 0.0000]]]) + >>> m = nn.ZeroPad1d(2) + >>> input = torch.randn(1, 2, 3) + >>> input + tensor([[[ 1.6616, 1.4523, -1.1255], + [-3.6372, 0.1182, -1.8652]]]) + >>> m(input) + tensor([[[ 0.0000, 0.0000, 1.6616, 1.4523, -1.1255, 0.0000, 0.0000], + [ 0.0000, 0.0000, -3.6372, 0.1182, -1.8652, 0.0000, 0.0000]]]) + >>> # using different paddings for different sides + >>> m = nn.ZeroPad1d((3, 1)) + >>> m(input) + tensor([[[ 0.0000, 0.0000, 0.0000, 1.6616, 1.4523, -1.1255, 0.0000], + [ 0.0000, 0.0000, 0.0000, -3.6372, 0.1182, -1.8652, 0.0000]]]) + """ + + padding: Tuple[int, int] + + def __init__(self, padding: _size_2_t) -> None: + super().__init__(padding, 0.) + + def extra_repr(self) -> str: + return f'{self.padding}' + +class ZeroPad2d(ConstantPad2d): + r"""Pads the input tensor boundaries with zero. + + For `N`-dimensional padding, use :func:`torch.nn.functional.pad()`. + + Args: + padding (int, tuple): the size of the padding. If is `int`, uses the same + padding in all boundaries. If a 4-`tuple`, uses (:math:`\text{padding\_left}`, + :math:`\text{padding\_right}`, :math:`\text{padding\_top}`, :math:`\text{padding\_bottom}`) + + Shape: + - Input: :math:`(N, C, H_{in}, W_{in})` or :math:`(C, H_{in}, W_{in})`. + - Output: :math:`(N, C, H_{out}, W_{out})` or :math:`(C, H_{out}, W_{out})`, where + + :math:`H_{out} = H_{in} + \text{padding\_top} + \text{padding\_bottom}` + + :math:`W_{out} = W_{in} + \text{padding\_left} + \text{padding\_right}` + + Examples:: + + >>> # xdoctest: +IGNORE_WANT("non-deterministic") + >>> m = nn.ZeroPad2d(2) + >>> input = torch.randn(1, 1, 3, 3) + >>> input + tensor([[[[-0.1678, -0.4418, 1.9466], + [ 0.9604, -0.4219, -0.5241], + [-0.9162, -0.5436, -0.6446]]]]) + >>> m(input) + tensor([[[[ 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000], + [ 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000], + [ 0.0000, 0.0000, -0.1678, -0.4418, 1.9466, 0.0000, 0.0000], + [ 0.0000, 0.0000, 0.9604, -0.4219, -0.5241, 0.0000, 0.0000], + [ 0.0000, 0.0000, -0.9162, -0.5436, -0.6446, 0.0000, 0.0000], + [ 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000], + [ 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000]]]]) + >>> # using different paddings for different sides + >>> m = nn.ZeroPad2d((1, 1, 2, 0)) + >>> m(input) + tensor([[[[ 0.0000, 0.0000, 0.0000, 0.0000, 0.0000], + [ 0.0000, 0.0000, 0.0000, 0.0000, 0.0000], + [ 0.0000, -0.1678, -0.4418, 1.9466, 0.0000], + [ 0.0000, 0.9604, -0.4219, -0.5241, 0.0000], + [ 0.0000, -0.9162, -0.5436, -0.6446, 0.0000]]]]) + """ + + padding: Tuple[int, int, int, int] + + def __init__(self, padding: _size_4_t) -> None: + super().__init__(padding, 0.) + + def extra_repr(self) -> str: + return f'{self.padding}' + +class ZeroPad3d(ConstantPad3d): + r"""Pads the input tensor boundaries with zero. + + For `N`-dimensional padding, use :func:`torch.nn.functional.pad()`. + + Args: + padding (int, tuple): the size of the padding. If is `int`, uses the same + padding in all boundaries. If a 6-`tuple`, uses + (:math:`\text{padding\_left}`, :math:`\text{padding\_right}`, + :math:`\text{padding\_top}`, :math:`\text{padding\_bottom}`, + :math:`\text{padding\_front}`, :math:`\text{padding\_back}`) + + Shape: + - Input: :math:`(N, C, D_{in}, H_{in}, W_{in})` or :math:`(C, D_{in}, H_{in}, W_{in})`. + - Output: :math:`(N, C, D_{out}, H_{out}, W_{out})` or + :math:`(C, D_{out}, H_{out}, W_{out})`, where + + :math:`D_{out} = D_{in} + \text{padding\_front} + \text{padding\_back}` + + :math:`H_{out} = H_{in} + \text{padding\_top} + \text{padding\_bottom}` + + :math:`W_{out} = W_{in} + \text{padding\_left} + \text{padding\_right}` + + Examples:: + + >>> m = nn.ZeroPad3d(3) + >>> input = torch.randn(16, 3, 10, 20, 30) + >>> output = m(input) + >>> # using different paddings for different sides + >>> m = nn.ZeroPad3d((3, 3, 6, 6, 0, 1)) + >>> output = m(input) + """ + + padding: Tuple[int, int, int, int, int, int] + + def __init__(self, padding: _size_6_t) -> None: + super().__init__(padding, 0.) + + def extra_repr(self) -> str: + return f'{self.padding}' diff --git a/shared/package-files/01/01c54018e8006762dfb2a1e172c62075c0ee1f7cf0848bd2a82801e9b1ebba74/blob b/shared/package-files/01/01c54018e8006762dfb2a1e172c62075c0ee1f7cf0848bd2a82801e9b1ebba74/blob new file mode 100644 index 0000000000000000000000000000000000000000..4513a3ed1f1735288d6244b007c3cb61b0acd815 Binary files /dev/null and b/shared/package-files/01/01c54018e8006762dfb2a1e172c62075c0ee1f7cf0848bd2a82801e9b1ebba74/blob differ diff --git a/shared/package-files/01/01c5c8af8cb64df4a61bc7b791549f8d0e7658b998a9e9765d6f17da176a60f0/blob b/shared/package-files/01/01c5c8af8cb64df4a61bc7b791549f8d0e7658b998a9e9765d6f17da176a60f0/blob new file mode 100644 index 0000000000000000000000000000000000000000..4399ed8a96e20baa407a7bda3614d6ca9e0a0e63 Binary files /dev/null and b/shared/package-files/01/01c5c8af8cb64df4a61bc7b791549f8d0e7658b998a9e9765d6f17da176a60f0/blob differ diff --git a/shared/package-files/01/01c845a11b07d7a69214dfa709016e006a49bc1ce6cd23515faee11187192df2/blob b/shared/package-files/01/01c845a11b07d7a69214dfa709016e006a49bc1ce6cd23515faee11187192df2/blob new file mode 100644 index 0000000000000000000000000000000000000000..8ab17751f63d36d2ff36e4028ff0372385d56e99 --- /dev/null +++ b/shared/package-files/01/01c845a11b07d7a69214dfa709016e006a49bc1ce6cd23515faee11187192df2/blob @@ -0,0 +1,23 @@ +#pragma once +// @generated by torchgen/gen.py from DispatchKeyFunction.h + +// NB: The implementing C++ file is RegisterDispatchKey.cpp + +// The only #includes we need are for custom classes that have defaults in the C++ API +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { + +namespace cpu { + +TORCH_API at::Tensor & exponential_(at::Tensor & self, double lambd=1, c10::optional generator=c10::nullopt); + +} // namespace cpu +} // namespace at diff --git a/shared/package-files/01/01d085db8e2882eb8f9c57c8ec9184f9c723a391a3889965c61f68bf665b19c0/blob b/shared/package-files/01/01d085db8e2882eb8f9c57c8ec9184f9c723a391a3889965c61f68bf665b19c0/blob new file mode 100644 index 0000000000000000000000000000000000000000..594af3b59ccfb046cafa0bed42972d3998c1c6d2 --- /dev/null +++ b/shared/package-files/01/01d085db8e2882eb8f9c57c8ec9184f9c723a391a3889965c61f68bf665b19c0/blob @@ -0,0 +1,23 @@ +#pragma once + +// @generated by torchgen/gen.py from NativeFunction.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + +namespace at { +namespace native { +TORCH_API at::Tensor & _sparse_sparse_matmul_out(const at::Tensor & self, const at::Tensor & other, at::Tensor & out); +TORCH_API at::Tensor sparse_sparse_matmul_cpu(const at::Tensor & self, const at::Tensor & other); +TORCH_API at::Tensor sparse_sparse_matmul_cuda(const at::Tensor & self, const at::Tensor & other); +} // namespace native +} // namespace at diff --git a/shared/package-files/01/01d34359ebbeea494634cf8ec1d5dd5e2c53269b26384a71f8a1119829e9fbae/blob b/shared/package-files/01/01d34359ebbeea494634cf8ec1d5dd5e2c53269b26384a71f8a1119829e9fbae/blob new file mode 100644 index 0000000000000000000000000000000000000000..7a2712750b39dbfa9c9b717ac4187e452f7286df --- /dev/null +++ b/shared/package-files/01/01d34359ebbeea494634cf8ec1d5dd5e2c53269b26384a71f8a1119829e9fbae/blob @@ -0,0 +1,29 @@ +#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 bitwise_left_shift(const at::Tensor & self, const at::Scalar & other); +TORCH_API at::Tensor & bitwise_left_shift_out(at::Tensor & out, const at::Tensor & self, const at::Scalar & other); +TORCH_API at::Tensor & bitwise_left_shift_outf(const at::Tensor & self, const at::Scalar & other, at::Tensor & out); +TORCH_API at::Tensor & bitwise_left_shift_(at::Tensor & self, const at::Scalar & other); +TORCH_API at::Tensor bitwise_left_shift(const at::Scalar & self, const at::Tensor & other); +TORCH_API at::Tensor & bitwise_left_shift_out(at::Tensor & out, const at::Scalar & self, const at::Tensor & other); +TORCH_API at::Tensor & bitwise_left_shift_outf(const at::Scalar & self, const at::Tensor & other, at::Tensor & out); + +} // namespace compositeexplicitautograd +} // namespace at diff --git a/shared/package-files/01/01d44aaf573f8474c8b90378709815734e2f64a9477e78d0b214ba5d4126d246/blob b/shared/package-files/01/01d44aaf573f8474c8b90378709815734e2f64a9477e78d0b214ba5d4126d246/blob new file mode 100644 index 0000000000000000000000000000000000000000..94340a85aea2b35fced73a0bd5c0c500890a8673 Binary files /dev/null and b/shared/package-files/01/01d44aaf573f8474c8b90378709815734e2f64a9477e78d0b214ba5d4126d246/blob differ diff --git a/shared/package-files/01/01d4f4cafcf54da898d269face5b7f113dc32ac4f2c15563904ac2efaf5ce8bd/blob b/shared/package-files/01/01d4f4cafcf54da898d269face5b7f113dc32ac4f2c15563904ac2efaf5ce8bd/blob new file mode 100644 index 0000000000000000000000000000000000000000..683eda0f22c75a4c793d76f66b81d17faf93b687 --- /dev/null +++ b/shared/package-files/01/01d4f4cafcf54da898d269face5b7f113dc32ac4f2c15563904ac2efaf5ce8bd/blob @@ -0,0 +1,27 @@ +from typing import Any + +def is_known_charset(charset): ... + +class JSONRequestMixin: + def json(self): ... + +class ProtobufRequestMixin: + protobuf_check_initialization: Any + def parse_protobuf(self, proto_type): ... + +class RoutingArgsRequestMixin: + routing_args: Any + routing_vars: Any + +class ReverseSlashBehaviorRequestMixin: + def path(self): ... + def script_root(self): ... + +class DynamicCharsetRequestMixin: + default_charset: Any + def unknown_charset(self, charset): ... + def charset(self): ... + +class DynamicCharsetResponseMixin: + default_charset: Any + charset: Any diff --git a/shared/package-files/01/01d50bc69fc20d9275b61ce0aecff425b26cd9d91c6bc6b9f8e8a6864aa1df6b/blob b/shared/package-files/01/01d50bc69fc20d9275b61ce0aecff425b26cd9d91c6bc6b9f8e8a6864aa1df6b/blob new file mode 100644 index 0000000000000000000000000000000000000000..c8fe713a70b303427775e242fe2ce2259ec7558a --- /dev/null +++ b/shared/package-files/01/01d50bc69fc20d9275b61ce0aecff425b26cd9d91c6bc6b9f8e8a6864aa1df6b/blob @@ -0,0 +1,120 @@ +""" +Sends updates to a Slack app. + +Usage: +>>> from tqdm.contrib.slack import tqdm, trange +>>> for i in trange(10, token='{token}', channel='{channel}'): +... ... + +![screenshot](https://img.tqdm.ml/screenshot-slack.png) +""" +import logging +from os import getenv + +try: + from slack_sdk import WebClient +except ImportError: + raise ImportError("Please `pip install slack-sdk`") + +from ..auto import tqdm as tqdm_auto +from .utils_worker import MonoWorker + +__author__ = {"github.com/": ["0x2b3bfa0", "casperdcl"]} +__all__ = ['SlackIO', 'tqdm_slack', 'tsrange', 'tqdm', 'trange'] + + +class SlackIO(MonoWorker): + """Non-blocking file-like IO using a Slack app.""" + def __init__(self, token, channel): + """Creates a new message in the given `channel`.""" + super(SlackIO, self).__init__() + self.client = WebClient(token=token) + self.text = self.__class__.__name__ + try: + self.message = self.client.chat_postMessage(channel=channel, text=self.text) + except Exception as e: + tqdm_auto.write(str(e)) + self.message = None + + def write(self, s): + """Replaces internal `message`'s text with `s`.""" + if not s: + s = "..." + s = s.replace('\r', '').strip() + if s == self.text: + return # skip duplicate message + message = self.message + if message is None: + return + self.text = s + try: + future = self.submit(self.client.chat_update, channel=message['channel'], + ts=message['ts'], text='`' + s + '`') + except Exception as e: + tqdm_auto.write(str(e)) + else: + return future + + +class tqdm_slack(tqdm_auto): + """ + Standard `tqdm.auto.tqdm` but also sends updates to a Slack app. + May take a few seconds to create (`__init__`). + + - create a Slack app with the `chat:write` scope & invite it to a + channel: + - copy the bot `{token}` & `{channel}` and paste below + >>> from tqdm.contrib.slack import tqdm, trange + >>> for i in tqdm(iterable, token='{token}', channel='{channel}'): + ... ... + """ + def __init__(self, *args, **kwargs): + """ + Parameters + ---------- + token : str, required. Slack token + [default: ${TQDM_SLACK_TOKEN}]. + channel : int, required. Slack channel + [default: ${TQDM_SLACK_CHANNEL}]. + mininterval : float, optional. + Minimum of [default: 1.5] to avoid rate limit. + + See `tqdm.auto.tqdm.__init__` for other parameters. + """ + if not kwargs.get('disable'): + kwargs = kwargs.copy() + logging.getLogger("HTTPClient").setLevel(logging.WARNING) + self.sio = SlackIO( + kwargs.pop('token', getenv("TQDM_SLACK_TOKEN")), + kwargs.pop('channel', getenv("TQDM_SLACK_CHANNEL"))) + kwargs['mininterval'] = max(1.5, kwargs.get('mininterval', 1.5)) + super(tqdm_slack, self).__init__(*args, **kwargs) + + def display(self, **kwargs): + super(tqdm_slack, self).display(**kwargs) + fmt = self.format_dict + if fmt.get('bar_format', None): + fmt['bar_format'] = fmt['bar_format'].replace( + '', '`{bar:10}`').replace('{bar}', '`{bar:10u}`') + else: + fmt['bar_format'] = '{l_bar}`{bar:10}`{r_bar}' + if fmt['ascii'] is False: + fmt['ascii'] = [":black_square:", ":small_blue_diamond:", ":large_blue_diamond:", + ":large_blue_square:"] + fmt['ncols'] = 336 + self.sio.write(self.format_meter(**fmt)) + + def clear(self, *args, **kwargs): + super(tqdm_slack, self).clear(*args, **kwargs) + if not self.disable: + self.sio.write("") + + +def tsrange(*args, **kwargs): + """Shortcut for `tqdm.contrib.slack.tqdm(range(*args), **kwargs)`.""" + return tqdm_slack(range(*args), **kwargs) + + +# Aliases +tqdm = tqdm_slack +trange = tsrange diff --git a/shared/package-files/01/01d5bcff0c3fe3f3a1e6e9dd9405e2354245e9e94a6002c8c9cfdc30c26caa98/blob b/shared/package-files/01/01d5bcff0c3fe3f3a1e6e9dd9405e2354245e9e94a6002c8c9cfdc30c26caa98/blob new file mode 100644 index 0000000000000000000000000000000000000000..1aa9ffb96fa26026ebe77db42e93679f547a70ba --- /dev/null +++ b/shared/package-files/01/01d5bcff0c3fe3f3a1e6e9dd9405e2354245e9e94a6002c8c9cfdc30c26caa98/blob @@ -0,0 +1,42 @@ +import sys +from typing import Any, Text, TypeVar, Union + +ucd_3_2_0: UCD +ucnhash_CAPI: Any +unidata_version: str + +_default = TypeVar("_default") + +def bidirectional(__chr: Text) -> Text: ... +def category(__chr: Text) -> Text: ... +def combining(__chr: Text) -> int: ... +def decimal(__chr: Text, __default: _default = ...) -> Union[int, _default]: ... +def decomposition(__chr: Text) -> Text: ... +def digit(__chr: Text, __default: _default = ...) -> Union[int, _default]: ... +def east_asian_width(__chr: Text) -> Text: ... + +if sys.version_info >= (3, 8): + def is_normalized(__form: str, __unistr: str) -> bool: ... + +def lookup(__name: Union[Text, bytes]) -> Text: ... +def mirrored(__chr: Text) -> int: ... +def name(__chr: Text, __default: _default = ...) -> Union[Text, _default]: ... +def normalize(__form: Text, __unistr: Text) -> Text: ... +def numeric(__chr: Text, __default: _default = ...) -> Union[float, _default]: ... + +class UCD(object): + # The methods below are constructed from the same array in C + # (unicodedata_functions) and hence identical to the methods above. + unidata_version: str + def bidirectional(self, __chr: Text) -> str: ... + def category(self, __chr: Text) -> str: ... + def combining(self, __chr: Text) -> int: ... + def decimal(self, __chr: Text, __default: _default = ...) -> Union[int, _default]: ... + def decomposition(self, __chr: Text) -> str: ... + def digit(self, __chr: Text, __default: _default = ...) -> Union[int, _default]: ... + def east_asian_width(self, __chr: Text) -> str: ... + def lookup(self, __name: Union[Text, bytes]) -> Text: ... + def mirrored(self, __chr: Text) -> int: ... + def name(self, __chr: Text, __default: _default = ...) -> Union[Text, _default]: ... + def normalize(self, __form: Text, __unistr: Text) -> Text: ... + def numeric(self, __chr: Text, __default: _default = ...) -> Union[float, _default]: ... diff --git a/shared/package-files/01/01d656a85bda9d2c11867ce514af6fca12c35e8329cbd8307d6f5d8519f4c4de/blob b/shared/package-files/01/01d656a85bda9d2c11867ce514af6fca12c35e8329cbd8307d6f5d8519f4c4de/blob new file mode 100644 index 0000000000000000000000000000000000000000..38a7804015be1822f4012f74319a459daeb5e885 --- /dev/null +++ b/shared/package-files/01/01d656a85bda9d2c11867ce514af6fca12c35e8329cbd8307d6f5d8519f4c4de/blob @@ -0,0 +1,25 @@ +#pragma once + +namespace at { namespace native { +#if defined(USE_ROCM) +// take these out when ROCm implements std:: math functions +#include +template +static __forceinline__ __device__ scalar_t device_sqrt(scalar_t val); + +template <> +__forceinline__ __device__ float device_sqrt(float val) { + return ::sqrtf(val); +} + +template <> +__forceinline__ __device__ double device_sqrt(double val) { + return ::sqrt(val); +} +#else +template +__forceinline__ __device__ double device_sqrt(scalar_t val) { + return std::sqrt(val); +} +#endif +}} diff --git a/shared/package-files/01/01df026c4ba31f1a96a6df39f6cb2e2a31710de639c493c0243cb19092df2bdc/blob b/shared/package-files/01/01df026c4ba31f1a96a6df39f6cb2e2a31710de639c493c0243cb19092df2bdc/blob new file mode 100644 index 0000000000000000000000000000000000000000..15af0241ec5b083d5e61847b611f1d5c66c3e02d --- /dev/null +++ b/shared/package-files/01/01df026c4ba31f1a96a6df39f6cb2e2a31710de639c493c0243cb19092df2bdc/blob @@ -0,0 +1,348 @@ +from torch.fx.experimental.migrate_gradual_types.constraint import Conj, Disj, T, F, BinConstraintT, BVar, is_bool_expr +from torch.fx.experimental.migrate_gradual_types.constraint import BinConstraintD, TVar, DVar +from torch.fx.experimental.migrate_gradual_types.constraint import Prod, is_algebraic_expression, is_dim +from torch.fx.experimental.migrate_gradual_types.constraint_generator import ConstraintGenerator +from torch.fx.experimental.migrate_gradual_types.constraint_transformation import transform_constraint +from torch.fx.experimental.migrate_gradual_types.operation import op_add, op_eq, op_neq, op_gt, op_lt +from torch.fx.experimental.migrate_gradual_types.operation import op_leq, op_sub, op_div, op_mul, op_mod +from torch.fx.tensor_type import TensorType, Dyn + +try: + import z3 # type: ignore[import] + from torch.fx.experimental.migrate_gradual_types.z3_types import tensor_type, z3_dyn, D + HAS_Z3 = True + + def transform_to_z3(constraint, counter, dimension_dict): + if isinstance(constraint, Conj): + conjuncts = [] + for c in constraint.conjucts: + new_c, counter = transform_to_z3(c, counter, dimension_dict) + conjuncts.append(new_c) + return z3.And(conjuncts), counter + + elif isinstance(constraint, Disj): + disjuncts = [] + for c in constraint.disjuncts: + new_c, counter = transform_to_z3(c, counter, dimension_dict) + disjuncts.append(new_c) + return z3.Or(disjuncts), counter + + elif isinstance(constraint, T): + return True, counter + + elif isinstance(constraint, F): + return False, counter + + elif isinstance(constraint, BinConstraintT): + if constraint.op == op_eq: + lhs, counter = transform_var(constraint.lhs, counter, dimension_dict) + rhs, counter = transform_var(constraint.rhs, counter, dimension_dict) + return (lhs == rhs), counter + + else: + raise NotImplementedError('Method not yet implemented') + + elif isinstance(constraint, BinConstraintD): + if constraint.op == op_eq: + + if isinstance(constraint.lhs, BVar) and is_bool_expr(constraint.rhs): + transformed_rhs, counter = transform_to_z3(constraint.rhs, counter, dimension_dict) + transformed_lhs = z3.Bool(constraint.lhs.c) + return transformed_lhs == transformed_rhs, counter + + elif is_dim(constraint.lhs) and is_dim(constraint.rhs): + # with dimension transformations we consider the encoding + lhs, counter = transform_dimension(constraint.lhs, counter, dimension_dict) + rhs, counter = transform_dimension(constraint.rhs, counter, dimension_dict) + return lhs == rhs, counter + + else: + # then we have an algebraic expression which means that we disregard the + # first element of the encoding + lhs, counter = transform_algebraic_expression(constraint.lhs, counter, dimension_dict) + rhs, counter = transform_algebraic_expression(constraint.rhs, counter, dimension_dict) + return lhs == rhs, counter + + # The assumption here is that the LHS and RHS must be dimensions + elif constraint.op == op_neq: + assert is_dim(constraint.lhs) + assert is_dim(constraint.rhs) + lhs, counter = transform_dimension(constraint.lhs, counter, dimension_dict) + rhs, counter = transform_dimension(constraint.rhs, counter, dimension_dict) + if constraint.rhs == Dyn or constraint.lhs == Dyn: + if constraint.rhs == Dyn: + return lhs.arg(0) == 1, counter + elif constraint.lhs == Dyn: + return rhs.arg(0) == 1, counter + + # if one of the instances is a number + elif isinstance(constraint.lhs, int) or isinstance(constraint.rhs, int): + if isinstance(constraint.lhs, int): + return z3.Or([rhs.arg(0) == 0, z3.And([rhs.arg(0) == 1, lhs.arg(1) != rhs.arg(1)])]), counter + + elif isinstance(constraint.rhs, int): + return z3.Or([lhs.arg(0) == 0, z3.And([lhs.arg(0) == 1, lhs.arg(1) != rhs.arg(1)])]), counter + + else: + return z3.Or([z3.And([lhs.arg(0) == 0, rhs.arg(0) != 0]), + z3.And([lhs.arg(0) != 0, rhs.arg(0) == 0]), + z3.And([lhs.arg(0) != 0, rhs.arg(0) != 0, lhs.arg(1) != rhs.arg(1)])]), counter + + + elif constraint.op == op_leq: + # if the dimensions are not dyn, this will come into effect + # there would have been another constraint specifying if a given dimension + # is dyn or not + assert is_dim(constraint.lhs) and is_dim(constraint.rhs) + lhs, counter = transform_algebraic_expression(constraint.lhs, counter, dimension_dict) + rhs, counter = transform_algebraic_expression(constraint.rhs, counter, dimension_dict) + return lhs <= rhs, counter + + elif constraint.op == op_gt: + assert is_dim(constraint.lhs) and is_dim(constraint.rhs) + lhs, counter = transform_algebraic_expression(constraint.lhs, counter, dimension_dict) + rhs, counter = transform_algebraic_expression(constraint.rhs, counter, dimension_dict) + return lhs > rhs, counter + + elif constraint.op == op_lt: + assert is_dim(constraint.lhs) and is_dim(constraint.rhs) + lhs, counter = transform_algebraic_expression(constraint.lhs, counter, dimension_dict) + rhs, counter = transform_algebraic_expression(constraint.rhs, counter, dimension_dict) + return lhs < rhs, counter + + else: + raise NotImplementedError('operation not yet implemented') + + else: + raise NotImplementedError('Operation not yet implemented') + + + def transform_var(tensor, counter, dimension_dict): + """ + Transforms tensor variables to a format understood by z3 + Args: + tensor: Tensor variable or a tensor type potentially with variable dimensions + Returns: Transformed variable to a z3 format + + """ + if isinstance(tensor, TensorType): + res = [] + for t in tensor.__args__: + transformed, counter = transform_dimension(t, counter, dimension_dict) + res.append(transformed) + + assert len(res) <= 4 + if len(tensor.__args__) == 1: + return tensor_type.tensor1(res[0]), counter + elif len(tensor.__args__) == 2: + return tensor_type.tensor2(res[0], res[1]), counter + elif len(tensor.__args__) == 3: + return tensor_type.tensor3(res[0], res[1], res[2]), counter + elif len(tensor.__args__) == 4: + return tensor_type.tensor4(res[0], res[1], res[2], res[3]), counter + + elif tensor == Dyn: + return z3_dyn, counter + + elif isinstance(tensor, TVar): + return z3.Const(tensor.tvar, tensor_type), counter + + def transform_dimension(dimension, counter, dimension_dict): + """ + Takes a dimension variable or a number and transforms it to a tuple + according to our scheme + Args: + dimension: The dimension to be transformed + counter: variable tracking + + Returns: tuple and the current counter + + """ + if dimension == Dyn: + counter += 1 + return D(0, z3.Int(counter)), counter + elif isinstance(dimension, int): + return D(1, dimension), counter + elif isinstance(dimension, DVar): + if dimension.c in dimension_dict: + return D(z3.Int(dimension_dict[dimension.c]), z3.Int(dimension.c)), counter + else: + counter += 1 + dimension_dict[dimension.c] = counter + return D(z3.Int(counter), z3.Int(dimension.c)), counter + + + def transform_algebraic_expression(expr, counter, dimension_dict): + """ + Transforms an algebraic expression to z3 format + Args: + expr: An expression is either a dimension variable or an algebraic-expression + + + Returns: the transformed expression + + """ + assert is_algebraic_expression(expr) or is_dim(expr) + + if is_dim(expr): + transformed, counter = transform_dimension(expr, counter, dimension_dict) + return transformed.arg(1), counter + + elif isinstance(expr, Prod): + + dims = [] + for dim in expr.products: + assert is_dim(dim) + d, counter = transform_dimension(dim, counter, dimension_dict) + dims.append(d.arg(1)) + return z3.Product(dims), counter + + elif is_algebraic_expression(expr): + + lhs, counter = transform_algebraic_expression(expr.lhs, counter, dimension_dict) + rhs, counter = transform_algebraic_expression(expr.rhs, counter, dimension_dict) + + if expr.op == op_sub: + c = lhs - rhs + + elif expr.op == op_add: + c = lhs + rhs + + elif expr.op == op_div: + c = lhs / rhs + + elif expr.op == op_mul: + c = lhs * rhs + + elif expr.op == op_mod: + c = lhs % rhs + + else: + raise NotImplementedError('operation not yet implemented') + + return c, counter + + else: + raise RuntimeError + + + def transform_all_constraints(traced, counter=0): + """ + Given a trace, generates constraints and transforms them to z3 format + + """ + dimension_dict = {} # type: ignore[var-annotated] + + generator = ConstraintGenerator(traced) + new_constraints, counter = generator.generate_constraints(counter) + + # print(new_constraints.conjucts[0]) + # print(*new_constraints.conjucts, sep='\n') + + # transform precision, matching, consistency till obtaining a fixed point + new_constraints, counter = iterate_till_fixed_point(new_constraints, counter) + # print(new_constraints) + # print(new_constraints.conjucts) + # new_constraints.conjucts = new_constraints.conjucts[:-1] + # print(*new_constraints.conjucts, sep='\n') + + transformed, counter = transform_to_z3(new_constraints, counter, dimension_dict) + # print(transformed) + return transformed + + def iterate_till_fixed_point(constraints, counter): + """ + Transform constraints till reaching a fixed point + """ + old_c = None + while old_c != constraints: + old_c = constraints + constraints, counter = transform_constraint(constraints, counter) + return constraints, counter + + def transform_all_constraints_trace_time(tracer_root, graph, node, counter=0): + """ + Takes a node and a graph and generates two sets of constraints. + One set constraints the node's constraints and another set + constraints the negation of the node's constraints + Args: + tracer_root: the root for getting the module instances + graph: the graph so far in the tracing process + node: node that represents a conditional + counter: variable tracking + + Returns: Two sets of constraints. One with a conjunction with the + the conditional constraint and the other with a conjunction with + its negation. + + """ + dimension_dict = {} # type: ignore[var-annotated] + + generator = ConstraintGenerator(tracer_root, graph) + new_constraints, counter = generator.generate_constraints(counter) + + condition_constraint = new_constraints.conjucts[-1] + + # we know the constraint is a conjunction where the last constraint is about the conditional + # so remove the last constraint + new_constraints.conjucts = new_constraints.conjucts[:-1] + + # transform precision, matching, consistency till obtaining a fixed point + new_constraints, counter = iterate_till_fixed_point(new_constraints, counter) + + + # since the function returns a list of one element, we get the first element + # we are only interested in the RHS in this case because the LHS just stores + # the result + + # we make sure the constraint is of the form: + # c = b where b is a boolean expression + # and we consider b (constraint.rhs) for transformation + assert isinstance(condition_constraint.lhs, BVar) + assert is_bool_expr(condition_constraint.rhs) + condition_constraint_rhs = condition_constraint.rhs + + # transform the condition constraint + condition_constraint_rhs, counter = iterate_till_fixed_point(condition_constraint_rhs, counter) + + transformed, counter = transform_to_z3(new_constraints, counter, dimension_dict) + + transformed_condition_constraint, counter = transform_to_z3(condition_constraint_rhs, counter, dimension_dict) + + negation_transformed_condition_constraint = z3.Not(transformed_condition_constraint) + + return z3.And([transformed, transformed_condition_constraint]), \ + z3.And([transformed, negation_transformed_condition_constraint]) + + + def evaluate_conditional_with_constraints(tracer_root, graph, node, counter=0, user_constraints=None): + """ + Given an IR and a node representing a conditional, evaluate the conditional + and its negation + Args: + tracer_root: Tracer root for module instances + node: The node to be evaluated + + Returns: the results of evaluating the condition and the negation with + the rest of the constraints + + """ + + transformed_positive, transformed_negative = \ + transform_all_constraints_trace_time(tracer_root, graph, node, counter) + + s = z3.Solver() + s.add(transformed_positive) + if user_constraints is not None: + s.add(user_constraints) + condition = s.check() + + s = z3.Solver() + s.add(transformed_negative) + if user_constraints is not None: + s.add(user_constraints) + negation = s.check() + return condition, negation + +except ImportError: + HAS_Z3 = False diff --git a/shared/package-files/01/01e0d376352c8f8de9e5e13cf97756480f3a3a3244ea4d681b96c966af352e17/blob b/shared/package-files/01/01e0d376352c8f8de9e5e13cf97756480f3a3a3244ea4d681b96c966af352e17/blob new file mode 100644 index 0000000000000000000000000000000000000000..c6bc855ef688ef60721365761df4ff5b9ad433dd --- /dev/null +++ b/shared/package-files/01/01e0d376352c8f8de9e5e13cf97756480f3a3a3244ea4d681b96c966af352e17/blob @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:01e0d376352c8f8de9e5e13cf97756480f3a3a3244ea4d681b96c966af352e17 +size 171375 diff --git a/shared/package-files/01/01e0efff3bb4894fe8574bf14ab773cd8e4690acce571fb99e6060141fd45e10/blob b/shared/package-files/01/01e0efff3bb4894fe8574bf14ab773cd8e4690acce571fb99e6060141fd45e10/blob new file mode 100644 index 0000000000000000000000000000000000000000..ba016aec6dafe74e48076875202704a3b85b822a --- /dev/null +++ b/shared/package-files/01/01e0efff3bb4894fe8574bf14ab773cd8e4690acce571fb99e6060141fd45e10/blob @@ -0,0 +1,1434 @@ +""" +Created on Sat Aug 22 19:49:17 2020 + +@author: matth +""" + + +def _linprog_highs_doc(c, A_ub=None, b_ub=None, A_eq=None, b_eq=None, + bounds=None, method='highs', callback=None, + maxiter=None, disp=False, presolve=True, + time_limit=None, + dual_feasibility_tolerance=None, + primal_feasibility_tolerance=None, + ipm_optimality_tolerance=None, + simplex_dual_edge_weight_strategy=None, + mip_rel_gap=None, + **unknown_options): + r""" + Linear programming: minimize a linear objective function subject to linear + equality and inequality constraints using one of the HiGHS solvers. + + Linear programming solves problems of the following form: + + .. math:: + + \min_x \ & c^T x \\ + \mbox{such that} \ & A_{ub} x \leq b_{ub},\\ + & A_{eq} x = b_{eq},\\ + & l \leq x \leq u , + + where :math:`x` is a vector of decision variables; :math:`c`, + :math:`b_{ub}`, :math:`b_{eq}`, :math:`l`, and :math:`u` are vectors; and + :math:`A_{ub}` and :math:`A_{eq}` are matrices. + + Alternatively, that's: + + minimize:: + + c @ x + + such that:: + + A_ub @ x <= b_ub + A_eq @ x == b_eq + lb <= x <= ub + + Note that by default ``lb = 0`` and ``ub = None`` unless specified with + ``bounds``. + + Parameters + ---------- + c : 1-D array + The coefficients of the linear objective function to be minimized. + A_ub : 2-D array, optional + The inequality constraint matrix. Each row of ``A_ub`` specifies the + coefficients of a linear inequality constraint on ``x``. + b_ub : 1-D array, optional + The inequality constraint vector. Each element represents an + upper bound on the corresponding value of ``A_ub @ x``. + A_eq : 2-D array, optional + The equality constraint matrix. Each row of ``A_eq`` specifies the + coefficients of a linear equality constraint on ``x``. + b_eq : 1-D array, optional + The equality constraint vector. Each element of ``A_eq @ x`` must equal + the corresponding element of ``b_eq``. + bounds : sequence, optional + A sequence of ``(min, max)`` pairs for each element in ``x``, defining + the minimum and maximum values of that decision variable. Use ``None`` + to indicate that there is no bound. By default, bounds are + ``(0, None)`` (all decision variables are non-negative). + If a single tuple ``(min, max)`` is provided, then ``min`` and + ``max`` will serve as bounds for all decision variables. + method : str + + This is the method-specific documentation for 'highs', which chooses + automatically between + :ref:`'highs-ds' ` and + :ref:`'highs-ipm' `. + :ref:`'interior-point' ` (default), + :ref:`'revised simplex' `, and + :ref:`'simplex' ` (legacy) + are also available. + integrality : 1-D array or int, optional + Indicates the type of integrality constraint on each decision variable. + + ``0`` : Continuous variable; no integrality constraint. + + ``1`` : Integer variable; decision variable must be an integer + within `bounds`. + + ``2`` : Semi-continuous variable; decision variable must be within + `bounds` or take value ``0``. + + ``3`` : Semi-integer variable; decision variable must be an integer + within `bounds` or take value ``0``. + + By default, all variables are continuous. + + For mixed integrality constraints, supply an array of shape `c.shape`. + To infer a constraint on each decision variable from shorter inputs, + the argument will be broadcast to `c.shape` using `np.broadcast_to`. + + This argument is currently used only by the ``'highs'`` method and + ignored otherwise. + + Options + ------- + maxiter : int + The maximum number of iterations to perform in either phase. + For :ref:`'highs-ipm' `, this does not + include the number of crossover iterations. Default is the largest + possible value for an ``int`` on the platform. + disp : bool (default: ``False``) + Set to ``True`` if indicators of optimization status are to be + printed to the console during optimization. + presolve : bool (default: ``True``) + Presolve attempts to identify trivial infeasibilities, + identify trivial unboundedness, and simplify the problem before + sending it to the main solver. It is generally recommended + to keep the default setting ``True``; set to ``False`` if + presolve is to be disabled. + time_limit : float + The maximum time in seconds allotted to solve the problem; + default is the largest possible value for a ``double`` on the + platform. + dual_feasibility_tolerance : double (default: 1e-07) + Dual feasibility tolerance for + :ref:`'highs-ds' `. + The minimum of this and ``primal_feasibility_tolerance`` + is used for the feasibility tolerance of + :ref:`'highs-ipm' `. + primal_feasibility_tolerance : double (default: 1e-07) + Primal feasibility tolerance for + :ref:`'highs-ds' `. + The minimum of this and ``dual_feasibility_tolerance`` + is used for the feasibility tolerance of + :ref:`'highs-ipm' `. + ipm_optimality_tolerance : double (default: ``1e-08``) + Optimality tolerance for + :ref:`'highs-ipm' `. + Minimum allowable value is 1e-12. + simplex_dual_edge_weight_strategy : str (default: None) + Strategy for simplex dual edge weights. The default, ``None``, + automatically selects one of the following. + + ``'dantzig'`` uses Dantzig's original strategy of choosing the most + negative reduced cost. + + ``'devex'`` uses the strategy described in [15]_. + + ``steepest`` uses the exact steepest edge strategy as described in + [16]_. + + ``'steepest-devex'`` begins with the exact steepest edge strategy + until the computation is too costly or inexact and then switches to + the devex method. + + Currently, ``None`` always selects ``'steepest-devex'``, but this + may change as new options become available. + mip_rel_gap : double (default: None) + Termination criterion for MIP solver: solver will terminate when the + gap between the primal objective value and the dual objective bound, + scaled by the primal objective value, is <= mip_rel_gap. + unknown_options : dict + Optional arguments not used by this particular solver. If + ``unknown_options`` is non-empty, a warning is issued listing + all unused options. + + Returns + ------- + res : OptimizeResult + A :class:`scipy.optimize.OptimizeResult` consisting of the fields: + + x : 1D array + The values of the decision variables that minimizes the + objective function while satisfying the constraints. + fun : float + The optimal value of the objective function ``c @ x``. + slack : 1D array + The (nominally positive) values of the slack, + ``b_ub - A_ub @ x``. + con : 1D array + The (nominally zero) residuals of the equality constraints, + ``b_eq - A_eq @ x``. + success : bool + ``True`` when the algorithm succeeds in finding an optimal + solution. + status : int + An integer representing the exit status of the algorithm. + + ``0`` : Optimization terminated successfully. + + ``1`` : Iteration or time limit reached. + + ``2`` : Problem appears to be infeasible. + + ``3`` : Problem appears to be unbounded. + + ``4`` : The HiGHS solver ran into a problem. + + message : str + A string descriptor of the exit status of the algorithm. + nit : int + The total number of iterations performed. + For the HiGHS simplex method, this includes iterations in all + phases. For the HiGHS interior-point method, this does not include + crossover iterations. + crossover_nit : int + The number of primal/dual pushes performed during the + crossover routine for the HiGHS interior-point method. + This is ``0`` for the HiGHS simplex method. + ineqlin : OptimizeResult + Solution and sensitivity information corresponding to the + inequality constraints, `b_ub`. A dictionary consisting of the + fields: + + residual : np.ndnarray + The (nominally positive) values of the slack variables, + ``b_ub - A_ub @ x``. This quantity is also commonly + referred to as "slack". + + marginals : np.ndarray + The sensitivity (partial derivative) of the objective + function with respect to the right-hand side of the + inequality constraints, `b_ub`. + + eqlin : OptimizeResult + Solution and sensitivity information corresponding to the + equality constraints, `b_eq`. A dictionary consisting of the + fields: + + residual : np.ndarray + The (nominally zero) residuals of the equality constraints, + ``b_eq - A_eq @ x``. + + marginals : np.ndarray + The sensitivity (partial derivative) of the objective + function with respect to the right-hand side of the + equality constraints, `b_eq`. + + lower, upper : OptimizeResult + Solution and sensitivity information corresponding to the + lower and upper bounds on decision variables, `bounds`. + + residual : np.ndarray + The (nominally positive) values of the quantity + ``x - lb`` (lower) or ``ub - x`` (upper). + + marginals : np.ndarray + The sensitivity (partial derivative) of the objective + function with respect to the lower and upper + `bounds`. + + Notes + ----- + + Method :ref:`'highs-ds' ` is a wrapper + of the C++ high performance dual revised simplex implementation (HSOL) + [13]_, [14]_. Method :ref:`'highs-ipm' ` + is a wrapper of a C++ implementation of an **i**\ nterior-\ **p**\ oint + **m**\ ethod [13]_; it features a crossover routine, so it is as accurate + as a simplex solver. Method :ref:`'highs' ` chooses + between the two automatically. For new code involving `linprog`, we + recommend explicitly choosing one of these three method values instead of + :ref:`'interior-point' ` (default), + :ref:`'revised simplex' `, and + :ref:`'simplex' ` (legacy). + + The result fields `ineqlin`, `eqlin`, `lower`, and `upper` all contain + `marginals`, or partial derivatives of the objective function with respect + to the right-hand side of each constraint. These partial derivatives are + also referred to as "Lagrange multipliers", "dual values", and + "shadow prices". The sign convention of `marginals` is opposite that + of Lagrange multipliers produced by many nonlinear solvers. + + References + ---------- + .. [13] Huangfu, Q., Galabova, I., Feldmeier, M., and Hall, J. A. J. + "HiGHS - high performance software for linear optimization." + https://highs.dev/ + .. [14] Huangfu, Q. and Hall, J. A. J. "Parallelizing the dual revised + simplex method." Mathematical Programming Computation, 10 (1), + 119-142, 2018. DOI: 10.1007/s12532-017-0130-5 + .. [15] Harris, Paula MJ. "Pivot selection methods of the Devex LP code." + Mathematical programming 5.1 (1973): 1-28. + .. [16] Goldfarb, Donald, and John Ker Reid. "A practicable steepest-edge + simplex algorithm." Mathematical Programming 12.1 (1977): 361-371. + """ + pass + + +def _linprog_highs_ds_doc(c, A_ub=None, b_ub=None, A_eq=None, b_eq=None, + bounds=None, method='highs-ds', callback=None, + maxiter=None, disp=False, presolve=True, + time_limit=None, + dual_feasibility_tolerance=None, + primal_feasibility_tolerance=None, + simplex_dual_edge_weight_strategy=None, + **unknown_options): + r""" + Linear programming: minimize a linear objective function subject to linear + equality and inequality constraints using the HiGHS dual simplex solver. + + Linear programming solves problems of the following form: + + .. math:: + + \min_x \ & c^T x \\ + \mbox{such that} \ & A_{ub} x \leq b_{ub},\\ + & A_{eq} x = b_{eq},\\ + & l \leq x \leq u , + + where :math:`x` is a vector of decision variables; :math:`c`, + :math:`b_{ub}`, :math:`b_{eq}`, :math:`l`, and :math:`u` are vectors; and + :math:`A_{ub}` and :math:`A_{eq}` are matrices. + + Alternatively, that's: + + minimize:: + + c @ x + + such that:: + + A_ub @ x <= b_ub + A_eq @ x == b_eq + lb <= x <= ub + + Note that by default ``lb = 0`` and ``ub = None`` unless specified with + ``bounds``. + + Parameters + ---------- + c : 1-D array + The coefficients of the linear objective function to be minimized. + A_ub : 2-D array, optional + The inequality constraint matrix. Each row of ``A_ub`` specifies the + coefficients of a linear inequality constraint on ``x``. + b_ub : 1-D array, optional + The inequality constraint vector. Each element represents an + upper bound on the corresponding value of ``A_ub @ x``. + A_eq : 2-D array, optional + The equality constraint matrix. Each row of ``A_eq`` specifies the + coefficients of a linear equality constraint on ``x``. + b_eq : 1-D array, optional + The equality constraint vector. Each element of ``A_eq @ x`` must equal + the corresponding element of ``b_eq``. + bounds : sequence, optional + A sequence of ``(min, max)`` pairs for each element in ``x``, defining + the minimum and maximum values of that decision variable. Use ``None`` + to indicate that there is no bound. By default, bounds are + ``(0, None)`` (all decision variables are non-negative). + If a single tuple ``(min, max)`` is provided, then ``min`` and + ``max`` will serve as bounds for all decision variables. + method : str + + This is the method-specific documentation for 'highs-ds'. + :ref:`'highs' `, + :ref:`'highs-ipm' `, + :ref:`'interior-point' ` (default), + :ref:`'revised simplex' `, and + :ref:`'simplex' ` (legacy) + are also available. + + Options + ------- + maxiter : int + The maximum number of iterations to perform in either phase. + Default is the largest possible value for an ``int`` on the platform. + disp : bool (default: ``False``) + Set to ``True`` if indicators of optimization status are to be + printed to the console during optimization. + presolve : bool (default: ``True``) + Presolve attempts to identify trivial infeasibilities, + identify trivial unboundedness, and simplify the problem before + sending it to the main solver. It is generally recommended + to keep the default setting ``True``; set to ``False`` if + presolve is to be disabled. + time_limit : float + The maximum time in seconds allotted to solve the problem; + default is the largest possible value for a ``double`` on the + platform. + dual_feasibility_tolerance : double (default: 1e-07) + Dual feasibility tolerance for + :ref:`'highs-ds' `. + primal_feasibility_tolerance : double (default: 1e-07) + Primal feasibility tolerance for + :ref:`'highs-ds' `. + simplex_dual_edge_weight_strategy : str (default: None) + Strategy for simplex dual edge weights. The default, ``None``, + automatically selects one of the following. + + ``'dantzig'`` uses Dantzig's original strategy of choosing the most + negative reduced cost. + + ``'devex'`` uses the strategy described in [15]_. + + ``steepest`` uses the exact steepest edge strategy as described in + [16]_. + + ``'steepest-devex'`` begins with the exact steepest edge strategy + until the computation is too costly or inexact and then switches to + the devex method. + + Currently, ``None`` always selects ``'steepest-devex'``, but this + may change as new options become available. + unknown_options : dict + Optional arguments not used by this particular solver. If + ``unknown_options`` is non-empty, a warning is issued listing + all unused options. + + Returns + ------- + res : OptimizeResult + A :class:`scipy.optimize.OptimizeResult` consisting of the fields: + + x : 1D array + The values of the decision variables that minimizes the + objective function while satisfying the constraints. + fun : float + The optimal value of the objective function ``c @ x``. + slack : 1D array + The (nominally positive) values of the slack, + ``b_ub - A_ub @ x``. + con : 1D array + The (nominally zero) residuals of the equality constraints, + ``b_eq - A_eq @ x``. + success : bool + ``True`` when the algorithm succeeds in finding an optimal + solution. + status : int + An integer representing the exit status of the algorithm. + + ``0`` : Optimization terminated successfully. + + ``1`` : Iteration or time limit reached. + + ``2`` : Problem appears to be infeasible. + + ``3`` : Problem appears to be unbounded. + + ``4`` : The HiGHS solver ran into a problem. + + message : str + A string descriptor of the exit status of the algorithm. + nit : int + The total number of iterations performed. This includes iterations + in all phases. + crossover_nit : int + This is always ``0`` for the HiGHS simplex method. + For the HiGHS interior-point method, this is the number of + primal/dual pushes performed during the crossover routine. + ineqlin : OptimizeResult + Solution and sensitivity information corresponding to the + inequality constraints, `b_ub`. A dictionary consisting of the + fields: + + residual : np.ndnarray + The (nominally positive) values of the slack variables, + ``b_ub - A_ub @ x``. This quantity is also commonly + referred to as "slack". + + marginals : np.ndarray + The sensitivity (partial derivative) of the objective + function with respect to the right-hand side of the + inequality constraints, `b_ub`. + + eqlin : OptimizeResult + Solution and sensitivity information corresponding to the + equality constraints, `b_eq`. A dictionary consisting of the + fields: + + residual : np.ndarray + The (nominally zero) residuals of the equality constraints, + ``b_eq - A_eq @ x``. + + marginals : np.ndarray + The sensitivity (partial derivative) of the objective + function with respect to the right-hand side of the + equality constraints, `b_eq`. + + lower, upper : OptimizeResult + Solution and sensitivity information corresponding to the + lower and upper bounds on decision variables, `bounds`. + + residual : np.ndarray + The (nominally positive) values of the quantity + ``x - lb`` (lower) or ``ub - x`` (upper). + + marginals : np.ndarray + The sensitivity (partial derivative) of the objective + function with respect to the lower and upper + `bounds`. + + Notes + ----- + + Method :ref:`'highs-ds' ` is a wrapper + of the C++ high performance dual revised simplex implementation (HSOL) + [13]_, [14]_. Method :ref:`'highs-ipm' ` + is a wrapper of a C++ implementation of an **i**\ nterior-\ **p**\ oint + **m**\ ethod [13]_; it features a crossover routine, so it is as accurate + as a simplex solver. Method :ref:`'highs' ` chooses + between the two automatically. For new code involving `linprog`, we + recommend explicitly choosing one of these three method values instead of + :ref:`'interior-point' ` (default), + :ref:`'revised simplex' `, and + :ref:`'simplex' ` (legacy). + + The result fields `ineqlin`, `eqlin`, `lower`, and `upper` all contain + `marginals`, or partial derivatives of the objective function with respect + to the right-hand side of each constraint. These partial derivatives are + also referred to as "Lagrange multipliers", "dual values", and + "shadow prices". The sign convention of `marginals` is opposite that + of Lagrange multipliers produced by many nonlinear solvers. + + References + ---------- + .. [13] Huangfu, Q., Galabova, I., Feldmeier, M., and Hall, J. A. J. + "HiGHS - high performance software for linear optimization." + https://highs.dev/ + .. [14] Huangfu, Q. and Hall, J. A. J. "Parallelizing the dual revised + simplex method." Mathematical Programming Computation, 10 (1), + 119-142, 2018. DOI: 10.1007/s12532-017-0130-5 + .. [15] Harris, Paula MJ. "Pivot selection methods of the Devex LP code." + Mathematical programming 5.1 (1973): 1-28. + .. [16] Goldfarb, Donald, and John Ker Reid. "A practicable steepest-edge + simplex algorithm." Mathematical Programming 12.1 (1977): 361-371. + """ + pass + + +def _linprog_highs_ipm_doc(c, A_ub=None, b_ub=None, A_eq=None, b_eq=None, + bounds=None, method='highs-ipm', callback=None, + maxiter=None, disp=False, presolve=True, + time_limit=None, + dual_feasibility_tolerance=None, + primal_feasibility_tolerance=None, + ipm_optimality_tolerance=None, + **unknown_options): + r""" + Linear programming: minimize a linear objective function subject to linear + equality and inequality constraints using the HiGHS interior point solver. + + Linear programming solves problems of the following form: + + .. math:: + + \min_x \ & c^T x \\ + \mbox{such that} \ & A_{ub} x \leq b_{ub},\\ + & A_{eq} x = b_{eq},\\ + & l \leq x \leq u , + + where :math:`x` is a vector of decision variables; :math:`c`, + :math:`b_{ub}`, :math:`b_{eq}`, :math:`l`, and :math:`u` are vectors; and + :math:`A_{ub}` and :math:`A_{eq}` are matrices. + + Alternatively, that's: + + minimize:: + + c @ x + + such that:: + + A_ub @ x <= b_ub + A_eq @ x == b_eq + lb <= x <= ub + + Note that by default ``lb = 0`` and ``ub = None`` unless specified with + ``bounds``. + + Parameters + ---------- + c : 1-D array + The coefficients of the linear objective function to be minimized. + A_ub : 2-D array, optional + The inequality constraint matrix. Each row of ``A_ub`` specifies the + coefficients of a linear inequality constraint on ``x``. + b_ub : 1-D array, optional + The inequality constraint vector. Each element represents an + upper bound on the corresponding value of ``A_ub @ x``. + A_eq : 2-D array, optional + The equality constraint matrix. Each row of ``A_eq`` specifies the + coefficients of a linear equality constraint on ``x``. + b_eq : 1-D array, optional + The equality constraint vector. Each element of ``A_eq @ x`` must equal + the corresponding element of ``b_eq``. + bounds : sequence, optional + A sequence of ``(min, max)`` pairs for each element in ``x``, defining + the minimum and maximum values of that decision variable. Use ``None`` + to indicate that there is no bound. By default, bounds are + ``(0, None)`` (all decision variables are non-negative). + If a single tuple ``(min, max)`` is provided, then ``min`` and + ``max`` will serve as bounds for all decision variables. + method : str + + This is the method-specific documentation for 'highs-ipm'. + :ref:`'highs-ipm' `, + :ref:`'highs-ds' `, + :ref:`'interior-point' ` (default), + :ref:`'revised simplex' `, and + :ref:`'simplex' ` (legacy) + are also available. + + Options + ------- + maxiter : int + The maximum number of iterations to perform in either phase. + For :ref:`'highs-ipm' `, this does not + include the number of crossover iterations. Default is the largest + possible value for an ``int`` on the platform. + disp : bool (default: ``False``) + Set to ``True`` if indicators of optimization status are to be + printed to the console during optimization. + presolve : bool (default: ``True``) + Presolve attempts to identify trivial infeasibilities, + identify trivial unboundedness, and simplify the problem before + sending it to the main solver. It is generally recommended + to keep the default setting ``True``; set to ``False`` if + presolve is to be disabled. + time_limit : float + The maximum time in seconds allotted to solve the problem; + default is the largest possible value for a ``double`` on the + platform. + dual_feasibility_tolerance : double (default: 1e-07) + The minimum of this and ``primal_feasibility_tolerance`` + is used for the feasibility tolerance of + :ref:`'highs-ipm' `. + primal_feasibility_tolerance : double (default: 1e-07) + The minimum of this and ``dual_feasibility_tolerance`` + is used for the feasibility tolerance of + :ref:`'highs-ipm' `. + ipm_optimality_tolerance : double (default: ``1e-08``) + Optimality tolerance for + :ref:`'highs-ipm' `. + Minimum allowable value is 1e-12. + unknown_options : dict + Optional arguments not used by this particular solver. If + ``unknown_options`` is non-empty, a warning is issued listing + all unused options. + + Returns + ------- + res : OptimizeResult + A :class:`scipy.optimize.OptimizeResult` consisting of the fields: + + x : 1D array + The values of the decision variables that minimizes the + objective function while satisfying the constraints. + fun : float + The optimal value of the objective function ``c @ x``. + slack : 1D array + The (nominally positive) values of the slack, + ``b_ub - A_ub @ x``. + con : 1D array + The (nominally zero) residuals of the equality constraints, + ``b_eq - A_eq @ x``. + success : bool + ``True`` when the algorithm succeeds in finding an optimal + solution. + status : int + An integer representing the exit status of the algorithm. + + ``0`` : Optimization terminated successfully. + + ``1`` : Iteration or time limit reached. + + ``2`` : Problem appears to be infeasible. + + ``3`` : Problem appears to be unbounded. + + ``4`` : The HiGHS solver ran into a problem. + + message : str + A string descriptor of the exit status of the algorithm. + nit : int + The total number of iterations performed. + For the HiGHS interior-point method, this does not include + crossover iterations. + crossover_nit : int + The number of primal/dual pushes performed during the + crossover routine for the HiGHS interior-point method. + ineqlin : OptimizeResult + Solution and sensitivity information corresponding to the + inequality constraints, `b_ub`. A dictionary consisting of the + fields: + + residual : np.ndnarray + The (nominally positive) values of the slack variables, + ``b_ub - A_ub @ x``. This quantity is also commonly + referred to as "slack". + + marginals : np.ndarray + The sensitivity (partial derivative) of the objective + function with respect to the right-hand side of the + inequality constraints, `b_ub`. + + eqlin : OptimizeResult + Solution and sensitivity information corresponding to the + equality constraints, `b_eq`. A dictionary consisting of the + fields: + + residual : np.ndarray + The (nominally zero) residuals of the equality constraints, + ``b_eq - A_eq @ x``. + + marginals : np.ndarray + The sensitivity (partial derivative) of the objective + function with respect to the right-hand side of the + equality constraints, `b_eq`. + + lower, upper : OptimizeResult + Solution and sensitivity information corresponding to the + lower and upper bounds on decision variables, `bounds`. + + residual : np.ndarray + The (nominally positive) values of the quantity + ``x - lb`` (lower) or ``ub - x`` (upper). + + marginals : np.ndarray + The sensitivity (partial derivative) of the objective + function with respect to the lower and upper + `bounds`. + + Notes + ----- + + Method :ref:`'highs-ipm' ` + is a wrapper of a C++ implementation of an **i**\ nterior-\ **p**\ oint + **m**\ ethod [13]_; it features a crossover routine, so it is as accurate + as a simplex solver. + Method :ref:`'highs-ds' ` is a wrapper + of the C++ high performance dual revised simplex implementation (HSOL) + [13]_, [14]_. Method :ref:`'highs' ` chooses + between the two automatically. For new code involving `linprog`, we + recommend explicitly choosing one of these three method values instead of + :ref:`'interior-point' ` (default), + :ref:`'revised simplex' `, and + :ref:`'simplex' ` (legacy). + + The result fields `ineqlin`, `eqlin`, `lower`, and `upper` all contain + `marginals`, or partial derivatives of the objective function with respect + to the right-hand side of each constraint. These partial derivatives are + also referred to as "Lagrange multipliers", "dual values", and + "shadow prices". The sign convention of `marginals` is opposite that + of Lagrange multipliers produced by many nonlinear solvers. + + References + ---------- + .. [13] Huangfu, Q., Galabova, I., Feldmeier, M., and Hall, J. A. J. + "HiGHS - high performance software for linear optimization." + https://highs.dev/ + .. [14] Huangfu, Q. and Hall, J. A. J. "Parallelizing the dual revised + simplex method." Mathematical Programming Computation, 10 (1), + 119-142, 2018. DOI: 10.1007/s12532-017-0130-5 + """ + pass + + +def _linprog_ip_doc(c, A_ub=None, b_ub=None, A_eq=None, b_eq=None, + bounds=None, method='interior-point', callback=None, + maxiter=1000, disp=False, presolve=True, + tol=1e-8, autoscale=False, rr=True, + alpha0=.99995, beta=0.1, sparse=False, + lstsq=False, sym_pos=True, cholesky=True, pc=True, + ip=False, permc_spec='MMD_AT_PLUS_A', **unknown_options): + r""" + Linear programming: minimize a linear objective function subject to linear + equality and inequality constraints using the interior-point method of + [4]_. + + .. deprecated:: 1.9.0 + `method='interior-point'` will be removed in SciPy 1.11.0. + It is replaced by `method='highs'` because the latter is + faster and more robust. + + Linear programming solves problems of the following form: + + .. math:: + + \min_x \ & c^T x \\ + \mbox{such that} \ & A_{ub} x \leq b_{ub},\\ + & A_{eq} x = b_{eq},\\ + & l \leq x \leq u , + + where :math:`x` is a vector of decision variables; :math:`c`, + :math:`b_{ub}`, :math:`b_{eq}`, :math:`l`, and :math:`u` are vectors; and + :math:`A_{ub}` and :math:`A_{eq}` are matrices. + + Alternatively, that's: + + minimize:: + + c @ x + + such that:: + + A_ub @ x <= b_ub + A_eq @ x == b_eq + lb <= x <= ub + + Note that by default ``lb = 0`` and ``ub = None`` unless specified with + ``bounds``. + + Parameters + ---------- + c : 1-D array + The coefficients of the linear objective function to be minimized. + A_ub : 2-D array, optional + The inequality constraint matrix. Each row of ``A_ub`` specifies the + coefficients of a linear inequality constraint on ``x``. + b_ub : 1-D array, optional + The inequality constraint vector. Each element represents an + upper bound on the corresponding value of ``A_ub @ x``. + A_eq : 2-D array, optional + The equality constraint matrix. Each row of ``A_eq`` specifies the + coefficients of a linear equality constraint on ``x``. + b_eq : 1-D array, optional + The equality constraint vector. Each element of ``A_eq @ x`` must equal + the corresponding element of ``b_eq``. + bounds : sequence, optional + A sequence of ``(min, max)`` pairs for each element in ``x``, defining + the minimum and maximum values of that decision variable. Use ``None`` + to indicate that there is no bound. By default, bounds are + ``(0, None)`` (all decision variables are non-negative). + If a single tuple ``(min, max)`` is provided, then ``min`` and + ``max`` will serve as bounds for all decision variables. + method : str + This is the method-specific documentation for 'interior-point'. + :ref:`'highs' `, + :ref:`'highs-ds' `, + :ref:`'highs-ipm' `, + :ref:`'revised simplex' `, and + :ref:`'simplex' ` (legacy) + are also available. + callback : callable, optional + Callback function to be executed once per iteration. + + Options + ------- + maxiter : int (default: 1000) + The maximum number of iterations of the algorithm. + disp : bool (default: False) + Set to ``True`` if indicators of optimization status are to be printed + to the console each iteration. + presolve : bool (default: True) + Presolve attempts to identify trivial infeasibilities, + identify trivial unboundedness, and simplify the problem before + sending it to the main solver. It is generally recommended + to keep the default setting ``True``; set to ``False`` if + presolve is to be disabled. + tol : float (default: 1e-8) + Termination tolerance to be used for all termination criteria; + see [4]_ Section 4.5. + autoscale : bool (default: False) + Set to ``True`` to automatically perform equilibration. + Consider using this option if the numerical values in the + constraints are separated by several orders of magnitude. + rr : bool (default: True) + Set to ``False`` to disable automatic redundancy removal. + alpha0 : float (default: 0.99995) + The maximal step size for Mehrota's predictor-corrector search + direction; see :math:`\beta_{3}` of [4]_ Table 8.1. + beta : float (default: 0.1) + The desired reduction of the path parameter :math:`\mu` (see [6]_) + when Mehrota's predictor-corrector is not in use (uncommon). + sparse : bool (default: False) + Set to ``True`` if the problem is to be treated as sparse after + presolve. If either ``A_eq`` or ``A_ub`` is a sparse matrix, + this option will automatically be set ``True``, and the problem + will be treated as sparse even during presolve. If your constraint + matrices contain mostly zeros and the problem is not very small (less + than about 100 constraints or variables), consider setting ``True`` + or providing ``A_eq`` and ``A_ub`` as sparse matrices. + lstsq : bool (default: ``False``) + Set to ``True`` if the problem is expected to be very poorly + conditioned. This should always be left ``False`` unless severe + numerical difficulties are encountered. Leave this at the default + unless you receive a warning message suggesting otherwise. + sym_pos : bool (default: True) + Leave ``True`` if the problem is expected to yield a well conditioned + symmetric positive definite normal equation matrix + (almost always). Leave this at the default unless you receive + a warning message suggesting otherwise. + cholesky : bool (default: True) + Set to ``True`` if the normal equations are to be solved by explicit + Cholesky decomposition followed by explicit forward/backward + substitution. This is typically faster for problems + that are numerically well-behaved. + pc : bool (default: True) + Leave ``True`` if the predictor-corrector method of Mehrota is to be + used. This is almost always (if not always) beneficial. + ip : bool (default: False) + Set to ``True`` if the improved initial point suggestion due to [4]_ + Section 4.3 is desired. Whether this is beneficial or not + depends on the problem. + permc_spec : str (default: 'MMD_AT_PLUS_A') + (Has effect only with ``sparse = True``, ``lstsq = False``, ``sym_pos = + True``, and no SuiteSparse.) + A matrix is factorized in each iteration of the algorithm. + This option specifies how to permute the columns of the matrix for + sparsity preservation. Acceptable values are: + + - ``NATURAL``: natural ordering. + - ``MMD_ATA``: minimum degree ordering on the structure of A^T A. + - ``MMD_AT_PLUS_A``: minimum degree ordering on the structure of A^T+A. + - ``COLAMD``: approximate minimum degree column ordering. + + This option can impact the convergence of the + interior point algorithm; test different values to determine which + performs best for your problem. For more information, refer to + ``scipy.sparse.linalg.splu``. + unknown_options : dict + Optional arguments not used by this particular solver. If + `unknown_options` is non-empty a warning is issued listing all + unused options. + + Returns + ------- + res : OptimizeResult + A :class:`scipy.optimize.OptimizeResult` consisting of the fields: + + x : 1-D array + The values of the decision variables that minimizes the + objective function while satisfying the constraints. + fun : float + The optimal value of the objective function ``c @ x``. + slack : 1-D array + The (nominally positive) values of the slack variables, + ``b_ub - A_ub @ x``. + con : 1-D array + The (nominally zero) residuals of the equality constraints, + ``b_eq - A_eq @ x``. + success : bool + ``True`` when the algorithm succeeds in finding an optimal + solution. + status : int + An integer representing the exit status of the algorithm. + + ``0`` : Optimization terminated successfully. + + ``1`` : Iteration limit reached. + + ``2`` : Problem appears to be infeasible. + + ``3`` : Problem appears to be unbounded. + + ``4`` : Numerical difficulties encountered. + + message : str + A string descriptor of the exit status of the algorithm. + nit : int + The total number of iterations performed in all phases. + + + Notes + ----- + This method implements the algorithm outlined in [4]_ with ideas from [8]_ + and a structure inspired by the simpler methods of [6]_. + + The primal-dual path following method begins with initial 'guesses' of + the primal and dual variables of the standard form problem and iteratively + attempts to solve the (nonlinear) Karush-Kuhn-Tucker conditions for the + problem with a gradually reduced logarithmic barrier term added to the + objective. This particular implementation uses a homogeneous self-dual + formulation, which provides certificates of infeasibility or unboundedness + where applicable. + + The default initial point for the primal and dual variables is that + defined in [4]_ Section 4.4 Equation 8.22. Optionally (by setting initial + point option ``ip=True``), an alternate (potentially improved) starting + point can be calculated according to the additional recommendations of + [4]_ Section 4.4. + + A search direction is calculated using the predictor-corrector method + (single correction) proposed by Mehrota and detailed in [4]_ Section 4.1. + (A potential improvement would be to implement the method of multiple + corrections described in [4]_ Section 4.2.) In practice, this is + accomplished by solving the normal equations, [4]_ Section 5.1 Equations + 8.31 and 8.32, derived from the Newton equations [4]_ Section 5 Equations + 8.25 (compare to [4]_ Section 4 Equations 8.6-8.8). The advantage of + solving the normal equations rather than 8.25 directly is that the + matrices involved are symmetric positive definite, so Cholesky + decomposition can be used rather than the more expensive LU factorization. + + With default options, the solver used to perform the factorization depends + on third-party software availability and the conditioning of the problem. + + For dense problems, solvers are tried in the following order: + + 1. ``scipy.linalg.cho_factor`` + + 2. ``scipy.linalg.solve`` with option ``sym_pos=True`` + + 3. ``scipy.linalg.solve`` with option ``sym_pos=False`` + + 4. ``scipy.linalg.lstsq`` + + For sparse problems: + + 1. ``sksparse.cholmod.cholesky`` (if scikit-sparse and SuiteSparse are + installed) + + 2. ``scipy.sparse.linalg.factorized`` (if scikit-umfpack and SuiteSparse + are installed) + + 3. ``scipy.sparse.linalg.splu`` (which uses SuperLU distributed with SciPy) + + 4. ``scipy.sparse.linalg.lsqr`` + + If the solver fails for any reason, successively more robust (but slower) + solvers are attempted in the order indicated. Attempting, failing, and + re-starting factorization can be time consuming, so if the problem is + numerically challenging, options can be set to bypass solvers that are + failing. Setting ``cholesky=False`` skips to solver 2, + ``sym_pos=False`` skips to solver 3, and ``lstsq=True`` skips + to solver 4 for both sparse and dense problems. + + Potential improvements for combating issues associated with dense + columns in otherwise sparse problems are outlined in [4]_ Section 5.3 and + [10]_ Section 4.1-4.2; the latter also discusses the alleviation of + accuracy issues associated with the substitution approach to free + variables. + + After calculating the search direction, the maximum possible step size + that does not activate the non-negativity constraints is calculated, and + the smaller of this step size and unity is applied (as in [4]_ Section + 4.1.) [4]_ Section 4.3 suggests improvements for choosing the step size. + + The new point is tested according to the termination conditions of [4]_ + Section 4.5. The same tolerance, which can be set using the ``tol`` option, + is used for all checks. (A potential improvement would be to expose + the different tolerances to be set independently.) If optimality, + unboundedness, or infeasibility is detected, the solve procedure + terminates; otherwise it repeats. + + Whereas the top level ``linprog`` module expects a problem of form: + + Minimize:: + + c @ x + + Subject to:: + + A_ub @ x <= b_ub + A_eq @ x == b_eq + lb <= x <= ub + + where ``lb = 0`` and ``ub = None`` unless set in ``bounds``. The problem + is automatically converted to the form: + + Minimize:: + + c @ x + + Subject to:: + + A @ x == b + x >= 0 + + for solution. That is, the original problem contains equality, upper-bound + and variable constraints whereas the method specific solver requires + equality constraints and variable non-negativity. ``linprog`` converts the + original problem to standard form by converting the simple bounds to upper + bound constraints, introducing non-negative slack variables for inequality + constraints, and expressing unbounded variables as the difference between + two non-negative variables. The problem is converted back to the original + form before results are reported. + + References + ---------- + .. [4] Andersen, Erling D., and Knud D. Andersen. "The MOSEK interior point + optimizer for linear programming: an implementation of the + homogeneous algorithm." High performance optimization. Springer US, + 2000. 197-232. + .. [6] Freund, Robert M. "Primal-Dual Interior-Point Methods for Linear + Programming based on Newton's Method." Unpublished Course Notes, + March 2004. Available 2/25/2017 at + https://ocw.mit.edu/courses/sloan-school-of-management/15-084j-nonlinear-programming-spring-2004/lecture-notes/lec14_int_pt_mthd.pdf + .. [8] Andersen, Erling D., and Knud D. Andersen. "Presolving in linear + programming." Mathematical Programming 71.2 (1995): 221-245. + .. [9] Bertsimas, Dimitris, and J. Tsitsiklis. "Introduction to linear + programming." Athena Scientific 1 (1997): 997. + .. [10] Andersen, Erling D., et al. Implementation of interior point + methods for large scale linear programming. HEC/Universite de + Geneve, 1996. + """ + pass + + +def _linprog_rs_doc(c, A_ub=None, b_ub=None, A_eq=None, b_eq=None, + bounds=None, method='interior-point', callback=None, + x0=None, maxiter=5000, disp=False, presolve=True, + tol=1e-12, autoscale=False, rr=True, maxupdate=10, + mast=False, pivot="mrc", **unknown_options): + r""" + Linear programming: minimize a linear objective function subject to linear + equality and inequality constraints using the revised simplex method. + + .. deprecated:: 1.9.0 + `method='revised simplex'` will be removed in SciPy 1.11.0. + It is replaced by `method='highs'` because the latter is + faster and more robust. + + Linear programming solves problems of the following form: + + .. math:: + + \min_x \ & c^T x \\ + \mbox{such that} \ & A_{ub} x \leq b_{ub},\\ + & A_{eq} x = b_{eq},\\ + & l \leq x \leq u , + + where :math:`x` is a vector of decision variables; :math:`c`, + :math:`b_{ub}`, :math:`b_{eq}`, :math:`l`, and :math:`u` are vectors; and + :math:`A_{ub}` and :math:`A_{eq}` are matrices. + + Alternatively, that's: + + minimize:: + + c @ x + + such that:: + + A_ub @ x <= b_ub + A_eq @ x == b_eq + lb <= x <= ub + + Note that by default ``lb = 0`` and ``ub = None`` unless specified with + ``bounds``. + + Parameters + ---------- + c : 1-D array + The coefficients of the linear objective function to be minimized. + A_ub : 2-D array, optional + The inequality constraint matrix. Each row of ``A_ub`` specifies the + coefficients of a linear inequality constraint on ``x``. + b_ub : 1-D array, optional + The inequality constraint vector. Each element represents an + upper bound on the corresponding value of ``A_ub @ x``. + A_eq : 2-D array, optional + The equality constraint matrix. Each row of ``A_eq`` specifies the + coefficients of a linear equality constraint on ``x``. + b_eq : 1-D array, optional + The equality constraint vector. Each element of ``A_eq @ x`` must equal + the corresponding element of ``b_eq``. + bounds : sequence, optional + A sequence of ``(min, max)`` pairs for each element in ``x``, defining + the minimum and maximum values of that decision variable. Use ``None`` + to indicate that there is no bound. By default, bounds are + ``(0, None)`` (all decision variables are non-negative). + If a single tuple ``(min, max)`` is provided, then ``min`` and + ``max`` will serve as bounds for all decision variables. + method : str + This is the method-specific documentation for 'revised simplex'. + :ref:`'highs' `, + :ref:`'highs-ds' `, + :ref:`'highs-ipm' `, + :ref:`'interior-point' ` (default), + and :ref:`'simplex' ` (legacy) + are also available. + callback : callable, optional + Callback function to be executed once per iteration. + x0 : 1-D array, optional + Guess values of the decision variables, which will be refined by + the optimization algorithm. This argument is currently used only by the + 'revised simplex' method, and can only be used if `x0` represents a + basic feasible solution. + + Options + ------- + maxiter : int (default: 5000) + The maximum number of iterations to perform in either phase. + disp : bool (default: False) + Set to ``True`` if indicators of optimization status are to be printed + to the console each iteration. + presolve : bool (default: True) + Presolve attempts to identify trivial infeasibilities, + identify trivial unboundedness, and simplify the problem before + sending it to the main solver. It is generally recommended + to keep the default setting ``True``; set to ``False`` if + presolve is to be disabled. + tol : float (default: 1e-12) + The tolerance which determines when a solution is "close enough" to + zero in Phase 1 to be considered a basic feasible solution or close + enough to positive to serve as an optimal solution. + autoscale : bool (default: False) + Set to ``True`` to automatically perform equilibration. + Consider using this option if the numerical values in the + constraints are separated by several orders of magnitude. + rr : bool (default: True) + Set to ``False`` to disable automatic redundancy removal. + maxupdate : int (default: 10) + The maximum number of updates performed on the LU factorization. + After this many updates is reached, the basis matrix is factorized + from scratch. + mast : bool (default: False) + Minimize Amortized Solve Time. If enabled, the average time to solve + a linear system using the basis factorization is measured. Typically, + the average solve time will decrease with each successive solve after + initial factorization, as factorization takes much more time than the + solve operation (and updates). Eventually, however, the updated + factorization becomes sufficiently complex that the average solve time + begins to increase. When this is detected, the basis is refactorized + from scratch. Enable this option to maximize speed at the risk of + nondeterministic behavior. Ignored if ``maxupdate`` is 0. + pivot : "mrc" or "bland" (default: "mrc") + Pivot rule: Minimum Reduced Cost ("mrc") or Bland's rule ("bland"). + Choose Bland's rule if iteration limit is reached and cycling is + suspected. + unknown_options : dict + Optional arguments not used by this particular solver. If + `unknown_options` is non-empty a warning is issued listing all + unused options. + + Returns + ------- + res : OptimizeResult + A :class:`scipy.optimize.OptimizeResult` consisting of the fields: + + x : 1-D array + The values of the decision variables that minimizes the + objective function while satisfying the constraints. + fun : float + The optimal value of the objective function ``c @ x``. + slack : 1-D array + The (nominally positive) values of the slack variables, + ``b_ub - A_ub @ x``. + con : 1-D array + The (nominally zero) residuals of the equality constraints, + ``b_eq - A_eq @ x``. + success : bool + ``True`` when the algorithm succeeds in finding an optimal + solution. + status : int + An integer representing the exit status of the algorithm. + + ``0`` : Optimization terminated successfully. + + ``1`` : Iteration limit reached. + + ``2`` : Problem appears to be infeasible. + + ``3`` : Problem appears to be unbounded. + + ``4`` : Numerical difficulties encountered. + + ``5`` : Problem has no constraints; turn presolve on. + + ``6`` : Invalid guess provided. + + message : str + A string descriptor of the exit status of the algorithm. + nit : int + The total number of iterations performed in all phases. + + + Notes + ----- + Method *revised simplex* uses the revised simplex method as described in + [9]_, except that a factorization [11]_ of the basis matrix, rather than + its inverse, is efficiently maintained and used to solve the linear systems + at each iteration of the algorithm. + + References + ---------- + .. [9] Bertsimas, Dimitris, and J. Tsitsiklis. "Introduction to linear + programming." Athena Scientific 1 (1997): 997. + .. [11] Bartels, Richard H. "A stabilization of the simplex method." + Journal in Numerische Mathematik 16.5 (1971): 414-434. + """ + pass + + +def _linprog_simplex_doc(c, A_ub=None, b_ub=None, A_eq=None, b_eq=None, + bounds=None, method='interior-point', callback=None, + maxiter=5000, disp=False, presolve=True, + tol=1e-12, autoscale=False, rr=True, bland=False, + **unknown_options): + r""" + Linear programming: minimize a linear objective function subject to linear + equality and inequality constraints using the tableau-based simplex method. + + .. deprecated:: 1.9.0 + `method='simplex'` will be removed in SciPy 1.11.0. + It is replaced by `method='highs'` because the latter is + faster and more robust. + + Linear programming solves problems of the following form: + + .. math:: + + \min_x \ & c^T x \\ + \mbox{such that} \ & A_{ub} x \leq b_{ub},\\ + & A_{eq} x = b_{eq},\\ + & l \leq x \leq u , + + where :math:`x` is a vector of decision variables; :math:`c`, + :math:`b_{ub}`, :math:`b_{eq}`, :math:`l`, and :math:`u` are vectors; and + :math:`A_{ub}` and :math:`A_{eq}` are matrices. + + Alternatively, that's: + + minimize:: + + c @ x + + such that:: + + A_ub @ x <= b_ub + A_eq @ x == b_eq + lb <= x <= ub + + Note that by default ``lb = 0`` and ``ub = None`` unless specified with + ``bounds``. + + Parameters + ---------- + c : 1-D array + The coefficients of the linear objective function to be minimized. + A_ub : 2-D array, optional + The inequality constraint matrix. Each row of ``A_ub`` specifies the + coefficients of a linear inequality constraint on ``x``. + b_ub : 1-D array, optional + The inequality constraint vector. Each element represents an + upper bound on the corresponding value of ``A_ub @ x``. + A_eq : 2-D array, optional + The equality constraint matrix. Each row of ``A_eq`` specifies the + coefficients of a linear equality constraint on ``x``. + b_eq : 1-D array, optional + The equality constraint vector. Each element of ``A_eq @ x`` must equal + the corresponding element of ``b_eq``. + bounds : sequence, optional + A sequence of ``(min, max)`` pairs for each element in ``x``, defining + the minimum and maximum values of that decision variable. Use ``None`` + to indicate that there is no bound. By default, bounds are + ``(0, None)`` (all decision variables are non-negative). + If a single tuple ``(min, max)`` is provided, then ``min`` and + ``max`` will serve as bounds for all decision variables. + method : str + This is the method-specific documentation for 'simplex'. + :ref:`'highs' `, + :ref:`'highs-ds' `, + :ref:`'highs-ipm' `, + :ref:`'interior-point' ` (default), + and :ref:`'revised simplex' ` + are also available. + callback : callable, optional + Callback function to be executed once per iteration. + + Options + ------- + maxiter : int (default: 5000) + The maximum number of iterations to perform in either phase. + disp : bool (default: False) + Set to ``True`` if indicators of optimization status are to be printed + to the console each iteration. + presolve : bool (default: True) + Presolve attempts to identify trivial infeasibilities, + identify trivial unboundedness, and simplify the problem before + sending it to the main solver. It is generally recommended + to keep the default setting ``True``; set to ``False`` if + presolve is to be disabled. + tol : float (default: 1e-12) + The tolerance which determines when a solution is "close enough" to + zero in Phase 1 to be considered a basic feasible solution or close + enough to positive to serve as an optimal solution. + autoscale : bool (default: False) + Set to ``True`` to automatically perform equilibration. + Consider using this option if the numerical values in the + constraints are separated by several orders of magnitude. + rr : bool (default: True) + Set to ``False`` to disable automatic redundancy removal. + bland : bool + If True, use Bland's anti-cycling rule [3]_ to choose pivots to + prevent cycling. If False, choose pivots which should lead to a + converged solution more quickly. The latter method is subject to + cycling (non-convergence) in rare instances. + unknown_options : dict + Optional arguments not used by this particular solver. If + `unknown_options` is non-empty a warning is issued listing all + unused options. + + Returns + ------- + res : OptimizeResult + A :class:`scipy.optimize.OptimizeResult` consisting of the fields: + + x : 1-D array + The values of the decision variables that minimizes the + objective function while satisfying the constraints. + fun : float + The optimal value of the objective function ``c @ x``. + slack : 1-D array + The (nominally positive) values of the slack variables, + ``b_ub - A_ub @ x``. + con : 1-D array + The (nominally zero) residuals of the equality constraints, + ``b_eq - A_eq @ x``. + success : bool + ``True`` when the algorithm succeeds in finding an optimal + solution. + status : int + An integer representing the exit status of the algorithm. + + ``0`` : Optimization terminated successfully. + + ``1`` : Iteration limit reached. + + ``2`` : Problem appears to be infeasible. + + ``3`` : Problem appears to be unbounded. + + ``4`` : Numerical difficulties encountered. + + message : str + A string descriptor of the exit status of the algorithm. + nit : int + The total number of iterations performed in all phases. + + References + ---------- + .. [1] Dantzig, George B., Linear programming and extensions. Rand + Corporation Research Study Princeton Univ. Press, Princeton, NJ, + 1963 + .. [2] Hillier, S.H. and Lieberman, G.J. (1995), "Introduction to + Mathematical Programming", McGraw-Hill, Chapter 4. + .. [3] Bland, Robert G. New finite pivoting rules for the simplex method. + Mathematics of Operations Research (2), 1977: pp. 103-107. + """ + pass diff --git a/shared/package-files/01/01e28f93e12f93469326e7cb837a219677bba91d825c9a8cb1ef20368003fb2d/blob b/shared/package-files/01/01e28f93e12f93469326e7cb837a219677bba91d825c9a8cb1ef20368003fb2d/blob new file mode 100644 index 0000000000000000000000000000000000000000..2a2323d9e07eb496af00996118747fb23cee6a3c --- /dev/null +++ b/shared/package-files/01/01e28f93e12f93469326e7cb837a219677bba91d825c9a8cb1ef20368003fb2d/blob @@ -0,0 +1,79 @@ +from abc import ABCMeta, abstractmethod +from typing import Optional, Union + +from cryptography.hazmat.backends.interfaces import DSABackend +from cryptography.hazmat.primitives.asymmetric import AsymmetricVerificationContext +from cryptography.hazmat.primitives.asymmetric.utils import Prehashed +from cryptography.hazmat.primitives.hashes import HashAlgorithm +from cryptography.hazmat.primitives.serialization import Encoding, KeySerializationEncryption, PrivateFormat, PublicFormat + +class DSAParameters(metaclass=ABCMeta): + @abstractmethod + def generate_private_key(self) -> DSAPrivateKey: ... + +class DSAParametersWithNumbers(DSAParameters): + @abstractmethod + def parameter_numbers(self) -> DSAParameterNumbers: ... + +class DSAParameterNumbers(object): + @property + def p(self) -> int: ... + @property + def q(self) -> int: ... + @property + def g(self) -> int: ... + def __init__(self, p: int, q: int, g: int) -> None: ... + def parameters(self, backend: Optional[DSABackend] = ...) -> DSAParameters: ... + +class DSAPrivateKey(metaclass=ABCMeta): + @property + @abstractmethod + def key_size(self) -> int: ... + @abstractmethod + def parameters(self) -> DSAParameters: ... + @abstractmethod + def public_key(self) -> DSAPublicKey: ... + @abstractmethod + def sign(self, data: bytes, algorithm: Union[HashAlgorithm, Prehashed]) -> bytes: ... + +class DSAPrivateKeyWithSerialization(DSAPrivateKey): + @abstractmethod + def private_bytes( + self, encoding: Encoding, format: PrivateFormat, encryption_algorithm: KeySerializationEncryption + ) -> bytes: ... + @abstractmethod + def private_numbers(self) -> DSAPrivateNumbers: ... + +class DSAPrivateNumbers(object): + @property + def x(self) -> int: ... + @property + def public_numbers(self) -> DSAPublicNumbers: ... + def __init__(self, x: int, public_numbers: DSAPublicNumbers) -> None: ... + +class DSAPublicKey(metaclass=ABCMeta): + @property + @abstractmethod + def key_size(self) -> int: ... + @abstractmethod + def public_bytes(self, encoding: Encoding, format: PublicFormat) -> bytes: ... + @abstractmethod + def public_numbers(self) -> DSAPublicNumbers: ... + @abstractmethod + def verifier( + self, signature: bytes, signature_algorithm: Union[HashAlgorithm, Prehashed] + ) -> AsymmetricVerificationContext: ... + @abstractmethod + def verify(self, signature: bytes, data: bytes, algorithm: Union[HashAlgorithm, Prehashed]) -> None: ... + +DSAPublicKeyWithSerialization = DSAPublicKey + +class DSAPublicNumbers(object): + @property + def y(self) -> int: ... + @property + def parameter_numbers(self) -> DSAParameterNumbers: ... + def __init__(self, y: int, parameter_numbers: DSAParameterNumbers) -> None: ... + +def generate_parameters(key_size: int, backend: Optional[DSABackend] = ...) -> DSAParameters: ... +def generate_private_key(key_size: int, backend: Optional[DSABackend] = ...) -> DSAPrivateKey: ... diff --git a/shared/package-files/01/01e35aa20f07503095ac8b8620201762ef52183b2f57aa9e1a382f587ad5421a/blob b/shared/package-files/01/01e35aa20f07503095ac8b8620201762ef52183b2f57aa9e1a382f587ad5421a/blob new file mode 100644 index 0000000000000000000000000000000000000000..4198a4f2aeb8effcccf94a9c0114539f98124179 Binary files /dev/null and b/shared/package-files/01/01e35aa20f07503095ac8b8620201762ef52183b2f57aa9e1a382f587ad5421a/blob differ diff --git a/shared/package-files/01/01e3b606fa206169b77866870af87399462df226bb29f511887cceff56ad972b/blob b/shared/package-files/01/01e3b606fa206169b77866870af87399462df226bb29f511887cceff56ad972b/blob new file mode 100644 index 0000000000000000000000000000000000000000..586ed37c553156cb4053308fd11fb4992e46261a --- /dev/null +++ b/shared/package-files/01/01e3b606fa206169b77866870af87399462df226bb29f511887cceff56ad972b/blob @@ -0,0 +1,6 @@ +Wheel-Version: 1.0 +Generator: setuptools (79.0.1) +Root-Is-Purelib: true +Tag: py2-none-any +Tag: py3-none-any + diff --git a/shared/package-files/01/01e3b7a8fc9e43310e6a035bf4058e8965f667244ae2a4f211781db6d17e6332/blob b/shared/package-files/01/01e3b7a8fc9e43310e6a035bf4058e8965f667244ae2a4f211781db6d17e6332/blob new file mode 100644 index 0000000000000000000000000000000000000000..75910d2d9ab3ff13d448e631b691aa68b1653f44 --- /dev/null +++ b/shared/package-files/01/01e3b7a8fc9e43310e6a035bf4058e8965f667244ae2a4f211781db6d17e6332/blob @@ -0,0 +1,231 @@ +# +# The Python Imaging Library. +# $Id$ +# +# a Windows DIB display interface +# +# History: +# 1996-05-20 fl Created +# 1996-09-20 fl Fixed subregion exposure +# 1997-09-21 fl Added draw primitive (for tzPrint) +# 2003-05-21 fl Added experimental Window/ImageWindow classes +# 2003-09-05 fl Added fromstring/tostring methods +# +# Copyright (c) Secret Labs AB 1997-2003. +# Copyright (c) Fredrik Lundh 1996-2003. +# +# See the README file for information on usage and redistribution. +# +from __future__ import annotations + +from . import Image + + +class HDC: + """ + Wraps an HDC integer. The resulting object can be passed to the + :py:meth:`~PIL.ImageWin.Dib.draw` and :py:meth:`~PIL.ImageWin.Dib.expose` + methods. + """ + + def __init__(self, dc): + self.dc = dc + + def __int__(self): + return self.dc + + +class HWND: + """ + Wraps an HWND integer. The resulting object can be passed to the + :py:meth:`~PIL.ImageWin.Dib.draw` and :py:meth:`~PIL.ImageWin.Dib.expose` + methods, instead of a DC. + """ + + def __init__(self, wnd): + self.wnd = wnd + + def __int__(self): + return self.wnd + + +class Dib: + """ + A Windows bitmap with the given mode and size. The mode can be one of "1", + "L", "P", or "RGB". + + If the display requires a palette, this constructor creates a suitable + palette and associates it with the image. For an "L" image, 128 graylevels + are allocated. For an "RGB" image, a 6x6x6 colour cube is used, together + with 20 graylevels. + + To make sure that palettes work properly under Windows, you must call the + ``palette`` method upon certain events from Windows. + + :param image: Either a PIL image, or a mode string. If a mode string is + used, a size must also be given. The mode can be one of "1", + "L", "P", or "RGB". + :param size: If the first argument is a mode string, this + defines the size of the image. + """ + + def __init__(self, image, size=None): + if hasattr(image, "mode") and hasattr(image, "size"): + mode = image.mode + size = image.size + else: + mode = image + image = None + if mode not in ["1", "L", "P", "RGB"]: + mode = Image.getmodebase(mode) + self.image = Image.core.display(mode, size) + self.mode = mode + self.size = size + if image: + self.paste(image) + + def expose(self, handle): + """ + Copy the bitmap contents to a device context. + + :param handle: Device context (HDC), cast to a Python integer, or an + HDC or HWND instance. In PythonWin, you can use + ``CDC.GetHandleAttrib()`` to get a suitable handle. + """ + if isinstance(handle, HWND): + dc = self.image.getdc(handle) + try: + result = self.image.expose(dc) + finally: + self.image.releasedc(handle, dc) + else: + result = self.image.expose(handle) + return result + + def draw(self, handle, dst, src=None): + """ + Same as expose, but allows you to specify where to draw the image, and + what part of it to draw. + + The destination and source areas are given as 4-tuple rectangles. If + the source is omitted, the entire image is copied. If the source and + the destination have different sizes, the image is resized as + necessary. + """ + if not src: + src = (0, 0) + self.size + if isinstance(handle, HWND): + dc = self.image.getdc(handle) + try: + result = self.image.draw(dc, dst, src) + finally: + self.image.releasedc(handle, dc) + else: + result = self.image.draw(handle, dst, src) + return result + + def query_palette(self, handle): + """ + Installs the palette associated with the image in the given device + context. + + This method should be called upon **QUERYNEWPALETTE** and + **PALETTECHANGED** events from Windows. If this method returns a + non-zero value, one or more display palette entries were changed, and + the image should be redrawn. + + :param handle: Device context (HDC), cast to a Python integer, or an + HDC or HWND instance. + :return: A true value if one or more entries were changed (this + indicates that the image should be redrawn). + """ + if isinstance(handle, HWND): + handle = self.image.getdc(handle) + try: + result = self.image.query_palette(handle) + finally: + self.image.releasedc(handle, handle) + else: + result = self.image.query_palette(handle) + return result + + def paste(self, im, box=None): + """ + Paste a PIL image into the bitmap image. + + :param im: A PIL image. The size must match the target region. + If the mode does not match, the image is converted to the + mode of the bitmap image. + :param box: A 4-tuple defining the left, upper, right, and + lower pixel coordinate. See :ref:`coordinate-system`. If + None is given instead of a tuple, all of the image is + assumed. + """ + im.load() + if self.mode != im.mode: + im = im.convert(self.mode) + if box: + self.image.paste(im.im, box) + else: + self.image.paste(im.im) + + def frombytes(self, buffer): + """ + Load display memory contents from byte data. + + :param buffer: A buffer containing display data (usually + data returned from :py:func:`~PIL.ImageWin.Dib.tobytes`) + """ + return self.image.frombytes(buffer) + + def tobytes(self): + """ + Copy display memory contents to bytes object. + + :return: A bytes object containing display data. + """ + return self.image.tobytes() + + +class Window: + """Create a Window with the given title size.""" + + def __init__(self, title="PIL", width=None, height=None): + self.hwnd = Image.core.createwindow( + title, self.__dispatcher, width or 0, height or 0 + ) + + def __dispatcher(self, action, *args): + return getattr(self, "ui_handle_" + action)(*args) + + def ui_handle_clear(self, dc, x0, y0, x1, y1): + pass + + def ui_handle_damage(self, x0, y0, x1, y1): + pass + + def ui_handle_destroy(self): + pass + + def ui_handle_repair(self, dc, x0, y0, x1, y1): + pass + + def ui_handle_resize(self, width, height): + pass + + def mainloop(self): + Image.core.eventloop() + + +class ImageWindow(Window): + """Create an image window which displays the given image.""" + + def __init__(self, image, title="PIL"): + if not isinstance(image, Dib): + image = Dib(image) + self.image = image + width, height = image.size + super().__init__(title, width=width, height=height) + + def ui_handle_repair(self, dc, x0, y0, x1, y1): + self.image.draw(dc, (x0, y0, x1, y1)) diff --git a/shared/package-files/01/01e41371ee3a5c46755cc28b02fba8cad6b623fc4fb9ea94824552aa7d002d46/blob b/shared/package-files/01/01e41371ee3a5c46755cc28b02fba8cad6b623fc4fb9ea94824552aa7d002d46/blob new file mode 100644 index 0000000000000000000000000000000000000000..8078540fd9c25c3778b4e63ac557775b2a16fd56 --- /dev/null +++ b/shared/package-files/01/01e41371ee3a5c46755cc28b02fba8cad6b623fc4fb9ea94824552aa7d002d46/blob @@ -0,0 +1,25 @@ +#pragma once +// @generated by torchgen/gen.py from DispatchKeyFunction.h + +// NB: The implementing C++ file is RegisterDispatchKey.cpp + +// The only #includes we need are for custom classes that have defaults in the C++ API +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { + +namespace compositeimplicitautograd { + +TORCH_API at::Tensor linalg_cholesky(const at::Tensor & self, bool upper=false); +TORCH_API at::Tensor & linalg_cholesky_out(at::Tensor & out, const at::Tensor & self, bool upper=false); +TORCH_API at::Tensor & linalg_cholesky_outf(const at::Tensor & self, bool upper, at::Tensor & out); + +} // namespace compositeimplicitautograd +} // namespace at diff --git a/shared/package-files/01/01e823821d6b2de6f030ae3d9070c6f9abd00b91dda04d7358c9dc442197ea20/blob b/shared/package-files/01/01e823821d6b2de6f030ae3d9070c6f9abd00b91dda04d7358c9dc442197ea20/blob new file mode 100644 index 0000000000000000000000000000000000000000..6c25b55fdac53c4edcaf6f5deaac87735df89b18 --- /dev/null +++ b/shared/package-files/01/01e823821d6b2de6f030ae3d9070c6f9abd00b91dda04d7358c9dc442197ea20/blob @@ -0,0 +1,23 @@ +#pragma once + +// @generated by torchgen/gen.py from NativeFunction.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace at { +namespace native { +struct TORCH_API structured_bitwise_not_out : public at::meta::structured_bitwise_not { +void impl(const at::Tensor & self, const at::Tensor & out); +}; +} // namespace native +} // namespace at diff --git a/shared/package-files/01/01ea0e85b4cff9c0957caee712fbcb4049515f91e9f6c8dca15ee67e9ec7dab8/blob b/shared/package-files/01/01ea0e85b4cff9c0957caee712fbcb4049515f91e9f6c8dca15ee67e9ec7dab8/blob new file mode 100644 index 0000000000000000000000000000000000000000..8accef6afc3433c3371955eceb9f626e6fcd8558 --- /dev/null +++ b/shared/package-files/01/01ea0e85b4cff9c0957caee712fbcb4049515f91e9f6c8dca15ee67e9ec7dab8/blob @@ -0,0 +1,94 @@ +from contextlib import contextmanager, nullcontext +from typing import Any, Tuple + +import torch +import torch.nn as nn +from torch.utils.checkpoint import ( + _checkpoint_without_reentrant_generator, + _DEFAULT_DETERMINISM_MODE, +) + +from .contract import contract + + +@contextmanager +def _no_hook(module: nn.Module): + r""" + Disable hooks installed by checkpoint to avoid unintentional recursion + during backward recomputation. + """ + orig_enable_hook = checkpoint.state(module).enable_hook + checkpoint.state(module).enable_hook = False + try: + yield + finally: + checkpoint.state(module).enable_hook = orig_enable_hook + + +@contract() +def checkpoint(module: nn.Module) -> nn.Module: + r""" + This is a composable activation checkpointing API. Unlike functional + activation checkpointing APIs, this one does not require changing model + source code. Unlike ``nn.Module`` wrapper activation checkpointing APIs, + this one does not modify model structure or fully-qualified names either. + Under the hood, it registers activation checkpointing logic as pre- and + post-forward hooks. Hence, this API can be easily applied to any model or + sub-modules in the model. + + Args: + module (nn.Module): the target model or sub-module to apply activation + checkpointing. + + Example:: + >>> # xdoctest: +SKIP + >>> import torch.nn as nn + >>> + >>> class MyModel(nn.Module): + >>> def __init__(self): + >>> super().__init__() + >>> self.l1 = nn.Linear(10, 10) + >>> self.l2 = nn.Linear(10, 10) + >>> + >>> def forward(self, x): + >>> return self.l2(self.l1(x)) + >>> + >>> model = MyModel() + >>> checkpoint(model.l1) # apply activation checkpointing only to l1 + >>> model(torch.zeros(2, 10)).sum().backward() + + """ + torch._C._log_api_usage_once("torch.distributed.checkpoint") + + def forward_pre_hook(module: nn.Module, inputs: Tuple[Any, ...]) -> None: + if checkpoint.state(module).enable_hook: + + def context_fns(): + return nullcontext(), _no_hook(module) + + checkpoint.state( + module + )._ac_generator = _checkpoint_without_reentrant_generator( + module, True, context_fns, _DEFAULT_DETERMINISM_MODE, False, *inputs + ) + next(checkpoint.state(module)._ac_generator) + + def forward_hook(module: nn.Module, inputs: Tuple[Any, ...], output: Any) -> Any: + if checkpoint.state(module).enable_hook: + try: + next(checkpoint.state(module)._ac_generator) + except StopIteration: + pass + else: + raise RuntimeError( + "Expected non-reentrant activation checkpoint generator to be exhausted, but it was not!" + ) + + # Ensure that we no longer hold on to the generator. always_call=True helps ensure we + # clear this even in the case of exception in fwd pass. + checkpoint.state(module)._ac_generator = None + + checkpoint.state(module).enable_hook = True + module.register_forward_pre_hook(forward_pre_hook) + module.register_forward_hook(forward_hook, prepend=True, always_call=True) + return module diff --git a/shared/package-files/01/01ecbc2e4ba9c6ad16579df9448808f7655a02886afdf77efc3da6899a7de5d3/blob b/shared/package-files/01/01ecbc2e4ba9c6ad16579df9448808f7655a02886afdf77efc3da6899a7de5d3/blob new file mode 100644 index 0000000000000000000000000000000000000000..061292e9bd0a10fbcd44471288704b81a780e43b --- /dev/null +++ b/shared/package-files/01/01ecbc2e4ba9c6ad16579df9448808f7655a02886afdf77efc3da6899a7de5d3/blob @@ -0,0 +1,772 @@ +# This file is part of Hypothesis, which may be found at +# https://github.com/HypothesisWorks/hypothesis/ +# +# Copyright the Hypothesis Authors. +# Individual contributors are listed in AUTHORS.rst and the git log. +# +# This Source Code Form is subject to the terms of the Mozilla Public License, +# v. 2.0. If a copy of the MPL was not distributed with this file, You can +# obtain one at https://mozilla.org/MPL/2.0/. + +"""The settings module configures runtime options for Hypothesis. + +Either an explicit settings object can be used or the default object on +this module can be modified. +""" + +import contextlib +import datetime +import inspect +import os +import warnings +from enum import Enum, EnumMeta, IntEnum, unique +from typing import ( + TYPE_CHECKING, + Any, + ClassVar, + Collection, + Dict, + List, + Optional, + TypeVar, + Union, +) + +import attr + +from hypothesis.errors import ( + HypothesisDeprecationWarning, + InvalidArgument, + InvalidState, +) +from hypothesis.internal.reflection import get_pretty_function_description +from hypothesis.internal.validation import check_type, try_convert +from hypothesis.utils.conventions import not_set +from hypothesis.utils.dynamicvariables import DynamicVariable + +if TYPE_CHECKING: + from hypothesis.database import ExampleDatabase + +__all__ = ["settings"] + +all_settings: Dict[str, "Setting"] = {} + +T = TypeVar("T") + + +class settingsProperty: + def __init__(self, name, show_default): + self.name = name + self.show_default = show_default + + def __get__(self, obj, type=None): + if obj is None: + return self + else: + try: + result = obj.__dict__[self.name] + # This is a gross hack, but it preserves the old behaviour that + # you can change the storage directory and it will be reflected + # in the default database. + if self.name == "database" and result is not_set: + from hypothesis.database import ExampleDatabase + + result = ExampleDatabase(not_set) + return result + except KeyError: + raise AttributeError(self.name) from None + + def __set__(self, obj, value): + obj.__dict__[self.name] = value + + def __delete__(self, obj): + raise AttributeError(f"Cannot delete attribute {self.name}") + + @property + def __doc__(self): + description = all_settings[self.name].description + default = ( + repr(getattr(settings.default, self.name)) + if self.show_default + else "(dynamically calculated)" + ) + return f"{description}\n\ndefault value: ``{default}``" + + +default_variable = DynamicVariable(None) + + +class settingsMeta(type): + def __init__(cls, *args, **kwargs): + super().__init__(*args, **kwargs) + + @property + def default(cls): + v = default_variable.value + if v is not None: + return v + if hasattr(settings, "_current_profile"): + settings.load_profile(settings._current_profile) + assert default_variable.value is not None + return default_variable.value + + def _assign_default_internal(cls, value): + default_variable.value = value + + def __setattr__(cls, name, value): + if name == "default": + raise AttributeError( + "Cannot assign to the property settings.default - " + "consider using settings.load_profile instead." + ) + elif not (isinstance(value, settingsProperty) or name.startswith("_")): + raise AttributeError( + f"Cannot assign hypothesis.settings.{name}={value!r} - the settings " + "class is immutable. You can change the global default " + "settings with settings.load_profile, or use @settings(...) " + "to decorate your test instead." + ) + return super().__setattr__(name, value) + + +class settings(metaclass=settingsMeta): + """A settings object configures options including verbosity, runtime controls, + persistence, determinism, and more. + + Default values are picked up from the settings.default object and + changes made there will be picked up in newly created settings. + """ + + __definitions_are_locked = False + _profiles: ClassVar[Dict[str, "settings"]] = {} + __module__ = "hypothesis" + + def __getattr__(self, name): + if name in all_settings: + return all_settings[name].default + else: + raise AttributeError(f"settings has no attribute {name}") + + def __init__( + self, + parent: Optional["settings"] = None, + *, + # This looks pretty strange, but there's good reason: we want Mypy to detect + # bad calls downstream, but not to freak out about the `= not_set` part even + # though it's not semantically valid to pass that as an argument value. + # The intended use is "like **kwargs, but more tractable for tooling". + max_examples: int = not_set, # type: ignore + derandomize: bool = not_set, # type: ignore + database: Optional["ExampleDatabase"] = not_set, # type: ignore + verbosity: "Verbosity" = not_set, # type: ignore + phases: Collection["Phase"] = not_set, # type: ignore + stateful_step_count: int = not_set, # type: ignore + report_multiple_bugs: bool = not_set, # type: ignore + suppress_health_check: Collection["HealthCheck"] = not_set, # type: ignore + deadline: Union[int, float, datetime.timedelta, None] = not_set, # type: ignore + print_blob: bool = not_set, # type: ignore + backend: str = not_set, # type: ignore + ) -> None: + if parent is not None: + check_type(settings, parent, "parent") + if derandomize not in (not_set, False): + if database not in (not_set, None): # type: ignore + raise InvalidArgument( + "derandomize=True implies database=None, so passing " + f"{database=} too is invalid." + ) + database = None + + defaults = parent or settings.default + if defaults is not None: + for setting in all_settings.values(): + value = locals()[setting.name] + if value is not_set: + object.__setattr__( + self, setting.name, getattr(defaults, setting.name) + ) + else: + object.__setattr__(self, setting.name, setting.validator(value)) + + def __call__(self, test: T) -> T: + """Make the settings object (self) an attribute of the test. + + The settings are later discovered by looking them up on the test itself. + """ + # Aliasing as Any avoids mypy errors (attr-defined) when accessing and + # setting custom attributes on the decorated function or class. + _test: Any = test + + # Using the alias here avoids a mypy error (return-value) later when + # ``test`` is returned, because this check results in type refinement. + if not callable(_test): + raise InvalidArgument( + "settings objects can be called as a decorator with @given, " + f"but decorated {test=} is not callable." + ) + if inspect.isclass(test): + from hypothesis.stateful import RuleBasedStateMachine + + if issubclass(_test, RuleBasedStateMachine): + attr_name = "_hypothesis_internal_settings_applied" + if getattr(test, attr_name, False): + raise InvalidArgument( + "Applying the @settings decorator twice would " + "overwrite the first version; merge their arguments " + "instead." + ) + setattr(test, attr_name, True) + _test.TestCase.settings = self + return test # type: ignore + else: + raise InvalidArgument( + "@settings(...) can only be used as a decorator on " + "functions, or on subclasses of RuleBasedStateMachine." + ) + if hasattr(_test, "_hypothesis_internal_settings_applied"): + # Can't use _hypothesis_internal_use_settings as an indicator that + # @settings was applied, because @given also assigns that attribute. + descr = get_pretty_function_description(test) + raise InvalidArgument( + f"{descr} has already been decorated with a settings object.\n" + f" Previous: {_test._hypothesis_internal_use_settings!r}\n" + f" This: {self!r}" + ) + + _test._hypothesis_internal_use_settings = self + _test._hypothesis_internal_settings_applied = True + return test + + @classmethod + def _define_setting( + cls, + name, + description, + *, + default, + options=None, + validator=None, + show_default=True, + ): + """Add a new setting. + + - name is the name of the property that will be used to access the + setting. This must be a valid python identifier. + - description will appear in the property's docstring + - default is the default value. This may be a zero argument + function in which case it is evaluated and its result is stored + the first time it is accessed on any given settings object. + """ + if settings.__definitions_are_locked: + raise InvalidState( + "settings have been locked and may no longer be defined." + ) + if options is not None: + options = tuple(options) + assert default in options + + def validator(value): + if value not in options: + msg = f"Invalid {name}, {value!r}. Valid options: {options!r}" + raise InvalidArgument(msg) + return value + + else: + assert validator is not None + + all_settings[name] = Setting( + name=name, + description=description.strip(), + default=default, + validator=validator, + ) + setattr(settings, name, settingsProperty(name, show_default)) + + @classmethod + def lock_further_definitions(cls): + settings.__definitions_are_locked = True + + def __setattr__(self, name, value): + raise AttributeError("settings objects are immutable") + + def __repr__(self): + from hypothesis.internal.conjecture.data import AVAILABLE_PROVIDERS + + bits = sorted( + f"{name}={getattr(self, name)!r}" + for name in all_settings + if (name != "backend" or len(AVAILABLE_PROVIDERS) > 1) # experimental + ) + return "settings({})".format(", ".join(bits)) + + def show_changed(self): + bits = [] + for name, setting in all_settings.items(): + value = getattr(self, name) + if value != setting.default: + bits.append(f"{name}={value!r}") + return ", ".join(sorted(bits, key=len)) + + @staticmethod + def register_profile( + name: str, + parent: Optional["settings"] = None, + **kwargs: Any, + ) -> None: + """Registers a collection of values to be used as a settings profile. + + Settings profiles can be loaded by name - for example, you might + create a 'fast' profile which runs fewer examples, keep the 'default' + profile, and create a 'ci' profile that increases the number of + examples and uses a different database to store failures. + + The arguments to this method are exactly as for + :class:`~hypothesis.settings`: optional ``parent`` settings, and + keyword arguments for each setting that will be set differently to + parent (or settings.default, if parent is None). + """ + check_type(str, name, "name") + settings._profiles[name] = settings(parent=parent, **kwargs) + + @staticmethod + def get_profile(name: str) -> "settings": + """Return the profile with the given name.""" + check_type(str, name, "name") + try: + return settings._profiles[name] + except KeyError: + raise InvalidArgument(f"Profile {name!r} is not registered") from None + + @staticmethod + def load_profile(name: str) -> None: + """Loads in the settings defined in the profile provided. + + If the profile does not exist, InvalidArgument will be raised. + Any setting not defined in the profile will be the library + defined default for that setting. + """ + check_type(str, name, "name") + settings._current_profile = name + settings._assign_default_internal(settings.get_profile(name)) + + +@contextlib.contextmanager +def local_settings(s): + with default_variable.with_value(s): + yield s + + +@attr.s() +class Setting: + name = attr.ib() + description = attr.ib() + default = attr.ib() + validator = attr.ib() + + +def _max_examples_validator(x): + check_type(int, x, name="max_examples") + if x < 1: + raise InvalidArgument( + f"max_examples={x!r} should be at least one. You can disable " + "example generation with the `phases` setting instead." + ) + return x + + +settings._define_setting( + "max_examples", + default=100, + validator=_max_examples_validator, + description=""" +Once this many satisfying examples have been considered without finding any +counter-example, Hypothesis will stop looking. + +Note that we might call your test function fewer times if we find a bug early +or can tell that we've exhausted the search space; or more if we discard some +examples due to use of .filter(), assume(), or a few other things that can +prevent the test case from completing successfully. + +The default value is chosen to suit a workflow where the test will be part of +a suite that is regularly executed locally or on a CI server, balancing total +running time against the chance of missing a bug. + +If you are writing one-off tests, running tens of thousands of examples is +quite reasonable as Hypothesis may miss uncommon bugs with default settings. +For very complex code, we have observed Hypothesis finding novel bugs after +*several million* examples while testing :pypi:`SymPy`. +If you are running more than 100k examples for a test, consider using our +:ref:`integration for coverage-guided fuzzing ` - it really +shines when given minutes or hours to run. +""", +) + + +settings._define_setting( + "derandomize", + default=False, + options=(True, False), + description=""" +If True, seed Hypothesis' random number generator using a hash of the test +function, so that every run will test the same set of examples until you +update Hypothesis, Python, or the test function. + +This allows you to `check for regressions and look for bugs +`__ using +:ref:`separate settings profiles ` - for example running +quick deterministic tests on every commit, and a longer non-deterministic +nightly testing run. +""", +) + + +def _validate_database(db): + from hypothesis.database import ExampleDatabase + + if db is None or isinstance(db, ExampleDatabase): + return db + raise InvalidArgument( + "Arguments to the database setting must be None or an instance of " + f"ExampleDatabase. Try passing database=ExampleDatabase({db!r}), or " + "construct and use one of the specific subclasses in " + "hypothesis.database" + ) + + +settings._define_setting( + "database", + default=not_set, + show_default=False, + description=""" +An instance of :class:`~hypothesis.database.ExampleDatabase` that will be +used to save examples to and load previous examples from. May be ``None`` +in which case no storage will be used. + +See the :doc:`example database documentation ` for a list of built-in +example database implementations, and how to define custom implementations. +""", + validator=_validate_database, +) + + +@unique +class Phase(IntEnum): + explicit = 0 #: controls whether explicit examples are run. + reuse = 1 #: controls whether previous examples will be reused. + generate = 2 #: controls whether new examples will be generated. + target = 3 #: controls whether examples will be mutated for targeting. + shrink = 4 #: controls whether examples will be shrunk. + explain = 5 #: controls whether Hypothesis attempts to explain test failures. + + def __repr__(self): + return f"Phase.{self.name}" + + +class HealthCheckMeta(EnumMeta): + def __iter__(self): + deprecated = (HealthCheck.return_value, HealthCheck.not_a_test_method) + return iter(x for x in super().__iter__() if x not in deprecated) + + +@unique +class HealthCheck(Enum, metaclass=HealthCheckMeta): + """Arguments for :attr:`~hypothesis.settings.suppress_health_check`. + + Each member of this enum is a type of health check to suppress. + """ + + def __repr__(self): + return f"{self.__class__.__name__}.{self.name}" + + @classmethod + def all(cls) -> List["HealthCheck"]: + # Skipping of deprecated attributes is handled in HealthCheckMeta.__iter__ + note_deprecation( + "`Healthcheck.all()` is deprecated; use `list(HealthCheck)` instead.", + since="2023-04-16", + has_codemod=True, + stacklevel=1, + ) + return list(HealthCheck) + + data_too_large = 1 + """Checks if too many examples are aborted for being too large. + + This is measured by the number of random choices that Hypothesis makes + in order to generate something, not the size of the generated object. + For example, choosing a 100MB object from a predefined list would take + only a few bits, while generating 10KB of JSON from scratch might trigger + this health check. + """ + + filter_too_much = 2 + """Check for when the test is filtering out too many examples, either + through use of :func:`~hypothesis.assume()` or :ref:`filter() `, + or occasionally for Hypothesis internal reasons.""" + + too_slow = 3 + """Check for when your data generation is extremely slow and likely to hurt + testing.""" + + return_value = 5 + """Deprecated; we always error if a test returns a non-None value.""" + + large_base_example = 7 + """Checks if the natural example to shrink towards is very large.""" + + not_a_test_method = 8 + """Deprecated; we always error if :func:`@given ` is applied + to a method defined by :class:`python:unittest.TestCase` (i.e. not a test).""" + + function_scoped_fixture = 9 + """Checks if :func:`@given ` has been applied to a test + with a pytest function-scoped fixture. Function-scoped fixtures run once + for the whole function, not once per example, and this is usually not what + you want. + + Because of this limitation, tests that need to set up or reset + state for every example need to do so manually within the test itself, + typically using an appropriate context manager. + + Suppress this health check only in the rare case that you are using a + function-scoped fixture that does not need to be reset between individual + examples, but for some reason you cannot use a wider fixture scope + (e.g. session scope, module scope, class scope). + + This check requires the :ref:`Hypothesis pytest plugin`, + which is enabled by default when running Hypothesis inside pytest.""" + + differing_executors = 10 + """Checks if :func:`@given ` has been applied to a test + which is executed by different :ref:`executors`. + If your test function is defined as a method on a class, that class will be + your executor, and subclasses executing an inherited test is a common way + for things to go wrong. + + The correct fix is often to bring the executor instance under the control + of hypothesis by explicit parametrization over, or sampling from, + subclasses, or to refactor so that :func:`@given ` is + specified on leaf subclasses.""" + + +@unique +class Verbosity(IntEnum): + quiet = 0 + normal = 1 + verbose = 2 + debug = 3 + + def __repr__(self): + return f"Verbosity.{self.name}" + + +settings._define_setting( + "verbosity", + options=tuple(Verbosity), + default=Verbosity.normal, + description="Control the verbosity level of Hypothesis messages", +) + + +def _validate_phases(phases): + phases = tuple(phases) + for a in phases: + if not isinstance(a, Phase): + raise InvalidArgument(f"{a!r} is not a valid phase") + return tuple(p for p in list(Phase) if p in phases) + + +settings._define_setting( + "phases", + default=tuple(Phase), + description=( + "Control which phases should be run. " + "See :ref:`the full documentation for more details `" + ), + validator=_validate_phases, +) + + +def _validate_stateful_step_count(x): + check_type(int, x, name="stateful_step_count") + if x < 1: + raise InvalidArgument(f"stateful_step_count={x!r} must be at least one.") + return x + + +settings._define_setting( + name="stateful_step_count", + default=50, + validator=_validate_stateful_step_count, + description=""" +Number of steps to run a stateful program for before giving up on it breaking. +""", +) + +settings._define_setting( + name="report_multiple_bugs", + default=True, + options=(True, False), + description=""" +Because Hypothesis runs the test many times, it can sometimes find multiple +bugs in a single run. Reporting all of them at once is usually very useful, +but replacing the exceptions can occasionally clash with debuggers. +If disabled, only the exception with the smallest minimal example is raised. +""", +) + + +def validate_health_check_suppressions(suppressions): + suppressions = try_convert(list, suppressions, "suppress_health_check") + for s in suppressions: + if not isinstance(s, HealthCheck): + raise InvalidArgument( + f"Non-HealthCheck value {s!r} of type {type(s).__name__} " + "is invalid in suppress_health_check." + ) + if s in (HealthCheck.return_value, HealthCheck.not_a_test_method): + note_deprecation( + f"The {s.name} health check is deprecated, because this is always an error.", + since="2023-03-15", + has_codemod=False, + stacklevel=2, + ) + return suppressions + + +settings._define_setting( + "suppress_health_check", + default=(), + description="""A list of :class:`~hypothesis.HealthCheck` items to disable.""", + validator=validate_health_check_suppressions, +) + + +class duration(datetime.timedelta): + """A timedelta specifically measured in milliseconds.""" + + def __repr__(self): + ms = self.total_seconds() * 1000 + return f"timedelta(milliseconds={int(ms) if ms == int(ms) else ms!r})" + + +def _validate_deadline(x): + if x is None: + return x + invalid_deadline_error = InvalidArgument( + f"deadline={x!r} (type {type(x).__name__}) must be a timedelta object, " + "an integer or float number of milliseconds, or None to disable the " + "per-test-case deadline." + ) + if isinstance(x, (int, float)): + if isinstance(x, bool): + raise invalid_deadline_error + try: + x = duration(milliseconds=x) + except OverflowError: + raise InvalidArgument( + f"deadline={x!r} is invalid, because it is too large to represent " + "as a timedelta. Use deadline=None to disable deadlines." + ) from None + if isinstance(x, datetime.timedelta): + if x <= datetime.timedelta(0): + raise InvalidArgument( + f"deadline={x!r} is invalid, because it is impossible to meet a " + "deadline <= 0. Use deadline=None to disable deadlines." + ) + return duration(seconds=x.total_seconds()) + raise invalid_deadline_error + + +settings._define_setting( + "deadline", + default=duration(milliseconds=200), + validator=_validate_deadline, + description=""" +If set, a duration (as timedelta, or integer or float number of milliseconds) +that each individual example (i.e. each time your test +function is called, not the whole decorated test) within a test is not +allowed to exceed. Tests which take longer than that may be converted into +errors (but will not necessarily be if close to the deadline, to allow some +variability in test run time). + +Set this to ``None`` to disable this behaviour entirely. +""", +) + + +def is_in_ci() -> bool: + # GitHub Actions, Travis CI and AppVeyor have "CI" + # Azure Pipelines has "TF_BUILD" + return "CI" in os.environ or "TF_BUILD" in os.environ + + +settings._define_setting( + "print_blob", + default=is_in_ci(), + show_default=False, + options=(True, False), + description=""" +If set to ``True``, Hypothesis will print code for failing examples that can be used with +:func:`@reproduce_failure ` to reproduce the failing example. +The default is ``True`` if the ``CI`` or ``TF_BUILD`` env vars are set, ``False`` otherwise. +""", +) + + +def _backend_validator(value): + from hypothesis.internal.conjecture.data import AVAILABLE_PROVIDERS + + if value not in AVAILABLE_PROVIDERS: + if value == "crosshair": # pragma: no cover + install = '`pip install "hypothesis[crosshair]"` and try again.' + raise InvalidArgument(f"backend={value!r} is not available. {install}") + raise InvalidArgument( + f"backend={value!r} is not available - maybe you need to install a plugin?" + f"\n Installed backends: {sorted(AVAILABLE_PROVIDERS)!r}" + ) + return value + + +settings._define_setting( + "backend", + default="hypothesis", + show_default=False, + validator=_backend_validator, + description=""" +EXPERIMENTAL AND UNSTABLE - see :ref:`alternative-backends`. +The importable name of a backend which Hypothesis should use to generate primitive +types. We aim to support heuristic-random, solver-based, and fuzzing-based backends. +""", +) + +settings.lock_further_definitions() + + +def note_deprecation( + message: str, *, since: str, has_codemod: bool, stacklevel: int = 0 +) -> None: + if since != "RELEASEDAY": + date = datetime.date.fromisoformat(since) + assert datetime.date(2021, 1, 1) <= date + if has_codemod: + message += ( + "\n The `hypothesis codemod` command-line tool can automatically " + "refactor your code to fix this warning." + ) + warnings.warn(HypothesisDeprecationWarning(message), stacklevel=2 + stacklevel) + + +settings.register_profile("default", settings()) +settings.load_profile("default") +assert settings.default is not None + + +# Check that the kwonly args to settings.__init__ is the same as the set of +# defined settings - in case we've added or remove something from one but +# not the other. +assert set(all_settings) == { + p.name + for p in inspect.signature(settings.__init__).parameters.values() + if p.kind == inspect.Parameter.KEYWORD_ONLY +} diff --git a/shared/package-files/01/01eed22047545deacb1b4448b55589a9941df362a28570dd225606776d47c225/blob b/shared/package-files/01/01eed22047545deacb1b4448b55589a9941df362a28570dd225606776d47c225/blob new file mode 100644 index 0000000000000000000000000000000000000000..81fad02dbec82b47d0995333baafd9e5dff1277a --- /dev/null +++ b/shared/package-files/01/01eed22047545deacb1b4448b55589a9941df362a28570dd225606776d47c225/blob @@ -0,0 +1,70 @@ +"""Tests for distutils.extension.""" +import unittest +import os +import warnings + +from test.support import run_unittest +from test.support.warnings_helper import check_warnings +from distutils.extension import read_setup_file, Extension + +class ExtensionTestCase(unittest.TestCase): + + def test_read_setup_file(self): + # trying to read a Setup file + # (sample extracted from the PyGame project) + setup = os.path.join(os.path.dirname(__file__), 'Setup.sample') + + exts = read_setup_file(setup) + names = [ext.name for ext in exts] + names.sort() + + # here are the extensions read_setup_file should have created + # out of the file + wanted = ['_arraysurfarray', '_camera', '_numericsndarray', + '_numericsurfarray', 'base', 'bufferproxy', 'cdrom', + 'color', 'constants', 'display', 'draw', 'event', + 'fastevent', 'font', 'gfxdraw', 'image', 'imageext', + 'joystick', 'key', 'mask', 'mixer', 'mixer_music', + 'mouse', 'movie', 'overlay', 'pixelarray', 'pypm', + 'rect', 'rwobject', 'scrap', 'surface', 'surflock', + 'time', 'transform'] + + self.assertEqual(names, wanted) + + def test_extension_init(self): + # the first argument, which is the name, must be a string + self.assertRaises(AssertionError, Extension, 1, []) + ext = Extension('name', []) + self.assertEqual(ext.name, 'name') + + # the second argument, which is the list of files, must + # be a list of strings + self.assertRaises(AssertionError, Extension, 'name', 'file') + self.assertRaises(AssertionError, Extension, 'name', ['file', 1]) + ext = Extension('name', ['file1', 'file2']) + self.assertEqual(ext.sources, ['file1', 'file2']) + + # others arguments have defaults + for attr in ('include_dirs', 'define_macros', 'undef_macros', + 'library_dirs', 'libraries', 'runtime_library_dirs', + 'extra_objects', 'extra_compile_args', 'extra_link_args', + 'export_symbols', 'swig_opts', 'depends'): + self.assertEqual(getattr(ext, attr), []) + + self.assertEqual(ext.language, None) + self.assertEqual(ext.optional, None) + + # if there are unknown keyword options, warn about them + with check_warnings() as w: + warnings.simplefilter('always') + ext = Extension('name', ['file1', 'file2'], chic=True) + + self.assertEqual(len(w.warnings), 1) + self.assertEqual(str(w.warnings[0].message), + "Unknown Extension options: 'chic'") + +def test_suite(): + return unittest.makeSuite(ExtensionTestCase) + +if __name__ == "__main__": + run_unittest(test_suite()) diff --git a/shared/package-files/01/01f0252f4c6107f4747ae15ee550cabbfc63be3599914561424ad1bce6a312fc/blob b/shared/package-files/01/01f0252f4c6107f4747ae15ee550cabbfc63be3599914561424ad1bce6a312fc/blob new file mode 100644 index 0000000000000000000000000000000000000000..c6daa50be4658317a28f6cde9ed32804da3f762f --- /dev/null +++ b/shared/package-files/01/01f0252f4c6107f4747ae15ee550cabbfc63be3599914561424ad1bce6a312fc/blob @@ -0,0 +1,21 @@ +#pragma once + +// @generated by torchgen/gen.py from NativeFunction.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + +namespace at { +namespace native { +TORCH_API int64_t _version(const at::Tensor & self); +} // namespace native +} // namespace at diff --git a/shared/package-files/01/01f028778df06b7e62695defa5deef585f7614479ae3de65ae5391de33ef9dc0/blob b/shared/package-files/01/01f028778df06b7e62695defa5deef585f7614479ae3de65ae5391de33ef9dc0/blob new file mode 100644 index 0000000000000000000000000000000000000000..8288c021cc3602d12aeefdc8935eec7f43aa6cb8 --- /dev/null +++ b/shared/package-files/01/01f028778df06b7e62695defa5deef585f7614479ae3de65ae5391de33ef9dc0/blob @@ -0,0 +1,437 @@ +from pathlib import Path + +import numpy as np +from numpy.testing import assert_allclose, assert_equal +import pandas as pd +import pytest +from scipy import linalg + +from statsmodels import robust +import statsmodels.robust.covariance as robcov +import statsmodels.robust.norms as robnorms +import statsmodels.robust.scale as robscale + +from .results import results_cov as res_cov + +cur_dir = Path(__file__).parent.resolve() + +file_name = "hbk.csv" +file_path = Path(cur_dir).joinpath("results", file_name) + +dta_hbk = pd.read_csv(file_path) + + +def test_mahalanobis(): + rs = np.random.RandomState(987676453) + x = rs.randn(10, 3) + + d1 = (x**2).sum(1) + d0 = robcov.mahalanobis(x, np.eye(3)) + assert_allclose(d0, d1, rtol=1e-10) + d2 = robcov.mahalanobis(x, cov_inv=np.eye(3)) + assert_allclose(d2, d1, rtol=1e-10) + + d3 = robcov.mahalanobis(x, 2 * np.eye(3)) + assert_allclose(d3, 0.5 * d1, rtol=1e-10) + d4 = robcov.mahalanobis(x, cov_inv=2 * np.eye(3)) + assert_allclose(d4, 2 * d1, rtol=1e-10) + + +def test_outliers_gy(): + # regression test and basic properties + # no test for tie warnings + seed = 567812 # 123 + rs = np.random.RandomState(seed) + + nobs = 1000 + x = rs.randn(nobs) + d = x**2 + d2 = d.copy() + n_outl = 10 + d2[:n_outl] += 10 + res = robcov._outlier_gy(d2, distr=None, k_endog=1, trim_prob=0.975) + # next is regression test + res1 = [0.017865444296085831, 8.4163674239050081, 17.0, 42.0, 5.0238861873148881] + assert_allclose(res, res1, rtol=1e-13) + reject_thr = (d2 > res[1]).sum() + reject_float = nobs * res[0] + assert_equal(reject_thr, res[2]) + assert_equal(int(reject_float), res[2]) + # tests for fixed cutoff at 0.975 + assert_equal((d2 > res[4]).sum(), res[3]) + assert_allclose(res[3], nobs * 0.025 + n_outl, rtol=0.5) + # + n_outl because not under Null + + x3 = x[:-1].reshape(-1, 3) + # standardize, otherwise the sample wouldn't be close enough to distr + x3 = (x3 - x3.mean(0)) / x3.std(0) + d3 = (x3**2).sum(1) + nobs = len(d3) + n_outl = 0 + + res = robcov._outlier_gy(d3, distr=None, k_endog=3, trim_prob=0.975) + # next is regression test + res1 = [0.0085980695527445583, 12.605802816238732, 2.0, 9.0, 9.3484036044961485] + assert_allclose(res, res1, rtol=1e-13) + reject_thr = (d3 > res[1]).sum() + reject_float = nobs * res[0] + assert_equal(reject_thr, res[2]) + assert_equal(int(reject_float), res[2]) + # tests for fixed cutoff at 0.975 + assert_equal((d3 > res[4]).sum(), res[3]) + assert_allclose(res[3], nobs * 0.025 + n_outl, rtol=0.5) + # fixed cutoff at 0.975, + n_outl because not under Null + + +class TestOGKMad: + + @classmethod + def setup_class(cls): + + cls.res1 = robcov.cov_ogk(dta_hbk, rescale=False, ddof=0, reweight=0.9) + cls.res2 = res_cov.results_ogk_mad + + def test(self): + res1 = self.res1 + res2 = self.res2 + assert_allclose(res1.cov, res2.cov, rtol=1e-10) + assert_allclose(res1.mean, res2.center, rtol=1e-10) + assert_allclose(res1.cov_raw, res2.cov_raw, rtol=1e-8) + assert_allclose(res1.loc_raw, res2.center_raw, rtol=1e-8) + + +class TestOGKTau(TestOGKMad): + + @classmethod + def setup_class(cls): + + def sfunc(x): + return robscale.scale_tau(x, normalize=False, ddof=0)[1] + + cls.res1 = robcov.cov_ogk( + dta_hbk, scale_func=sfunc, rescale=False, ddof=0, reweight=0.9 + ) + cls.res2 = res_cov.results_ogk_tau + + def test(self): + # not inherited because of weak agreement with R + # I did not find options to improve agreement + res1 = self.res1 + res2 = self.res2 + assert_allclose(res1.cov, res2.cov, atol=0.05, rtol=1e-10) + assert_allclose(res1.mean, res2.center, atol=0.03, rtol=1e-10) + # cov raw differs in scaling, no idea why + # note rrcov uses C code for this case with hardoced tau scale + # our results are "better", i.e., correct outliers same as dgp + # rrcov has one extra outlier + fact = 1.1356801031633883 + assert_allclose(res1.cov_raw, res2.cov_raw * fact, rtol=1e-8) + assert_allclose(res1.loc_raw, res2.center_raw, rtol=0.2, atol=0.1) + + +def test_tyler(): + + # > library(ICSNP) + # > resty = tyler.shape(hbk, location = ccogk$center, eps=1e-13, + # print.it=TRUE) + # [1] "convergence was reached after 55 iterations" + + res2 = np.array( + [ + [ + 1.277856643343122, + 0.298374848328023, + 0.732491311584908, + 0.232045093295329, + ], + [ + 0.298374848328023, + 1.743589223324287, + 1.220675037619406, + 0.212549156887607, + ], + [ + 0.732491311584907, + 1.220675037619407, + 2.417486791841682, + 0.295767635758891, + ], + [ + 0.232045093295329, + 0.212549156887607, + 0.295767635758891, + 0.409157014373402, + ], + ] + ) + + # center is from an OGK version + center = np.array( + [ + 1.5583333333333333, + 1.8033333333333335, + 1.6599999999999999, + -0.0866666666666667, + ] + ) + k_vars = len(center) + + res1 = robcov.cov_tyler(dta_hbk.to_numpy() - center, normalize="trace") + assert_allclose(np.trace(res1.cov), k_vars, rtol=1e-13) + cov_det = res1.cov / np.linalg.det(res1.cov) ** (1.0 / k_vars) + assert_allclose(cov_det, res2, rtol=1e-11) + assert res1.n_iter == 56 + + res1 = robcov.cov_tyler(dta_hbk.to_numpy() - center, normalize="det") + assert_allclose(np.linalg.det(res1.cov), 1, rtol=1e-13) + assert_allclose(res1.cov, res2, rtol=1e-11) + assert res1.n_iter == 56 + + res1 = robcov.cov_tyler(dta_hbk.to_numpy() - center, normalize="normal") + cov_det = res1.cov / np.linalg.det(res1.cov) ** (1.0 / k_vars) + assert_allclose(cov_det, res2, rtol=1e-11) + assert res1.n_iter == 56 + + res1 = robcov.cov_tyler(dta_hbk.to_numpy() - center) + cov_det = res1.cov / np.linalg.det(res1.cov) ** (1.0 / k_vars) + assert_allclose(cov_det, res2, rtol=1e-11) + assert res1.n_iter == 56 + + +def test_cov_ms(): + # use CovM as local CovS + + # > CovSest(x) using package rrcov + # same result with > CovSest(x, method="sdet") + # but scale difers with method="biweight" + mean_r = np.array([1.53420879676, 1.82865741024, 1.65565146981]) + cov_r = np.array( + [ + [1.8090846049573, 0.0479283121828, 0.2446369025717], + [0.0479283121828, 1.8189886310494, 0.2513025527579], + [0.2446369025717, 0.2513025527579, 1.7287983150484], + ] + ) + + scale2_r = np.linalg.det(cov_r) ** (1 / 3) + shape_r = cov_r / scale2_r + scale_r = np.sqrt(scale2_r) + + exog_df = dta_hbk[["X1", "X2", "X3"]] + mod = robcov.CovM(exog_df) + # with default start, default start could get wrong local optimum + res = mod.fit() + assert_allclose(res.mean, mean_r, rtol=1e-5) + assert_allclose(res.shape, shape_r, rtol=1e-5) + assert_allclose(res.cov, cov_r, rtol=1e-5) + assert_allclose(res.scale, scale_r, rtol=1e-5) + + # with results start + res = mod.fit(start_mean=mean_r, start_shape=shape_r, start_scale=scale_r) + assert_allclose(res.mean, mean_r, rtol=1e-5) + assert_allclose(res.shape, shape_r, rtol=1e-5) + assert_allclose(res.cov, cov_r, rtol=1e-5) + assert_allclose(res.scale, scale_r, rtol=1e-5) + + mod_s = robcov.CovDetS(exog_df) + res = mod_s.fit() + assert_allclose(res.mean, mean_r, rtol=1e-5) + assert_allclose(res.shape, shape_r, rtol=1e-5) + assert_allclose(res.cov, cov_r, rtol=1e-5) + assert_allclose(res.scale, scale_r, rtol=1e-5) + + +def test_covdetmcd(): + + # results from rrcov + # > cdet = CovMcd(x = hbk, raw.only = TRUE, nsamp = "deterministic", + # use.correction=FALSE) + cov_dmcd_r = np.array( + """ + 2.2059619213639 0.0223939863695 0.7898958050933 0.4060613360808 + 0.0223939863695 1.1384166802155 0.4315534571891 -0.2344041030201 + 0.7898958050933 0.4315534571891 1.8930117467493 -0.3292893001459 + 0.4060613360808 -0.2344041030201 -0.3292893001459 0.6179686100845 + """.split(), + float, + ).reshape(4, 4) + + mean_dmcd_r = np.array([1.7725, 2.2050, 1.5375, -0.0575]) + + mod = robcov.CovDetMCD(dta_hbk) + res = mod.fit(40, maxiter_step=100, reweight=False) + assert_allclose(res.mean, mean_dmcd_r, rtol=1e-5) + assert_allclose(res.cov, cov_dmcd_r, rtol=1e-5) + + # with reweighting + # covMcd(x = hbk, nsamp = "deterministic", use.correction = FALSE) + # iBest: 5; C-step iterations: 7, 7, 7, 4, 6, 6 + # Log(Det.): -2.42931967153 + + mean_dmcdw_r = np.array( + [1.5338983050847, 1.8322033898305, 1.6745762711864, -0.0728813559322] + ) + cov_dmcdw_r = np.array( + """ + 1.5677744869295 0.09285770205078 0.252076010128 0.13873444408300 + 0.0928577020508 1.56769177397171 0.224929617385 -0.00516128856542 + 0.2520760101278 0.22492961738467 1.483829106079 -0.20275013775619 + 0.1387344440830 -0.00516128856542 -0.202750137756 0.43326701543885 + """.split(), + float, + ).reshape(4, 4) + + mod = robcov.CovDetMCD(dta_hbk) + res = mod.fit(40, maxiter_step=100) # default is reweight=True + assert_allclose(res.mean, mean_dmcdw_r, rtol=1e-5) + # R uses different trimming correction + # compare only shape (using trace for simplicity) + shape = res.cov / np.trace(res.cov) + shape_r = cov_dmcdw_r / np.trace(cov_dmcdw_r) + assert_allclose(shape, shape_r, rtol=1e-5) + + +def test_covdetmm(): + + # results from rrcov + # CovMMest(x = hbk, eff.shape=FALSE, + # control=CovControlMMest(sest=CovControlSest(method="sdet"))) + cov_dmm_r = np.array( + """ + 1.72174266670826 0.06925842715939 0.20781848922667 0.10749343153015 + 0.06925842715939 1.74566218886362 0.22161135221404 -0.00517023660647 + 0.20781848922667 0.22161135221404 1.63937749762534 -0.17217102475913 + 0.10749343153015 -0.00517023660647 -0.17217102475913 0.48174480967136 + """.split(), + float, + ).reshape(4, 4) + + mean_dmm_r = np.array( + [1.5388643420460, 1.8027582110408, 1.6811517253521, -0.0755069488908] + ) + + # using same c as rrcov + c = 5.81031555752526 + mod = robcov.CovDetMM(dta_hbk, norm=robnorms.TukeyBiweight(c=c)) + res = mod.fit() + + assert_allclose(res.mean, mean_dmm_r, rtol=1e-5) + assert_allclose(res.cov, cov_dmm_r, rtol=1e-5, atol=1e-5) + + # using c from table, + mod = robcov.CovDetMM(dta_hbk) + res = mod.fit() + + assert_allclose(res.mean, mean_dmm_r, rtol=1e-3) + assert_allclose(res.cov, cov_dmm_r, rtol=1e-3, atol=1e-3) + + +def test_cov_tyler_regularized_n_iter(): + # GH: n_iter was accumulated as `n_iter += i` inside `for i in + # range(maxiter)`, giving a triangular-number count instead of the + # actual number of completed iterations. + rs = np.random.RandomState(0) + x = rs.standard_normal((50, 3)) + res = robcov.cov_tyler_regularized(x, shrinkage_factor=0.1, maxiter=4, eps=0) + assert res.n_iter == 4 + + +def test_cov_tyler_regularized_corr_uses_scale(): + # GH: `corr * np.outer(scale_mad, scale_mad)` discarded its result + # instead of `corr *= ...`, so the plugin-shrinkage `corr` matrix never + # reflected the per-column MAD scale, only the (scale-free) correlation + # structure from the std-standardized data. + rs = np.random.RandomState(0) + nobs = 1000 + x = rs.standard_normal((nobs, 2)) + x[:, 0] *= 100 # column 0 has a much larger scale than column 1 + + res = robcov.cov_tyler_regularized(x, shrinkage_factor=None) + ratio = res.corr[0, 0] / res.corr[1, 1] + assert ratio > 100 + + +def test_robcov_SMOKE(): + # currently only smoke test or very loose comparisons to dgp + nobs, k_vars = 100, 3 + + mean = np.zeros(k_vars) + cov = linalg.toeplitz(1.0 / np.arange(1, k_vars + 1)) + + rs = np.random.RandomState(187649) + x = rs.multivariate_normal(mean, cov, size=nobs) + n_outliers = 1 + x[0, :2] = 50 + + # xtx = x.T.dot(x) + # cov_emp = np.cov(x.T) + cov_clean = np.cov(x[n_outliers:].T) + + # GK, OGK + robcov.cov_gk1(x[:, 0], x[:, 2]) + robcov.cov_gk(x) + robcov.cov_ogk(x) + + # Tyler + robcov.cov_tyler(x) + robcov.cov_tyler_regularized(x, shrinkage_factor=0.1) + + x2 = np.array([x, x]) + x2_ = np.rollaxis(x2, 1) + robcov.cov_tyler_pairs_regularized( + x2_, + start_cov=np.diag(robust.mad(x) ** 2), + shrinkage_factor=0.1, + nobs=x.shape[0], + k_vars=x.shape[1], + ) + + # others, M-, ... + + # estimation for multivariate t + r = robcov._cov_iter(x, robcov.weights_mvt, weights_args=(3, k_vars)) + # rough comparison with DGP cov + assert_allclose(r.cov, cov, rtol=0.5) + + # trimmed sample covariance + r = robcov._cov_iter( + x, robcov.weights_quantile, weights_args=(0.50,), rescale="med" + ) + # rough comparison with DGP cov + assert_allclose(r.cov, cov, rtol=0.5) + + # We use 0.75 quantile for truncation to get better efficiency + # at q=0.5, cov is pretty noisy at nobs=100 and passes at rtol=1 + res_li = robcov._cov_starting(x, standardize=True, quantile=0.75) + for _, res in enumerate(res_li): + # note: basic cov are not properly scaled + # check only those with _cov_iter rescaling, `n_iter` + # include also ogk + # need more generic detection of appropriate cov + if hasattr(res, "n_iter") or hasattr(res, "cov_ogk_raw"): + # inconsistent returns, redundant for now b/c no arrays + c = getattr(res, "cov", res) + # rough comparison with DGP cov + assert_allclose(c, cov, rtol=0.5) + # check average scaling + assert_allclose(np.diag(c).sum(), np.diag(cov).sum(), rtol=0.25) + c1, m1 = robcov._reweight(x, res.mean, res.cov) + assert_allclose(c1, cov, rtol=0.4) + assert_allclose(c1, cov_clean, rtol=1e-8) # oracle, w/o outliers + assert_allclose(m1, mean, rtol=0.5, atol=0.2) + + +def test_cov_iter_invalid_rescale_raises(): + rs = np.random.RandomState(28345) + x = rs.standard_normal((50, 3)) + with pytest.raises(ValueError, match="rescale"): + robcov._cov_iter( + x, robcov.weights_quantile, weights_args=(0.50,), rescale="not-a-rescale" + ) + + +def test_get_detcov_startidx_invalid_methods_cov_raises(): + rs = np.random.RandomState(28346) + z = rs.standard_normal((50, 3)) + with pytest.raises(ValueError, match="methods_cov"): + robcov._get_detcov_startidx(z, 30, methods_cov="not-all") diff --git a/shared/package-files/01/01f306b80bfb6a1e4eddc2e1856eeae103d236bac60bcf52e1045c947066ad22/blob b/shared/package-files/01/01f306b80bfb6a1e4eddc2e1856eeae103d236bac60bcf52e1045c947066ad22/blob new file mode 100644 index 0000000000000000000000000000000000000000..d8c6ccac52da1a834abb739587bfff0037f1c357 Binary files /dev/null and b/shared/package-files/01/01f306b80bfb6a1e4eddc2e1856eeae103d236bac60bcf52e1045c947066ad22/blob differ