code
stringlengths
1
1.72M
language
stringclasses
1 value
# # jython examples for jas. # $Id$ # from java.lang import System, Integer from jas import PolyRing, ZZ, QQ, ZM from jas import terminate, startLog from basic_sigbased_gb import sigbased_gb from basic_sigbased_gb import ggv, ggv_first_implementation from basic_sigbased_gb import coeff_free_sigbased_gb from basic_sigbased_gb import arris_algorithm, min_size_mons from basic_sigbased_gb import f5, f5z from staggered_linear_basis import staglinbasis #r = PolyRing( QQ(), "(B,S,T,Z,P,W)", PolyRing.lex ); r = PolyRing( ZM(32003), "(B,S,T,Z,P,W)", PolyRing.lex ); #r = PolyRing( ZM(19), "(B,S,T,Z,P,W)", PolyRing.lex ); print "Ring: " + str(r); print; [one,B,S,T,Z,P,W] = r.gens(); p1 = 45 * P + 35 * S - 165 * B - 36; p2 = 35 * P + 40 * Z + 25 * T - 27 * S; p3 = 15 * W + 25 * S * P + 30 * Z - 18 * T - 165 * B**2; p4 = -9 * W + 15 * T * P + 20 * S * Z; p5 = P * W + 2 * T * Z - 11 * B**3; p6 = 99 * W - 11 * B * S + 3 * B**2; p7 = 10000 * B**2 + 6600 * B + 2673; F = [p1,p2,p3,p4,p5,p6,p7]; #F = [p1,p2,p3,p4,p5,p6]; f = r.ideal( list=F ); print "Ideal: " + str(f); print; #startLog(); rg = f.GB(); rg = f.GB(); if not rg.isGB(): print "seq Output:", rg; print; #------------------- sbgb = sigbased_gb(); arri = arris_algorithm(); arrm = min_size_mons(); ggv = ggv(); ggv1 = ggv_first_implementation(); f5 = f5(); ff5 = f5z(); if True: gg = staglinbasis(F); gg = staglinbasis(F); t = System.currentTimeMillis(); gg = staglinbasis(F); t = System.currentTimeMillis() - t; print "stag executed in " + str(t) + " milliseconds"; if not r.ideal(list=gg).isGB(): print "stag Output:" + str([ str(ggg) for ggg in gg]); print; if True: gg = sbgb.basis_sig(F); t = System.currentTimeMillis(); gg = sbgb.basis_sig(F); t = System.currentTimeMillis() - t; print "sbgb executed in " + str(t) + " milliseconds"; if not r.ideal(list=gg).isGB(): print "sbgb Output:" + str([ str(ggg) for ggg in gg]); print; if True: gg = ff5.basis_sig(F); t = System.currentTimeMillis(); gg = ff5.basis_sig(F); t = System.currentTimeMillis() - t; print "f5 executed in " + str(t) + " milliseconds"; if not r.ideal(list=gg).isGB(): print "f5 Output:" + str([ str(ggg) for ggg in gg]); print; if True: gg = ggv1.basis_sig(F); t = System.currentTimeMillis(); gg = ggv1.basis_sig(F); t = System.currentTimeMillis() - t; print "ggv executed in " + str(t) + " milliseconds"; if not r.ideal(list=gg).isGB(): print "ggv Output:" + str([ str(ggg) for ggg in gg]); print; if True: gg = arri.basis_sig(F); t = System.currentTimeMillis(); gg = arri.basis_sig(F); t = System.currentTimeMillis() - t; print "arri executed in " + str(t) + " milliseconds"; if not r.ideal(list=gg).isGB(): print "arri Output:" + str([ str(ggg) for ggg in gg]); print; ## Output: for Z_32003 and Trinks 7 ## sequential GB executed in 44 ms ## stag executed in 99 milliseconds ## sbgb executed in 1180 milliseconds ## f5 executed in 128 milliseconds ## ggv executed in 110 milliseconds ## arri executed in 116 milliseconds ## Output: for Z_32003 and Trinks 6 ## sequential GB executed in 302 ms ## stag executed in 213 milliseconds ## sbgb executed in 28849 milliseconds ## f5 executed in 1248 milliseconds ## ggv executed in 237 milliseconds ## arri executed in 410 milliseconds ## Output: for Q and Trinks 7 ## sequential GB executed in 104 ms ## stag executed in 223 milliseconds ## sbgb executed in 1155 milliseconds ## f5 executed in 226 milliseconds ## ggv executed in 98 milliseconds ## arri executed in 111 milliseconds ## Output: for Q and Trinks 6 ## sequential GB executed in 779 ms ## stag executed in 196 milliseconds ## sbgb executed in 740980 milliseconds ## f5 executed in 1435 milliseconds ## ggv executed in 717 milliseconds ## arri executed in 562 milliseconds
Python
# # jython examples for jas. # $Id$ # import sys; from jas import PolyRing, QQ, RF from jas import Ideal from jas import startLog from jas import terminate # Montes JSC 2002, 33, 183-208, example 5.1 # integral function coefficients r = PolyRing( PolyRing(QQ(),"a, b",PolyRing.lex), "u,z,y,x", PolyRing.lex ); print "Ring: " + str(r); print; [one,a,b,u,z,y,x] = r.gens(); print "gens: ", [ str(f) for f in r.gens() ]; print; f1 = a * x + 2 * y + 3 * z + u - 6; f2 = x + 3 * y - z + 2 * u - b; f3 = 3 * x - a * y + z - 2; f4 = 5 * x + 4 * y + 3 * z + 3 * u - 9; F = [f1,f2,f3,f4]; print "F: ", [ str(f) for f in F ]; print; #startLog(); If = r.paramideal( "", list = F ); print "ParamIdeal: " + str(If); print; ## G = If.GB(); ## print "GB: " + str(G); ## print; ## sys.exit(); GS = If.CGBsystem(); GS = If.CGBsystem(); GS = If.CGBsystem(); print "CGBsystem: " + str(GS); print; bg = GS.isCGBsystem(); if bg: print "isCGBsystem: true"; else: print "isCGBsystem: false"; print; #terminate(); #sys.exit(); CG = If.CGB(); print "CGB: " + str(CG); print; bg = CG.isCGB(); if bg: print "isCGB: true"; else: print "isCGB: false"; print; terminate(); #------------------------------------------ #sys.exit();
Python
# # jython examples for jas. # $Id$ # import sys; from jas import PolyRing, QQ, RF from jas import Ideal from jas import startLog from jas import terminate # Montes JSC 2002, 33, 183-208, example 11.3 # integral function coefficients R = PolyRing( PolyRing(QQ(),"r, l, z",PolyRing.lex), "c1, c2, s1, s2", PolyRing.lex ); print "Ring: " + str(R); print; [one,r,l,z,c1,c2,s1,s2] = R.gens(); print "gens: ", [ str(f) for f in r.gens() ]; print; f1 = r - c1 + l * ( s1 * s2 - c1 * c2 ); f2 = z - s1 - l * ( s1 * c2 + s2 * c1 ); f3 = s1**2 + c1**2 - 1; f4 = s2**2 + c2**2 - 1; F = [f1,f2,f3,f4]; print "F: ", [ str(f) for f in F ]; print; startLog(); If = R.paramideal( "", list = F ); print "ParamIdeal: " + str(If); print; ## G = If.GB(); ## print "GB: " + str(G); ## print; ## sys.exit(); GS = If.CGBsystem(); #GS = If.CGBsystem(); #GS = If.CGBsystem(); print "CGBsystem: " + str(GS); print; bg = GS.isCGBsystem(); if bg: print "isCGBsystem: true"; else: print "isCGBsystem: false"; print; #terminate(); #sys.exit(); CG = If.CGB(); print "CGB: " + str(CG); print; bg = CG.isCGB(); if bg: print "isCGB: true"; else: print "isCGB: false"; print; terminate(); #------------------------------------------ #sys.exit();
Python
# # jython examples for jas. # $Id$ # from jas import SolvableModule from jas import SolvableSubModule # Quantum plane example rsan = """ # not with twosidedGB, because of field AN[ (i) (i^2 + 1) ] (Y,X,x,y) G RelationTable ( ( y ), ( x ), ( {i} x y ) ( X ), ( Y ), ( {i} Y X ) ) """; rsc = """ # not supported for rightGB C(Y,X,x,y) G |2| C(Y,X,x,y) G RelationTable ( ( y ), ( x ), ( 0i1 x y ) ( X ), ( Y ), ( 0i1 Y X ) ) """; r = SolvableModule( rsc ); #r = SolvableModule( rsan ); print "SolvableModule: " + str(r); print; ps = """ ( ( ( x + 1 ), ( y ) ), ( ( x y ), ( 0 ) ), ( ( x - X ), ( x - X ) ), ( ( y - Y ), ( y - Y ) ) ) """; f = SolvableSubModule( r, ps ); print "SolvableSubModule: " + str(f); print; flg = f.leftGB(); print "seq left GB:", flg; print; if flg.isLeftGB(): print "is left GB"; else: print "is not left GB"; ftg = f.twosidedGB(); print "seq twosided GB:", ftg; print; if ftg.isLeftGB(): print "twosided GB is left GB"; else: print "twosided GB is not left GB"; if ftg.isRightGB(): print "twosided GB is right GB"; else: print "twosided GB is not right GB"; if ftg.isTwosidedGB(): print "is twosided GB"; else: print "is not twosided GB"; from jas import startLog startLog(); frg = f.rightGB(); print "seq right GB:", frg; print; if frg.isRightGB(): print "is right GB"; else: print "is not right GB";
Python
# # jython for jas example 2 integer programming. # $Id$ # # CLO2, p372 # 3 A - 2 B + C = -1 # 4 A + B - C - D = 5 # # max: A + 1000 B + C + 100 D # import sys; from jas import Ring from jas import Ideal r = Ring( "Rat(w1,w2,w3,w4,t,z1,z2) W( (0,0,0,0,1,1,1),(1,1,2,2,0,0,0) )" ); print "Ring: " + str(r); print; ps = """ ( ( z1^3 z2^4 - w1 ), ( t^2 z2^3 - w2 ), ( t z1^2 - w3 ), ( t z1 - w4 ), ( t z1 z2 - 1 ) ) """; f = Ideal( r, ps ); print "Ideal: " + str(f); print; rg = f.GB(); print "seq Output:", rg; print; pf = """ ( ( t z2^6 ) ) """; fp = Ideal( r, pf ); print "Ideal: " + str(fp); print; nf = fp.NF(rg); print "NFs: " + str(nf); print; #rg = f.parGB(2); #print "par Output:", rg; #print; #f.distClient(); # starts in background #rg = f.distGB(2); #print "dist Output:", rg; #print; #sys.exit();
Python
# # jython examples for jas. # $Id$ # from java.lang import System from java.lang import Integer from jas import Ring from jas import Ideal from jas import terminate from jas import startLog # polynomial examples: absolute factorization over Q #r = Ring( "Rat(x) L" ); r = Ring( "Q(x,y) L" ); print "Ring: " + str(r); print; [one,x,y] = r.gens(); f1 = x**2 + y**2; f2 = x**3 + y**2; f3 = x**4 + 4; f = f1**3 * f2**1 * f3**2; print "f = ", f; print; startLog(); t = System.currentTimeMillis(); #G = r.squarefreeFactors(f); G = r.factorsAbsolute(f); t = System.currentTimeMillis() - t; print "G = ", G.toScript(); print print "factor time =", t, "milliseconds"; print #startLog(); terminate();
Python
# # test functionality of the jython interface to jas. # $Id$ # # test ideal Groebner bases execfile("examples/trinksTest.py") # test module Groebner bases execfile("examples/armbruster.py") # test solvable Groebner bases execfile("examples/wa_32.py") # test solvable module Groebner bases execfile("examples/solvablemodule.py") import sys; sys.exit();
Python
# # jython examples for jas. # $Id$ # import sys; from jas import Ring from jas import Ideal from jas import startLog from jas import terminate # ideal elimination example r = Ring( "Rat(x,y,z) G" ); print "Ring: " + str(r); print; ps1 = """ ( ( x^2 - 2 ), ( y^2 - 3 ), ( z^3 - x * y ) ) """; F1 = r.ideal( ps1 ); print "Ideal: " + str(F1); print; e = Ring( "Rat(z) G" ); print "Ring: " + str(e); print; #startLog(); rg1 = F1.eliminateRing(e); print "rg1 = ", rg1; print; rg2 = rg1.intersectRing(e); print "rg2 = ", rg2; print; terminate(); #sys.exit();
Python
# # jruby examples for jas. # $Id$ # from java.lang import System from java.lang import Integer from jas import SolvableRing, SolvPolyRing, PolyRing, RingElem from jas import QQ, startLog, SRC, SRF # Ore extension solvable polynomial example, Gomez-Torrecillas, 2003 pcz = PolyRing(QQ(),"x,y,z"); #is automatic: [one,x,y,z] = pcz.gens(); zrelations = [z, y, y * z + x ]; print "zrelations: = " + str([ str(f) for f in zrelations ]); print; pz = SolvPolyRing(QQ(), "x,y,z", PolyRing.lex, zrelations); print "SolvPolyRing: " + str(pz); print; #startLog(); fl = [ z**2 + y, y**2 + x]; ff = pz.ideal("",fl); print "ideal ff: " + str(ff); print; ff = ff.twosidedGB(); print "ideal ff: " + str(ff); print; f0 = SRC(ff,z + x + y + 1); print "f0 = " + str(f0); #f1 = SRC(ff, z-y+1 ); #f1 = SRC(ff, y*z+1 ); f1 = SRC(ff, y*z+x+1 ); print "f1 = " + str(f1); f2 = f1*f0; print "f2 = " + str(f2); fi = 1/f1; print "fi = " + str(fi); fi1 = fi*f1; f1i = f1*fi; print "fi*f1 = " + str(fi1); print "f1*fi = " + str(f1i); print; #exit(0); pzc = f0.elem.ring; print "SolvableResidueRing: " + str(pzc.toScript); # + ", assoz: " + str(pzc::ring.isAssociative); print "gens =" + str([ str(f) for f in pzc.generators() ]); print; pct = PolyRing(pzc,"t"); #is automatic: [one,y,z,t] = p.gens(); # no x #exit(0); trelations = [t, y, y * t + y, t, z, z * t - z ]; print "trelations: = " + str([ str(f) for f in trelations ]); print; startLog(); pt = SolvPolyRing(pzc, "t", PolyRing.lex, trelations); print "SolvPolyRing: " + str(pt); print; print "sp.gens =" + str([ str(f) for f in pt.gens() ]); #is automatic: one,y,z,t = rp.gens(); # no x #exit(0); #yi = 1 / y; # not invertible #print "yi = " + str(yi); a = t**2 + y; b = t + y + 1; c = t**2 - y * t - z; print "a = " + str(a); print "b = " + str(b); print "c = " + str(c); print ff = [ a*c, b*c ]; print "ff = " + str([ str(f) for f in ff ]); print ii = pt.ideal( "", ff ); print "SolvableIdeal: " + str(ii); print; #exit(0); rgl = ii.leftGB(); print "seq left GB: " + str(rgl); print "isLeftGB: " + str(rgl.isLeftGB()); print; p = RingElem(rgl.list.get(0)); print "p = " + str(p); print "c-p = " + str(c-p); #print "monic(p) = " + str(p.monic()); pp = p * p; print "p*p = " + str(pp); print "p*y*z = " + str(p*y*z); print "p*t = " + str(p*t); print "t*p = " + str(t*p); print; #no: fl = [ p, p*x ]; # x non existent #fl = [ p, p*y ]; #no: fl = [ p, p*z ]; #fl = [ p, p*t, p*y ]; #bad: fl = [ p, p*t, p*p ]; #bad: fl = [ p, p*p ]; #fl = [ p, p*t ]; #fl = [ p, p*(t+1) ]; fl = [ p*(t*t+1), p*(t*t*t), p*(t-3) ]; #fl = [ p ]; print "fl = " + str([ str(f) for f in fl ]); print iil = pt.ideal( "", fl ); print "SolvableIdeal_res: " + str(iil); print; iiq = iil.toQuotientCoefficients(); # beware of redefined generators print "SolvableIdeal_quot: " + str(iiq); print; #exit(0); rgll = iiq.leftGB(); print "seq left GB: " + str(rgll); print "isLeftGB: " + str(rgll.isLeftGB()); print; #rgr = rgl.rightGB(); #print "seq right GB: " + str(rgr); #print "isRightGB: " + str(rgr.isRightGB()); #print; #startLog(); rgt = iiq.twosidedGB(); print "seq twosided GB: " + str(rgt); print "isTwosidedGB: " + str(rgt.isTwosidedGB()); print; #terminate();
Python
# # jython examples for jas. # $Id$ # from java.lang import System from java.lang import Integer from jas import Ring from jas import Ideal from jas import terminate from jas import startLog # polynomial examples: gcd #r = Ring( "Mod 1152921504606846883 (x,y,z) L" ); r = Ring( "Rat(x,y,z) L" ); #r = Ring( "C(x,y,z) L" ); #r = Ring( "Z(x,y,z) L" ); print "Ring: " + str(r); print; [one,x,y,z] = r.gens(); a = r.random(); b = r.random(); c = abs(r.random()); #c = 1; #a = 0; print "a = ", a; print "b = ", b; print "c = ", c; print; ac = a * c; bc = b * c; print "ac = ", ac; print "bc = ", bc; print; t = System.currentTimeMillis(); d = r.gcd(ac,bc); t = System.currentTimeMillis() - t; #d = d.monic(); print "d = ", d; m = c % d; ## print "m = ", m; ## print; if m.isZERO(): print "gcd time =", t, "milliseconds,", "isGcd(c,d): true" ; else: print "gcd time =", t, "milliseconds,", "isGcd(c,d): ", str(m); print; #startLog(); terminate();
Python
# # jython examples for jas. # $Id$ # from jas import SolvableRing # U(so_3) example rs = """ # solvable polynomials, U(so_3): Rat(x,y,z) G RelationTable ( ( y ), ( x ), ( x y - z ), ( z ), ( x ), ( x z + y ), ( z ), ( y ), ( y z - x ) ) """; r = SolvableRing( rs ); print "SolvableRing: " + str(r); print; ps = """ ( ( x^2 + y^3 ) ) """; f = r.ideal( ps ); print "SolvableIdeal: " + str(f); print; rg = f.leftGB(); print "seq left GB:", rg; print; if rg.isLeftGB(): print "is left GB"; else: print "is not left GB"; rg = f.twosidedGB(); print "seq twosided GB:", rg; print; if rg.isLeftGB(): print "twosided GB is left GB"; else: print "twosided GB is not left GB"; if rg.isRightGB(): print "twosided GB is right GB"; else: print "twosided GB is not right GB"; if rg.isTwosidedGB(): print "is twosided GB"; else: print "is not twosided GB"; rg = f.rightGB(); print "seq right GB:", rg; print; if rg.isRightGB(): print "is right GB"; else: print "is not right GB";
Python
# # jython examples for jas. # $Id$ # import sys; from jas import Ring, PolyRing, Ideal from jas import QQ, ZZ from jas import startLog # characteristic set example Circle of Apollonius, from CLO IVA r = PolyRing( QQ(), "u1,u2,x1,x2,x3,x4,x5,x6,x7,x8", PolyRing.lex ); print "Ring: " + str(r); print; #[one,u1,u2,x1,x2,x3,x4,x5,x6,x7,x8] = r.gens(); h1 = 2 * x1 - u1; h2 = 2 * x2 - u2; h3 = 2 * x3 - u1; h4 = 2 * x4 - u2; h5 = u2 * x5 + u1 * x6 - u1 * u2; h6 = u1 * x5 - u2 * x6; h7 = x1**2 - x2**2 - 2 * x1 * x7 + 2 * x2 * x8; h8 = x1**2 - 2 * x1 * x7 - x3**2 + 2 * x3 * x7 - x4**2 + 2 * x4 * x8; g = ( ( x5 - x7 )**2 + ( x6 - x8 )**2 - ( x1 - x7 )**2 - x8**2 ); L = [h1,h2,h3,h4,h5,h6,h7,h8]; #print "L = ", str(L); f = r.ideal( list=L ); print "Ideal: " + str(f); print; #sys.exit(); startLog(); c = f.CS(); print "seq char set:", c; print "is char set:", c.isCS(); print; print "g:", g; h = c.csReduction(g); print "h:", h; print; sys.exit();
Python
# # jython examples for jas. # $Id$ # import sys; from jas import Ring from jas import Ideal from jas import startLog from jas import terminate # Nabashima, ISSAC 2007, example F1 # integral function coefficients r = Ring( "IntFunc(a, b) (y,x) G" ); print "Ring: " + str(r); print; ps = """ ( ( { a } x^4 y + x y^2 + { b } x ), ( x^3 + 2 x y ), ( { b } x^2 + x^2 y ) ) """; #startLog(); f = r.paramideal( ps ); print "ParamIdeal: " + str(f); print; gs = f.CGBsystem(); gs = f.CGBsystem(); gs = f.CGBsystem(); gs = f.CGBsystem(); print "CGBsystem: " + str(gs); print; #sys.exit(); bg = gs.isCGBsystem(); if bg: print "isCGBsystem: true"; else: print "isCGBsystem: false"; print; #sys.exit(); gs = f.CGB(); print "CGB: " + str(gs); print; bg = gs.isCGB(); if bg: print "isCGB: true"; else: print "isCGB: false"; print; terminate(); #------------------------------------------ #sys.exit();
Python
# # jython examples for jas. # $Id$ # import sys; from jas import Ring from jas import Ideal from jas import startLog from jas import terminate # output gb of rose #r = Ring( "Mod 19 (U3,U4,A46) L" ); #r = Ring( "Mod 1152921504606846883 (U3,U4,A46) L" ); # 2^60-93 #r = Ring( "Quat(U3,U4,A46) L" ); #r = Ring( "Z(U3,U4,A46) L" ); #r = Ring( "C(U3,U4,A46) L" ); #r = Ring( "Rat(A46,U3,U4) G" ); rz = Ring( "Int(A46) G" ); print "Ring: " + str(rz); print; r = Ring( "Rat(A46) G" ); print "Ring: " + str(r); print; ps = """ ( ( A46^34 + 347/70 A46^33 - 56411/58800 A46^32 - 441350327/6174000 A46^31 - 992593010489/3457440000 A46^30 - 217625706587/329280000 A46^29 - 373467217691021/355622400000 A46^28 - 38574512982739/31752000000 A46^27 - 968821009058023/952560000000 A46^26 - 5992612680961049/10886400000000 A46^25 - 13843426727931961/244944000000000 A46^24 + 1486519769228381881/5598720000000000 A46^23 + 61199280870444808261/167961600000000000 A46^22 + 513991046707657214269/1679616000000000000 A46^21 + 37908065080289396962277/201553920000000000000 A46^20 + 27223946509678338655459/335923200000000000000 A46^19 + 668594689016343141054373/48372940800000000000000 A46^18 - 36250135997129945800663817/2418647040000000000000000 A46^17 - 5712667240922865693346483691/290237644800000000000000000 A46^16 - 42053436689365696671983799179/2902376448000000000000000000 A46^15 - 561895388992743685886859196463/69657034752000000000000000000 A46^14 - 704377755966878925481768484749/193491763200000000000000000000 A46^13 - 2531676547158421516985730163481/1857520926720000000000000000000 A46^12 - 4750291847118917831874464404117/11145125560320000000000000000000 A46^11 - 1835783859800409552862056700927/16511297126400000000000000000000 A46^10 - 9916637291915563585725849353/412782428160000000000000000000 A46^9 - 252376016954713294866494065459/59440669655040000000000000000000 A46^8 - 178806028363626133639831815853/297203348275200000000000000000000 A46^7 - 31482408916666847417595615109/475525357240320000000000000000000 A46^6 - 3818476405879526813756500117/713288035860480000000000000000000 A46^5 - 896701239882765996997050397/3170169048268800000000000000000000 A46^4 - 4844358439974218651958787/760840571584512000000000000000000 A46^3 + 171452325388464998728627/730406948721131520000000000000000 A46^2 + 15230552381256429497/811563276356812800000000000000 A46 + 79792266297612001/259700248434180096000000000000 ) ) """; ps1=""" ( ( A46^33 * U3 + 129/28 A46^32 * U3 - 75613/29400 A46^31 * U3 - 871585543/12348000 A46^30 * U3 - 12095701697/46099200 A46^29 * U3 - 124924301563/219520000 A46^28 * U3 - 378293923381/444528000 A46^27 * U3 - 1617620272123/1764000000 A46^26 * U3 - 82886347203347/119070000000 A46^25 * U3 - 668049914090789/2177280000000 A46^24 * U3 + 99688309115142847/1959552000000000 A46^23 * U3 + 231138576685539839/933120000000000 A46^22 * U3 + 11659387634813949601/41990400000000000 A46^21 * U3 + 70151923964052383971/335923200000000000 A46^20 * U3 + 23176161047838396328367/201553920000000000000 A46^19 * U3 + 164454230781271289566939/4031078400000000000000 A46^18 * U3 - 55282700662490687816927/120932352000000000000000 A46^17 * U3 - 747149106093593978873861/50388480000000000000000 A46^16 * U3 - 841282928607636046387355983/58047528960000000000000000 A46^15 * U3 - 54661970877464131720410138953/5804752896000000000000000000 A46^14 * U3 - 830787778268485831652841532151/174142586880000000000000000000 A46^13 * U3 - 274531406380976793484077680017/139314069504000000000000000000 A46^12 * U3 - 750317990428317888436020594041/1114512556032000000000000000000 A46^11 * U3 - 1416119253746536814898928216649/7430083706880000000000000000000 A46^10 * U3 - 33046099809889641357330063959/743008370688000000000000000000 A46^9 * U3 - 25135248767946559916964025799/2972033482752000000000000000000 A46^8 * U3 - 38214637789543687723872942433/29720334827520000000000000000000 A46^7 * U3 - 3604383688017858128502121387/23776267862016000000000000000000 A46^6 * U3 - 10419538500903067530134609/792542262067200000000000000000 A46^5 * U3 - 268160889047530270882049141/356644017930240000000000000000000 A46^4 * U3 - 4494450124912371106208621/228252171475353600000000000000000 A46^3 * U3 + 19160001876330286653661/36520347436056576000000000000000 A46^2 * U3 + 4148034694905888017/81156327635681280000000000000 A46 * U3 + 11398895185373143/12985012421709004800000000000 U3 ) ) """; ps2=""" ( ( A46^32 * U3^2 + 149/35 A46^31 * U3^2 - 119419/29400 A46^30 * U3^2 - 17080619/246960 A46^29 * U3^2 - 32939303767/138297600 A46^28 * U3^2 - 29988193601/61740000 A46^27 * U3^2 - 3784045943831/5556600000 A46^26 * U3^2 - 2693634126319/3969000000 A46^25 * U3^2 - 21841275550799/47628000000 A46^24 * U3^2 - 21239300351867/145152000000 A46^23 * U3^2 + 100022001638857211/979776000000000 A46^22 * U3^2 + 296696864208881153/1399680000000000 A46^21 * U3^2 + 17088141121241394989/83980800000000000 A46^20 * U3^2 + 19261885997631012911/139968000000000000 A46^19 * U3^2 + 13468170505032365821223/201553920000000000000 A46^18 * U3^2 + 35088518623022364409189/2015539200000000000000 A46^17 * U3^2 - 99017698968245042551237/15116544000000000000000 A46^16 * U3^2 - 3789770743783848575384507/302330880000000000000000 A46^15 * U3^2 - 2933051673126807110607585563/290237644800000000000000000 A46^14 * U3^2 - 948072476821568942948806667/161243136000000000000000000 A46^13 * U3^2 - 18896655281197310848727704481/6965703475200000000000000000 A46^12 * U3^2 - 2845096388251912350859674973/2786281390080000000000000000 A46^11 * U3^2 - 39111610674783351035074010869/123834728448000000000000000000 A46^10 * U3^2 - 1486938573940216107905934971/18575209267200000000000000000 A46^9 * U3^2 - 2445791954945323169329394873/148601674137600000000000000000 A46^8 * U3^2 - 333946045138720738819094237/123834728448000000000000000000 A46^7 * U3^2 - 406526799915645826522761061/1188813393100800000000000000000 A46^6 * U3^2 - 6322467405069477857023283/198135565516800000000000000000 A46^5 * U3^2 - 490026291814312040719379/247669456896000000000000000000 A46^4 * U3^2 - 169501103784936018875857/2853152143441920000000000000000 A46^3 * U3^2 + 2012646248526699378523/1826017371802828800000000000000 A46^2 * U3^2 + 5217570099427357/37572373905408000000000000 A46 * U3^2 + 1628413597910449/649250621085450240000000000 U3^2 ) ) """; ps3=""" ( ( U3^4 + 36097228800000000000000000/282475249 A46^33 + 1161224847360000000000000000/1977326743 A46^32 - 4677045387264000000000000000/13841287201 A46^31 - 874485621920563200000000000000/96889010407 A46^30 - 22660530808584929280000000000000/678223072849 A46^29 - 48947976962992465920000000000000/678223072849 A46^28 - 212357741794443264000000000000/1977326743 A46^27 - 33417694635162617446400000000000/290667031221 A46^26 - 1195585718651671592960000000000/13841287201 A46^25 - 4622243456144475926528000000000/124571584809 A46^24 + 57492745364488210585600000000/7626831723 A46^23 + 5064235904207031314222080000000/160163466183 A46^22 + 796549541441999106994688000000/22880495169 A46^21 + 1776805509375610240638745600000/68641485507 A46^20 + 6571948331935947500408320000/466948881 A46^19 + 15900562307775474505007648000/3268642167 A46^18 - 781823011269699906939632000/4202539929 A46^17 - 23911885581267405621130949120/12607619787 A46^16 - 66484142665897834547281936/36756909 A46^15 - 31344755225898717841650588049/27016328115 A46^14 - 748245898727397783769699627/1286491815 A46^13 - 61180345995024957255947775667/257298363000 A46^12 - 1772332138625205728147155697/22054145400 A46^11 - 1763442424064055410851226129/78414739200 A46^10 - 72564573592100205725791837/14002632000 A46^9 - 65329613048147169962793719/67212633600 A46^8 - 87361765982805204782291/600112800 A46^7 - 6483564254536224014425081/384072192000 A46^6 - 23648026104539505065429/16460236800 A46^5 - 880685511246977438581/10973491200 A46^4 - 31439956654789887473/15676416000 A46^3 + 17918243525346457327/300987187200 A46^2 + 10074090036167/1866240 A46 + 34829612499283/382205952 ) ) """; ps4=""" ( ( A46 * U4 + 7/20 U4 + 2806378846741861368786614566878031251136601782233486293371124444033709909300049715978016727056150885946954243402645730462178807446021415693833183139081658586984935909957265108287928306576671117507805428087796888020739324547730219269915178825763993883433817341952000000000000000/193099928700513998070936429904026968056396066087989232333196930214044975387024916636846108968424103894255784064885243976305160746405290836679402752295622754790839675018341679885489238996414850488675112243144046216420956878738117538991288033099828416943500600350187 A46^32 * U3 + 140608368210259054916983904673796347993009087108223449480869140637168687474157820242084293427769280716150829987371903694486407125016157557573489507333502558345102130864385866957396552184077632209367448052303724048297487583320428452817989972383673573195382911926272000000000000000/1351699500903597986496555009328188776394772462615924626332378511498314827709174416457922762778968727259790488454196707834136125224837035856755819266069359283535877725128391759198424672974903953420725785702008323514946698151166822772939016231698798918604504202451309 A46^31 * U3 + 2973132530031750926781836728171190368295908349443863657109054185698567452354483691980282671132312007156981877065422976124734148815655910511834380182331303177950358622308259910423832682100194502857004946063777788209711503282994815361158167402207667989232295462169477120000000000000/28385689518975557716427655195891964304290221714934417152979948741464611381892662745616378018358343272455600257538130864516858629721577752991872204587456544954253432227696226943166918132472983021835241499742174793813880661174503278231719340865674777290694588251477489 A46^30 * U3 - 738219222373037292445012084441369194910728746958545194778441077198902948054263364937417682200010729210575746685991736931724571115099030702915394756575817790642985569814303481715585979651308619587706574566955474220298898070223241914619143731590342509740953174566721552384000000000000/596099479898486712044980759113731250390094656013622760212578923570756839019745917657943938385525208721567605408300748154854031224153132812829316296336587444039322076781620765806505280781932643458540071494585670670091493884664568842866106158179170323104586353281027269 A46^29 * U3 - 26263613198277033357242907881790564317638488547844618743001644843010275951255995601618105986940603997061861718415452159942810394664057894925733725044191873926510994765442061292542368154720543459005227757920995136654748098710382908816433885918895473973271287136201940664320000000000000/4172696359289406984314865313796118752730662592095359321488052464995297873138221423605607568698676461050973237858105237083978218569071929689805214074356112108275254537471345360645536965473528504209780500462099694690640457192651981900062743107254192261732104472967190883 A46^28 * U3 - 9560261987467874294850640971728702760731659080417859619462176031496681069887590878558384729317157715276514804678872739436230630658282680026803340746414284932116802254277874675348065517256502425989246849745315895036906790401640417642341755791726718494097465403286844184985600000000000/596099479898486712044980759113731250390094656013622760212578923570756839019745917657943938385525208721567605408300748154854031224153132812829316296336587444039322076781620765806505280781932643458540071494585670670091493884664568842866106158179170323104586353281027269 A46^27 * U3 - 144636713736027890114035034090555770840107473490985685648308419164337400894146263765715981457017308677715082713471432001864714782421560684446718632104959754377888118909536279270581334669935787514862899283922492256748522286708189406470339423887947462918232309558821679529984000000000000/5364895319086380408404826832023581253510851904122604841913210312136811551177713258921495445469726878494108448674706733393686281017378195315463846667029286996353898691034586892258547527037393791126860643451271036030823444961981119585794955423612532907941277179529245421 A46^26 * U3 - 24532425560872733727048401118804283865911311477564921900335177229012489937286467620463606284515609505035616190873825110294676684892007020876691541110492442185186251334711679953191506232457944676021905960044901546391272864711217070545467913465760834235337077332640608895369216000000000/766413617012340058343546690289083036215835986303229263130458616019544507311101894131642206495675268356301206953529533341955183002482599330780549523861326713764842670147798127465506789576770541589551520493038719432974777851711588512256422203373218986848753882789892203 A46^25 * U3 - 61280378855985472962083715267099870468639547774190782208008687497788816915947177474302623147240238616774447758611668598585355022788830824893247197811650042416494226679277235085459349523493402070913785423068849805945203419134911827923486496461119063853055966658119121257129574400000000/2299240851037020175030640070867249108647507958909687789391375848058633521933305682394926619487025805068903620860588600025865549007447797992341648571583980141294528010443394382396520368730311624768654561479116158298924333555134765536769266610119656960546261648369676609 A46^24 * U3 - 1484357436021657507567420650984058019197004585757942514498995263423808522091214018761612749478663033895612373062807866818414484967623858841053321992327465827514651989711202442802087572810894125998644840666538477463088224296505304638389800637458850650417392471695314042172211200000000/109487659573191436906220955755583290887976569471889894732922659431363501044443127733091743785096466908043029564789933334565026143211799904397221360551618101966406095735399732495072398510967220227078788641862674204710682550244512644608060314767602712406964840398556029 A46^23 * U3 - 142706740914560864457369678713491100078718980040431434176679594896408407693192038718320939423503224607224793619606860312440116490102586591426353170601317496666073657735251911434293391435267804199376695206269942247915428218586358462081096742118453704497075161839492889751191552000000/2956166808476168796467965805400748853975367375741027157788911804646814528199964448793477082197604606517161798249328200033255705866718597418724976734893688753092964584855792777366954759796114946131127293330292203527188428856601841404417628498725273234988050690761012783 A46^22 * U3 + 3437067913738929851828191102489541091985420513352095924549529468703404236611368673420787140580385095687914414418203044807769960408456154049568142240000401501441029724428786621410870408162134547736165823446770365996810358019535793543622855984068400287198402234509017467116735692800000/422309544068024113781137972200106979139338196534432451112701686378116361171423492684782440313943515216737399749904028576179386552388371059817853819270526964727566369265113253909564965685159278018732470475756029075312632693800263057773946928389324747855435812965858969 A46^21 * U3 + 12665325755293011964582773351828201837497408957482566179025807264260205331500166852839160281570134088487784028319208757397082649585467393387792231298887791806004696105674306391612545456300491907001838309111269128096161395643695348999989978496685257886403350330750962195611697479680000/1266928632204072341343413916600320937418014589603297353338105059134349083514270478054347320941830545650212199249712085728538159657165113179453561457811580894182699107795339761728694897055477834056197411427268087225937898081400789173321840785167974243566307438897576907 A46^20 * U3 + 472460708046707276929317308260575825818443603966144032149144933738614980186931958850077619729999743406167265787440681567111099352622569281813602576458470534069879413676204407012264193237661238006825286040265059435939142815940360874733243831244058419301704863623227097616300687360000/60329934866860587683019710314300997019905456647776064444671669482588051595917641812111777187706216459533914249986289796597055221769767294259693402752932423532509481323587607701366423669308468288390352925108004153616090384828609008253420989769903535407919401852265567 A46^19 * U3 + 49390047765871082949860891586805882007616506646541386751626133624251152479425727198070508507708042448289532261339277046519001543624931425618731092311111454034423497441761556818193037978230663070411942523132669576228611039810197751659696742852563815776238111135652689883724583731200/11081008444933577329534232506708346391411206323060909795960102558026376823739975026714408054884815268077657719385236901415785652978120523435453890301559016567195619018618132026781588020893392134602309720938204844541730887009336348454709977712839424870842339115722247 A46^18 * U3 + 129068221133437408101386032010227938242790415417408002956440388834868112181036866325987181792617952620211570225145421401636968642407417865428308813969801472080155460044151903911373059980563777215433387329713871436510348502082703071326443785803142144287247590693723735936473435504640/77567059114535041306739627546958424739878444261426368571720717906184637766179825187000856384193706876543604035696658309910499570846843664048177232110913115970369333130326924187471116146253744942216168046567433911792116209065354439182969843989875974095896373810055729 A46^17 * U3 + 12783978249076530856412299581616499812448814070864143616141639515320829793115590125926560504059268257844159130491162326200688965203538567110804552270764562224831755709762903109729453955480299083281536877866482795304181415809809747877796974966623540360991948948407257749615539560448/232701177343605123920218882640875274219635332784279105715162153718553913298539475561002569152581120629630812107089974929731498712540530992144531696332739347911107999390980772562413348438761234826648504139702301735376348627196063317548909531969627922287689121430167187 A46^16 * U3 - 1810442970097170462121122653290427291604967782620000014180906504389275928944428879269826615110693111930022066722356506712480414023024345146923757896554522544082287653722476697782328057603177530844114988866728376051365543251948667665657844199641256470495166203610372754104633985024/3392145442326605304959458930625003997370777445834972386518398742252972497063257661239104506597392429003364607975072520841567036625955262276159354173946637724651720107740244497994363679865324122837441751307613727920938026635511127077972442156991660674747654831343545 A46^15 * U3 - 270639555533122280020486247514756020301825934358369840608010596756492667631965814059407427090369596575058017999403434671889521831726503036761805006306129032875224481365310003762906407037966481686173976406974516397321267076580148872307324693442737067092534607150395172934720327272832/498645380022010979829040462801875587613504284537740940818204615111186957068298876202148362469816687063494597372335660563710354384015423554595425063570155745523802855837815941205171460940202646057103937442219218004377889915420135680461948997077774119187905260207501115 A46^14 * U3 - 1435948341205771592618056822768583583847960643508655403782679773815551216480844799951609196462939014609390424305428592870359320910647059517420727369800472093539593358295705161364370776721823709904982580674821197915654942789644804770077615722633391761110116425814824933514747954464/4038268383722149172570784441220242854012830292660681412521903264586872020313401977665600603092133844051624533303657762906627424554708645566856374016603140148394904890166957735707575809363481098616002084890016342763021460280370389378538621615466262708032922418266125 A46^13 * U3 - 24031158593232439577778424195027450454772002899626269270999618447601656149784654839122276071971243436018537991067130120319932291937910513510530154436517553834823319688270120213094719167314095473720221761127649325967639043315665428464820334187025317629951306324495868404822629086296/134236911348351843098270045621466866730124986864072399717750703996191750825995749157075115524896810946741187375897970359936383987082400454395753337285576744128805506776152891566359869240901645564547003977625417625011994772636432792658457195911102149817275285411208125 A46^12 * U3 - 55342608527391903114377714171300343766958416997314322747423256743530874483390328684036373961531616542340488099823707750319655515404839491476271584066825595064560837447788507941963050626463472192927052092190464771899480038023820496414639119032434176994304931597908860375406025786078/763232724523486193615878259390625899408424925312868786966639717006918811839232973778798513984413296525757036794391317189352583240839934012135854689137993488046637024241555012048731827969697927638424394044213088782211055992990003592543799485323123651818222337052297625 A46^11 * U3 - 2029624852259950049380302093920186872530375028355631473518046159913882812276759452807058944803805569580457303136641881139738479285051882346521262597896200616610534853804143612625821026733823701571937719332556063675018717208715246680768950536936393557501213975920703061913308587814/84803636058165132623986473265625099934269436145874309662959968556324312426581441530977612664934810725084115199376813021039175915648881556903983854348665943116293002693506112449859091996633103070936043782690343198023450665887778176949311053924791516868691370783588625 A46^10 * U3 - 1168942911153266036621765763524847385999721254478313573544681811727225087201633669304728449000690805131434160354788200355429868149616777944697604839445821146293319865569802164294050791015324448927695484221067203620046595245414313118308514802029950573572440600781377894978809819943/181722077267496712765685299854910928430577363169730663563485646906409240914103088994952027139146022982323103998664599330798234104961889050508536830747141306677770720057513098106840911421356649437720093820050735424335965712616667522034237972695981821861481508821975625 A46^9 * U3 - 101409764297139370497431870913772400890980479461654448912068336828050482388546012701358058370032729748116854879439321035194274795413256750973689666942448462456840973308098467386964329640348557236019188613852479460195591937286545711022988218130783801374434056440021146855389791263/72688830906998685106274119941964371372230945267892265425394258762563696365641235597980810855658409192929241599465839732319293641984755620203414732298856522671108288023005239242736364568542659775088037528020294169734386285046667008813695189078392728744592603528790250 A46^8 * U3 - 3322794676291853666085201130675181837616673614933545069242421946525758427676251695684072633966150401809622984292825237098582373428490919709859723984671293905443481868170729806447368393045191340333060166403807452609937752781689646834959249508572627032878032237058297511762260717/13845491601333082877385546655612261213758275289122336271503668335726418355360235351996344924887316036748426971326826615679865455616143927657793282342639337651639673909143855093854545632103363766683435719622913175187502149532698477869275274110170043570398591148341000 A46^7 * U3 - 235997802096027015525218011390431135161602429335194555350491794738198772970078394908866958050373633238495091699843397584952514894044850979218568026142058202580747771909113137749719827302612618129281900176792733050978935129822521807364852652110897499832909022097494923166043147/7417227643571294398599399994077997078799076047744108716876965179853438404657268938569470495475347876829514448925085686971356494080077104102389258397842502313378396737041350943136363731483944875008983421226560629564733294392517041715683182559019666198427816686611250 A46^6 * U3 - 3496748794132449388555216753002710407113019869328151832331519672134490805457467271923368355368145123271002659562187642206698039955131848140898636455957544259518289841694390481218777439807140629994396001816472151472171553970751649445797629489197230923775536860056783627934479/1130244212353721051215146665764266221531287778703864185428870884549095375947774314448681218358148247897830773169536866586111465764583177767983125089195047971562422359930110619906493520988029695239464140377380667362245073431240692070961246866136330087379476828436000 A46^5 * U3 - 25797731568499728113711563609522696636972574369245543976139702215108120141166264492184554278639511568603311186805558250985505155379498427020368472760296798230482403566780044258141402965693251712985897771176010862913999745411179857703742819398871451136186089552354116699661/129170767126139548710302476087344711032147174709013049763299529662753757251174207365563567812359799759752088362232784752698453230238077459198071438765148339607133983992012642275027830970060536598795901757414933412828008392141793379538428213272723438557654494678400 A46^4 * U3 - 105307750747592845167925795351809474019566402815312738506184953133174877999878727791254675413428352747128321422294719175016172361719591143541377238760546940146607913162164819516842775340285454038918138509577296566880300576934730064221978046439482447941555635234543414413987/16607670059075084834181746925515748561276065319730249255281368099496911646579540947001030147303402826253839932287072325346943986744895673325466327841233357949488655084687339721075006839007783276988044511667634295935029650418230577369226484563635870671698435030080000 A46^3 * U3 + 6729992771983469644834688420302244188161700009523433301108672306478446515336817887911228386552702182506838452635857560083522640089937561680000956097567263329228552440470166784211722333574861459688985916960390707820563713605127900163322847651117899308325942825648612997/67786408404388101364007130308227545148065572733592854103189257548966986312569554885718490397156746229607509927702336021824261170387329278879454399351972889589749612590560570290102068730644013375461406170071976718102161838441757458649904018627085186415095653184000 A46^2 * U3 + 97004104716134687567531815774189859076177884454360758941608137811927278665332561915062791777635759119435458822688898910056883442317958132684946302161704171063308484365878439710058473575123783245727688981281817771384031307613137609700123391407537243830931947114431/6831585629064056574855845836052158745080934515857178544035198543609673601669897191808363859627789995425297044867960294464526195050373321126677188143307925380675194012654126509458510328107232388557460939286669359345141026801890396437380097619257766330571494400 A46 * U3 + 91815250260603771367686439814867337622922814376622703580092567517752668189839523750475603039746288206705982958930474905045662465449513750706031249185792777351062825505761724720085638243587008740273119957261765515541418363044444151757419729917247863640658968103/351338689494722909564014928711253878318448060815512039407524496528497499514451855578715855638000628336158133736066529429604204316876342229371969675941550448149009977793640791915009102588371951411526562591885852766321538521240077531065262163276113697000819712 U3 ) ) """; ps5=""" ( ( U3^2 * U4 + 535179163636213160230552332612905761790726203364450534489129686242659247983859225063689303002742332435127911688744222034136908867349929123331100864371658990936252805314758914346647230739008414163809378439226935298947238851749778443095061790353887385009084423995392000000000000000/348416638018627423852659631690165992696423968578095238206531661082875150589988624585082662615359891459868853047741275214579945040097279766315202366058735323894271720291427837740051083562531195231732794190712907389828879861536476746186614041056457073638389583231854077 A46^31 * U3^3 + 117444957438518475167713581434975737067164998391805610491814809960560346257088363610575217412650923824342320317819214071400331125353389211274396241076281078058047842081052040344628591911420714970389327499109713526665438238583003654833271274497439548231330310580181401600000000000000/2438916466130391966968617421831161948874967780046666667445721627580126054129920372095578638307519240219081971334188926502059615280680958364206416562411147267259902042039994864180357584937718366622129559334990351728802159030755337223306298287395199515468727082622978539 A46^30 * U3^3 + 2401741581776741318484092416102407292900015435135593836159021006355478379624893489598800836632769384261155218893078011625298104568085745627327942804937416501911688374548247994274079800109905304371024073616832343444568942958320613360649846757743965134232833554270042193920000000000000/17072415262912743768780321952818133642124774460326666672120051393060882378909442604669050468152634681533573799339322485514417306964766708549444915936878030870819314294279964049262503094564028566354906915344932462101615113215287360563144088011766396608281089578360849773 A46^29 * U3^3 - 805568218873790937813389084592233191792825630736851320718859307972639139165702967980087508722852747263747190017939561005107936647865901266983449666943346565871280018184856673037268657368899455757140347277745038838145391480304288946439289988670652938164442307992695603200000000000000/2072374107058772364996455265949022002801273200386473989101277914764615780098834073399133293821996117411589883156796371074004412984162432829701405980777102013220841619536874248754407890091587282621115868336668102336034204494341240299572403747093030802161288330321259221 A46^28 * U3^3 - 7685682775116980037756417525104129020857901100253508944433808002299072796987780826355035229956095427761674994214377901743588098560205258976689072899389795364550488078379086807213438803727723516868672038614031636269842625366221371250239578203300336002844575259786307614801920000000000000/2509645043648173334010707327064265645392341845668020000801647554779949709699688062886350418818437298185435348502880405370619344123820706156768402642721070538010439201259154715241587954900912199254171316555705071928937421642647242002782180937729660301417320168019044916631 A46^27 * U3^3 - 1034113844705967884541016548705263783711258150109052467551058076026319678448759166131211515280654219796468782344958028728719356943011812509405877602376788836215237969187146349036450163464263286874467724055879617971867571915156566751269616939474200904886354631269920338765414400000000000/119506906840389206381462253669726935494873421222286666704840359751426176652366098232683353277068442770735016595375257398600921148753366959846114411558146216095735200059959748344837521661948199964484348407414527234711305792507011523942008616082364776257967627048525948411 A46^26 * U3^3 - 48658714056579159584588250657320626399886844717677219117243540154602424522685502681521979204132079896072758913281262740708279626890869807641530459145331943833017069929236863886983924086820489878464574416932681640220499275442882030223770711661291180467191894819368336275978321920000000000/3226686484690508572299480849082627258361582373001740001030689713288506769613884652282450538480847954809845448075131949762224871016340907915845089112069947834584850401618913205310613084872601399041077407000192235337205256397689311146434232634223848958965125930310200607097 A46^25 * U3^3 - 8255947206923045970115261594812428132415296386179673138598668698030130733176457946142061749654776338102806089384084736737962150165972226111226766639416349566788039796025933969548991539844303719591225974525365272074129459969218772790071341578178550260218707253120429402938146816000000000/460955212098644081757068692726089608337368910428820000147241387612643824230554950326064362640121136401406492582161707108889267288048701130835012730295706833512121485945559029330087583553228771291582486714313176476743608056812758735204890376317692708423589418615742943871 A46^24 * U3^3 - 19945713493372992010989573088745323542756396319972931197979116120090053547915047057950693601445545496940530403318628583782260656315550176840007325651552659987878417938292973350492923084265613272190430226035072662253316611695490659970858884921554483178528771682266082834119655424000000000/1382865636295932245271206078178268825012106731286460000441724162837931472691664850978193087920363409204219477746485121326667801864146103392505038190887120500536364457836677087990262750659686313874747460142939529430230824170438276205614671128953078125270768255847228831613 A46^23 * U3^3 - 435093775488421369600147732183313564461463032259212791823425518543075036047179553289353390602878450300140400400876508808029170501403708143242207930225443742617112912856658164191471704385406656699565008229508861688289615831997614509046870265598882388184233731177202498351136768000000000/65850744585520583108152670389441372619624130061260000021034483944663403461507850046580623234303019485915213226023101015555609612578385875833573247185100976216017355135079861332869654793318395898797498102044739496677658293830394105029270053759670386917655631230820420553 A46^22 * U3^3 + 1666712214493918375843073715679404854923553599857383781647492939009113706816140218151303957915155518916011997458056804212971047568027330977305056462875462122879154305439206460319912215754500114817599379012537086490342649170430864147520080485377840240561213239361225941393442471936000000/1777970103809055743920122100514917060729851511654020000567931066505911893460711951257676827326181526119710757102623727420001459539616418647506477673997726357832468588647156255987480679419596689267532448755207966410296773933420640835790291451511100446776702043232151354931 A46^21 * U3^3 + 1284088025543201778701542120995051734041815978306710257005722604826526562109618762971947126682732875656141515493855498879095407124008034223158582017519436364169634168807052804122297828912887489492802203539147042679430553728949689548527311377444129568517124121118716963986204576972800000/253995729115579391988588871502131008675693073093431428652561580929415984780101707322525261046597360874244393871803389631428779934230916949643782524856818051118924084092450893712497239917085241323933206965029709487185253419060091547970041635930157206682386006176021622133 A46^20 * U3^3 + 4254014381230883330619305014989375799554837810367142599761760649672291739447040860678177727995158715416431102910496713847267271580162773653334863631889973825919344031375754538234961810569091573254261817527160589941054559827804400510444074230128005539082809168028853708352942800568320000/761987187346738175965766614506393026027079219280294285957684742788247954340305121967575783139792082622733181615410168894286339802692750848931347574570454153356772252277352681137491719751255723971799620895089128461555760257180274643910124907790471620047158018528064866399 A46^19 * U3^3 + 745516437593004300883570660646246938247823802410590380979420190673989967797085587628924839737460064182360717893802831288295892815613347860630889607237862285660785165032805451166314560759396503899171227181213064059364949918934022222627542591929187087049764507673930916328360804352000/182337206830997409898484473440151477871997898846684442679512979848826981177388160317677861483558765882443929556212052858168542666353852799457130312172877280056657633950072429082912591469551501309356214619547530141554381492505449783180216536920428719800707829272090181 A46^18 * U3^3 + 100659132205313930529625050503119312070810564089441017863641173372860790994172383194397174444036783482169409680952402366953488358200797270823652786371161310119627780987982282462009952616082069316251196025335382901954198189565730812891991210118588783206461023328312986396596201321267200/46652276776330908732597955990187328124106890976344548119858249558464160469814599304137292845293392813636725405025112381282837130777107194832531484157374744083067688914939960069642350188852391263579568626229946640503413893296751508810823973946355405309009674603759073453 A46^17 * U3^3 + 31840686398285739366370901635863389542030022459808048577847041429885472147377770155737274410841071887893024815380774859603070679264257251115288897069582531630147721152091634280145756325435744966628395355333013175929902375331398691019183890365382567317614167783255315159428074691624960/46652276776330908732597955990187328124106890976344548119858249558464160469814599304137292845293392813636725405025112381282837130777107194832531484157374744083067688914939960069642350188852391263579568626229946640503413893296751508810823973946355405309009674603759073453 A46^16 * U3^3 - 13828528445690452987305064022092959448876463072880660857470397879545100109724829810338301593203092974158319894346856522064022294423111854351244636838712011841678369295025322372766599272518628248765532325453911764768121252460833528916104395772737785984090513826255228303325154466127872/139956830328992726197793867970561984372320672929033644359574748675392481409443797912411878535880178440910176215075337143848511392331321584497594452472124232249203066744819880208927050566557173790738705878689839921510241679890254526432471921839066215927029023811277220359 A46^15 * U3^3 - 33610752624740506302912013993814981775024007915215935211163351291344044163786135068634072771353605827815789041344588941769903151215762730402577426802629600007206325972644549999333779030662823436337121030730985687375264611402234685156485004573481758060166931327023163395774356304113664/99969164520709090141281334264687131694514766377881174542553391910994629578174141366008484668485841743507268725053812245606079565950943988926853180337231594463716476246299914434947893261826552707670504199064171372507315485635896090308908515599333011376449302722340871685 A46^14 * U3^3 - 440458073572699732774489360478761084951279455207275623193025208264809731530938512938804891081421616585621742589211241713795773058743821672163780025900276255331592774249357759549304463610560721287707008918417645237050696497113058739332361880620366592325582276896858182823540813585536384/1499537467810636352119220013970306975417721495668217618138300878664919443672612120490127270027287626152609030875807183684091193489264159833902797705058473916955747143694498716524218398927398290615057562985962570587609732284538441354633627733989995170646739540835113075275 A46^13 * U3^3 - 6996214565149446678253694413083490264717525678004855498090489246100920822500988095095030219926214938120572903557109272761916802518646083631510656210142715036721759509042764836946925860045014447394355560737664073350497528956878636493202886375323607681733788379035427399732074066732736/39670303381233765929079894549479020513696335864238561326410076155156599038957992605558922487494381644248916160735639780002412526171009519415417928705250632723697014383452346997995195738820060598281946110739750544645760113347577813614646236348941671181130675683468599875 A46^12 * U3^3 - 52720968043649456846417369507000756940194406072631641273516890434262149856954069120692268860993592166109579882175849063584157212108249084107098488501914404760103187541211164434424785557474548152913921719930232076831591869022033755032242197725738904601218545055852510881677688297536184/642658914775987008051094291701560132321880641000664693487843233713536904431119480210054544297408982636832441803917364436039082923970354214529770445025060250123891633011928021367522170968884981692167526993983958823261313836230760580557269028852855073134316946072191317975 A46^11 * U3^3 - 560521169089131499065785274068646758491670755018612288505863123339558028653018546907577396130067320298156818038178669090843281588218301520813686567954392296875641272535840128326520911631312236737399924421960962557597703529589857661762970259131745451459708625790997896125768972935928/18361683279313914515745551191473146637768018314304705528224092391815340126603413720287272694211685218195212622969067555315402369256295834700850584143573150003539760943197943467643490599110999476919072199828113109236037538178021730873064829395795859232409055602062609085 A46^10 * U3^3 - 4197422272012614585634130742038816517252315110924247183388171916467791237166762578598405913589164581591069795124771062594877274429670076994003284050036156103051961891924620808585164846207763280779766288975531255051754977759088637973954664073448069462858272840556659782286260872647812/459042081982847862893638779786828665944200457857617638205602309795383503165085343007181817355292130454880315574226688882885059231407395867521264603589328750088494023579948586691087264977774986922976804995702827730900938454450543271826620734894896480810226390051565227125 A46^9 * U3^3 - 4106654994410345218350715474180779469031652386352768990088763404863224321126834681787202405252012606245929498654531112676402813452159609458415502006915204469860173111678951294367642751272844986752033113410832855341088770049302498143130605877209294548098061602991987492963051239744/1873641150950399440382199101170729248751838603500480155941233917532177563939123849008905376960376042672980879894802811766877792781254677010290875933017668367708138871754892190575866387664387701726435938757970725432248728385512421517659676468958761146164189347149245825 A46^8 * U3^3 - 10861509873129061552037235599451402972763702999367178857883272454799214845428691114656489287350714907124422743117360275388527760856063819431352503904308954737409956132586217400390831701855393788768594250812823801249588131220343764676215839452260384917296536245871426396362711599029/26230976113305592165350787416390209482525740449006722183177274845450485895147733886124675277445264597421732318527239364736289098937565478144072263062247357147913944204568490668062129427301427824170103142611590156051482197397173901247235470565422656046298650860089441550 A46^7 * U3^3 - 1124486478466758794641936904982948237084283820279761242642612077110909965390094116007619021675739939209813695144499796429672334602667319111431706473000996398421642195295148270757273990731860799515046565486145747844982383328993615581180179952020178830599171027345719008701601415523/18736411509503994403821991011707292487518386035004801559412339175321775639391238490089053769603760426729808798948028117668777927812546770102908759330176683677081388717548921905758663876643877017264359387579707254322487283855124215176596764689587611461641893471492458250 A46^6 * U3^3 - 13634406027258739162572410843253056158384774240138183339467954043156022885658076072571122964861139837559116738714581975870696472208621260986499059519385686842525264750880868543070223665506121563803996657564834448591138230910580178478122708511083518804685049985931165670484826297/2141304172514742217579656115623690570002101261143405892504267334322488644501855827438749002240429763054835291308346070590717477464291059440332429637734478134523587282005591074943847300187871659115926787151966543351141403869157053163039630250238584167044787825313423800 A46^5 * U3^3 - 275610949766603790350543874491973128402944565236452331621829945535128551051089218509229304570354572863614983692536142099515347666278429222971179578469228299012270654864962841491251938427241318189542247237765029951590277176611163743592667595081103539096197325545120410752450853/611801192147069205022758890178197305714886074612401683572647809806425327000530236411071143497265646587095797516670305883062136418368874125809265610781279467006739223430168878555384942910820474033121939186276155243183258248330586618011322928639595476298510807232406800 A46^4 * U3^3 - 57091321219446868547123718685194170669561742150029307684083906984399449382980015516422277491250022223527057750658840237853760266613003361978501494129695368914676980282464037464506358216208278225667602395223784571111874119085762583994232092883441120694085505220223346971423259/3496006812268966885844336515303984604085063283499438191843701770322430440003029922348977962841517980497690271523830319331783636676393566433195803490178739811467081276743822163173628245204688423046411081064435172818190047133317637817207559592226259864562918898470896000 A46^3 * U3^3 + 2096019020134284361588278549962801625099190206781628224639171740828930915568065430755481920106589988497979688771818295815492190569468006618308754762164717538084498525703860854191800473065932573287633087040724218118612995977781646506334852358874110328385808128162955638079/14269415560281497493242189858383610628918625646936482415688578654377267102053183356526440664659257063255878659280940078905239333373034965033452259143586693108028903170382947604790319368182401726720045228834429276808938967891092399253908406498882693324746607748860800 A46^2 * U3^3 + 144724249725887284436232581781817786550817001839619049910175696311756292310832604781793691600419996522748911371809754829004775699207861014225518336712102081581627568566107942347420832194840104563187671858359656942129120425684588448408665047033556866808539561866776501/4314260184514436127964380909564205783497694829005739203533961800265235707347901241580178583419276511944332172118198058625922700944228258513515422265634676676652729605557958459498206914038519040580512540841853144915778977442507150190146154648188267067194741571840 A46 * U3^3 + 34523752399540034716636145000935730218516677827634880256328110824710605643763228906652973946423825292328221117422519494495751855171799684110699308767573648503790821554402991388888863972166596620407299382152069987750344858727174998460595722071373991687451348757265/52827675728748197485278133586500478981604426477621296369803613880798804579770219284655247960236038921767332719814670105623543276868101124655290884885322571550849750272138266850998452008634927027516480091941058917336069111540903879879340669161488984496262141696 U3^3 ) ) """; ps6=""" ( ( U3 * U4^3 + 41822330490195068041017320363097809729090890052699731534033293673080362045613806875773900749189755394694179768458994485940692483615892634922652342251410719603257617491056399521754985563535628528166060660260046980535041591378337983957604595139759378622893247460686601951641600000000000000000/356450080441422916364430404818046149990025416021600380113859661592463002937141992302140913567282244477259049192463045797202514832886802745887131987012951584257301943346187289394823441396232477000190857226368174895516164344503923290523438801001095804385269931852430936453389 A46^33 + 454125157206527413523601969987620494847328162420135984302287459170369832878272220272886380031914311891233003000504439954565744301327926677967038692247319542412616194634678505272858478303439697166808691979442683766268105374119197842122316902319990742401536311538368167952547840000000000000000/831716854363320138183670944575441016643392637383734220265672543715747006853331315371662131656991903780271114782413773526805867943402539740403307969696887029933704534474437008587921363257875779667112000194859074756204383470509154344554690535669223543565629840989005518391241 A46^32 - 14740085336461820800966266074682241729581054272188710537515241908189807762813569534360041532382661570106035157724159025403425541339461211407295309969242948500584368294316900034869383665586431029071989963112162284745485647807851469068632801796651905968443260670347124770482847744000000000000000/52398161824889168705571269508252784048533736155175255876737370254092061431759872868414714294390489938157080231292067732188769680434360003645408402090903882885823385671889531541039045885246174119028056012276121709640876158642076723706945503747161083244634679982307347658648183 A46^31 - 9149331424499552779979794487803049109145854134654822152707377782056977306922942650458296507280354954701791394660220920473087273186333364153948147270760935725093184452955662120588287066833595316280317830971486425063174196982668087569045226676196390232025049390929919119574244207001600000000000000/1100361398322672542816996659673308465019208459258680373411484775335933290066957330236709000182200288701298684857133422375964163289121560076553576443908981540602291099109680162361819963590169656499589176257798555902458399331483611197845855578690382748137328279628454300831611843 A46^30 - 79973012198225026539332842880094613358418060119022835029835910425124670099764459027277518388837201641732137026202824480404214035628958792843162201239309141530235969873589550508448718782972837671619969580166184326037129487506541556889887126810734028550977167372000415444560765391994880000000000000/2567509929419569266572992205904386418378153071603587537960131142450511010156233770552321000425134006969696931333311318877249714341283640178625011702454290261405345897922587045510913248377062531832374744601529963772402931773461759461640329683610893078987099319133060035273760967 A46^29 - 8299397433438618012971050717608586981007096658561248516910138778913485394953866129982359922925735316581762478702897711207576975054100165652131628929716109958379944654693325699234875749400905318226733372296404518054930456353699133199857710268046545544970469824348289708598182344299520000000000000/122262377591408060312999628852589829446578717695408930379053863926214810007439703359634333353577809855699853873014824708440462587680173341839286271545442393400254566567742240262424440398907739611065464028644283989162044370164845688649539508743375860904147586625383811203512427 A46^28 - 1009095872071060606887382314527808282304198676274688330469220230071145794033535363745528418711512251257265245188164841956986767644719780200297491853553606313847573922892151658199998953665772946824914444133907829818800088800411900616394966638527678678559806341695040379358176887422246912000000000000/9903252584904052885352969937059776185172876133328123360703362978023399610602615972130381001639802598311688163714200801383677469602094040688982187995180833865420619891987121461256379672311526908496302586320187003122125593983352500780612700208213444733235954516656088707484506587 A46^27 - 17315208871659672382889994991298216489948823684300447200387695359236475124436480420376202114747618244141605164691824173316146543744310447948881287127831116503491247576077521276794352818587011612296482326427954766142441690371899121755561881707409211508579604162112995865737896762901299200000000000/157194485474667506116713808524758352145601208465525767630212110762276184295279618605244142883171469814471240693876203196566309041303080010936225206272711648657470157015668594623117137655738522357084168036828365128922628475926230171120836511241483249733904039946922042975944549 A46^26 - 355912103283291653350342202441876054749468980229513306853575234001898259812970951366303068842390266228175806871138615053043787098181575854719444584002263604429051532090218493757283996626942336013246526185261992049786421446412979193448620795644178642889464382438869086312841888992127016960000000000/4244251107816022665151272830168475507931232628569195726015726990581456975972549702341591857845629684990723498734657486307290344115183160295278080569363214513751694239423052054824162716704940103641272536994365858480910968850008214620262585803520047742815409078566895160350502823 A46^25 - 22500215142403543279349306218081169611665243245444094081053540155023353065879988896297915009225132894908494486994564419892386896801934687727963175381359248310045430450423575265267918061375611015895078661355902220676428093155477822434762767854058633074606376473106078760663121039247968256000000000/606321586830860380735896118595496501133033232652742246573675284368779567996078528905941693977947097855817642676379640901041477730740451470754011509909030644821670605631864579260594673814991443377324648142052265497272995550001173517180369400502863963259344154080985022907214689 A46^24 + 32673087924159313144791905275717518339829777902894646782455060134934567490559434999059780860378598405024654197705939033389093954547300991047620772736355387222770403567834688718752714161637753797576326177011424906610337687450739278051783922665936466482962665445318545262436466728042148326400000000/5456894281477743426623065067359468510197299093874680219163077559319016111964706760153475245801523880702358784087416768109373299576664063236786103589181275803395035450686781213345352064334922990395921833278470389475456959950010561654623324604525775669334097386728865206164932201 A46^23 + 1104476613898878470428452483404305645696373154435799116198630014006790595031027352442953347316486180518984682424499974769238555293892978509198039261572798669589819427036166245573413843280166968329333248039556067221899335330112207191529323373567807146257408223366473003726728025624000104960000000/37121729805971043718524252158907949048961218325678096729000527614415075591596644626894389427221250889131692408757937198022947616167782743107388459790348814989081873814195790566975184111121925104734162131146057071261611972449051439827369555132828405913837397188631736096360083 A46^22 + 78113480257566589843454213154883751458293793164562951385751797138539577840045698708433870322843582703179960018071553825115618374965480805851557122788075034745129320776152687748718547900383557327895464091642273092813119121008016975113831330943443029648706513051422069517463619351777438820096000000/2338668977776175754267027886011200790084556754517720093927033239708149762270588611494346533914938806015296621751750043475445699818570312815765472966791975344312158050294334805719436599000681281598252214262201595489481554264290240709124281973368189572571756022883799374070685229 A46^21 + 8395276376303141598390829139882556608548753795333152128887172440477769331506706983960503595713255764449491015079245760485357931286228197098907656335096624996307325605986758954601108746818602104646481755620539840786476094323961082674609265938980034638463288197875497334999695180183262425971200000/334095568253739393466718269430171541440650964931102870561004748529735680324369801642049504844991258002185231678821434782206528545510044687966496138113139334901736864327762115102776657000097325942607459180314513641354507752041462958446325996195455653224536574697685624867240747 A46^20 + 1980830687381076339084629170133609739180380880215294749410365337574729337777957070632004952411058046327505217385303454420099905980785666056543363976205429431407119959330949327855470437048628780012191977441692141470352845169941328389007388270439665640289698273307474532663228874959149967256320000/143183814965888311485736401184359232045993270684758373097573463655601005853301343560878359219281967715222242148066329192374226519504304866271355487762774000672172941854755192186904281571470282546831768220134791560580503322303484125048425426940909565667658532013293839228817463 A46^19 + 702091132949191502045640382611695646026178320839883517672739200609357661071215369230485179018215789550721046578374598929240937327355327668355522069483080934376708869486654867322142997232774287348753757914178992350603911472387418363244015679942880338944525806103128925167085917623892484556464000/143183814965888311485736401184359232045993270684758373097573463655601005853301343560878359219281967715222242148066329192374226519504304866271355487762774000672172941854755192186904281571470282546831768220134791560580503322303484125048425426940909565667658532013293839228817463 A46^18 - 26433410235178253131164568590264182053663342966938907183003177081908265950075927144928504095882195140380650366718219667766773538150084001651408286437201753129205947322295717753544109541401358911647830600006212366636193412718513659512611675534262638709507230297656780911489899859088163252104000/429551444897664934457209203553077696137979812054275119292720390966803017559904030682635077657845903145666726444198987577122679558512914598814066463288322002016518825564265576560712844714410847640495304660404374681741509966910452375145276280822728697002975596039881517686452389 A46^17 - 36588941424973786825226031379192323188694220080503719244669152016528167903934256688892636045811947246452459444223170684913020286311345813411596839167079667051478933505562383477365997492491009488269523510100891279267477520527793501298375191462023458969167972627835965786511419141962714020174080/20454830709412615926533771597765604577999038669251196156796209093657286550471620508696908459897423959317463164009475598910603788500614980895907926823253428667453277407822170312414897367352897506690252602876398794368643331757640589292632203848701366523951218859041977032688209 A46^16 - 321333621660414138288318264757386991534769910679354013783840583853994409935788586791159864436843010390611984538928952685258511624721739694382405481016998808554437914129696961450517494564423154689101019268062664959334760483746323046684415109519127596246390980123789139075174901071183005966554488/184093476384713543338803944379890441201991348023260765411165881842915578954244584578272176139076815633857168476085280390195434096505534828063171341409280858007079496670399532811734076306176077560212273425887589149317789985818765303633689834638312298715560969731377793294193881 A46^15 - 297844721921145322765306527355860406934008939169980445647884079222865480952075045050385650004580591246687712266033786754423786883489838690861527534993455211693991394970866545156968100893505892393812058175717385845665650930957741425381878068688495541752226534683879631214290521382589457098661971/262990680549590776198291349114129201717130497176086807730236974061307969934635120826103108770109736619795954965836114843136334423579335468661673344870401225724399280957713618302477251865965825086017533465553698784739699979741093290905271192340446141022229956759111133277419830 A46^14 - 451879932351907431338340841430894291445765587061006243890312609075513994394090487211287876791443241336702645913369115324679497644368945637845627225355027484550118544624707338874219923703785680226085214156696766542732612750915702425388991747367656078911167375594394305408128145699286227195203039/788972041648772328594874047342387605151391491528260423190710922183923909803905362478309326310329209859387864897508344529409003270738006405985020034611203677173197842873140854907431755597897475258052600396661096354219099939223279872715813577021338423066689870277333399832259490 A46^13 - 5320311585057193929116580887725053048673711797951597468291152199479233897939064740829295546757123058099231381384546836150171434463598328526972269844562130162789158735497528507679194843684312884543346736256634246332090848994957191293298207019966632338305847326064328022091724095239631394444614337/22542058332822066531282115638353931575754042615093154948306026348112111708683010356523123608866548853125367568500238415125971522021085897313857715274605819347805652653518310140212335874225642150230074297047459895834831426834950853506166102200609669230476853436495239995207414000 A46^12 - 362392746608515719372641040156549702648285106850030418671446645004524075469397447508371929006539117538692298420067983710297061362768282375139330712098123029408339164065434243491074476680334774441684136089288247838831323010949142346356824849579571331534045674787558012078606230561135787887949871/4508411666564413306256423127670786315150808523018630989661205269622422341736602071304624721773309770625073513700047683025194304404217179462771543054921163869561130530703662028042467174845128430046014859409491979166966285366990170701233220440121933846095370687299047999041482800 A46^11 - 155718157831390278974558432491864519634779570729825416271843627583866505195625371450767361228547485547131717071612734991086436233519540316144548267366374648257565699340887077601451758110896914837331994622765481537988675137980472319274860288480400497182597917963360319541332897673699613001900139/6869960634764820276200263813593579146896470130314104365198027077519881663598631727702285290321233936190588211352453612228867511473092844895651875131308440182188389380119865947493283314049719512451070261957321111111567672940175498211403002575423899194050088666360454093777497600 A46^10 - 45201548094888346900126189229758597421851803521277808642167463508827660396693637290758710792553278488070609212455021345000119146078696472196451660991329985879243486243508404638669646114695294849026046972039432309027960523963229014364806077507073721111320914116188285819616980932331878040743049/8587450793456025345250329766991973933620587662892630456497533846899852079498289659627856612901542420238235264190567015286084389341366056119564843914135550227735486725149832434366604142562149390563837827446651388889459591175219372764253753219279873992562610832950567617221872000 A46^9 - 1953129387759091287411246093721824623775778716719168388328766612507051710224152064386589191585418322171515414473927996208486195431232117229550712885298021138550712056198139675205800600486010459477444720900066414100009247618626937808864666954121404483671145377185645585361795757512848953771727/1962845895647091507485789661026736899113277180089744104342293450719966189599609065057795797234638267483025203243558174922533574706597955684471964323230982909196682680034247413569509518299919860700305789130663174603305049411478713774686572164406828341157168190388701169650713600 A46^8 - 376134847222603342228005080394985602907218977535587514699426664550583601459354985670099124083557791013853499761803409404040812308856476452671356746803998334683915044848315929579536086205259194433291389544619656281935845620125586677702558497845124290906144446668089290971220577745466063821/2503629968937616718731874567636144003971016811338959316763129401428528303060725848288004843411528402401817861280048692503231600391068821026112199391876253710710054438819193129552945814158061046811614526952376498218501338535049379814651240005620954516782102283659057614350400 A46^7 - 574485486982304350778070191971122027743291593240873280940414570314432804154563998121312928497476285147145839708807365153231143249845428378451535410210139619924467103332329351315189638465205694465434576925840400070753365257384354164688588108696337944766401214964460997424273537531595188679/32700473063674993877314280067084329847784709372590489035273526875801185999160500875598430607824044439533947575902676800042208658169062152177791992057159232139886425323352726590079292266554266733865985658153488956323282789029216389415852930685661446749807050235546874962944000 A46^6 - 11511257781723192579987461460171218665430662046039138877189380600683547596344289008862892439158437560118751792069494864896646099764172740280826359491156661557991789303166781418829521172671095190437798106362980957418171493748387515586895216124868996215985307716367044170468765302175191523/7630110381524165238039998682319676964483098853604447441563822937686943399804116870972967141825610369224587767710624586676515353572781168841484798146670487499306832575448969537685168195529328904568729986902480756475432650773483824197032350493321004241621645054960937491353600 A46^5 - 1671303995297463181793089014042140921533205745175671854516004230292597522756847916940561516331382516496857206868368002684300205049090986725992113164539129267661714078303721803021367606163396471932149786832020402699788845934151506635865863054320744139050271729184411228168473604636972839/19620283838204996326388568040250597908670825623554293421164116125480711599496300525359058364694426663720368545541606080025325194901437291306675195234295539283931855194011635954047575359932560040319591394892093373793969673417529833649511758411396868049884230141328124977766400 A46^4 - 60908092525844337290393747162251644298087521040833441461527761929200066595412859133091070618059209993364079718454967764919058787501486800829921561765930651085782549124215742770618379064496572773262751298821893631502246026461480269869465295797601392220253848115075799372526327938111547/28028976911721423323412240057500854155244036605077562030234451607829587999280429321941511949563466662457669350773722971464750278430624701866678850334707913262759793134302337077210821942760800057599416278417276248277099533453614048070731083444852668642691757344754464253952000 A46^3 + 45086394754577700869380844548742167538951281901932651744568905863102388384166263647335650948182916349574945031051918658847888488603435323077118198631600514293001349841754886818523071957433889642885763744141389343414660044929152119754129057333007696856923108253108183335928470691323/732185519326600445999340148440838639157395241928556722422450980775956584470998970042553781539617088325424832020211538846426129722269379967129569967927063856659847657385856968547548001770078042320964343599471706077442600057563795541439505853253294201278478559209912535613440 A46^2 + 3731272476720292507686304261693030416127583479257486748224902831742134747688100663209642453477726001478166688384847374161566164080254468319618379882752444074260128081142704326346717896603236118487929226426342553598574093896870131278947045099476660390852113706889521422745255/648548681376311336096354298151253046305799356866989727202426109672580591403591774768418528149462415254238265324025243450986863770434187187437615121817481448997172315569955506437383079799176270479879130881051326953517042284548430007652623523644145232141509494765016064 A46 + 9280862118536625477466695256284609672515130143361639412543372050128009110823486812077779222084224626376141852085219762625785282075028284601725310082870373135311800354168551231605316413369320027988216942534660872550537108296929260273306523538001567960935496614750288886518875/94873407104191829737523828758126159916734077347399640093612048043531789371039711051837224689292787602905711955971692756258649785846372525705159697820157286253300635877662062655982896244908071567342318574599508400057350185625370332548040926887372102530415103234196635648 ), ( U4^4 - 20/7 A46^2 ) ) """; f = Ideal( r, ps ); print "Ideal: " + str(f); print; rg = f.isGB(); print "is GB output:", rg; print; ri = f.toInteger(); print "integer Output:", ri; print; rip = ri.list.get(0); print "integer polynomial:", rip; print; #startLog(); rfi = rz.squarefreeFactors(rip); print "#squarefree Output:", str(len(rfi)); print; for h, i in rfi.iteritems(): print "h**i = ", h, "**" + str(i); #print "g = ", g; print; startLog(); terminate();
Python
# # jython examples for jas. # $Id$ # import sys; from jas import Ring, PolyRing, ParamIdeal, QQ from jas import startLog from jas import terminate # 2 univariate polynomials of degree 2 example for comprehensive GB # integral/rational function coefficients #rp = PolyRing(QQ(), "a,b" ); rp = PolyRing(QQ(), "a" ); r = PolyRing( rp, "x,y,z", PolyRing.lex ); print "Ring: " + str(r); print; #one,a,b,x,y = r.gens(); one,a,x,y,z = r.gens(); #f1 = x * ( x**2 + a * y + b ); #f2 = x * ( y**2 + b * x + a ); f1 = ( x**2 + a * y**2 - x ); f2 = ( a * x**2 + y**2 - y ); f3 = ( x - y ) * z - 1; print "f1 = " + str(f1); print "f2 = " + str(f2); print "f3 = " + str(f3); f = r.paramideal( "", list=[f1,f2,f3] ); print "ParamIdeal: " + str(f); print; #sys.exit(); # long run time startLog(); gs = f.CGBsystem(); print "CGBsystem: " + str(gs); print; #sys.exit(); bg = gs.isCGBsystem(); if bg: print "isCGBsystem: true"; else: print "isCGBsystem: false"; print; #sys.exit(); gs = f.CGB(); print "CGB: " + str(gs); print; terminate(); sys.exit(); bg = gs.isCGB(); if bg: print "isCGB: true"; else: print "isCGB: false"; print; terminate();
Python
# Implementations of algorithms found in joint paper by Eder and Perry # Copyright (C) 2010-2011, the University of Southern Mississippi # released into the public domain # # Originally from http://www.math.usm.edu/perry/Research/basic_sigbased_gb.py # slightly changed for JAS compatibility, changes are labled with JAS # $Id$ # this implementation has one significant difference from the paper: # the paper maintains monic signatures, but # this implementation maintains monic polynomials class sigbased_gb: # the base class from which all other classes are derived def basis_sig(self,F): # incremental basis computation # F is a container of generators of an ideal F.sort(key=lambda x: -x.lm().degree()) # JAS #print "JAS F = " + str([ str(g) for g in F]); G = list() for f in F: G = self.incremental_basis(G,f) Gnew = [g[1] for g in G] R = f.parent() print "size before reduction", len(G) G = R.ideal(Gnew).interreduced_basis() return G def spoly_multipliers(self,f,g): # multipliers for the s-polynomial of f and g # returns uf,ug such that # that is, spoly(f,g) = uf.f - ug.g tf = f.lm(); tg = g.lm() tfg = tf.lcm(tg) R = self.R return (R.monomial_quotient(tfg,tf),R.monomial_quotient(tfg,tg)) def subset(self,S,criterion): # this should be changed to use Python's filter() command result = set() for s in S: if criterion(s): result.add(s) return result def min_sig_degree(self,P): # determines the minimal degree of a signature in P return min([p[0].degree() for p in P]) def new_pair(self,sig,p,q,G): # creates a new critical pair from p and q, with signature sig # it needs G for the sake of F5; see derived class below return (sig,p,q) def spoly(self,s,G): # computes the spolynomial # assumes that s has the form (signature, poly, poly) f = s[1]; g = s[2] tf = f.lm(); tg = g.lm() tfg = tf.lcm(tg) R = f.parent() uf = R.monomial_quotient(tfg,tf); ug = R.monomial_quotient(tfg,tg) return uf*f - ug*g def initialize_Syz(self,F,G): # initializes Syz; initially, this does nothing return set() def prune_P(self,P,Syz): # prunes P using Syz; initially, this does nothing return P def prune_S(self,S,Syz,Done,G): # prunes S using Syz, Done, and G; initially, this does nothing # (Done is used as a shortcut) return S def update_Syz(self,Syz,sigma,r): # updates Syz using sigma and r # some algorithms use this; some don't return Syz def sigsafe_reduction(self,s,sigma,G,F,Syz): # computes a complete sigma-reduction of s modulo G # F is assumed to be a subset of G that represents the previous GB incrementally # Syz is sent but not used (I should probably remove this) r = s r_sigma = sigma R = self.R reduced = True while (r != 0) and reduced: reduced = False r = r.reduce(F) if any(g[1] != 0 and R.monomial_divides(g[1].lm(),r.lm()) for g in G): for g in G: if g[1] != 0 and R.monomial_divides(g[1].lm(),r.lm()): u = self.R.monomial_quotient(r.lt(),g[1].lt(),coeff=True) sig_ug = u*g[0] if (sig_ug < r_sigma) or ((sig_ug.lm() == r_sigma.lm()) and (sig_ug.lc() != r_sigma.lc())): reduced = True r -= u*g[1] if (sig_ug.lm() == r_sigma.lm()): r_sigma -= sig_ug # ensure that r is monic if r != 0: c = r.lc() r *= c**(-1) r_sigma *= c**(-1) return r_sigma, r def sig_redundant(self,sigma,r,G): # test whether (sigma,r) is signature-redundant wrt G R = self.R return any(g[0] != 0 and R.monomial_divides(g[0].lm(),sigma.lm()) and R.monomial_quotient(sigma.lm(),g[0].lm())*g[1].lm()==r.lm() for g in G) #if any ((g[0] != 0 and R.monomial_divides(g[0].lm(),sigma.lm())) and (g[1] != 0 and R.monomial_divides(g[1].lm(),r.lm())) and not R.monomial_quotient(sigma.lm(),g[0].lm())*g[1].lm()==r.lm() for g in G): # print "counterexample at", (sigma, r.lm()) return any ((g[0] != 0 and R.monomial_divides(g[0].lm(),sigma.lm())) and (g[1] != 0 and R.monomial_divides(g[1].lm(),r.lm())) for g in G) def incremental_basis(self,F,g): # assuming that F is a Groebner basis of the ideal generated by F, # compute a Groebner basis of F+[g] self.R = g.parent(); R = self.R # to record a signature, we use only the leading monomial of a minimal representation # so that elements of F have "signature" 0 and g has "signature" 1 G = [(R(0),F[i]) for i in xrange(len(F))] + [(R(1),g)] #print "JAS G = " + str([ str(gg[0])+","+str(gg[1]) for gg in G]); # the structure of a pair can vary, except for its first entry, # which should be the signature P = set([self.new_pair(self.spoly_multipliers(g,f)[0],g,f,G) for f in F]) Syz = self.initialize_Syz(F,G) # Done will track new polynomials computed by the algorithm Done = list() while len(P) != 0: P = self.prune_P(P,Syz) if len(P) != 0: S = list(self.subset(P,lambda x: x[0].degree() == self.min_sig_degree(P))) print "treating", len(S), "signatures of degree", self.min_sig_degree(P) P.difference_update(S) while len(S) != 0: S = self.prune_S(S,Syz,Done,G) if len(S) != 0: # sort by signature S.sort(key=lambda x:x[0]); s = S.pop(0) sigma,r = self.sigsafe_reduction(self.spoly(s,G),s[0],G,F,Syz) if (r != 0) and (not self.sig_redundant(sigma,r,G)): #print "new polynomial", (sigma,r.lm()) for (tau,g) in G: if (g != 0): rmul,gmul = self.spoly_multipliers(r,g) if rmul*sigma.lm() != gmul*tau.lm(): if rmul*sigma.lm() > gmul*tau.lm(): p = self.new_pair(rmul*sigma,r,g,G) else: p = self.new_pair(gmul*tau,g,r,G) if p[0].degree() == sigma.degree(): S.append(p) else: P.add(p) G.append((sigma,r)) Done.append((sigma,r)) elif r == 0: #print "zero reduction at", (sigma,r.lm()) self.update_Syz(Syz,sigma,r) Done.append((sigma,r)) #else: #print "sig-redundant at", sigma return list(self.subset(G,lambda x: x[1] != 0)) class ggv(sigbased_gb): # the plugin implementation of ggv def new_pair(self,sig,p,q,G): # creates a new critical pair from p and q, with signature sig # it needs G for the sake of F5; see derived class below i = -1; j = -1; k = 0 up,uq = self.spoly_multipliers(p,q) while (i<0 or j<0) and k < len(G): if p == G[k][1]: i = k elif q == G[k][1]: j = k k += 1; if (i == -1): i=len(G) elif (j == -1): j = len(G) return (sig,i,j) def initialize_Syz(self,F,G): # recognize trivial syzygies return set([f.lm() for f in F]) def spoly(self,s,G): # ggv only computes part of an S-polynomial # (as if it were computing a row of the Macaulay matrix # and not subsequently triangularizing) f = G[s[1]][1]; g = G[s[2]][1] tf = f.lm(); tg = g.lm() tfg = tf.lcm(tg) uf = self.R.monomial_quotient(tfg,tf) return uf*f def prune_P(self,P,Syz): # remove any pair whose signature is divisible by an element of Syz result = set() R = self.R for p in P: if not any(R.monomial_divides(t,p[0]) for t in Syz): result.add(p) return result def prune_S(self,S,Syz,Done,G): # watch out for new syzygies discovered, and allow only one polynomial # per signature result = list() R = self.R for s in S: if not any(R.monomial_divides(t,s[0]) for t in Syz): if not any(s[0].lm()==sig[0].lm() and s[1]<sig[1] for sig in S): if not any(s[0].lm()==sig[0].lm() for sig in result): result.append(s) return result def update_Syz(self,Syz,sigma,r): # add non-trivial syzygies to the basis # polynomials that reduce to zero indicate non-trivial syzygies if r == 0: Syz.add(sigma.lm()) return Syz class ggv_first_implementation(ggv): def new_pair(self,sig,p,q,G): # creates a new critical pair from p and q, with signature sig # it needs G for the sake of F5; see derived class below i = -1; j = -1; k = 0 return (sig,p,q) def spoly(self,s,G): # ggv only computes part of an S-polynomial # (as if it were computing a row of the Macaulay matrix # and not subsequently triangularizing) # -- at least, that's how I read "(t_i,m+1)" on p. 6 of that paper f = s[1]; g = s[2] tf = f.lm(); tg = g.lm() tfg = tf.lcm(tg) uf = self.R.monomial_quotient(tfg,tf) return uf*f def prune_S(self,S,Syz,Done,G): # watch out for new syzygies discovered, and allow only one polynomial # per signature result = list() R = self.R for s in S: if not any(R.monomial_divides(t,s[0]) for t in Syz): if not any(s[0].lm()==sig[0].lm() for sig in Done): result.append(s) return result class coeff_free_sigbased_gb(sigbased_gb): # child class of sigbased_gb that implements semi-complete reduction def sigsafe_reduction(self,s,sigma,G,F,Syz): # see sigbased_gb.sigsafe_reduction r = s r_sigma = sigma R = self.R reduced = True while (r != 0) and reduced: reduced = False r = r.reduce(F) if any( g[1] != 0 and R.monomial_divides(g[1].lm(),r.lm()) for g in G ): for g in G: if g[1] != 0 and R.monomial_divides(g[1].lm(),r.lm()): u = self.R.monomial_quotient(r.lt(),g[1].lt(),coeff=True) sig_ug = u*g[0] if sig_ug.lm() < r_sigma: reduced = True r -= u*g[1] # ensure that r is monic if r != 0: c = r.lc() r *= c**(-1) return r_sigma, r class arris_algorithm(coeff_free_sigbased_gb): # the plugin implementation of arri's algorithm def initialize_Syz(self,F,G): # recognize trivial syzygies return set([f.lm() for f in F]) def update_Syz(self,Syz,sigma,r): # add non-trivial syzygies to the basis # polynomials that reduce to zero indicate non-trivial syzygies if r == 0: Syz.add(sigma.lm()) return Syz def prune_P(self,P,Syz): # remove any pair whose signature is divisible by an element of Syz result = set() for p in P: if not any(self.R.monomial_divides(t,p[0]) for t in Syz): result.add(p) return result def prune_S(self,S,Syz,Done,G): # watch out for new syzygies discovered, and apply arri's rewritable criterion: # for any s-polynomial of a given signature, if there exists another (s-)polynomial # in S or Done of identical signature but lower lm, discard the first result = list() for s in S: if not any(self.R.monomial_divides(t,s[0]) for t in Syz): if not any(s[0]==sig[0] and s[1].lm()>sig[1].lm() for sig in S): for (sig,f) in Done: if self.R.monomial_divides(sig,s[0]): u = self.R.monomial_quotient(s[0],sig) if u*f.lm() < s[1].lm(): break else: result.append(s) return result def new_pair(self,sig,p,q,G): # in arri's algorithm, each pair is (sigma,s) where s is the s-polynomial # and sigma is its natural signature tp = p.lm(); tq = q.lm() tpq = tp.lcm(tq) R = p.parent() #JAS tpq.parent() up = R.monomial_quotient(tpq,tp); uq = R.monomial_quotient(tpq,tq) return (sig,up*p-uq*q) def spoly(self,s,G): return s[1] class f5(coeff_free_sigbased_gb): # the plugin implementation of arri's algorithm def initialize_Syz(self,F,G): # recognize trivial syzygies return set([f.lm() for f in F]) def update_Syz(self,Syz,sigma,r): # recognize trivial syzygies # see class f5z for a more thorough update_Syz in line w/arri and ggv return Syz def prune_P(self,P,Syz): # remove any pair whose signature is divisible by an element of Syz result = set() for p in P: if not any(self.R.monomial_divides(t,p[0]) for t in Syz): result.add(p) return result def prune_S(self,S,Syz,Done,G): # watch out for new syzygies discovered, and apply faugere's rewritable criterion: # for any (sigma,p,q) in S, if there exists (tau,g) such that tau divides sigma # but g was generated after p, discard (sigma,p,q) result = list() for (sig,u,j,v,k) in S: if not any(self.R.monomial_divides(t,sig) for t in Syz): if G[j][0] == 0 or not any(self.R.monomial_divides(Done[i][0],G[j][0]*u) and Done[i][0] > G[j][0] for i in xrange(len(Done))): result.append((sig,u,j,v,k)) return result def new_pair(self,sig,p,q,G): # it's easier to deal with faugere's criterion if one creates pairs # using indices rather than polynomials # note that this while look gives f5 a disadvantage i = -1; j = -1; k = 0 up,uq = self.spoly_multipliers(p,q) while (i<0 or j<0) and k < len(G): if p == G[k][1]: i = k elif q == G[k][1]: j = k k += 1; if (i == -1): i=len(G) elif (j == -1): j = len(G) return (sig,up,i,uq,j) def spoly(self,s,G): # since s has the structure (sigma,up,i,uq,j) # we have to compute the s-polynomial by looking up f and g f = G[s[2]][1]; g = G[s[4]][1] uf = s[1]; ug = s[3] return uf*f - ug*g class f5z(f5): def update_Syz(self,Syz,sigma,r): # recognize trivial syzygies if r == 0: Syz.add(sigma.lm()) return Syz class min_size_mons(arris_algorithm): # the plugin implementation of arri's algorithm def prune_S(self,S,Syz,Done,G): # watch out for new syzygies discovered, and apply the minimal "number of monomials" criterion: # for any s-polynomial of a given signature, if there exists another polynomial # in Done of identical signature but fewer monomials, replace this s-polynomial # by the multiple of the polynomial with fewer monomials result = list() R = G[0][1].parent() for (sigma,s) in S: if not any(R.monomial_divides(tau,sigma) for tau in Syz): if not any(tau == sigma for (tau,g) in result): for (tau,g) in Done: if tau.divides(sigma) and len(g.monomials()) < len(s.monomials()): u = R.monomial_quotient(sigma,tau) result.append((u*tau,u*g)) break else: result.append((sigma,s)) return result
Python
# # jython examples for jas. # $Id$ # import sys; from jas import Ring from jas import Ideal from jas import startLog from jas import terminate # Nabashima, ISSAC 2007, example Ex-4.8 # integral function coefficients r = Ring( "IntFunc(a, b, c) (y,x) L" ); print "Ring: " + str(r); print; ps = """ ( ( { a } x^2 + { b } y^2 ), ( { c } x^2 + y^2 ), ( { 2 a } x - { 2 c } y ) ) """; #startLog(); f = r.paramideal( ps ); print "ParamIdeal: " + str(f); print; gs = f.CGBsystem(); print "CGBsystem: " + str(gs); print; bg = gs.isCGBsystem(); if bg: print "isCGBsystem: true"; else: print "isCGBsystem: false"; print; #sys.exit(); gs = f.CGB(); print "CGB: " + str(gs); print; bg = gs.isCGB(); if bg: print "isCGB: true"; else: print "isCGB: false"; print; terminate(); #------------------------------------------ #sys.exit();
Python
# # jython examples for jas. # $Id$ # from java.lang import System from java.lang import Integer from jas import Ring from jas import Ideal from jas import terminate from jas import startLog # polynomial examples: factorization over Q #r = Ring( "Rat(x) L" ); r = Ring( "Q(x) L" ); print "Ring: " + str(r); print; [one,x] = r.gens(); #f = x**15 - 1; #f = x * ( x + 1 )**2 * ( x**2 + x + 1 )**3; #f = x**6 - 3 * x**5 + x**4 - 3 * x**3 - x**2 - 3 * x+ 1; #f = x**(3*11*11) + 3 * x**(2*11*11) - x**(11*11); #f = x**(3*11*11*11) + 3 * x**(2*11*11*11) - x**(11*11*11); #f = (x**2+1)*(x-3)*(x-5)**3; #f = x**4 + 1; #f = x**12 + x**9 + x**6 + x**3 + 1; #f = x**24 - 1; #f = x**20 - 1; #f = x**22 - 1; #f = x**8 - 40 * x**6 + 352 * x**4 - 960 * x**2 + 576; #f = 362408718672000 * x**9 + 312179013226080 * x**8 - 591298435728000 * x**6 - 509344705789920 * x**5 - 1178946881112000 * x**2 - 4170783473878580 * x - 2717923400363451; #f = 292700016000 * x**8 + 614670033600 * x**7 - 417466472400 * x**6 - 110982089400 * x**5 + 1185906158780 * x**4 - 161076194335 * x**3 + 204890011200 * x**2 - 359330651400 * x - 7719685302; #f = x**10 - 212 * x**9 - 1760 * x**8 + 529 * x**7 - 93699 * x**6 - 726220 * x**5 + 37740 * x**4 + 169141 * x**3 + 24517680 * x**2 - 9472740; #f = x**4 - 1; #f = x**3 - x**2 + x - 1; #f = x**8 + 4 * x**6 + 8 * x**4 - 8 * x**2 + 4; #f = x**16 + 272 * x**12 - 7072 * x**8 + 3207424 * x**4 + 12960000; #f = x**16 + 16 * x**12 + 96 * x**8 + 256 * x**4 + 256; f = x**24 + 272 * x**20 - 7072 * x**16 + 3207424 * x**12 + 12960000 * x**8; print "f = ", f; print; startLog(); t = System.currentTimeMillis(); #G = r.squarefreeFactors(f); G = r.factors(f); t = System.currentTimeMillis() - t; print "#G = ", len(G); #print "factor time =", t, "milliseconds"; g = one; for h, i in G.iteritems(): print "h**i = (", h, ")**" + str(i); h = h**i; g = g*h; #print "g = ", g; if cmp(f,g) == 0: print "factor time =", t, "milliseconds,", "isFactors(f,g): true" ; else: print "factor time =", t, "milliseconds,", "isFactors(f,g): ", cmp(f,g); print; #startLog(); terminate();
Python
# # jython examples for jas. # $Id$ # import sys; from jas import Ring from jas import ZZ from jas import QQ from jas import CC from jas import RF from jas import startLog from jas import terminate # example for rational and complex numbers # # zn = ZZ(7); print "zn:", zn; print "zn^2:", zn*zn; print; x = 10000000000000000000000000000000000000000000000000; rn = QQ(2*x,4*x); print "rn:", rn; print "rn^2:", rn*rn; print; rn = QQ((6,4)); print "rn:", rn; print "rn^2:", rn*rn; print; c = CC(); print "c:", c; c = c.one(); print "c:", c; c = CC((2,),(3,)); print "c:", c; print "c^5:", c**5 + c.one(); print; c = CC( (2,),rn ); print "c:", c; print; r = Ring( "Q(x,y) L" ); print "Ring: " + str(r); print; # sage like: with generators for the polynomial ring [one,x,y] = r.gens(); zero = r.zero(); try: f = RF(r); except: f = None; print "f: " + str(f); d = x**2 + 5 * x - 6; f = RF(r,d); print "f: " + str(f); n = d*d + y + 1; f = RF(r,d,n); print "f: " + str(f); print; # beware not to mix expressions f = f**2 - f; print "f^2-f: " + str(f); print; f = f/f; print "f/f: " + str(f); f = RF(r,d,one); print "f: " + str(f); f = RF(r,zero); print "f: " + str(f); f = RF(r,d,y); print "f: " + str(f); print "one: " + str(f.one()); print "zero: " + str(f.zero()); print; terminate(); #sys.exit();
Python
# # jython examples for jas. # $Id$ # import sys; from jas import Ring from jas import Ideal from jas import startLog from jas import terminate # rational function coefficients # IP (alpha,beta,gamma,epsilon,theta,eta) # (c3,c2,c1) /G/ #r = Ring( "IntFunc(alpha,beta,gamma,epsilon,theta,eta)(c3,c2,c1) G" ); # ( { alpha } c1 - { beta } c1**2 - { gamma } c1 c2 + { epsilon } c3 ), # ( - { gamma } c1 c2 + { epsilon + theta } c3 - { gamma } c2 ), # ( { gamma } c2 c3 + { eta } c2 - { epsilon + theta } c3 ) r = Ring( "IntFunc(a,b,g,e,t,eta)(c3,c2,c1) G" ); print "Ring: " + str(r); print; ps = """ ( ( { a } c1 - { b } c1**2 - { g } c1 c2 + { e } c3 ), ( - { g } c1 c2 + { e + t } c3 - { g } c2 ), ( { g } c2 c3 + { eta } c2 - { e + t } c3 ) ) """; f = r.paramideal( ps ); print "ParamIdeal: " + str(f); print; #sys.exit(); #startLog(); gs = f.CGBsystem(); print "CGBsystem: " + str(gs); print; sys.exit(); bg = gs.isCGBsystem(); if bg: print "isCGBsystem: true"; else: print "isCGBsystem: false"; print; #sys.exit(); gs = f.CGB(); print "CGB: " + str(gs); print; bg = gs.isCGB(); if bg: print "isCGB: true"; else: print "isCGB: false"; print; terminate(); #sys.exit();
Python
# # jython examples for jas. # $Id$ # from jas import SolvableRing # U(sl_2) example rs = """ # solvable polynomials, U(sl_2): Rat(e,f,h) G RelationTable ( ( f ), ( e ), ( e f - h ), ( h ), ( e ), ( e h + 2 e ), ( h ), ( f ), ( f h - 2 f ) ) """; r = SolvableRing( rs ); print "SolvableRing: " + str(r); print; ps = """ ( ( e^2 + f^3 ) ) """; f = r.ideal( ps ); print "SolvableIdeal: " + str(f); print; rg = f.leftGB(); print "seq left GB:", rg; print; rg = f.twosidedGB(); print "seq twosided GB:", rg; print; #rg = f.rightGB(); #print "seq right GB:", rg; #print;
Python
# # jython examples for jas. # $Id$ # import sys; from java.lang import System from java.lang import Integer from jas import Ring from jas import PolyRing from jas import Ideal from jas import terminate from jas import startLog from jas import QQ, DD, CR # polynomial examples: complex roots over Q #r = Ring( "Rat(x) L" ); #r = Ring( "Q(x) L" ); r = PolyRing( CR(QQ()), "x", PolyRing.lex ); print "Ring: " + str(r); print; [one,I,x] = r.gens(); print "one = ", one; print "I = ", I; print "x = ", x; print; f1 = x**3 - 2; f2 = ( x - I ) * ( x + I ) * ( x - 2 * I ) * ( x + (1,2) * I ); f3 = ( x**3 - 2 * I ); #f = f1 * f2 * f3; #f = f1 * f2; #f = f1 * f3; #f = f2 * f3; f = f2; print "f = ", f; print; startLog(); t = System.currentTimeMillis(); R = r.complexRoots(f); t = System.currentTimeMillis() - t; #print "R = ", [ a.elem.ring for a in R ]; print "R = ", [ a.elem.ring.getRoot() for a in R ]; print "complex roots time =", t, "milliseconds"; #terminate(); #sys.exit(); #eps = QQ(1,10) ** (DD().elem.DEFAULT_PRECISION-3); # not too big eps = QQ(1,10) ** 10; print "eps = ", eps; t = System.currentTimeMillis(); R = r.complexRoots(f,eps); t = System.currentTimeMillis() - t; #print "R = ", [ str(a) for a in R ]; print "R = ", [ a.elem.decimalMagnitude() for a in R ]; print "complex root refinement time =", t, "milliseconds"; #startLog(); terminate();
Python
# # jython examples for jas. # $Id$ # from java.lang import System from java.lang import Integer from jas import WordRing, WordPolyRing, WordIdeal from jas import terminate, startLog from jas import QQ, ZZ, GF, ZM # non-commutative polynomial examples: simple test r = WordPolyRing(QQ(),"x,y"); print "WordPolyRing: " + str(r); print; [one,x,y] = r.gens(); print "one = " + str(one); print "x = " + str(x); print "y = " + str(y); print; f1 = x*y - (1,10); f2 = y*x + x + y; print "f1 = " + str(f1); print "f2 = " + str(f2); print; c1 = f1 * f2; c2 = f2 * f1; s = c1 - c2; print "c1 = " + str(c1); print "c2 = " + str(c2); print "s = " + str(s); print; F = r.ideal( list=[f1,f2] ); print "F = " + str(F); print; startLog(); G = F.GB(); print "G = " + str(G); print "isGB(G) = " + str(G.isGB()); print; F = r.ideal( list=[f1,f2,c1,c2,s] ); print "F = " + str(F); print; G = F.GB(); print "G = " + str(G); print "isGB(G) = " + str(G.isGB()); print; p = r.random(3,6,4); print "p = " + str(p); print; pp = p**5; print "pp = " + str(len(pp)); print "p == pp: " + str(p == pp); print "pp == pp: " + str(pp == pp); print "pp-pp == 0: " + str(pp-pp == 0); print; #exit(0); ri = WordPolyRing(ZZ(),"x,y"); print "WordPolyRing: " + str(ri); print; [one,x,y] = ri.gens(); print "one = " + str(one); print "x = " + str(x); print "y = " + str(y); print; f1 = x*y - 10; f2 = y*x + x + y; print "f1 = " + str(f1); print "f2 = " + str(f2); print; c1 = f1 * f2; c2 = f2 * f1; s = c1 - c2; print "c1 = " + str(c1); print "c2 = " + str(c2); print "s = " + str(s); print; Fi = ri.ideal( list=[f1,f2] ); print "Fi = " + str(Fi); print; #not implemented: #Gi = Fi.GB(); #print "Gi = " + str(Gi); #print "isGB(Gi) = " + str(Gi.isGB()); #print; #exit(0); rp = WordPolyRing(GF(23),"x,y"); print "WordPolyRing: " + str(rp); print; [one,x,y] = rp.gens(); print "one = " + str(one); print "x = " + str(x); print "y = " + str(y); print; f1 = x*y - 10; f2 = y*x + x + y; print "f1 = " + str(f1); print "f2 = " + str(f2); print; c1 = f1 * f2; c2 = f2 * f1; s = c1 - c2; s1 = 22 * y*x*x*y + x*y*y*x + 22 * y*x*y + x*y*y + x*y*x + 22 * x*x*y; print "c1 = " + str(c1); print "c2 = " + str(c2); print "s = " + str(s); print "s1 = " + str(s1); print "s == s1: " + str(s==s1); print; Fp = rp.ideal( list=[f1,f2] ); print "Fp = " + str(Fp); print; Gp = Fp.GB(); print "Gp = " + str(Gp); print "isGB(Gp) = " + str(Gp.isGB()); print;
Python
# # jython examples for jas. # $Id$ # from java.lang import System from java.lang import Integer from jas import SolvableRing, SolvPolyRing, PolyRing from jas import QQ, startLog, SRC, SRF # Ore extension solvable polynomial example, Gomez-Torrecillas, 2003 p = PolyRing(QQ(),"x,y,z,t"); #is automatic: [one,x,y,z,t] = p.gens(); relations = [z, y, y * z + x, t, y, y * t + y, t, z, z * t - z ]; print "relations: = " + str([ str(f) for f in relations ]); print; rp = SolvPolyRing(QQ(), "x,y,z,t", PolyRing.lex, relations); print "SolvPolyRing: " + str(rp); print; print "gens =", [ str(f) for f in rp.gens() ]; f1 = x**2 + y**2 + z**2 + t**2 + 1; print "f1 = ", f1; F = [ f1 ]; print "F =", [ str(f) for f in F ]; print I = rp.ideal( list=F ); print "SolvableIdeal: " + str(I); print; rgl = I.leftGB(); print "seq left GB:" + str(rgl); print "isLeftGB: " + str(rgl.isLeftGB()); print; #rgr = I.rightGB(); #print "seq right GB:" + str(rgr); #print "isRightGB: " + str(rgr.isRightGB()); #print; #startLog(); rgt = I.twosidedGB(); print "seq twosided GB:" + str(rgt); print "isTwosidedGB: " + str(rgt.isTwosidedGB()); print; #startLog(); #rgi = rgl.intersect(rgt); #print "leftGB intersect twosidedGB:" + str(rgi); #print; #startLog(); #rgtu = rgt.univariates(); #print "univariate polynomials for twosidedGB: " + str([ str(f) for f in rgtu ]); #print; #startLog(); sr = SRC(rgt,one); print "SolvableResidue: " + str(sr); print "SolvableResidue: " + str(sr-sr); print; st = SRC(rgt,t-x); print "SolvableResidue: " + str(st); print "SolvableResidue: " + str(st-st); print "SolvableResidue: " + str(st**4+3*st); print; #exit(0); sc = SRF(rp,one); print "SolvableQuotient: " + str(sc); print "SolvableQuotient: " + str(sc-sc); print; scx = SRF(rp,x); print "SolvableQuotient: " + str(scx); print "SolvableQuotient: " + str(scx*scx); print; scy = SRF(rp,y); scyi = 1 / scy; print "SolvableQuotient: " + str(scy); print "SolvableQuotient: " + str(scyi); print "SolvableQuotient: " + str(scyi*scy); print "SolvableQuotient: " + str(scy*scyi); print; sca = SRF(rp,x*y + t*z*x); scai = 1 / sca; print "SolvableQuotient: " + str(sca); print "SolvableQuotient: " + str(scai); print "SolvableQuotient: " + str(scai*sca); print "SolvableQuotient: " + str(sca*scai); print; scb = SRF(rp, z*(x-y) - t*z ); scbi = 1 / scb; print "SolvableQuotient: " + str(scb); print "SolvableQuotient: " + str(scbi); print "SolvableQuotient: " + str(scbi*scb); print "SolvableQuotient: " + str(scb*scbi); print; scc = sca*scb; scci = 1 / scc; print "SolvableQuotient: " + str(scc); print "SolvableQuotient: " + str(scci); print "SolvableQuotient: " + str(scci*scb); print "SolvableQuotient: " + str(scci*sca*scb); print "SolvableQuotient: " + str(sca*scb*scci); #print "SolvableQuotient: " + str(sca*scci*scb); print; scd = scci + scb + sca; print "SolvableQuotient: " + str(scd); print "SolvableQuotient: " + str(scd-(scci+scb) == sca); print "SolvableQuotient: " + str(sca == scd-(scci+scb)); print; sce = scai + scbi; print "SolvableQuotient: " + str(sce); #exit(0);
Python
# # jython examples for jas. # $Id$ # import sys from java.lang import System from java.lang import Integer from jas import Ring from jas import PolyRing from jas import Ideal from jas import QQ, AN from jas import terminate from jas import startLog # polynomial examples: factorization over Q(i)(sqrt2) Q = PolyRing(QQ(),"i",PolyRing.lex); print "Q = " + str(Q); Q.inject_variables(); print "i = " + str(i); imag = i**2 + 1; print "imag = " + str(imag); Qi = AN(imag,field=True); print "Qi = " + str(Qi.factory()); Qi.inject_variables(); print "i = " + str(i); print; Wr = PolyRing(Qi,"w2",PolyRing.lex) print "Wr = " + str(Wr); Wr.inject_variables(); print "i = " + str(i); print "w2 = " + str(w2); w2p = w2**2 - 2; print "w2p = " + str(w2p); Qw2 = AN(w2p,field=True); print "Qw2 = " + str(Qw2.factory()); Qw2.inject_variables(); print "i = " + str(i); print "w2 = " + str(w2); print; Qiw2 = PolyRing(Qw2,"x",PolyRing.lex) print "Qiw2 = " + str(Qiw2); Qiw2.inject_variables(); print "i = " + str(i); print "w2 = " + str(w2); print "x = " + str(x); print; #sys.exit(); f = ( x**2 + 1 ) * ( x**2 - 2 ); print "f = ", f; print; startLog(); t = System.currentTimeMillis(); G = Qiw2.factors(f); t = System.currentTimeMillis() - t; #print "G = ", G; #print "factor time =", t, "milliseconds"; g = one; for h, i in G.iteritems(): print "h**i = (", h, ")**" + str(i); h = h**i; g = g*h; #print "g = ", g; if cmp(f,g) == 0: print "factor time =", t, "milliseconds,", "isFactors(f,g): true" ; else: print "factor time =", t, "milliseconds,", "isFactors(f,g): ", cmp(f,g); print; #startLog(); terminate();
Python
# # jython examples for jas. # $Id$ # from java.lang import System from java.lang import Integer from jas import PolyRing, QQ, ZM, ZZ from jas import terminate from jas import startLog # polynomial examples: squarefree: characteristic 0 #r = PolyRing(PolyRing(QQ(),"u,v",PolyRing.lex),"x, y",PolyRing.lex) #r = PolyRing(PolyRing(ZZ(),"u,v",PolyRing.lex),"x, y",PolyRing.lex) r = PolyRing(PolyRing(ZM(7),"u,v",PolyRing.lex),"x, y",PolyRing.lex) print "Ring: " + str(r); print; [one,u,v,x,y] = r.gens(); a = r.random(k=1,l=3); b = r.random(k=1,l=3); c = r.random(k=1,l=3); if a.isZERO(): a = x; if b.isZERO(): b = y; if c.isZERO(): c = y; f = a**2 * c**3 * b; print "a = ", a; print "b = ", b; print "c = ", c; print "f = ", f; print; t = System.currentTimeMillis(); F = r.squarefreeFactors(f); t = System.currentTimeMillis() - t; print "factors:"; for g in F.keys(): i = F[g]; print "g = %s**%s" % (g,i); print print "factor time =", t, "milliseconds"; #startLog(); terminate();
Python
# # jython for jas example integer programming. # $Id$ # # CLO2, p370 # 4 A + 5 B + C = 37 # 2 A + 3 B + D = 20 # # max: 11 A + 15 B # import sys; from jas import Ring from jas import Ideal r = Ring( "Rat(w1,w2,w3,w4,z1,z2) W( (0,0,0,0,1,1),(1,1,2,2,0,0) )" ); print "Ring: " + str(r); print; ps = """ ( ( z1^4 z2^2 - w1 ), ( z1^5 z2^3 - w2 ), ( z1 - w3 ), ( z2 - w4 ) ) """; f = Ideal( r, ps ); print "Ideal: " + str(f); print; rg = f.GB(); print "seq Output:", rg; print; pf = """ ( ( z1^37 z2^20 ) ) """; fp = Ideal( r, pf ); print "Ideal: " + str(fp); print; nf = fp.NF(rg); print "NFs: " + str(nf); print; #rg = f.parGB(2); #print "par Output:", rg; #print; #f.distClient(); # starts in background #rg = f.distGB(2); #print "dist Output:", rg; #print; #sys.exit();
Python
# # jython examples for jas. # $Id$ # from jas import SolvableModule from jas import SolvableSubModule # Quantum plane example rsan = """ AN[ (i) (i^2 + 1) ] (Y,X,x,y) G RelationTable ( ( y ), ( x ), ( {i} x y ) ( X ), ( Y ), ( {i} Y X ) ) """; rsc = """ C(Y,X,x,y) G RelationTable ( ( y ), ( x ), ( 0i1 x y ) ( X ), ( Y ), ( 0i1 Y X ) ) """; r = SolvableModule( rsc ); #r = SolvableModule( rsan ); print "SolvableModule: " + str(r); print; ps = """ ( ( ( x + 1 ), ( y ) ), ( ( x y ), ( 0 ) ), ( ( x - X ), ( x - X ) ), ( ( y - Y ), ( y - Y ) ) ) """; # ( ( y^2 x ) ), # ( ( y^3 x^2 ) ) # ( ( x + 1 ) ), # ( ( x + 1 ), ( y ) ), # ( ( x y ), ( 0 ) ) f = SolvableSubModule( r, ps ); print "SolvableSubModule: " + str(f); print; #flg = f.leftGB(); #print "seq left GB Output:", flg; #print; ftg = f.twosidedGB(); print "seq twosided GB Output:", ftg; print; from edu.jas.gbmod import SolvableSyzygyAbstract; from edu.jas.gbmod import ModSolvableGroebnerBase; s = SolvableSyzygyAbstract().leftZeroRelations( ftg.mset ); #sl = ModuleList(f.pset.vars,f.pset.tord,s,f.pset.table); print "leftSyzygy:", s; print; if SolvableSyzygyAbstract().isLeftZeroRelation(s,ftg.mset): print "is Syzygy"; else: print "is not Syzygy";
Python
# # jython examples for jas. # $Id$ # import sys; from jas import Ring from jas import Ideal from jas import startLog # example from rose (modified) # optimal is # Rat(A46, U3, U4) # r = Ring( "Rat(U3,U4,A46) G" ); print "Ring: " + str(r); print; ps = """ ( ( U4^4 - 20/7 A46^2 ), ( A46^2 U3^4 + 7/10 A46 U3^4 + 7/48 U3^4 - 50/27 A46^2 - 35/27 A46 - 49/216 ), ( A46^5 U4^3 + 7/5 A46^4 U4^3 + 609/1000 A46^3 U4^3 + 49/1250 A46^2 U4^3 - 27391/800000 A46 U4^3 - 1029/160000 U4^3 + 3/7 A46^5 U3 U4^2 + 3/5 A46^6 U3 U4^2 + 63/200 A46^3 U3 U4^2 + 147/2000 A46^2 U3 U4^2 + 4137/800000 A46 U3 U4^2 - 7/20 A46^4 U3^2 U4 - 77/125 A46^3 U3^2 U4 - 23863/60000 A46^2 U3^2 U4 - 1078/9375 A46 U3^2 U4 - 24353/1920000 U3^2 U4 - 3/20 A46^4 U3^3 - 21/100 A46^3 U3^3 - 91/800 A46^2 U3^3 - 5887/200000 A46 U3^3 - 343/128000 U3^3 ) ) """; f = Ideal( r, ps ); print "Ideal: " + str(f); print; startLog(); o = f.optimize(); print "optimized Ideal: " + str(o); print; #rg = f.GB(); #print "Output:", rg; #print; org = o.GB(); print "opt Output:", org; print;
Python
# # jython examples for jas. # $Id$ # from java.lang import System from java.lang import Integer from jas import Ring, PolyRing from jas import terminate from jas import startLog from jas import QQ, DD # polynomial examples: ideal prime decomposition #r = Ring( "Rat(x) L" ); #r = Ring( "Q(x) L" ); r = PolyRing(QQ(),"x,y,z",PolyRing.lex); print "Ring: " + str(r); print; [one,x,y,z] = r.gens(); f1 = (x**2 - 5)**2; f2 = y**3 - x; f3 = z**2 - y * x; #print "f1 = ", f1; print "f2 = ", f2; print "f3 = ", f3; print; F = r.ideal( list=[f2,f3] ); print "F = ", F; print; startLog(); t = System.currentTimeMillis(); P = F.primeDecomp(); t1 = System.currentTimeMillis() - t; print "P = ", P; print; print "prime decomp time =", t1, "milliseconds"; print; print "F = ", F; print; #startLog(); terminate();
Python
# # jython examples for jas. # $Id$ # import sys; from jas import Ring, PolyRing, RF, ZZ from jas import Ideal # Raksanyi & Walter example # rational function coefficients #r = Ring( "RatFunc(a1, a2, a3, a4) (x1, x2, x3, x4) G" ); r = PolyRing( RF(PolyRing(ZZ(),"a1, a2, a3, a4",PolyRing.lex)), "x1, x2, x3, x4", PolyRing.grad ); print "Ring: " + str(r); print; ps = """ ( ( x4 - { a4 - a2 } ), ( x1 + x2 + x3 + x4 - { a1 + a3 + a4 } ), ( x1 x3 + x1 x4 + x2 x3 + x3 x4 - { a1 a4 + a1 a3 + a3 a4 } ), ( x1 x3 x4 - { a1 a3 a4 } ) ) """; f = r.ideal( ps ); print "Ideal: " + str(f); print; rg = f.GB(); rg = f.GB(); print "GB:", rg; print; from edu.jas.kern import ComputerThreads; ComputerThreads.terminate(); #sys.exit();
Python
# # jython examples for jas. # $Id$ # from jas import SolvableRing # ? example rs = """ Rat(a,b,e1,e2,e3) L RelationTable ( ( e3 ), ( e1 ), ( e1 e3 - e1 ), ( e3 ), ( e2 ), ( e2 e3 - e2 ) ) """; r = SolvableRing( rs ); print "SolvableRing: " + str(r); print; ps = """ ( ( e1 e3^3 + e2^10 - a ), ( e1^3 e2^2 + e3 ), ( e3^3 + e3^2 - b ) ) """; f = r.ideal( ps ); print "SolvIdeal: " + str(f); print; from edu.jas.gbmod import SolvableSyzygyAbstract; R = SolvableSyzygyAbstract().resolution( f.pset ); for i in range(0,R.size()): print "\n %s. resolution" % (i+1); print "\n", R[i];
Python
# # jython examples for jas. # $Id$ # from jas import Ring from jas import Ideal from edu.jas import application rs = """ # polynomial ring: Rat(x1,x2,x3,y1,y2) G|3| """; ps = """ ( ( y1 + y2 - 1 ), ( x1 - y1^2 - y1 - y2 ), ( x2 - y1 - y2^2 ), ( x3 - y1 y2 ) ) """; r = Ring( rs ); print "Ring: " + str(r); i = Ideal( r, ps ); print "Ideal: " + str(i); g = i.GB(); print "seq GB:", g; rsi = """ # polynomial ring: Rat(x1,x2,x3) G """; ri = Ring( rsi ); print "Ring: " + str(ri); y = application.Ideal(g.pset).intersect(ri.ring); len = y.list.size(); print "seq intersect y: ", y; rs = """ # polynomial ring: Rat(y1,y2,x1,x2,x3) G|2| """; ps = """ ( ( y1 + y2 - 1 ), ( x1 - y1^2 - y1 - y2 ), ( x2 - y1 - y2^2 ), ( x3 - y1 y2 ) ) """; r = Ring( rs ); print "Ring: " + str(r); i = Ideal( r, ps ); print "Ideal: " + str(i); g = i.GB(); print "seq GB:", g; rsb = """ # polynomial ring: Rat(y1,y2) G """; rb = Ring( rsb ); print "Ring: " + str(rb); y = application.Ideal(g.pset).intersect(rb.ring); len = y.list.size(); print "seq intersect y: ", y;
Python
# # jython examples for jas. # $Id$ # import sys; from jas import Ring from jas import ParamIdeal from jas import startLog from jas import terminate # 2 univariate polynomials of degree 2 example for comprehensive GB # integral/rational function coefficients #r = Ring( "RatFunc(u,v) (x,y) L" ); r = Ring( "IntFunc(a3, b3, a2, b2, a1, b1, a0, b0) (x) L" ); print "Ring: " + str(r); print; ps = """ ( ( { a3 } x^3 + { a2 } x^2 + { a1 } x + { a0 } ), ( { b3 } x^3 + { b2 } x^2 + { b1 } x + { b0 } ) ) """; f = r.paramideal( ps ); print "ParamIdeal: " + str(f); print; #sys.exit(); # long run time startLog(); gs = f.CGBsystem(); print "CGBsystem: " + str(gs); print; #sys.exit(); bg = gs.isCGBsystem(); if bg: print "isCGBsystem: true"; else: print "isCGBsystem: false"; print; #sys.exit(); gs = f.CGB(); print "CGB: " + str(gs); print; sys.exit(); bg = gs.isCGB(); if bg: print "isCGB: true"; else: print "isCGB: false"; print; terminate();
Python
# # jython examples for jas. # $Id$ # import sys from java.lang import System from jas import PolyRing, Ideal from jas import QQ, AN, RF from jas import terminate, startLog # polynomial examples: prime/primary decomposition in Q(sqrt(2))(x)(sqrt(x))[y,z] Q = PolyRing(QQ(),"w2",PolyRing.lex); print "Q = " + str(Q); [e,a] = Q.gens(); #print "e = " + str(e); print "a = " + str(a); root = a**2 - 2; print "root = " + str(root); Q2 = AN(root,field=True); print "Q2 = " + str(Q2.factory()); [one,w2] = Q2.gens(); #print "one = " + str(one); #print "w2 = " + str(w2); print; Qp = PolyRing(Q2,"x",PolyRing.lex); print "Qp = " + str(Qp); [ep,wp,ap] = Qp.gens(); #print "ep = " + str(ep); #print "wp = " + str(wp); #print "ap = " + str(ap); print; Qr = RF(Qp); print "Qr = " + str(Qr.factory()); [er,wr,ar] = Qr.gens(); #print "er = " + str(er); #print "wr = " + str(wr); #print "ar = " + str(ar); print; Qwx = PolyRing(Qr,"wx",PolyRing.lex); print "Qwx = " + str(Qwx); [ewx,wwx,ax,wx] = Qwx.gens(); #print "ewx = " + str(ewx); print "ax = " + str(ax); #print "wwx = " + str(wwx); print "wx = " + str(wx); print; rootx = wx**2 - ax; print "rootx = " + str(rootx); Q2x = AN(rootx,field=True); print "Q2x = " + str(Q2x.factory()); [ex2,w2x2,ax2,wx] = Q2x.gens(); #print "ex2 = " + str(ex2); #print "w2x2 = " + str(w2x2); #print "ax2 = " + str(ax2); #print "wx = " + str(wx); print; Yr = PolyRing(Q2x,"y,z",PolyRing.lex) print "Yr = " + str(Yr); [e,w2,x,wx,y,z] = Yr.gens(); print "e = " + str(e); print "w2 = " + str(w2); print "x = " + str(x); print "wx = " + str(wx); print "y = " + str(y); print "z = " + str(z); print; f1 = ( y**2 - x ) * ( y**2 - 2 ); #f1 = ( y**2 - x )**3 * ( y**2 - 2 )**2; f2 = ( z**2 - y**2 ); print "f1 = ", f1; print "f2 = ", f2; print; F = Yr.ideal( list=[f1,f2] ); print "F = ", F; print; #sys.exit(); startLog(); t = System.currentTimeMillis(); P = F.primeDecomp(); #P = F.primaryDecomp(); t1 = System.currentTimeMillis() - t; print "P = ", P; print; print "prime/primary decomp time =", t1, "milliseconds"; print; print "F = ", F; print; #startLog(); terminate();
Python
# # jython examples for jas. # $Id$ # ## \begin{PossoExample} ## \Name{Hawes2} ## \Parameters{a;b;c} ## \Variables{x;y[2];z[2]} ## \begin{Equations} ## x+2y_1z_1+3ay_1^2+5y_1^4+2cy_1 \& ## x+2y_2z_2+3ay_2^2+5y_2^4+2cy_2 \& ## 2 z_2+6ay_2+20 y_2^3+2c \& ## 3 z_1^2+y_1^2+b \& ## 3z_2^2+y_2^2+b \& ## \end{Equations} ## \end{PossoExample} import sys; from jas import Ring from jas import Ideal from jas import startLog from jas import terminate #startLog(); # Hawes & Gibson example 2 # integral function coefficients r = Ring( "IntFunc(a, c, b) (y2, y1, z1, z2, x) L" ); print "Ring: " + str(r); print; ps = """ ( ( x + 2 y1 z1 + { 3 a } y1^2 + 5 y1^4 + { 2 c } y1 ), ( x + 2 y2 z2 + { 3 a } y2^2 + 5 y2^4 + { 2 c } y2 ), ( 2 z2 + { 6 a } y2 + 20 y2^3 + { 2 c } ), ( 3 z1^2 + y1^2 + { b } ), ( 3 z2^2 + y2^2 + { b } ) ) """; f = r.ideal( ps ); print "Ideal: " + str(f); print; #startLog(); rgl = f.GB(); print "GB:", rgl; print; bg = rgl.isGB(); print "isGB:", bg; print; terminate(); #sys.exit();
Python
# # jython examples for jas. # $Id$ # #import sys; #from jas import startLog, terminate from edu.jas.arith import PrimeList # example for prime numbers # pl = PrimeList(PrimeList.Range.small); print "pl: " + str(pl); print; pp = ""; for i in range(0,pl.size()+10): pp = pp + " " + str(pl.get(i)) print "pp: " + pp; print; pl = PrimeList(PrimeList.Range.low); print "pl: " + str(pl); print; pp = ""; for i in range(0,pl.size()+10): pp = pp + " " + str(pl.get(i)) print "pp: " + pp; print; pl = PrimeList(PrimeList.Range.medium); print "pl: " + str(pl); print; pp = ""; for i in range(0,pl.size()+10): pp = pp + " " + str(pl.get(i)) print "pp: " + pp; print; pl = PrimeList(PrimeList.Range.large); print "pl: " + str(pl); print; pp = ""; for i in range(0,pl.size()+10): pp = pp + " " + str(pl.get(i)) print "pp: " + pp; print; #pl = PrimeList(PrimeList.Range.mersenne); #print "pl: " + str(pl); #print;
Python
# # jython examples for jas. # $Id$ # import sys; from jas import Ring from jas import Ideal from jas import startLog from jas import terminate # example from rose (modified) #r = Ring( "Mod 19 (U3,U4,A46) L" ); #r = Ring( "Mod 1152921504606846883 (U3,U4,A46) L" ); # 2^60-93 #r = Ring( "Quat(U3,U4,A46) L" ); #r = Ring( "Z(U3,U4,A46) L" ); #r = Ring( "C(U3,U4,A46) L" ); r = Ring( "Rat(A46,U3,U4) L" ); print "Ring: " + str(r); print; ps = """ ( %s ( U4^4 - 20/7 A46^2 ), ( A46^2 U3^4 + 7/10 A46 U3^4 + 7/48 U3^4 - 50/27 A46^2 - 35/27 A46 - 49/216 ), ( A46^5 U4^3 + 7/5 A46^4 U4^3 + 609/1000 A46^3 U4^3 + 49/1250 A46^2 U4^3 - 27391/800000 A46 U4^3 - 1029/160000 U4^3 + 3/7 A46^5 U3 U4^2 + 3/5 A46^6 U3 U4^2 + 63/200 A46^3 U3 U4^2 + 147/2000 A46^2 U3 U4^2 + 4137/800000 A46 U3 U4^2 - 7/20 A46^4 U3^2 U4 - 77/125 A46^3 U3^2 U4 - 23863/60000 A46^2 U3^2 U4 - 1078/9375 A46 U3^2 U4 - 24353/1920000 U3^2 U4 - 3/20 A46^4 U3^3 - 21/100 A46^3 U3^3 - 91/800 A46^2 U3^3 - 5887/200000 A46 U3^3 - 343/128000 U3^3 ) ) """; pp1 = """ ( 20 A46 + 7 ), """; pp2 = """ ( 5480334637123239936000000000000000000 A46^32 + 23330567455181792870400000000000000000 A46^31 - 22260410953422455439360000000000000000 A46^30 - 379039147753503876710400000000000000000 A46^29 - 1305289515920841108357120000000000000000 A46^28 - 2661894008686715272062566400000000000000 A46^27 - 3732109213267597335472373760000000000000 A46^26 - 3719328899522099347074318336000000000000 A46^25 - 2513175000419852400394764288000000000000 A46^24 - 801907472074794268996141056000000000000 A46^23 + 559468735767998648283977220096000000000 A46^22 + 1161692745234469227508358814105600000000 A46^21 + 1115120737963786660933876454522880000000 A46^20 + 754183677763034219243933188227072000000 A46^19 + 366205139138005719200006792439398400000 A46^18 + 95407136698255889087520898673541120000 A46^17 - 35897763757636362165902256717692928000 A46^16 - 68696958358719191677546842722559590400 A46^15 - 55382563098545072682320366954843996160 A46^14 - 32223104574376823941781148035505979392 A46^13 - 14867126462105106300205537184606126080 A46^12 - 5596017809975575801376014016653721600 A46^11 - 1730893404306213749794640488178116608 A46^10 - 438698743729822786570094575456788480 A46^9 - 90199241991532353478039712103521280 A46^8 - 14778859703096558479650421488297984 A46^7 - 1874056025467134008603806670325120 A46^6 - 174876413639867324175892636604160 A46^5 - 10843113615171040141214782270464 A46^4 - 325577720150105105056746125600 A46^3 + 6040454553390756509792153750 A46^2 + 761038687880048862537750000 A46 + 13745464623924567359765625 ), """; pp = ps % pp1; f = Ideal( r, pp ); print "Ideal: " + str(f); print; startLog(); rg = f.GB(); print "seq Output:", rg; print; #sys.exit();
Python
# # jython examples for jas. # $Id$ # import sys from java.lang import System from java.lang import Integer from jas import Ring from jas import PolyRing from jas import Ideal from jas import ZM, QQ, AN, RF from jas import terminate from jas import startLog # polynomial examples: factorization over Z_p(x)(sqrt3(x))[y] Q = PolyRing(ZM(5),"x",PolyRing.lex); print "Q = " + str(Q); [e,a] = Q.gens(); #print "e = " + str(e); print "a = " + str(a); Qr = RF(Q); print "Qr = " + str(Qr.factory()); [er,ar] = Qr.gens(); #print "er = " + str(er); #print "ar = " + str(ar); print; Qwx = PolyRing(Qr,"wx",PolyRing.lex); print "Qwx = " + str(Qwx); [ewx,ax,wx] = Qwx.gens(); #print "ewx = " + str(ewx); print "ax = " + str(ax); print "wx = " + str(wx); print; #rootx = wx**5 - 2; # not working #rootx = wx**5 - 1/ax; #rootx = wx**5 - ax; #rootx = wx**5 - ( ax**2 + 3 * ax ); rootx = wx**5 - ( ax**2 + 3 / ax ); print "rootx = " + str(rootx); Q2x = AN(rootx,field=True); print "Q2x = " + str(Q2x.factory()); [ex2,ax2,wx] = Q2x.gens(); #print "ex2 = " + str(ex2); #print "w2x2 = " + str(w2x2); #print "ax2 = " + str(ax2); #print "wx = " + str(wx); print; #Yr = PolyRing(Q2x,"y,z,c0,c1,c2",PolyRing.lex) Yr = PolyRing(Q2x,"y,z",PolyRing.lex) print "Yr = " + str(Yr); #[e,x,wx,y,z,c0,c1,c2] = Yr.gens(); [e,x,wx,y,z] = Yr.gens(); print "e = " + str(e); print "x = " + str(x); print "wx = " + str(wx); print "y = " + str(y); print "z = " + str(z); print; #f = ( y**2 - x ); f = ( y**2 - ( wx ) ); #f = ( y**2 - ( 1 / wx ) ); #f = ( y**2 - ( wx**2 + wx + 2 ) + z**2 + y * wx ); #f = wx**3; print "f = ", f; print; f = f**5; print "f = ", f; print; #g = ( y**2 + ( c0 + c1 * wx + c2 * wx**2 ) ); #print "g = ", g; #g = g**5; #print "g = ", g; #print; #sys.exit(); startLog(); t = System.currentTimeMillis(); #ok: G = Yr.factors(f); G = Yr.squarefreeFactors(f); t = System.currentTimeMillis() - t; print "#G = ", len(G); #print "factor time =", t, "milliseconds"; #sys.exit(); print "f = ", f; g = e; for h, i in G.iteritems(): if i > 1: print "h**i = ", h, "**" + str(i); else: print "h = ", h; h = h**i; g = g*h; print "g = ", g; if cmp(f,g) == 0: print "factor time =", t, "milliseconds,", "isFactors(f,g): true" ; else: print "factor time =", t, "milliseconds,", "isFactors(f,g): ", cmp(f,g); print; #startLog(); terminate();
Python
# # jython examples for jas. # $Id$ # import sys from java.lang import System from java.lang import Integer from jas import Ring from jas import PolyRing from jas import Ideal from jas import QQ, AN, RF, EF from jas import terminate from jas import startLog # polynomial examples: factorization over Q(sqrt(2))(x)(sqrt(x))[y] Yr = EF(QQ()).extend("w2","w2^2 - 2").extend("x").extend("wx","wx^2 - x").polynomial("y").build(); #print "Yr = " + str(Yr); #print [one,w2,x,wx,y] = Yr.gens(); print "one = " + str(one); print "w2 = " + str(w2); print "x = " + str(x); print "wx = " + str(wx); print "y = " + str(y); print; f = ( y**2 - x ) * ( y**2 - 2 ); #f = ( y**2 - x )**2 * ( y**2 - 2 )**3; #f = ( y**4 - x * 2 ); #f = ( y**7 - x * 2 ); #f = ( y**2 - 2 ); #f = ( y**2 - x ); #f = ( w2 * y**2 - 1 ); #f = ( y**2 - 1/x ); #f = ( y**2 - (1,2) ); #f = ( y**2 - 1/x ) * ( y**2 - (1,2) ); print "f = ", f; print; #sys.exit(); startLog(); t = System.currentTimeMillis(); G = Yr.factors(f); t = System.currentTimeMillis() - t; #print "G = ", G; #print "factor time =", t, "milliseconds"; #sys.exit(); print "f = ", f; g = one; for h, i in G.iteritems(): if i > 1: print "h**i = ", h, "**" + str(i); else: print "h = ", h; h = h**i; g = g*h; #print "g = ", g; if cmp(f,g) == 0: print "factor time =", t, "milliseconds,", "isFactors(f,g): true" ; else: print "factor time =", t, "milliseconds,", "isFactors(f,g): ", cmp(f,g); print; #startLog(); terminate();
Python
# # jython examples for jas. # $Id$ # import sys; from java.lang import System from java.lang import Integer from jas import Ring, PolyRing from jas import terminate from jas import startLog from jas import QQ, DD # polynomial examples: complex roots over Q r = PolyRing(QQ(),"I,x,y,z",PolyRing.lex); print "Ring: " + str(r); print; [one,I,x,y,z] = r.gens(); f1 = z - x - y * I; f2 = I**2 + 1; #f3 = z**3 - 2; f3 = z**3 - 2*I; print "f1 = ", f1; print "f2 = ", f2; print "f3 = ", f3; print; F = r.ideal( list=[f1,f2,f3] ); print "F = ", F; print; startLog(); G = F.GB(); print "G = ", G; print; #terminate(); #sys.exit(); r = PolyRing(QQ(),"x,y",PolyRing.lex); print "Ring: " + str(r); print; [one,x,y] = r.gens(); # y**3 - 3 * I * x * y**2 - 3 * x**2 * y + I * x**3 - 2 * I = z**3 - 2 #fr = y**3 - 3 * x**2 * y; #fi = -3 * x * y**2 + x**3 - 2; # y**3 - 3 * I * x * y**2 - 3 * x**2 * y + I * x**3 + 2 = z**3 - 2 I fr = y**3 - 3 * x**2 * y - 2; fi = -3 * x * y**2 + x**3; print "fr = ", fr; print "fi = ", fi; print; F = r.ideal( list=[fr,fi] ); print "F = ", F; print; G = F.GB(); print "G = ", G; print; t = System.currentTimeMillis(); R = G.complexRoots(); t = System.currentTimeMillis() - t; print "R = ", R; print; print "complex roots: "; G.complexRootsPrint() print; print "complex roots time =", t, "milliseconds"; print; print "G = ", G; print; #startLog(); terminate();
Python
# # jython examples for jas. # $Id$ # #import sys; from jas import Ring from jas import Ideal from jas import startLog # mark, d-gb diplom example r = Ring( "Z(x,y,z) L" ); print "Ring: " + str(r); print; ps = """ ( ( z + x y**2 + 4 x**2 + 1 ), ( y**2 z + 2 x + 1 ), ( x**2 z + y**2 + x ) ) """; f = r.ideal( ps ); print "Ideal: " + str(f); print; #startLog(); eg = f.eGB(); print "seq e-GB:", eg; print "is e-GB:", eg.isGB(); print; dg = f.dGB(); print "seq d-GB:", dg; print "is d-GB:", dg.isGB(); print; print "d-GB == e-GB:", eg.list.equals(dg.list); print "d-GB == e-GB:", eg == dg;
Python
# # jython examples for jas. # $Id$ # import sys; from java.lang import System from java.lang import Integer from jas import Ring from jas import PolyRing from jas import Ideal from jas import QQ, AN from jas import terminate from jas import startLog # polynomial examples: factorization over Q(i) Qr = PolyRing(QQ(),"i",PolyRing.lex); print "Qr = " + str(Qr); [e,a] = Qr.gens(); print "e = " + str(e); print "a = " + str(a); imag = a**2 + 1; print "imag = " + str(imag); Qi = AN(imag,field=True); print "Qi = " + str(Qi.factory()); [one,i] = Qi.gens(); print "one = " + str(one); print "i = " + str(i); b = i**2 + 1; print "b = " + str(b); c = 1 / i; print "c = " + str(c); #Qix = AN(i**2 + 1); #print "Qix = " + str(Qix.factory()); print; r = PolyRing(Qi,"x",PolyRing.lex) print "r = " + str(r); [one,i,x] = r.gens(); print "one = " + str(one); print "i = " + str(i); print "x = " + str(x); #f = x**7 - 1; f = x**6 + x**5 + x**4 + x**3 + x**2 + x + 1; print "f = ", f; print; startLog(); t = System.currentTimeMillis(); G = r.factors(f); t = System.currentTimeMillis() - t; print "#G = ", str(len(G)); #print "factor time =", t, "milliseconds"; ## f2 = one; ## for h, i in G.iteritems(): ## print "h**i = (", h, ")**" + str(i); ## h = h**i; ## f2 = f2*h; #print "f2 = ", f2; print; ## if cmp(f,f2) == 0: ## print "factor time =", t, "milliseconds,", "isFactors(f,g): true" ; ## else: ## print "factor time =", t, "milliseconds,", "isFactors(f,g): ", cmp(f,f2); ## print; r2 = PolyRing(Qi,"a,b",PolyRing.lex) print "r2 = " + str(r2); [one,i,a,b] = r2.gens(); print "one = " + str(one); print "i = " + str(i); print "a = " + str(a); print "b = " + str(b); y = a + i * b; #g = y**7 - 1; g = y**6 + y**5 + y**4 + y**3 + y**2 + y + 1; g = - g; print "g = ", g; print; #sys.exit(); #startLog(); t = System.currentTimeMillis(); G = r2.factors(g); t = System.currentTimeMillis() - t; print "#G = ", str(len(G)); #print "factor time =", t, "milliseconds"; ## g2 = one; ## for h, i in G.iteritems(): ## print "h**i = (", h, ")**" + str(i); ## h = h**i; ## g2 = g2*h; #print "g2 = ", g2; print; ## if cmp(g,g2) == 0: ## print "factor time =", t, "milliseconds,", "isFactors(f,g): true" ; ## else: ## print "factor time =", t, "milliseconds,", "isFactors(f,g): ", cmp(g,g2); ## print; #sys.exit(); #startLog(); terminate();
Python
# # jython examples for jas. # $Id$ # import sys; from jas import Ring from jas import Ideal from jas import startLog from jas import terminate # Nabashima, ISSAC 2007, example F6 # integral function coefficients r = Ring( "IntFunc(a, b,c, d) (x) G" ); print "Ring: " + str(r); print; ps = """ ( ( x^4 + { a } x^3 + { b } x^2 + { c } x + { d } ), ( 4 x^3 + { 3 a } x^2 + { 2 b } x + { c } ) ) """; #startLog(); f = r.paramideal( ps ); print "ParamIdeal: " + str(f); print; gs = f.CGBsystem(); gs = f.CGBsystem(); gs = f.CGBsystem(); gs = f.CGBsystem(); print "CGBsystem: " + str(gs); print; bg = gs.isCGBsystem(); if bg: print "isCGBsystem: true"; else: print "isCGBsystem: false"; print; #sys.exit(); gs = f.CGB(); print "CGB: " + str(gs); print; bg = gs.isCGB(); if bg: print "isCGB: true"; else: print "isCGB: false"; print; terminate(); #------------------------------------------ #sys.exit();
Python
# # jython examples for jas. # $Id$ # import sys; from jas import Ring from jas import Ideal from jas import startLog from jas import terminate #import rational; # trinks 6/7 example #r = Ring( "Mod 19 (B,S,T,Z,P,W) L" ); #r = Ring( "Mod 1152921504606846883 (B,S,T,Z,P,W) L" ); # 2^60-93 #r = Ring( "Quat(B,S,T,Z,P,W) L" ); #r = Ring( "Z(B,S,T,Z,P,W) L" ); #r = Ring( "C(B,S,T,Z,P,W) L" ); #r = Ring( "Z(B,S,T,Z,P,W) L" ); #r = Ring( "IntFunc(e,f)(B,S,T,Z,P,W) L" ); r = Ring( "Z(B,S,T,Z,P,W) L" ); #r = Ring( "Q(B,S,T,Z,P,W) L" ); print "Ring: " + str(r); print; # sage like: with generators for the polynomial ring print "r.gens() = ", [ str(f) for f in r.gens() ]; print; #[one,e,f,B,S,T,Z,P,W] = r.gens(); [one,B,S,T,Z,P,W] = r.gens(); f1 = 45 * P + 35 * S - 165 * B - 36; f2 = 35 * P + 40 * Z + 25 * T - 27 * S; f3 = 15 * W + 25 * S * P + 30 * Z - 18 * T - 165 * B**2; f4 = - 9 * W + 15 * T * P + 20 * S * Z; f5 = P * W + 2 * T * Z - 11 * B**3; f6 = 99 * W - 11 *B * S + 3 * B**2; f7 = 10000 * B**2 + 6600 * B + 2673; #all ok: #f7 = f7 + e * f6**0; #f7 = f7 + 5959345574908321469098512640906154241024000000**2 * f6; #f7 = f7 + 35555./332 * f1; F = [ f1, f2, f3, f4, f5, f6, f7 ]; #F = [ f1, f2, f3, f4, f5, f6 ]; #print "F = ", [ str(f) for f in F ]; I = r.ideal( "", list=F ); print "Ideal: " + str(I); print; #sys.exit(); rg = I.GB(); print "seq Output:", rg; print; terminate(); sys.exit(); ps = """ ( ( 45 P + 35 S - 165 B - 36 ), ( 35 P + 40 Z + 25 T - 27 S ), ( 15 W + 25 S P + 30 Z - 18 T - 165 B**2 ), ( - 9 W + 15 T P + 20 S Z ), ( P W + 2 T Z - 11 B**3 ), ( 99 W - 11 B S + 3 B**2 ), ( 10000 B**2 + 6600 B + 2673 ) ) """; # ( 10000 B**2 + 6600 B + 2673 ) # ( B**2 + 33/50 B + 2673/10000 ) #f = Ideal( r, ps ); #print "Ideal: " + str(f); #print; f = r.ideal( ps ); print "Ideal: " + str(f); print; #startLog(); rg = f.GB(); #print "seq Output:", rg; #print; terminate(); #sys.exit();
Python
# # jython examples for jas. # $Id$ # from jas import Ring from jas import Ideal # trinks 7 example r = Ring( "Rat(B,S,T,Z,P,W) L" ); print "Ring: " + str(r); print; ps = """ ( ( 45 P + 35 S - 165 B - 36 ), ( 35 P + 40 Z + 25 T - 27 S ), ( 15 W + 25 S P + 30 Z - 18 T - 165 B**2 ), ( - 9 W + 15 T P + 20 S Z ), ( P W + 2 T Z - 11 B**3 ), ( 99 W - 11 B S + 3 B**2 ), ( B**2 + 33/50 B + 2673/10000 ) ) """; f = Ideal( r, ps ); print "Ideal: " + str(f); print; #Katsura equations for N = 3: #r = Ring( "Rat(u0,u1,u2,u3) L" ); #print "Ring: " + str(r); #print; ps = """ ( u3*u3 + u2*u2 + u1*u1 + u0*u0 + u1*u1 + u2*u2 + u3*u3 - u0, u3*0 + u2*u3 + u1*u2 + u0*u1 + u1*u0 + u2*u1 + u3*u2 - u1, u3*0 + u2*0 + u1*u3 + u0*u2 + u1*u1 + u2*u0 + u3*u1 - u2, u3 + u2 + u1 + u0 + u1 + u2 + u3 - 1 ) """; #f = Ideal( r, ps ); #print "Ideal: " + str(f); #print; rg = f.GB(); print "seq Output:", rg; print; from edu.jas.gbmod import SyzygyAbstract; from edu.jas.gbmod import ModGroebnerBaseAbstract; from edu.jas.poly import ModuleList; s = SyzygyAbstract().zeroRelations( rg.list ); sl = ModuleList(rg.pset.ring,s); print "syzygy:", sl; print; z = SyzygyAbstract().isZeroRelation( s, rg.list ); print "is Syzygy ?", if z: print "true" else: print "false" print; zg = sl; for i in range(1,len(r.ring.vars)+1): print "\n %s. resolution" % i; sl = zg; mg = ModGroebnerBaseAbstract().GB(sl); print "Mod GB: ", mg; print; zg = SyzygyAbstract().zeroRelations(mg); print "syzygies of Mod GB: ", zg; print; if ModGroebnerBaseAbstract().isGB( mg ): print "is GB"; else: print "is not GB"; if SyzygyAbstract().isZeroRelation(zg,mg): print "is Syzygy"; else: print "is not Syzygy"; if not zg: break;
Python
# # jython examples for jas. # $Id$ # import sys; from jas import Ring from jas import ParamIdeal from jas import startLog from jas import terminate # Raksanyi & Walter example # integral/rational function coefficients #r = Ring( "RatFunc(a1, a2, a3, a4) (x1, x2, x3, x4) L" ); r = Ring( "IntFunc(a1, a2, a3, a4) (x1, x2, x3, x4) L" ); print "Ring: " + str(r); print; ps = """ ( ( x4 - { a4 - a2 } ), ( x1 + x2 + x3 + x4 - { a1 + a3 + a4 } ), ( x1 x3 + x1 x4 + x2 x3 + x3 x4 - { a1 a4 + a1 a3 + a3 a4 } ), ( x1 x3 x4 - { a1 a3 a4 } ) ) """; f = r.paramideal( ps ); print "ParamIdeal: " + str(f); print; #sys.exit(); #startLog(); gs = f.CGBsystem(); print "CGBsystem: " + str(gs); print; #sys.exit(); bg = gs.isCGBsystem(); if bg: print "isCGBsystem: true"; else: print "isCGBsystem: false"; print; rs = gs.regularRepresentation(); print "regular representation: " + str(rs); print; rs = gs.regularRepresentationBC(); print "boolean closed regular representation: " + str(rs); print; startLog(); bg = rs.isRegularGB(); if bg: print "pre isRegularGB: true"; else: print "pre isRegularGB: false"; print; rsg = rs.regularGB(); print "regular GB: " + str(rsg); print; bg = rsg.isRegularGB(); if bg: print "post isRegularGB: true"; else: print "post isRegularGB: false"; print; ss = rsg.stringSlice(); print "regular string slice: " + str(ss); terminate(); #sys.exit();
Python
# # jython examples for jas. from jas import Module from jas import SubModule # Armbruster module example r = Module( "Rat(u,v,l) L" ); print "Module: " + str(r); print; ps = """ ( ( ( 1 ), ( 2 ), ( 0 ), ( l^2 ) ), ( ( 0 ), ( l + 3 v ), ( 0 ), ( u ) ), ( ( 1 ), ( 0 ), ( 0 ), ( l^2 ) ), ( ( l + v ), ( 0 ), ( 0 ), ( u ) ), ( ( l^2 ), ( 0 ), ( 0 ), ( v ) ), ( ( u ), ( 0 ), ( 0 ), ( v l + v^2 ) ), ( ( 1 ), ( 0 ), ( l + 3 v ), ( 0 ) ), ( ( l^2 ), ( 0 ), ( 2 u ), ( v ) ), ( ( 0 ), ( 1 ), ( l + v ), ( 0 ) ), ( ( 0 ), ( l^2 ), ( u ), ( 0 ) ), ( ( 0 ), ( v ), ( u l^2 ), ( 0 ) ), ( ( 0 ), ( v l + v^2 ), ( u^2 ), ( 0 ) ) ) """; f = SubModule( r, ps ); print "SubModule: " + str(f); print; rg = f.GB(); print "seq Output:", rg; print; print "isGB:", rg.isGB();
Python
# # jython examples for jas. # $Id$ # #import sys; from jas import Ring from jas import Ideal from jas import startLog # mark, d-gb diplom example, due to kandri-rody 1984 # # The MAS DIIPEGB implementation contains an error because the output e-GB # is not correct. Also the cited result from k-r contains this error. # The polynomial # # ( 2 x * y^2 - x^13 + 2 x^11 - x^9 + 2 x^7 - 2 x^3 ), # # is in the DIIPEGB output, but it must be # # ( 2 x * y^2 - x^13 + 2 x^11 - 3 x^9 + 2 x^7 - 2 x^3 ), # # Test by adding the polynomials to the input. # Frist polynomial produces a different e-GB. # Second polynomial reproduces the e-GB with the second polynomial. r = Ring( "Z(x,y) L" ); print "Ring: " + str(r); print; ps = """ ( ( y**6 + x**4 y**4 - x**2 y**4 - y**4 - x**4 y**2 + 2 x**2 y**2 + x**6 - x**4 ), ( 2 x**3 y**4 - x y**4 - 2 x**3 y**2 + 2 x y**2 + 3 x**5 - 2 x** 3 ), ( 3 y**5 + 2 x**4 y**3 - 2 x**2 y**3 - 2 y**3 - x**4 y + 2 x**2 y ) ) """; f = r.ideal( ps ); print "Ideal: " + str(f); print; #startLog(); eg = f.eGB(); print "seq e-GB:", eg; print "is e-GB:", eg.isGB(); print; #startLog(); dg = f.dGB(); print "seq d-GB:", dg; print "is d-GB:", dg.isGB(); print; print "d-GB == e-GB:", eg.list.equals(dg.list); print "d-GB == e-GB:", eg == dg;
Python
# # jython examples for jas. # $Id$ # ## \begin{PossoExample} ## \Name{Hawes2} ## \Parameters{a;b;c} ## \Variables{x;y[2];z[2]} ## \begin{Equations} ## x+2y_1z_1+3ay_1^2+5y_1^4+2cy_1 \& ## x+2y_2z_2+3ay_2^2+5y_2^4+2cy_2 \& ## 2 z_2+6ay_2+20 y_2^3+2c \& ## 3 z_1^2+y_1^2+b \& ## 3z_2^2+y_2^2+b \& ## \end{Equations} ## \end{PossoExample} import sys; from jas import Ring from jas import Ideal from jas import startLog from jas import terminate #startLog(); # Hawes & Gibson example 2 # rational function coefficients #r = Ring( "IntFunc(a, c, b) (y2, y1, z1, z2, x) L" ); r = Ring( "IntFunc(b, c, a) (y2, y1, z2, z1, x) G" ); print "Ring: " + str(r); print; ps = """ ( ( x + 2 y1 z1 + { 3 a } y1^2 + 5 y1^4 + { 2 c } y1 ), ( x + 2 y2 z2 + { 3 a } y2^2 + 5 y2^4 + { 2 c } y2 ), ( 2 z2 + { 6 a } y2 + 20 y2^3 + { 2 c } ), ( 3 z1^2 + y1^2 + { b } ), ( 3 z2^2 + y2^2 + { b } ) ) """; startLog(); f = r.paramideal( ps ); print "ParamIdeal: " + str(f); print; gs = f.CGBsystem(); print "CGBsystem: " + str(gs); print; bg = gs.isCGBsystem(); if bg: print "isCGBsystem: true"; else: print "isCGBsystem: false"; print; sys.exit(); gs = f.CGBsystem(); gs = f.CGBsystem(); gs = f.CGBsystem(); print "CGBsystem: " + str(gs); print; gs = f.CGB(); print "CGB: " + str(gs); print; bg = gs.isCGB(); if bg: print "isCGB: true"; else: print "isCGB: false"; print; terminate(); #------------------------------------------ #sys.exit();
Python
# implementation of the Staggered Linear Basis Algorithm of Gebauer and M\"oller # "Buchberger's algorithm and Staggered Linear Bases" # in Proceedings of SYMSAC 1986 (Waterloo/Ontario), pages 218--221 # ACM Press, 1986 # Originally from http://www.math.usm.edu/perry/Research/staggered_linear_basis.py # small changes for JAS compatibility, changes are labled with JAS # $Id$ # usage: staglinbasis(F) where F is a list of polynomials # result: groebner basis of F # example: # sage: R = PolynomialRing(GF(32003),x,5) # sage: I = sage.rings.ideal.Cyclic(R,5).homogenize() # sage: F = list(I.gens()) # sage: B = staglinbasis(F) # >> reduction to zero: (9, 12, x1*x2*x3^3*x4^2) x2 # >> reduction to zero: (7, 12, x1*x2*x3^3*x4^2) x2 # >> reduction to zero: (5, 12, x1^2*x3^3*x4^2) x1 # ... [more omitted] # >> 32 reductions to zero # sage: len(B) # >> 42 # minimal_pair # used to select a minimal critical pair from a list; # form of the list is (i,j,t) where t=lcm(lt(g[i]),lt(g[j])); # chosen by smallest lcm # inputs: list of pairs P # outputs: minimal pair in P def minimal_pair(P): result = P.pop() P.add(result) for p in P: if p[2] < result[2]: result = p return result # spol # compute the s-polynomial corresponding to the critical pair p # inputs: critical pair p, basis G # outputs: s-polynomial def spol(p,G): i,j,tij = p R = G[i].parent() # JAS ti = R.monomial_quotient(tij,G[i].lm()) tj = R.monomial_quotient(tij,G[j].lm()) return ti*G[i] - tj*G[j] # monid_quotient # computes the quotient I:J of the monomial ideals I and J # for each tI in I, and for each tJ in J, it computes lcm(tI,tJ)/tJ # this corresponds to computing the u's such that uv is in I for each v in J # note that the ideals must be simplified for this to work correctly # (see below) # inputs: lists of monomials I and J (generators of ideals) # outputs: list of monomials that generate I:J def monid_quotient(I,J,R): # JAS result = set() for tI in I: # R = tI.parent() #JAS for tJ in J: u = R.monomial_quotient(tI.lcm(tJ),tJ).lm() # JAS if not any(R.monomial_divides(t,u) for t in result): result.add(u) return result # monid_add # expands the monomial ideal I by the monomial t # simplifies the result # inputs: list of monomials I (generators of ideal), monomial t # outputs: simplified I+(t) def monid_add(I,t): result = set() R = t.parent() for u in I: if not(R.monomial_divides(t,u)) and not(R.monomial_divides(u,t)): result.add(u) if not any(R.monomial_divides(u,t) for u in result): result.add(t) return result # simplify_monid # simplifies the list of generators of the monomial ideal I # by pruning redundant elements # inputs: list of monomials I (generators of ideal) # outputs: simplified I def simplify_monid(I,R): # JAS result = set() for t in I: #R = t.parent() #JAS if not any(u != t and R.monomial_divides(u,t) for u in I): result.add(t) return result # staglinbasis # computes the Groebner Basis of a polynomial ideal using the # Staggered Linear Basis algorithm of Gebauer-Moeller # inputs: list of polynomials F # outputs: Groebner basis of F def staglinbasis(F): # tracks the number of zero reductions num_zrs = 0 # get polynomial ring R = F[0].parent() G = list(F) # JAS m = len(G) # Z is the set of monomial used to detect principal syzygies # in general, Z should be simplified anytime you modify it Z = [set([G[j].lm() for j in xrange(i)]) for i in xrange(m)] Z = [simplify_monid(ZI,R) for ZI in Z] # JAS # initial set of critical pairs P = set() for i in xrange(m-1): for j in xrange(i+1,m): tij = G[i].lm().lcm(G[j].lm()) tj = R.monomial_quotient(tij,G[j].lm()) # JAS if not any(R.monomial_divides(t,tj) for t in Z[j]): P.add((i,j,tij)) # main loop while len(P) != 0: # choose the pair w/smallest lcm p = minimal_pair(P) P.remove(p) # compute S-polynomial, reduce it s = spol(p,G) i,j,tij = p r = s.reduce(G) if r == 0: print "reduction to zero:", p, R.monomial_quotient(tij,G[j].lm()) num_zrs += 1 else: # new polynomial; add to basis r *= r.lc()**(-1) G.append(r) # update ideals here, also below # need new ideal for G[-1]=r, essentially # Znew = (Z[j] + t[i])):(lcm(t[i],t[j])/t[j]) + (t[1], ..., t[m]) # where t[i] = lm(g[i]) Znew = Z[j].copy() # JAS Znew.update([G[i].lm()]) Znew = simplify_monid(Znew,R) #JAS tj = R.monomial_quotient(tij,G[j].lm()).lm() # JAS Znew = monid_quotient(Znew,[tj],R) # JAS Znew.update([g.lm() for g in G[:-1]]) Znew = simplify_monid(Znew,R) Z.append(Znew) # compute new critical pairs w/new polynomial m = len(G) - 1 for i in xrange(m): tim = G[i].lm().lcm(G[m].lm()) tm = R.monomial_quotient(tim,G[m].lm()) # don't add pairs detected by Z[m] if not any(R.monomial_divides(t,tm) for t in Z[m]): P.add((i,m,tim)) # update Z[j] Z[j].add(R.monomial_quotient(tij,G[j].lm()).lm()) # JAS Z[j] = simplify_monid(Z[j],R) # JAS # prune pairs detected by new Z[j] Q = set() for (i,j,tij) in P: tj = R.monomial_quotient(tij,G[j].lm()) if any(R.monomial_divides(t,tj) for t in Z[j]): Q.add((i,j,tij)) P.difference_update(Q) print num_zrs, "reductions to zero" return G
Python
# # read output of jas runnings and prepare input for gnuplot # import re; import os; exam = "kat_6"; runs = "t16"; #bname = exam + "_" + runs; bname = "k6seqpair-2" fname = bname + ".out"; oname = bname + ".po"; f=open(fname,"r"); print f; o=open(oname,"w"); print o; res = {}; resold = {}; for line in f: if line.find("executed in") > 0: print line, if line.find("sequential") >= 0: s = re.search(".*in (\d+)",line); if s != None: t = ('0', s.group(1)); res[ int( t[0] ) ] = float( t[1] ); else: if line.find("-old") >= 0: s = re.search("(\d+).*in (\d+)",line); if s != None: t = s.groups(); t0 = int( t[0] ); if resold.has_key( t0 ): resold[ t0 ] = ( resold[ t0 ] + float(t[1]) )/2.0; else: resold[ t0 ] = float( t[1] ); else: s = re.search("(\d+).*in (\d+)",line); if s != None: t = s.groups(); t0 = int( t[0] ); if res.has_key( t0 ): res[ t0 ] = ( res[ t0 ] + float(t[1]) )/2.0; else: res[ t0 ] = float( t[1] ); # print "t = ", t, "\n"; print "\nres = ", res; ks = res.keys(); #print "ks = ", ks; ks.sort(); #print "ks = ", ks; s1 = ks[0]; st = res[ s1 ]; #print "s1 = ", s1; #print "st = ", st; speed = {}; speedold = {}; for k in ks: speed[ k ] = st / res[ k ]; #print "speed = ", speed; print; o.write("\n#threads time speedup\n"); print "#threads time speedup"; for k in ks: o.write(str(k) + " " + str(res[k]) + " " + str(speed[k]) +"\n"); print(str(k) + " " + str(res[k]) + " " + str(speed[k])); f.close(); o.close(); #--------------------------------------- pscript = """ set grid set term %s set output "%s.ps" set title "GBs of Katsuras example on compute" set time set xlabel "#CPUs" set multiplot set size 0.75,0.5 set origin 0,0.5 set ylabel "milliseconds" # smooth acsplines plot "%s.po" title '%s computing time' with linespoints, \ "%s.po" using 1:( %s/$1 ) title '%s ideal' with linespoints set size 0.75,0.5 set origin 0,0 set ylabel "speedup" # smooth bezier plot "%s.po" using 1:3 title '%s speedup' with linespoints, \ "%s.po" using 1:1 title '%s ideal' with linespoints unset multiplot pause mouse """; #--------------------------------------- psname = bname + ".ps"; pname = "plotin.gp" p=open(pname,"w"); print p; pscript = pscript % ("x11",bname,bname,exam,bname,str(res[0]),exam,bname,exam,bname,exam); #pscript = pscript % ("postscript",bname,bname,exam,bname,str(res[0]),exam,bname,exam,bname,exam); p.write(pscript); p.close(); os.system("gnuplot plotin.gp"); cmd = "ps2pdf " + psname; print "cmd: " + cmd; #os.system(cmd);
Python
# # jython examples for jas. # $Id$ # import sys; from jas import Ring, Ideal from jas import startLog # example from rose (modified) #r = Ring( "Mod 19 (U3,U4,A46) L" ); #r = Ring( "Mod 1152921504606846883 (U3,U4,A46) L" ); # 2^60-93 #r = Ring( "Quat(U3,U4,A46) L" ); #r = Ring( "Z(U3,U4,A46) L" ); #r = Ring( "C(U3,U4,A46) L" ); r = Ring( "Rat(A46,U3,U4) G" ); print "Ring: " + str(r); print; ps = """ ( ( U4^4 - 20/7 A46^2 ), ( A46^2 U3^4 + 7/10 A46 U3^4 + 7/48 U3^4 - 50/27 A46^2 - 35/27 A46 - 49/216 ), ( A46^5 U4^3 + 7/5 A46^4 U4^3 + 609/1000 A46^3 U4^3 + 49/1250 A46^2 U4^3 - 27391/800000 A46 U4^3 - 1029/160000 U4^3 + 3/7 A46^5 U3 U4^2 + 3/5 A46^6 U3 U4^2 + 63/200 A46^3 U3 U4^2 + 147/2000 A46^2 U3 U4^2 + 4137/800000 A46 U3 U4^2 - 7/20 A46^4 U3^2 U4 - 77/125 A46^3 U3^2 U4 - 23863/60000 A46^2 U3^2 U4 - 1078/9375 A46 U3^2 U4 - 24353/1920000 U3^2 U4 - 3/20 A46^4 U3^3 - 21/100 A46^3 U3^3 - 91/800 A46^2 U3^3 - 5887/200000 A46 U3^3 - 343/128000 U3^3 ) ) """; f = Ideal( r, ps ); print "Ideal: " + str(f); print; #startLog(); rg = f.GB(); #print "seq Output:", rg; #print; #sys.exit(); rg = f.parNewGB(2); #print "par-new Output:", rg; #print; rg = f.parGB(2); #print "par Output:", rg; #print; f.distClient(); # starts in background rg = f.distGB(2); #print "dist Output:", rg; #print; sys.exit();
Python
# # jython examples for jas. # $Id$ # import sys from java.lang import System from java.lang import Integer from jas import Ring from jas import PolyRing from jas import Ideal from jas import ZM, QQ, AN, RF from jas import terminate from jas import startLog # polynomial examples: factorization over Z_p(sqrt(2))(x)(sqrt(x))[y] Q = PolyRing(ZM(5),"w2",PolyRing.lex); print "Q = " + str(Q); [e,a] = Q.gens(); #print "e = " + str(e); print "a = " + str(a); root = a**2 - 2; print "root = " + str(root); Q2 = AN(root,field=True); print "Q2 = " + str(Q2.factory()); [one,w2] = Q2.gens(); #print "one = " + str(one); #print "w2 = " + str(w2); print; Qp = PolyRing(Q2,"x",PolyRing.lex); print "Qp = " + str(Qp); [ep,wp,ap] = Qp.gens(); #print "ep = " + str(ep); #print "wp = " + str(wp); #print "ap = " + str(ap); print; Qr = RF(Qp); print "Qr = " + str(Qr.factory()); [er,wr,ar] = Qr.gens(); #print "er = " + str(er); #print "wr = " + str(wr); #print "ar = " + str(ar); print; Qwx = PolyRing(Qr,"wx",PolyRing.lex); print "Qwx = " + str(Qwx); [ewx,wwx,ax,wx] = Qwx.gens(); #print "ewx = " + str(ewx); print "ax = " + str(ax); #print "wwx = " + str(wwx); print "wx = " + str(wx); print; #rootx = wx**5 - ax; rootx = wx**2 - ax; print "rootx = " + str(rootx); Q2x = AN(rootx,field=True); print "Q2x = " + str(Q2x.factory()); [ex2,w2x2,ax2,wx] = Q2x.gens(); #print "ex2 = " + str(ex2); #print "w2x2 = " + str(w2x2); #print "ax2 = " + str(ax2); #print "wx = " + str(wx); print; Yr = PolyRing(Q2x,"y",PolyRing.lex) print "Yr = " + str(Yr); [e,w2,x,wx,y] = Yr.gens(); print "e = " + str(e); print "w2 = " + str(w2); print "x = " + str(x); print "wx = " + str(wx); print "y = " + str(y); print; #f = ( y**5 - x ) * ( y**2 - 2 ); f = ( y**2 - x ) * ( y**2 - 2 ); #f = ( y**2 - x )**5 * ( y**2 - 2 )**3; #f = ( y**4 - x * 2 ); #f = ( y**7 - x * 2 ); #f = ( y**2 - 2 ); #f = ( y**2 - x ); #f = ( w2 * y**2 - 1 ); #f = ( y**2 - 1/x ); #f = ( y**2 - 3 ); # 1/2 = 3 mod 5 #f = ( y**2 - 1/x ) * ( y**2 - 3 ); # 1/2 = 3 mod 5 print "f = ", f; print; #sys.exit(); startLog(); t = System.currentTimeMillis(); G = Yr.factors(f); t = System.currentTimeMillis() - t; #print "G = ", G; #print "factor time =", t, "milliseconds"; #sys.exit(); print "f = ", f; g = e; for h, i in G.iteritems(): if i > 1: print "h**i = ", h, "**" + str(i); else: print "h = ", h; h = h**i; g = g*h; #print "g = ", g; if cmp(f,g) == 0: print "factor time =", t, "milliseconds,", "isFactors(f,g): true" ; else: print "factor time =", t, "milliseconds,", "isFactors(f,g): ", cmp(f,g); print; #startLog(); terminate();
Python
# # jython examples for jas. # $Id$ # import sys; from jas import Ring from jas import Ideal from jas import startLog from jas import terminate # Nabashima, ISSAC 2007, example F4 # integral function coefficients r = Ring( "IntFunc(a, b, c, d) (y, x) L" ); print "Ring: " + str(r); print; ps = """ ( ( { a } x^3 y + { c } x y^2 ), ( x^4 y + { 3 d } y ), ( { c } x^2 + { b } x y ), ( x^2 y^2 + { a } x^2 ), ( x^5 + y^5 ) ) """; #startLog(); f = r.paramideal( ps ); print "ParamIdeal: " + str(f); print; gs = f.CGBsystem(); gs = f.CGBsystem(); gs = f.CGBsystem(); gs = f.CGBsystem(); print "CGBsystem: " + str(gs); print; sys.exit(); bg = gs.isCGBsystem(); if bg: print "isCGBsystem: true"; else: print "isCGBsystem: false"; print; #sys.exit(); gs = f.CGB(); print "CGB: " + str(gs); print; bg = gs.isCGB(); if bg: print "isCGB: true"; else: print "isCGB: false"; print; terminate(); #------------------------------------------ #sys.exit();
Python
# # jython examples for jas. # $Id$ # import sys; from java.lang import System from java.lang import Integer from jas import Ring, PolyRing from jas import terminate from jas import startLog from jas import QQ, ZM, RF # polynomial examples: ideal prime decomposition in char p > 0, inseparable cases cr = PolyRing(ZM(5),"c",PolyRing.lex); print "coefficient Ring: " + str(cr); rf = RF(cr); print "coefficient quotient Ring: " + str(rf.ring); r = PolyRing(rf,"x,y,z",PolyRing.lex); print "Ring: " + str(r); print; [one,c,x,y,z] = r.gens(); print one,c,x,y,z; #sys.exit(); f1 = (x**2 - 2); #**2; f2 = (y**2 - c)**5; f3 = (z**2 - 2 * c); #**5; print "f1 = ", f1; print "f2 = ", f2; print "f3 = ", f3; #print "f4 = ", f4; print; F = r.ideal( list=[f1,f2,f3] ); #F = r.ideal( list=[f1,f3] ); #F = r.ideal( list=[f2,f3] ); print "F = ", F; print; startLog(); t = System.currentTimeMillis(); P = F.primeDecomp(); t = System.currentTimeMillis() - t; print "P = ", P; print; print "decomp time =", t, "milliseconds"; print; print "F = ", F; print; #startLog(); terminate();
Python
# # jython examples for jas. # $Id$ # import sys; from jas import Ring from jas import ParamIdeal from jas import startLog from jas import terminate # Raksanyi & Walter example # integral/rational function coefficients #nono: r = Ring( "RatFunc(a1, a2, a3, a4) (x1, x2, x3, x4) L" ); r = Ring( "IntFunc(a1, a2, a3, a4) (x1, x2, x3, x4) G" ); #r = Ring( "IntFunc(a1, a2, a3, a4) (x4, x3, x2, x1) L" ); print "Ring: " + str(r); print; ps = """ ( ( x4 - { a4 - a2 } ), ( x1 + x2 + x3 + x4 - { a1 + a3 + a4 } ), ( x1 x3 + x1 x4 + x2 x3 + x3 x4 - { a1 a4 + a1 a3 + a3 a4 } ), ( x1 x3 x4 - { a1 a3 a4 } ) ) """; f = r.paramideal( ps ); print "ParamIdeal: " + str(f); print; #sys.exit(); #startLog(); gs = f.CGBsystem(); print "CGBsystem: " + str(gs); print; #sys.exit(); bg = gs.isCGBsystem(); if bg: print "isCGBsystem: true"; else: print "isCGBsystem: false"; print; #sys.exit(); gs = f.CGBsystem(); gs = f.CGBsystem(); gs = f.CGBsystem(); print "2-CGBsystem: " + str(gs); print; gs = f.CGB(); print "CGB: " + str(gs); print; bg = gs.isCGB(); if bg: print "isCGB: true"; else: print "isCGB: false"; print; terminate(); #sys.exit();
Python
# # jython examples for jas. # $Id$ # import sys; from jas import Ring from jas import Ideal from jas import startLog from jas import terminate # hermite polynomial example # H(0) = 1 # H(1) = 2 * x # H(n) = 2 * x * H(n-1) - 2 * (n-1) * H(n-2) r = Ring( "Z(x) L" ); print "Ring: " + str(r); print; # sage like: with generators for the polynomial ring [one,x] = r.gens(); x2 = 2 * x; N = 10; H = [one,x2]; for n in range(2,N): h = x2 * H[n-1] - 2 * (n-1) * H[n-2]; H.append( h ); for n in range(0,N): print "H[%s] = %s" % (n,H[n]); print; #sys.exit();
Python
# # jython examples for jas. # $Id$ # import sys from java.lang import System from java.lang import Integer from jas import Ring from jas import PolyRing from jas import Ideal from jas import ZM, QQ, AN, RF from jas import terminate from jas import startLog # polynomial examples: factorization over Z_p(x)(sqrt3(x))[y] Q = PolyRing(ZM(5),"x",PolyRing.lex); print "Q = " + str(Q); [e,a] = Q.gens(); #print "e = " + str(e); print "a = " + str(a); Qr = RF(Q); print "Qr = " + str(Qr.factory()); [er,ar] = Qr.gens(); #print "er = " + str(er); #print "ar = " + str(ar); print; Qwx = PolyRing(Qr,"wx",PolyRing.lex); print "Qwx = " + str(Qwx); [ewx,ax,wx] = Qwx.gens(); #print "ewx = " + str(ewx); print "ax = " + str(ax); print "wx = " + str(wx); print; rootx = wx**3 - ax; print "rootx = " + str(rootx); Q2x = AN(rootx,field=True); print "Q2x = " + str(Q2x.factory()); [ex2,ax2,wx] = Q2x.gens(); #print "ex2 = " + str(ex2); #print "w2x2 = " + str(w2x2); #print "ax2 = " + str(ax2); #print "wx = " + str(wx); print; #Yr = PolyRing(Q2x,"y,z,c0,c1,c2",PolyRing.lex) Yr = PolyRing(Q2x,"y,z",PolyRing.lex) print "Yr = " + str(Yr); #[e,x,wx,y,z,c0,c1,c2] = Yr.gens(); [e,x,wx,y,z] = Yr.gens(); print "e = " + str(e); print "x = " + str(x); print "wx = " + str(wx); print "y = " + str(y); print "z = " + str(z); print; #f = ( y**2 - x ); #f = ( y**2 - ( wx**2 + wx + 2 ) ); f = ( y**2 - ( wx**2 + wx + 2 ) + z**2 + y * wx ); #f = wx**3; print "f = ", f; print; f = f**5; print "f = ", f; print; #g = ( y**2 + ( c0 + c1 * wx + c2 * wx**2 ) ); #print "g = ", g; #g = g**5; #print "g = ", g; #print; #sys.exit(); startLog(); t = System.currentTimeMillis(); #ok: G = Yr.factors(f); G = Yr.squarefreeFactors(f); t = System.currentTimeMillis() - t; print "#G = ", len(G); #print "factor time =", t, "milliseconds"; #sys.exit(); print "f = ", f; g = e; for h, i in G.iteritems(): if i > 1: print "h**i = ", h, "**" + str(i); else: print "h = ", h; h = h**i; g = g*h; print "g = ", g; if cmp(f,g) == 0: print "factor time =", t, "milliseconds,", "isFactors(f,g): true" ; else: print "factor time =", t, "milliseconds,", "isFactors(f,g): ", cmp(f,g); print; #startLog(); terminate();
Python
# # jython unit tests for jas. # $Id$ # from java.lang import System from java.lang import Integer from jas import PolyRing, ZZ, QQ, ZM, GF from jas import terminate from jas import startLog import unittest # some unit tests: class RingElemTest (unittest.TestCase): def testRingZZ(self): r = PolyRing( ZZ(), "(t,x)", PolyRing.lex ); self.assertEqual(str(r),'PolyRing(ZZ(),"t,x",PolyRing.lex)'); [one,x,t] = r.gens(); self.assertTrue(one.isONE()); self.assertTrue(len(x)==1); self.assertTrue(len(t)==1); # f = 11 * x**4 - 13 * t * x**2 - 11 * x**2 + 2 * t**2 + 11 * t; f = f**2 + f + 3; #print "f = " + str(f); self.assertEqual(str(f),'( 4 * x**4 - 52 * t**2 * x**3 + 44 * x**3 + 213 * t**4 * x**2 - 330 * t**2 * x**2 + 123 * x**2 - 286 * t**6 * x + 528 * t**4 * x - 255 * t**2 * x + 11 * x + 121 * t**8 - 242 * t**6 + 132 * t**4 - 11 * t**2 + 3 )'); #end def testRingQQ(self): r = PolyRing( QQ(), "(t,x)", PolyRing.lex ); self.assertEqual(str(r),'PolyRing(QQ(),"t,x",PolyRing.lex)'); [one,x,t] = r.gens(); self.assertTrue(one.isONE()); self.assertTrue(len(x)==1); self.assertTrue(len(t)==1); # f = 11 * x**4 - 13 * t * x**2 - 11 * x**2 + 2 * t**2 + 11 * t; f = f**2 + f + 3; #print "f = " + str(f); self.assertEqual(str(f),'( 4 * x**4 - 52 * t**2 * x**3 + 44 * x**3 + 213 * t**4 * x**2 - 330 * t**2 * x**2 + 123 * x**2 - 286 * t**6 * x + 528 * t**4 * x - 255 * t**2 * x + 11 * x + 121 * t**8 - 242 * t**6 + 132 * t**4 - 11 * t**2 + 3 )'); #end def testRingZM(self): r = PolyRing( GF(17), "(t,x)", PolyRing.lex ); self.assertEqual(str(r),'PolyRing(GF(17),"t,x",PolyRing.lex)'); [one,x,t] = r.gens(); self.assertTrue(one.isONE()); self.assertTrue(len(x)==1); self.assertTrue(len(t)==1); # f = 11 * x**4 - 13 * t * x**2 - 11 * x**2 + 2 * t**2 + 11 * t; f = f**2 + f + 3; #print "f = " + str(f); self.assertEqual(str(f),'( 4 * x**4 + 16 * t**2 * x**3 + 10 * x**3 + 9 * t**4 * x**2 + 10 * t**2 * x**2 + 4 * x**2 + 3 * t**6 * x + t**4 * x + 11 * x + 2 * t**8 + 13 * t**6 + 13 * t**4 + 6 * t**2 + 3 )'); #end if __name__ == '__main__': #print str(__name__) + ": " + str(sys.modules[__name__]) unittest.main()
Python
# # jython examples for jas. # $Id$ # from java.lang import System from java.lang import Integer from jas import Ring, PolyRing from jas import terminate from jas import startLog from jas import QQ, ZM # polynomial examples: ideal radical decomposition, dim > 0, char p separable #r = Ring( "Rat(x) L" ); #r = Ring( "Q(x) L" ); r = PolyRing(ZM(5),"x,y,z",PolyRing.lex); print "Ring: " + str(r); print; [one,x,y,z] = r.gens(); #f1 = (x**2 - 5)**2; #f1 = (y**10 - x**5)**3; f2 = y**6 + 2 * x * y**4 + 3 * x**2 * y**2 + 4 * x**3; f2 = f2**5; f3 = z**10 - x**5; f4 = (y**2 - x)**3; #print "f1 = ", f1; print "f2 = ", f2; print "f3 = ", f3; #print "f4 = ", f4; print; F = r.ideal( list=[f2,f3] ); print "F = ", F; print; startLog(); t = System.currentTimeMillis(); R = F.radicalDecomp(); t = System.currentTimeMillis() - t; print "R = ", R; print; print "decomp time =", t, "milliseconds"; print; print "F = ", F; print; #startLog(); terminate();
Python
'''jython interface to JAS. ''' # $Id$ from java.lang import System from java.io import StringReader from java.util import ArrayList, List, Collections from org.apache.log4j import BasicConfigurator; from edu.jas.structure import RingElem, RingFactory, Power from edu.jas.arith import BigInteger, BigRational, BigComplex, BigDecimal,\ ModInteger, ModIntegerRing, BigQuaternion, BigOctonion,\ Product, ProductRing, PrimeList from edu.jas.poly import GenPolynomial, GenPolynomialRing, Monomial,\ GenSolvablePolynomial, GenSolvablePolynomialRing,\ RecSolvablePolynomial, RecSolvablePolynomialRing,\ GenWordPolynomial, GenWordPolynomialRing,\ Word, WordFactory,\ GenPolynomialTokenizer, OrderedPolynomialList, PolyUtil,\ TermOrderOptimization, TermOrder, PolynomialList,\ AlgebraicNumber, AlgebraicNumberRing,\ OrderedModuleList, ModuleList,\ Complex, ComplexRing from edu.jas.ps import UnivPowerSeries, UnivPowerSeriesRing,\ UnivPowerSeriesMap, Coefficients, \ MultiVarPowerSeries, MultiVarPowerSeriesRing,\ MultiVarPowerSeriesMap, MultiVarCoefficients,\ StandardBaseSeq from edu.jas.gb import EReductionSeq, DGroebnerBaseSeq, EGroebnerBaseSeq,\ GroebnerBaseDistributedEC, GroebnerBaseDistributedHybridEC,\ GroebnerBaseSeq, GroebnerBaseSeqPairSeq,\ OrderedPairlist, OrderedSyzPairlist,\ ReductionSeq, GroebnerBaseParallel, GroebnerBaseSeqPairParallel,\ SolvableGroebnerBaseParallel, SolvableGroebnerBaseSeq,\ SolvableReductionSeq, WordGroebnerBaseSeq from edu.jas.gbufd import GroebnerBasePseudoRecSeq, GroebnerBasePseudoSeq,\ GroebnerBasePseudoParallel,\ RGroebnerBasePseudoSeq, RGroebnerBaseSeq, RReductionSeq,\ CharacteristicSetWu from edu.jas.gbmod import ModGroebnerBaseAbstract, ModSolvableGroebnerBaseAbstract,\ SolvableQuotient, SolvableQuotientRing,\ QuotSolvablePolynomial, QuotSolvablePolynomialRing,\ SolvableSyzygyAbstract, SyzygyAbstract from edu.jas.vector import GenVector, GenVectorModul,\ GenMatrix, GenMatrixRing from edu.jas.application import PolyUtilApp, Residue, ResidueRing, Ideal,\ Local, LocalRing, IdealWithRealAlgebraicRoots,\ SolvableIdeal, SolvableResidue, SolvableResidueRing,\ SolvableLocal, SolvableLocalRing,\ SolvableLocalResidue, SolvableLocalResidueRing,\ ResidueSolvablePolynomial, ResidueSolvablePolynomialRing,\ LocalSolvablePolynomial, LocalSolvablePolynomialRing,\ QLRSolvablePolynomial, QLRSolvablePolynomialRing,\ ComprehensiveGroebnerBaseSeq, ExtensionFieldBuilder from edu.jas.kern import ComputerThreads, StringUtil, Scripting from edu.jas.ufd import GreatestCommonDivisor, PolyUfdUtil, GCDFactory,\ FactorFactory, SquarefreeFactory, Quotient, QuotientRing from edu.jas.root import RealRootsSturm, Interval, RealAlgebraicNumber, RealAlgebraicRing,\ ComplexRootsSturm, Rectangle, RootFactory from edu.jas.integrate import ElementaryIntegration from edu.jas.util import ExecutableServer from edu.jas import structure, arith, poly, ps, gb, gbmod, vector,\ application, util, ufd from edu import jas #PrettyPrint.setInternal(); from org.python.core import PyInstance, PyList, PyTuple,\ PyInteger, PyLong, PyFloat, PyString # set output to Python scripting Scripting.setLang(Scripting.Lang.Python); def startLog(): '''Configure the log4j system and start logging. ''' BasicConfigurator.configure(); def terminate(): '''Terminate the running thread pools. ''' ComputerThreads.terminate(); def noThreads(): '''Turn off automatic parallel threads usage. ''' print "nt = ", ComputerThreads.NO_THREADS; ComputerThreads.setNoThreads(); #NO_THREADS = #0; #1; #True; print "nt = ", ComputerThreads.NO_THREADS; auto_inject = True def inject_variable(name, value): '''Inject a variable into the main global namespace INPUT: - "name" - a string - "value" - anything Found in Sage. AUTHORS: - William Stein ''' assert type(name) is str import sys depth = 0 while True: G = sys._getframe(depth).f_globals #print "G = `%s` " % G; depth += 1 if depth > 100: print "depth limit %s reached " % depth; break if G is None: continue # orig: if G["__name__"] == "__main__" and G["__package__"] is None: try: if G["__name__"] is None: break except: #print "G[__name__] undefined"; break if G["__name__"] == "__main__": try: if G["__package__"] is None: break except: break if G is None: print "error at G no global environment found for `%s` = `%s` " % (name, value); return if name in G: print "redefining global variable `%s` from `%s` " % (name, G[name]); G[name] = value def inject_generators(gens): '''Inject generators as variables into the main global namespace INPUT: - "gens" - generators ''' for v in gens: #print "vars = " + str(v); s = str(v); if s.find("/") < 0 and s.find("(") < 0 and s.find(",") < 0 and s.find("{") < 0 and s.find("[") < 0 and s.find("|") < 0: if s[0:1] == "1": s = "one" + s[1:] #print "var = " + s; inject_variable(s,v) class Ring: '''Represents a JAS polynomial ring: GenPolynomialRing. Methods to create ideals and ideals with parametric coefficients. ''' def __init__(self,ringstr="",ring=None,fast=False): '''Ring constructor. ''' if ring == None: sr = StringReader( ringstr ); tok = GenPolynomialTokenizer(sr); self.pset = tok.nextPolynomialSet(); self.ring = self.pset.ring; else: self.ring = ring; if fast: return; self.engine = GCDFactory.getProxy(self.ring.coFac); try: self.sqf = SquarefreeFactory.getImplementation(self.ring.coFac); # print "sqf: ", self.sqf; # except Exception, e: # print "error " + str(e) except: pass try: self.factor = FactorFactory.getImplementation(self.ring.coFac); #print "factor: ", self.factor; except: pass # except Exception, e: # print "error " + str(e) #print "dict: " + str(self.__dict__) vns = "" import re; ri = re.compile(r'\A[0-9].*'); for v in self.ring.generators(): #print "vars = " + str(v); vs = str(v); vr = RingElem(v); vs = vs.replace(" ",""); vs = vs.replace("\n",""); if vs.find("(") >= 0: vs = vs.replace("(",""); vs = vs.replace(")",""); if vs.find("{") >= 0: vs = vs.replace("{",""); vs = vs.replace("}",""); if vs.find("[") >= 0: vs = vs.replace("[",""); vs = vs.replace("]",""); if vs.find(",") >= 0: vs = vs.replace(",",""); #if vs.find("|") >= 0: # vs = vs.replace("|","div"); # case "1"? if vs.find("/") >= 0: vs = vs.replace("/","div"); if vs[0:1] == "1": vs = 'one' + vs[1:]; if vs == "1": vs = "one"; if ri.match(vs): #print "vs = " + str(vs); continue; try: if self.__dict__[vs] is None: self.__dict__[vs] = vr; else: print vs + " not redefined to " + str(v); except: self.__dict__[vs] = vr; if auto_inject: inject_variable(vs,vr) vns = vns + vs + " " if auto_inject: print "globally defined variables: " + vns #print "dict: " + str(self.__dict__) def __str__(self): '''Create a string representation. ''' return str(self.ring.toScript()); def ideal(self,ringstr="",list=None): '''Create an ideal. ''' return Ideal(self,ringstr,list=list); def paramideal(self,ringstr="",list=None,gbsys=None): '''Create an ideal in a polynomial ring with parameter coefficients. ''' return ParamIdeal(self,ringstr,list,gbsys); def gens(self): '''Get list of generators of the polynomial ring. ''' L = self.ring.generators(); N = [ RingElem(e) for e in L ]; return N; def inject_variables(self): '''Inject generators as variables into the main global namespace ''' inject_generators(self.gens()); def one(self): '''Get the one of the polynomial ring. ''' return RingElem( self.ring.getONE() ); def zero(self): '''Get the zero of the polynomial ring. ''' return RingElem( self.ring.getZERO() ); def random(self,k=5,l=7,d=3,q=0.3): '''Get a random polynomial. ''' r = self.ring.random(k,l,d,q); if self.ring.coFac.isField(): r = r.monic(); return RingElem( r ); def element(self,poly): '''Create an element from a string or object. ''' if not isinstance(poly,str): try: if self.ring == poly.ring: return RingElem(poly); except Exception, e: pass poly = str(poly); I = Ideal(self, "( " + poly + " )"); list = I.pset.list; if len(list) > 0: return RingElem( list[0] ); def gcd(self,a,b): '''Compute the greatest common divisor of a and b. ''' if isinstance(a,RingElem): a = a.elem; else: a = self.element( a ); a = a.elem; if isinstance(b,RingElem): b = b.elem; else: b = self.element( b ); b = b.elem; return RingElem( self.engine.gcd(a,b) ); def squarefreeFactors(self,a): '''Compute squarefree factors of polynomial. ''' if isinstance(a,RingElem): a = a.elem; else: a = self.element( a ); a = a.elem; cf = self.ring.coFac; if cf.getClass().getSimpleName() == "GenPolynomialRing": e = self.sqf.recursiveSquarefreeFactors( a ); else: e = self.sqf.squarefreeFactors( a ); L = {}; for a in e.keySet(): i = e.get(a); L[ RingElem( a ) ] = i; return L; def factors(self,a): '''Compute irreducible factorization for modular, integer, rational number and algebriac number coefficients. ''' if isinstance(a,RingElem): a = a.elem; else: a = self.element( a ); a = a.elem; try: cf = self.ring.coFac; if cf.getClass().getSimpleName() == "GenPolynomialRing": e = self.factor.recursiveFactors( a ); else: e = self.factor.factors( a ); L = {}; for a in e.keySet(): i = e.get(a); L[ RingElem( a ) ] = i; return L; except Exception, e: print "error " + str(e) return None def factorsAbsolute(self,a): '''Compute absolute irreducible factorization for (modular,) rational number coefficients. ''' if isinstance(a,RingElem): a = a.elem; else: a = self.element( a ); a = a.elem; try: L = self.factor.factorsAbsolute( a ); ## L = {}; ## for a in e.keySet(): ## i = e.get(a); ## L[ RingElem( a ) ] = i; return L; except Exception, e: print "error in factorsAbsolute " + str(e) return None def realRoots(self,a,eps=None): '''Compute real roots of univariate polynomial. ''' if isinstance(a,RingElem): a = a.elem; else: a = self.element( a ); a = a.elem; if isinstance(eps,RingElem): eps = eps.elem; try: if eps == None: #R = RealRootsSturm().realRoots( a ); R = RootFactory.realAlgebraicNumbers( a ); else: R = RootFactory.realAlgebraicNumbers( a, eps ); R = [ RingElem(r) for r in R ]; #R = [ RingElem(BigDecimal(r.getRational())) for r in R ]; return R; except Exception, e: print "error " + str(e) return None def complexRoots(self,a,eps=None): '''Compute complex roots of univariate polynomial. ''' if isinstance(a,RingElem): a = a.elem; else: a = self.element( a ); a = a.elem; if isinstance(eps,RingElem): eps = eps.elem; cmplx = False; try: x = a.ring.coFac.getONE().getRe(); cmplx = True; except Exception, e: pass; try: if eps == None: if cmplx: R = RootFactory.complexAlgebraicNumbersComplex(a); else: R = RootFactory.complexAlgebraicNumbers(a); # R = ComplexRootsSturm(a.ring.coFac).complexRoots( a ); # R = [ r.centerApprox() for r in R ]; # R = [ r.ring.getRoot() for r in R ]; R = [ RingElem(r) for r in R ]; else: if cmplx: R = RootFactory.complexAlgebraicNumbersComplex(a,eps); else: R = RootFactory.complexAlgebraicNumbers(a,eps); R = [ RingElem(r) for r in R ]; # R = [ r.decimalMagnitude() for r in R ]; # R = ComplexRootsSturm(a.ring.coFac).complexRoots( a, eps ); # R = ComplexRootsSturm(a.ring.coFac).approximateRoots( a, eps ); return R; except Exception, e: print "error " + str(e) return None def integrate(self,a): '''Integrate (univariate) rational function. ''' if isinstance(a,RingElem): a = a.elem; else: a = self.element( a ); a = a.elem; cf = self.ring; try: cf = cf.ring; except: pass; integrator = ElementaryIntegration(cf.coFac); ei = integrator.integrate(a); return ei; def powerseriesRing(self): '''Get a power series ring from this ring. ''' pr = MultiVarPowerSeriesRing(self.ring); return MultiSeriesRing(ring=pr); class Ideal: '''Represents a JAS polynomial ideal: PolynomialList and Ideal. Methods for Groebner bases, ideal sum, intersection and others. ''' def __init__(self,ring,polystr="",list=None): '''Ideal constructor. ''' self.ring = ring; if list == None: sr = StringReader( polystr ); tok = GenPolynomialTokenizer(ring.ring,sr); self.list = tok.nextPolynomialList(); else: self.list = pylist2arraylist(list,rec=1); self.pset = OrderedPolynomialList(ring.ring,self.list); self.roots = None; self.croots = None; self.prime = None; self.primary = None; def __str__(self): '''Create a string representation. ''' return str(self.pset.toScript()); def __eq__(self,other): '''Test if two ideals are equal. ''' o = other; if isinstance(other,Ideal): o = other.pset; return self.pset.equals(o) def paramideal(self): '''Create an ideal in a polynomial ring with parameter coefficients. ''' return ParamIdeal(self.ring,"",self.list); def GB(self): '''Compute a Groebner base. ''' s = self.pset; cofac = s.ring.coFac; F = s.list; t = System.currentTimeMillis(); if cofac.isField(): G = GroebnerBaseSeq(ReductionSeq(),OrderedSyzPairlist()).GB(F); #G = GroebnerBaseSeq().GB(F); else: v = None; try: v = cofac.vars; except: pass if v == None: G = GroebnerBasePseudoSeq(cofac).GB(F); else: G = GroebnerBasePseudoRecSeq(cofac).GB(F); t = System.currentTimeMillis() - t; print "sequential GB executed in %s ms" % t; return Ideal(self.ring,"",G); def isGB(self): '''Test if this is a Groebner base. ''' s = self.pset; cofac = s.ring.coFac; F = s.list; t = System.currentTimeMillis(); if cofac.isField(): b = GroebnerBaseSeq().isGB(F); else: v = None; try: v = cofac.vars; except: pass if v == None: b = GroebnerBasePseudoSeq(cofac).isGB(F); else: b = GroebnerBasePseudoRecSeq(cofac).isGB(F); t = System.currentTimeMillis() - t; #print "isGB executed in %s ms" % t; return b; def eGB(self): '''Compute an e-Groebner base. ''' s = self.pset; cofac = s.ring.coFac; F = s.list; t = System.currentTimeMillis(); G = EGroebnerBaseSeq().GB(F) t = System.currentTimeMillis() - t; print "sequential e-GB executed in %s ms" % t; return Ideal(self.ring,"",G); def iseGB(self): '''Test if this is an e-Groebner base. ''' s = self.pset; cofac = s.ring.coFac; F = s.list; t = System.currentTimeMillis(); b = EGroebnerBaseSeq().isGB(F) t = System.currentTimeMillis() - t; print "is e-GB test executed in %s ms" % t; return b; def dGB(self): '''Compute an d-Groebner base. ''' s = self.pset; cofac = s.ring.coFac; F = s.list; t = System.currentTimeMillis(); G = DGroebnerBaseSeq().GB(F) t = System.currentTimeMillis() - t; print "sequential d-GB executed in %s ms" % t; return Ideal(self.ring,"",G); def isdGB(self): '''Test if this is a d-Groebner base. ''' s = self.pset; cofac = s.ring.coFac; F = s.list; t = System.currentTimeMillis(); b = DGroebnerBaseSeq().isGB(F) t = System.currentTimeMillis() - t; print "is d-GB test executed in %s ms" % t; return b; def parNewGB(self,th): '''Compute in parallel a Groebner base. ''' s = self.pset; F = s.list; bbpar = GroebnerBaseSeqPairParallel(th); t = System.currentTimeMillis(); G = bbpar.GB(F); t = System.currentTimeMillis() - t; bbpar.terminate(); print "parallel-new %s executed in %s ms" % (th, t); return Ideal(self.ring,"",G); def parGB(self,th): '''Compute in parallel a Groebner base. ''' s = self.pset; F = s.list; cofac = s.ring.coFac; if cofac.isField(): bbpar = GroebnerBaseParallel(th); else: bbpar = GroebnerBasePseudoParallel(th,cofac); t = System.currentTimeMillis(); G = bbpar.GB(F); t = System.currentTimeMillis() - t; bbpar.terminate(); print "parallel %s executed in %s ms" % (th, t); return Ideal(self.ring,"",G); def distGB(self,th=2,machine="examples/machines.localhost",port=55711): '''Compute on a distributed system a Groebner base. ''' s = self.pset; F = s.list; t = System.currentTimeMillis(); #old: gbd = GBDist(th,machine,port); gbd = GroebnerBaseDistributedEC(machine,th,port); #gbd = GroebnerBaseDistributedHybridEC(machine,th,port); t1 = System.currentTimeMillis(); G = gbd.GB(F); t1 = System.currentTimeMillis() - t1; gbd.terminate(); t = System.currentTimeMillis() - t; print "distributed %s executed in %s ms (%s ms start-up)" % (th,t1,t-t1); return Ideal(self.ring,"",G); def distClient(self,port=4711): #8114 '''Client for a distributed computation. ''' e1 = ExecutableServer( port ); e1.init(); e2 = ExecutableServer( port+1 ); e2.init(); self.exers = [e1,e2]; return None; def distClientStop(self): '''Stop client for a distributed computation. ''' for es in self.exers: es.terminate(); return None; def eReduction(self,p): '''Compute a e-normal form of p with respect to this ideal. ''' s = self.pset; G = s.list; if isinstance(p,RingElem): p = p.elem; t = System.currentTimeMillis(); n = EReductionSeq().normalform(G,p); t = System.currentTimeMillis() - t; print "sequential eReduction executed in %s ms" % t; return RingElem(n); def reduction(self,p): '''Compute a normal form of p with respect to this ideal. ''' s = self.pset; G = s.list; if isinstance(p,RingElem): p = p.elem; n = ReductionSeq().normalform(G,p); return RingElem(n); def NF(self,reducer): '''Compute a normal form of this ideal with respect to reducer. ''' s = self.pset; F = s.list; G = reducer.list; t = System.currentTimeMillis(); N = ReductionSeq().normalform(G,F); t = System.currentTimeMillis() - t; print "sequential NF executed in %s ms" % t; return Ideal(self.ring,"",N); def interreduced_basis(self): '''Compute a interreduced ideal basis of this. Compatibility method for Sage/Singular. ''' F = self.pset.list; N = ReductionSeq().irreducibleSet(F); #N = GroebnerBaseSeq().minimalGB(F); return [ RingElem(n) for n in N ]; def intersectRing(self,ring): '''Compute the intersection of this and the given polynomial ring. ''' s = jas.application.Ideal(self.pset); N = s.intersect(ring.ring); return Ideal(ring,"",N.getList()); def intersect(self,id2): '''Compute the intersection of this and the given ideal id2. ''' s1 = jas.application.Ideal(self.pset); s2 = jas.application.Ideal(id2.pset); N = s1.intersect(s2); return Ideal(self.ring,"",N.getList()); def eliminateRing(self,ring): '''Compute the elimination ideal of this and the given polynomial ring. ''' s = jas.application.Ideal(self.pset); N = s.eliminate(ring.ring); r = Ring( ring=N.getRing() ); return Ideal(r,"",N.getList()); def sat(self,id2): '''Compute the saturation of this with respect to given ideal id2. ''' s1 = jas.application.Ideal(self.pset); s2 = jas.application.Ideal(id2.pset); #Q = s1.infiniteQuotient(s2); Q = s1.infiniteQuotientRab(s2); return Ideal(self.ring,"",Q.getList()); def sum(self,other): '''Compute the sum of this and the ideal. ''' s = jas.application.Ideal(self.pset); t = jas.application.Ideal(other.pset); N = s.sum( t ); return Ideal(self.ring,"",N.getList()); def univariates(self): '''Compute the univariate polynomials in each variable of this ideal. ''' s = jas.application.Ideal(self.pset); L = s.constructUnivariate(); N = [ RingElem(e) for e in L ]; return N; def inverse(self,p): '''Compute the inverse polynomial modulo this ideal, if it exists. ''' s = jas.application.Ideal(self.pset); if isinstance(p,RingElem): p = p.elem; i = s.inverse(p); return RingElem(i); def optimize(self): '''Optimize the term order on the variables. ''' p = self.pset; o = TermOrderOptimization.optimizeTermOrder(p); r = Ring("",o.ring); return Ideal(r,"",o.list); def realRoots(self): '''Compute real roots of 0-dim ideal. ''' I = jas.application.Ideal(self.pset); self.roots = jas.application.PolyUtilApp.realAlgebraicRoots(I); for R in self.roots: R.doDecimalApproximation(); return self.roots; def realRootsPrint(self): '''Print decimal approximation of real roots of 0-dim ideal. ''' if self.roots == None: I = jas.application.Ideal(self.pset); self.roots = jas.application.PolyUtilApp.realAlgebraicRoots(I); for R in self.roots: R.doDecimalApproximation(); for Ir in self.roots: for Dr in Ir.decimalApproximation(): print str(Dr); print; def radicalDecomp(self): '''Compute radical decomposition of this ideal. ''' I = jas.application.Ideal(self.pset); self.radical = I.radicalDecomposition(); return self.radical; def decomposition(self): '''Compute irreducible decomposition of this ideal. ''' I = jas.application.Ideal(self.pset); self.irrdec = I.decomposition(); return self.irrdec; def complexRoots(self): '''Compute complex roots of 0-dim ideal. ''' I = jas.application.Ideal(self.pset); self.croots = jas.application.PolyUtilApp.complexAlgebraicRoots(I); for R in self.croots: R.doDecimalApproximation(); return self.croots; def complexRootsPrint(self): '''Print decimal approximation of complex roots of 0-dim ideal. ''' if self.croots == None: I = jas.application.Ideal(self.pset); self.croots = jas.application.PolyUtilApp.realAlgebraicRoots(I); for R in self.croots: R.doDecimalApproximation(); for Ic in self.croots: for Dc in Ic.decimalApproximation(): print str(Dc); print; def primeDecomp(self): '''Compute prime decomposition of this ideal. ''' I = jas.application.Ideal(self.pset); self.prime = I.primeDecomposition(); return self.prime; def primaryDecomp(self): '''Compute primary decomposition of this ideal. ''' I = jas.application.Ideal(self.pset); ## if self.prime == None: ## self.prime = I.primeDecomposition(); self.primary = I.primaryDecomposition(); return self.primary; def toInteger(self): '''Convert rational coefficients to integer coefficients. ''' p = self.pset; l = p.list; r = p.ring; ri = GenPolynomialRing( BigInteger(), r.nvar, r.tord, r.vars ); pi = PolyUtil.integerFromRationalCoefficients(ri,l); r = Ring("",ri); return Ideal(r,"",pi); def toModular(self,mf): '''Convert integer coefficients to modular coefficients. ''' p = self.pset; l = p.list; r = p.ring; rm = GenPolynomialRing( mf, r.nvar, r.tord, r.vars ); pm = PolyUtil.fromIntegerCoefficients(rm,l); r = Ring("",rm); return Ideal(r,"",pm); def CS(self): '''Compute a Characteristic Set. ''' s = self.pset; cofac = s.ring.coFac; F = s.list; t = System.currentTimeMillis(); if cofac.isField(): G = CharacteristicSetWu().characteristicSet(F); else: print "CS not implemented for coefficients %s" % cofac.toScriptFactory(); G = None; t = System.currentTimeMillis() - t; print "sequential CS executed in %s ms" % t; return Ideal(self.ring,"",G); def isCS(self): '''Test for Characteristic Set. ''' s = self.pset; cofac = s.ring.coFac; F = s.list.clone(); Collections.reverse(F); # todo t = System.currentTimeMillis(); if cofac.isField(): b = CharacteristicSetWu().isCharacteristicSet(F); else: print "isCS not implemented for coefficients %s" % cofac.toScriptFactory(); b = False; t = System.currentTimeMillis() - t; return b; def csReduction(self,p): '''Compute a normal form of p with respect to this characteristic set. ''' s = self.pset; F = s.list.clone(); Collections.reverse(F); # todo if isinstance(p,RingElem): p = p.elem; t = System.currentTimeMillis(); n = CharacteristicSetWu().characteristicSetReduction(F,p); t = System.currentTimeMillis() - t; #print "sequential char set reduction executed in %s ms" % t; return RingElem(n); ## def syzygy(self): ## '''Syzygy of generating polynomials. ## ''' ## p = self.pset; ## l = p.list; ## s = SyzygyAbstract().zeroRelations( l ); ## m = Module("",p.ring); ## return SubModule(m,"",s); class ParamIdeal: '''Represents a JAS polynomial ideal with polynomial coefficients. Methods to compute comprehensive Groebner bases. ''' def __init__(self,ring,polystr="",list=None,gbsys=None): '''Parametric ideal constructor. ''' self.ring = ring; if list == None and polystr != None: sr = StringReader( polystr ); tok = GenPolynomialTokenizer(ring.ring,sr); self.list = tok.nextPolynomialList(); else: self.list = pylist2arraylist(list,rec=1); self.gbsys = gbsys; self.pset = OrderedPolynomialList(ring.ring,self.list); def __str__(self): '''Create a string representation. ''' if self.gbsys == None: return self.pset.toScript(); else: return self.gbsys.toString(); # toScript() not available # return self.pset.toScript() + "\n" + self.gbsys.toScript(); def optimizeCoeff(self): '''Optimize the term order on the variables of the coefficients. ''' p = self.pset; o = TermOrderOptimization.optimizeTermOrderOnCoefficients(p); r = Ring("",o.ring); return ParamIdeal(r,"",o.list); def optimizeCoeffQuot(self): '''Optimize the term order on the variables of the quotient coefficients. ''' p = self.pset; l = p.list; r = p.ring; q = r.coFac; c = q.ring; rc = GenPolynomialRing( c, r.nvar, r.tord, r.vars ); #print "rc = ", rc; lp = PolyUfdUtil.integralFromQuotientCoefficients(rc,l); #print "lp = ", lp; pp = PolynomialList(rc,lp); #print "pp = ", pp; oq = TermOrderOptimization.optimizeTermOrderOnCoefficients(pp); oor = oq.ring; qo = oor.coFac; cq = QuotientRing( qo ); rq = GenPolynomialRing( cq, r.nvar, r.tord, r.vars ); #print "rq = ", rq; o = PolyUfdUtil.quotientFromIntegralCoefficients(rq,oq.list); r = Ring("",rq); return ParamIdeal(r,"",o); def toIntegralCoeff(self): '''Convert rational function coefficients to integral function coefficients. ''' p = self.pset; l = p.list; r = p.ring; q = r.coFac; c = q.ring; rc = GenPolynomialRing( c, r.nvar, r.tord, r.vars ); #print "rc = ", rc; lp = PolyUfdUtil.integralFromQuotientCoefficients(rc,l); #print "lp = ", lp; r = Ring("",rc); return ParamIdeal(r,"",lp); def toModularCoeff(self,mf): '''Convert integral function coefficients to modular function coefficients. ''' p = self.pset; l = p.list; r = p.ring; c = r.coFac; #print "c = ", c; cm = GenPolynomialRing( mf, c.nvar, c.tord, c.vars ); #print "cm = ", cm; rm = GenPolynomialRing( cm, r.nvar, r.tord, r.vars ); #print "rm = ", rm; pm = PolyUfdUtil.fromIntegerCoefficients(rm,l); r = Ring("",rm); return ParamIdeal(r,"",pm); def toQuotientCoeff(self): '''Convert integral function coefficients to rational function coefficients. ''' p = self.pset; l = p.list; r = p.ring; c = r.coFac; #print "c = ", c; q = QuotientRing(c); #print "q = ", q; qm = GenPolynomialRing( q, r.nvar, r.tord, r.vars ); #print "qm = ", qm; pm = PolyUfdUtil.quotientFromIntegralCoefficients(qm,l); r = Ring("",qm); return ParamIdeal(r,"",pm); def GB(self): '''Compute a Groebner base. ''' I = Ideal(self.ring,"",self.pset.list); g = I.GB(); return ParamIdeal(g.ring,"",g.pset.list); def isGB(self): '''Test if this is a Groebner base. ''' I = Ideal(self.ring,"",self.pset.list); return I.isGB(); def CGB(self): '''Compute a comprehensive Groebner base. ''' s = self.pset; F = s.list; t = System.currentTimeMillis(); if self.gbsys == None: self.gbsys = ComprehensiveGroebnerBaseSeq(self.ring.ring.coFac).GBsys(F); G = self.gbsys.getCGB(); t = System.currentTimeMillis() - t; print "sequential comprehensive executed in %s ms" % t; return ParamIdeal(self.ring,"",G,self.gbsys); def CGBsystem(self): '''Compute a comprehensive Groebner system. ''' s = self.pset; F = s.list; t = System.currentTimeMillis(); S = ComprehensiveGroebnerBaseSeq(self.ring.ring.coFac).GBsys(F); t = System.currentTimeMillis() - t; print "sequential comprehensive system executed in %s ms" % t; return ParamIdeal(self.ring,None,F,S); def isCGB(self): '''Test if this is a comprehensive Groebner base. ''' s = self.pset; F = s.list; t = System.currentTimeMillis(); b = ComprehensiveGroebnerBaseSeq(self.ring.ring.coFac).isGB(F); t = System.currentTimeMillis() - t; print "isCGB executed in %s ms" % t; return b; def isCGBsystem(self): '''Test if this is a comprehensive Groebner system. ''' s = self.pset; S = self.gbsys; t = System.currentTimeMillis(); b = ComprehensiveGroebnerBaseSeq(self.ring.ring.coFac).isGBsys(S); t = System.currentTimeMillis() - t; print "isCGBsystem executed in %s ms" % t; return b; def regularRepresentation(self): '''Convert Groebner system to a representation with regular ring coefficents. ''' if self.gbsys == None: return None; G = PolyUtilApp.toProductRes(self.gbsys.list); ring = Ring(None,G[0].ring); return ParamIdeal(ring,None,G); def regularRepresentationBC(self): '''Convert Groebner system to a boolean closed representation with regular ring coefficents. ''' if self.gbsys == None: return None; G = PolyUtilApp.toProductRes(self.gbsys.list); ring = Ring(None,G[0].ring); res = RReductionSeq(); G = res.booleanClosure(G); return ParamIdeal(ring,None,G); def regularGB(self): '''Compute a Groebner base over a regular ring. ''' s = self.pset; F = s.list; t = System.currentTimeMillis(); G = RGroebnerBasePseudoSeq(self.ring.ring.coFac).GB(F); t = System.currentTimeMillis() - t; print "sequential regular GB executed in %s ms" % t; return ParamIdeal(self.ring,None,G); def isRegularGB(self): '''Test if this is Groebner base over a regular ring. ''' s = self.pset; F = s.list; t = System.currentTimeMillis(); b = RGroebnerBasePseudoSeq(self.ring.ring.coFac).isGB(F); t = System.currentTimeMillis() - t; print "isRegularGB executed in %s ms" % t; return b; def stringSlice(self): '''Get each component (slice) of regular ring coefficients separate. ''' s = self.pset; b = PolyUtilApp.productToString(s); return b; class SolvableRing(Ring): '''Represents a JAS solvable polynomial ring: GenSolvablePolynomialRing. Has a method to create solvable ideals. ''' def __init__(self,ringstr="",ring=None): '''Solvable polynomial ring constructor. ''' if ring == None: sr = StringReader( ringstr ); tok = GenPolynomialTokenizer(sr); self.pset = tok.nextSolvablePolynomialSet(); self.ring = self.pset.ring; else: self.ring = ring; if not self.ring.isAssociative(): print "warning: ring is not associative"; Ring.__init__(self,ring=self.ring) def __str__(self): '''Create a string representation. ''' return str(self.ring.toScript()); def ideal(self,ringstr="",list=None): '''Create a solvable ideal. ''' return SolvableIdeal(self,ringstr,list); def one(self): '''Get the one of the solvable polynomial ring. ''' return RingElem( self.ring.getONE() ); def zero(self): '''Get the zero of the solvable polynomial ring. ''' return RingElem( self.ring.getZERO() ); def element(self,poly): '''Create an element from a string or object. ''' if not isinstance(poly,str): try: if self.ring == poly.ring: return RingElem(poly); except Exception, e: pass poly = str(poly); I = SolvableIdeal(self, "( " + poly + " )"); list = I.pset.list; if len(list) > 0: return RingElem( list[0] ); class SolvableIdeal: '''Represents a JAS solvable polynomial ideal. Methods for left, right two-sided Groebner basees and others. ''' def __init__(self,ring,ringstr="",list=None): '''Constructor for an ideal in a solvable polynomial ring. ''' self.ring = ring; if list == None: sr = StringReader( ringstr ); tok = GenPolynomialTokenizer(ring.ring,sr); self.list = tok.nextSolvablePolynomialList(); else: self.list = pylist2arraylist(list,rec=1); self.pset = OrderedPolynomialList(ring.ring,self.list); def __str__(self): '''Create a string representation. ''' return str(self.pset.toScript()); def __cmp__(self,other): '''Compare two ideals. ''' t = False; if not isinstance(other,WordIdeal): return t; t = self.list.equals(other.list); return t; def leftGB(self): '''Compute a left Groebner base. ''' s = self.pset; F = s.list; t = System.currentTimeMillis(); G = SolvableGroebnerBaseSeq().leftGB(F); t = System.currentTimeMillis() - t; print "executed leftGB in %s ms" % t; return SolvableIdeal(self.ring,"",G); def isLeftGB(self): '''Test if this is a left Groebner base. ''' s = self.pset; F = s.list; t = System.currentTimeMillis(); b = SolvableGroebnerBaseSeq().isLeftGB(F); t = System.currentTimeMillis() - t; print "isLeftGB executed in %s ms" % t; return b; def twosidedGB(self): '''Compute a two-sided Groebner base. ''' s = self.pset; F = s.list; t = System.currentTimeMillis(); G = SolvableGroebnerBaseSeq().twosidedGB(F); t = System.currentTimeMillis() - t; print "executed twosidedGB in %s ms" % t; return SolvableIdeal(self.ring,"",G); def isTwosidedGB(self): '''Test if this is a two-sided Groebner base. ''' s = self.pset; F = s.list; t = System.currentTimeMillis(); b = SolvableGroebnerBaseSeq().isTwosidedGB(F); t = System.currentTimeMillis() - t; print "isTwosidedGB executed in %s ms" % t; return b; def rightGB(self): '''Compute a right Groebner base. ''' s = self.pset; F = s.list; t = System.currentTimeMillis(); G = SolvableGroebnerBaseSeq().rightGB(F); t = System.currentTimeMillis() - t; print "executed rightGB in %s ms" % t; return SolvableIdeal(self.ring,"",G); def isRightGB(self): '''Test if this is a right Groebner base. ''' s = self.pset; F = s.list; t = System.currentTimeMillis(); b = SolvableGroebnerBaseSeq().isRightGB(F); t = System.currentTimeMillis() - t; print "isRightGB executed in %s ms" % t; return b; def intersectRing(self,ring): '''Compute the intersection of this and the polynomial ring. ''' s = jas.application.SolvableIdeal(self.pset); N = s.intersect(ring.ring); return SolvableIdeal(self.ring,"",N.getList()); def intersect(self,other): '''Compute the intersection of this and the other ideal. ''' s = jas.application.SolvableIdeal(self.pset); t = jas.application.SolvableIdeal(other.pset); N = s.intersect( t ); return SolvableIdeal(self.ring,"",N.getList()); def sum(self,other): '''Compute the sum of this and the other ideal. ''' s = jas.application.SolvableIdeal(self.pset); t = jas.application.SolvableIdeal(other.pset); N = s.sum( t ); return SolvableIdeal(self.ring,"",N.getList()); def univariates(self): '''Compute the univariate polynomials in each variable of this twosided ideal. ''' s = jas.application.SolvableIdeal(self.pset); L = s.constructUnivariate(); N = [ RingElem(e) for e in L ]; return N; def toQuotientCoefficients(self): '''Convert to polynomials with SolvableQuotient coefficients. ''' if self.pset.ring.coFac.getClass().getSimpleName() == "SolvableResidueRing": cf = self.pset.ring.coFac.ring; else: if self.pset.ring.coFac.getClass().getSimpleName() == "GenSolvablePolynomialRing": cf = self.pset.ring.coFac; #else: if @pset.ring.coFac.getClass().getSimpleName() == "GenPolynomialRing" # cf = @pset.ring.coFac; # puts "cf = " + cf.toScript(); else: return self; rrel = self.pset.ring.table.relationList(); rrel.addAll(self.pset.ring.polCoeff.coeffTable.relationList()); #print "rrel = " + str(rrel); qf = SolvableQuotientRing(cf); qr = QuotSolvablePolynomialRing(qf,self.pset.ring); #print "qr = " + str(qr); qrel = [ RingElem(qr.fromPolyCoefficients(r)) for r in rrel ]; qring = SolvPolyRing(qf,self.ring.ring.getVars(),self.ring.ring.tord,qrel); #print "qring = " + str(qring); qlist = [ qr.fromPolyCoefficients(self.ring.ring.toPolyCoefficients(r)) for r in self.list ]; qlist = [ RingElem(r) for r in qlist ]; return SolvableIdeal(qring,"",qlist); def inverse(self,p): '''Compute the inverse polynomial modulo this ideal, if it exists. ''' s = jas.application.SolvableIdeal(self.pset); if isinstance(p,RingElem): p = p.elem; i = s.inverse(p); return RingElem(i); def leftReduction(self,p): '''Compute a left normal form of p with respect to this ideal. ''' s = self.pset; G = s.list; if isinstance(p,RingElem): p = p.elem; n = SolvableReductionSeq().leftNormalform(G,p); return RingElem(n); def rightReduction(self,p): '''Compute a right normal form of p with respect to this ideal. ''' s = self.pset; G = s.list; if isinstance(p,RingElem): p = p.elem; n = SolvableReductionSeq().rightNormalform(G,p); return RingElem(n); def parLeftGB(self,th): '''Compute a left Groebner base in parallel. ''' s = self.pset; F = s.list; bbpar = SolvableGroebnerBaseParallel(th); t = System.currentTimeMillis(); G = bbpar.leftGB(F); t = System.currentTimeMillis() - t; bbpar.terminate(); print "parallel %s leftGB executed in %s ms" % (th, t); return SolvableIdeal(self.ring,"",G); def parTwosidedGB(self,th): '''Compute a two-sided Groebner base in parallel. ''' s = self.pset; F = s.list; bbpar = SolvableGroebnerBaseParallel(th); t = System.currentTimeMillis(); G = bbpar.twosidedGB(F); t = System.currentTimeMillis() - t; bbpar.terminate(); print "parallel %s twosidedGB executed in %s ms" % (th, t); return SolvableIdeal(self.ring,"",G); class Module: '''Represents a JAS module over a polynomial ring. Method to create sub-modules. ''' def __init__(self,modstr="",ring=None,cols=0): '''Module constructor. ''' if ring == None: sr = StringReader( modstr ); tok = GenPolynomialTokenizer(sr); self.mset = tok.nextSubModuleSet(); if self.mset.cols >= 0: self.cols = self.mset.cols; else: self.cols = cols; else: self.mset = ModuleList(ring.ring,None); self.cols = cols; self.ring = self.mset.ring; def __str__(self): '''Create a string representation. ''' return str(self.mset.toScript()); def submodul(self,modstr="",list=None): '''Create a sub-module. ''' return SubModule(self,modstr,list); def element(self,poly): '''Create an element from a string or object. ''' if not isinstance(poly,str): try: if self.ring == poly.ring: return RingElem(poly); except Exception, e: pass poly = str(poly); I = SubModule(self, "( " + poly + " )"); list = I.mset.list; if len(list) > 0: return RingElem( list[0] ); def gens(self): '''Get the generators of this module. ''' gm = GenVectorModul(self.ring,self.cols); L = gm.generators(); #for g in L: # print "g = ", str(g); N = [ RingElem(e) for e in L ]; # want use val here, but can not return N; def inject_variables(self): '''Inject generators as variables into the main global namespace ''' inject_generators(self.gens()); class SubModule: '''Represents a JAS sub-module over a polynomial ring. Methods to compute Groebner bases. ''' def __init__(self,module,modstr="",list=None): '''Constructor for a sub-module. ''' self.module = module; if list == None: sr = StringReader( modstr ); tok = GenPolynomialTokenizer(module.ring,sr); self.list = tok.nextSubModuleList(); else: if isinstance(list,PyList) or isinstance(list,PyTuple): if len(list) != 0: if isinstance(list[0],RingElem): list = [ re.elem for re in list ]; self.list = pylist2arraylist(list,self.module.ring,rec=2); else: self.list = list; #print "list = ", str(list); #e = self.list[0]; #print "e = ", e; self.mset = OrderedModuleList(module.ring,self.list); self.cols = self.mset.cols; self.rows = self.mset.rows; #print "list = %s" % self.list; #print "cols = %s" % self.cols; #print "mset = %s" % self.mset.toString(); #print "mset = %s" % self.mset.toScript(); self.pset = self.mset.getPolynomialList(); def __str__(self): '''Create a string representation. ''' return str(self.mset.toScript()); # + "\n\n" + str(self.pset); def GB(self): '''Compute a Groebner base. ''' t = System.currentTimeMillis(); G = ModGroebnerBaseAbstract().GB(self.mset); t = System.currentTimeMillis() - t; print "executed module GB in %s ms" % t; return SubModule(self.module,"",G.list); def isGB(self): '''Test if this is a Groebner base. ''' t = System.currentTimeMillis(); b = ModGroebnerBaseAbstract().isGB(self.mset); t = System.currentTimeMillis() - t; print "module isGB executed in %s ms" % t; return b; ## def isSyzygy(self,g): ## '''Test if this is a syzygy of the polynomials in g. ## ''' ## l = self.list; ## print "l = %s" % l; ## print "g = %s" % g; ## t = System.currentTimeMillis(); ## z = SyzygyAbstract().isZeroRelation( l, g.list ); ## t = System.currentTimeMillis() - t; ## print "executed isSyzygy in %s ms" % t; ## return z; class SolvableModule(Module): '''Represents a JAS module over a solvable polynomial ring. Method to create solvable sub-modules. ''' def __init__(self,modstr="",ring=None,cols=0): '''Solvable module constructor. ''' if ring == None: sr = StringReader( modstr ); tok = GenPolynomialTokenizer(sr); self.mset = tok.nextSolvableSubModuleSet(); if self.mset.cols >= 0: self.cols = self.mset.cols; else: self.mset = ModuleList(ring.ring,None); self.cols = cols; self.ring = self.mset.ring; def __str__(self): '''Create a string representation. ''' return str(self.mset.toScript()); def submodul(self,modstr="",list=None): '''Create a solvable sub-module. ''' return SolvableSubModule(self,modstr,list); def element(self,poly): '''Create an element from a string or object. ''' if not isinstance(poly,str): try: if self.ring == poly.ring: return RingElem(poly); except Exception, e: pass poly = str(poly); I = SolvableSubModule(self, "( " + poly + " )"); list = I.mset.list; if len(list) > 0: return RingElem( list[0] ); class SolvableSubModule: '''Represents a JAS sub-module over a solvable polynomial ring. Methods to compute left, right and two-sided Groebner bases. ''' def __init__(self,module,modstr="",list=None): '''Constructor for sub-module over a solvable polynomial ring. ''' self.module = module; if list == None: sr = StringReader( modstr ); tok = GenPolynomialTokenizer(module.ring,sr); self.list = tok.nextSolvableSubModuleList(); else: if isinstance(list,PyList) or isinstance(list,PyTuple): self.list = pylist2arraylist(list,self.module.ring,rec=2); else: self.list = list; self.mset = OrderedModuleList(module.ring,self.list); self.cols = self.mset.cols; self.rows = self.mset.rows; def __str__(self): '''Create a string representation. ''' return str(self.mset.toScript()); # + "\n\n" + str(self.pset); def leftGB(self): '''Compute a left Groebner base. ''' t = System.currentTimeMillis(); G = ModSolvableGroebnerBaseAbstract().leftGB(self.mset); t = System.currentTimeMillis() - t; print "executed left module GB in %s ms" % t; return SolvableSubModule(self.module,"",G.list); def isLeftGB(self): '''Test if this is a left Groebner base. ''' t = System.currentTimeMillis(); b = ModSolvableGroebnerBaseAbstract().isLeftGB(self.mset); t = System.currentTimeMillis() - t; print "module isLeftGB executed in %s ms" % t; return b; def twosidedGB(self): '''Compute a two-sided Groebner base. ''' t = System.currentTimeMillis(); G = ModSolvableGroebnerBaseAbstract().twosidedGB(self.mset); t = System.currentTimeMillis() - t; print "executed in %s ms" % t; return SolvableSubModule(self.module,"",G.list); def isTwosidedGB(self): '''Test if this is a two-sided Groebner base. ''' t = System.currentTimeMillis(); b = ModSolvableGroebnerBaseAbstract().isTwosidedGB(self.mset); t = System.currentTimeMillis() - t; print "module isTwosidedGB executed in %s ms" % t; return b; def rightGB(self): '''Compute a right Groebner base. ''' t = System.currentTimeMillis(); G = ModSolvableGroebnerBaseAbstract().rightGB(self.mset); t = System.currentTimeMillis() - t; print "executed module rightGB in %s ms" % t; return SolvableSubModule(self.module,"",G.list); def isRightGB(self): '''Test if this is a right Groebner base. ''' t = System.currentTimeMillis(); b = ModSolvableGroebnerBaseAbstract().isRightGB(self.mset); t = System.currentTimeMillis() - t; print "module isRightGB executed in %s ms" % t; return b; class SeriesRing: '''Represents a JAS power series ring: UnivPowerSeriesRing. Methods for univariate power series arithmetic. ''' def __init__(self,ringstr="",truncate=None,ring=None,cofac=None,name="z"): '''Ring constructor. ''' if ring == None: if len(ringstr) > 0: sr = StringReader( ringstr ); tok = GenPolynomialTokenizer(sr); pset = tok.nextPolynomialSet(); ring = pset.ring; vname = ring.vars; name = vname[0]; cofac = ring.coFac; if isinstance(cofac,RingElem): cofac = cofac.elem; if truncate == None: self.ring = UnivPowerSeriesRing(cofac,name); else: self.ring = UnivPowerSeriesRing(cofac,truncate,name); else: self.ring = ring; def __str__(self): '''Create a string representation. ''' return str(self.ring.toScript()); def gens(self): '''Get the generators of the power series ring. ''' L = self.ring.generators(); N = [ RingElem(e) for e in L ]; return N; def inject_variables(self): '''Inject generators as variables into the main global namespace ''' inject_generators(self.gens()); def one(self): '''Get the one of the power series ring. ''' return RingElem( self.ring.getONE() ); def zero(self): '''Get the zero of the power series ring. ''' return RingElem( self.ring.getZERO() ); def random(self,n): '''Get a random power series. ''' return RingElem( self.ring.random(n) ); def exp(self): '''Get the exponential power series. ''' return RingElem( self.ring.getEXP() ); def sin(self): '''Get the sinus power series. ''' return RingElem( self.ring.getSIN() ); def cos(self): '''Get the cosinus power series. ''' return RingElem( self.ring.getCOS() ); def tan(self): '''Get the tangens power series. ''' return RingElem( self.ring.getTAN() ); def create(self,ifunc=None,jfunc=None,clazz=None): '''Create a power series with given generating function. ifunc(int i) must return a value which is used in RingFactory.fromInteger(). jfunc(int i) must return a value of type ring.coFac. clazz must implement the Coefficients abstract class. ''' class coeff( Coefficients ): def __init__(self,cofac): self.coFac = cofac; def generate(self,i): if jfunc == None: return self.coFac.fromInteger( ifunc(i) ); else: return jfunc(i); if clazz == None: ps = UnivPowerSeries( self.ring, coeff(self.ring.coFac) ); else: ps = UnivPowerSeries( self.ring, clazz ); return RingElem( ps ); def fixPoint(self,psmap): '''Create a power series as fixed point of the given mapping. psmap must implement the UnivPowerSeriesMap interface. ''' ps = self.ring.fixPoint( psmap ); return RingElem( ps ); def gcd(self,a,b): '''Compute the greatest common divisor of a and b. ''' if isinstance(a,RingElem): a = a.elem; if isinstance(b,RingElem): b = b.elem; return RingElem( a.gcd(b) ); def fromPoly(self,a): '''Convert a GenPolynomial to a power series. ''' if isinstance(a,RingElem): a = a.elem; return RingElem( self.ring.fromPolynomial(a) ); class MultiSeriesRing: '''Represents a JAS power series ring: MultiVarPowerSeriesRing. Methods for multivariate power series arithmetic. ''' def __init__(self,ringstr="",truncate=None,ring=None,cofac=None,names=None): '''Ring constructor. ''' if ring == None: if len(ringstr) > 0: sr = StringReader( ringstr ); tok = GenPolynomialTokenizer(sr); pset = tok.nextPolynomialSet(); ring = pset.ring; names = ring.vars; cofac = ring.coFac; if isinstance(cofac,RingElem): cofac = cofac.elem; if truncate == None: self.ring = MultiVarPowerSeriesRing(cofac,names); else: self.ring = MultiVarPowerSeriesRing(cofac,len(names),truncate,names); else: self.ring = ring; def __str__(self): '''Create a string representation. ''' return str(self.ring.toScript()); def gens(self): '''Get the generators of the power series ring. ''' L = self.ring.generators(); N = [ RingElem(e) for e in L ]; return N; def inject_variables(self): '''Inject generators as variables into the main global namespace ''' inject_generators(self.gens()); def one(self): '''Get the one of the power series ring. ''' return RingElem( self.ring.getONE() ); def zero(self): '''Get the zero of the power series ring. ''' return RingElem( self.ring.getZERO() ); def random(self,n): '''Get a random power series. ''' return RingElem( self.ring.random(n) ); def exp(self,r): '''Get the exponential power series, var r. ''' return RingElem( self.ring.getEXP(r) ); def sin(self,r): '''Get the sinus power series, var r. ''' return RingElem( self.ring.getSIN(r) ); def cos(self,r): '''Get the cosinus power series, var r. ''' return RingElem( self.ring.getCOS(r) ); def tan(self,r): '''Get the tangens power series, var r. ''' return RingElem( self.ring.getTAN(r) ); def create(self,ifunc=None,jfunc=None,clazz=None): '''Create a power series with given generating function. ifunc(int i) must return a value which is used in RingFactory.fromInteger(). jfunc(int i) must return a value of type ring.coFac. clazz must implement the Coefficients abstract class. ''' class coeff( MultiVarCoefficients ): def __init__(self,r): MultiVarCoefficients.__init__(self,r); self.coFac = r.coFac; def generate(self,i): if jfunc == None: return self.coFac.fromInteger( ifunc(i) ); else: return jfunc(i); #print "ifunc" if clazz == None: ps = MultiVarPowerSeries( self.ring, coeff(self.ring) ); else: ps = MultiVarPowerSeries( self.ring, clazz ); #print "ps ", ps.toScript(); return RingElem( ps ); def fixPoint(self,psmap): '''Create a power series as fixed point of the given mapping. psmap must implement the UnivPowerSeriesMap interface. ''' ps = self.ring.fixPoint( psmap ); return RingElem( ps ); def gcd(self,a,b): '''Compute the greatest common divisor of a and b. ''' if isinstance(a,RingElem): a = a.elem; if isinstance(b,RingElem): b = b.elem; return RingElem( a.gcd(b) ); def fromPoly(self,a): '''Convert a GenPolynomial to a power series. ''' if isinstance(a,RingElem): a = a.elem; return RingElem( self.ring.fromPolynomial(a) ); class PSIdeal: '''Represents a JAS power series ideal. Method for Standard bases. ''' def __init__(self,ring,polylist,ideal=None,list=None): '''PSIdeal constructor. ''' if isinstance(ring,Ring) or isinstance(ring,PolyRing): ring = MultiVarPowerSeriesRing(ring.ring); if isinstance(ring,MultiSeriesRing): ring = ring.ring; self.ring = ring; #print "ring = ", ring.toScript(); if ideal != None: polylist = ideal.pset.list; if list == None: self.polylist = pylist2arraylist( [ a.elem for a in polylist ] ); #print "polylist = ", self.polylist; self.list = self.ring.fromPolynomial(self.polylist); else: self.polylist = None; self.list = pylist2arraylist( [ a.elem for a in list ] ); def __str__(self): '''Create a string representation. ''' ll = [ e.toScript() for e in self.list ] return "( " + ", ".join(ll) + " )"; def STD(self,trunc=None): '''Compute a standard base. ''' pr = self.ring; if trunc != None: pr.setTruncate(trunc); #print "pr = ", pr.toScript(); F = self.list; #print "F = ", F; tm = StandardBaseSeq(); t = System.currentTimeMillis(); S = tm.STD(F); t = System.currentTimeMillis() - t; print "sequential standard base executed in %s ms" % t; #Sp = [ RingElem(a.asPolynomial()) for a in S ]; Sp = [ RingElem(a) for a in S ]; #return Sp; return PSIdeal(self.ring,None,list=Sp); def pylist2arraylist(list,fac=None,rec=1): '''Convert a Python list to a Java ArrayList. If list is a Python list, it is converted, else list is left unchanged. ''' #print "list type(%s) = %s" % (list,type(list)); if isinstance(list,PyList) or isinstance(list,PyTuple): L = ArrayList(); for e in list: t = True; if isinstance(e,RingElem): t = False; e = e.elem; if isinstance(e,PyList) or isinstance(e,PyTuple): if rec <= 1: e = makeJasArith(e); else: t = False; e = pylist2arraylist(e,fac,rec-1); try: n = e.getClass().getSimpleName(); if n == "ArrayList": t = False; except: pass; if t and fac != None: #print "e.p(%s) = %s" % (e,e.getClass().getName()); e = fac.parse( str(e) ); #or makeJasArith(e) ? L.add(e); list = L; #print "list type(%s) = %s" % (list,type(list)); return list def arraylist2pylist(list,rec=1): '''Convert a Java ArrayList to a Python list. If list is a Java ArrayList list, it is converted, else list is left unchanged. ''' #print "list type(%s) = %s" % (list,type(list)); if isinstance(list,List): L = []; for e in list: if not isinstance(e,RingElem): e = RingElem(e); L.append(e); list = L; #print "list type(%s) = %s" % (list,type(list)); return list def makeJasArith(item): '''Construct a jas.arith object. If item is a python tuple or list then a BigRational, BigComplex is constructed. If item is a python float then a BigDecimal is constructed. ''' #print "item type(%s) = %s" % (item,type(item)); if isinstance(item,PyInteger) or isinstance(item,PyLong): return BigInteger( item ); if isinstance(item,PyFloat): # ?? what to do ?? return BigDecimal( str(item) ); if isinstance(item,PyTuple) or isinstance(item,PyList): if len(item) > 2: print "len(item) > 2, remaining items ignored"; #print "item[0] type(%s) = %s" % (item[0],type(item[0])); isc = isinstance(item[0],PyTuple) or isinstance(item[0],PyList) if len(item) > 1: isc = isc or isinstance(item[1],PyTuple) or isinstance(item[1],PyList); if isc: if len(item) > 1: re = makeJasArith( item[0] ); if not re.isField(): re = BigRational( re.val ); im = makeJasArith( item[1] ); if not im.isField(): im = BigRational( im.val ); jasArith = BigComplex( re, im ); else: re = makeJasArith( item[0] ); jasArith = BigComplex( re ); else: if len(item) > 1: jasArith = BigRational( item[0] ).divide( BigRational( item[1] ) ); else: jasArith = BigRational( item[0] ); return jasArith; print "makeJasArith: unknown item type(%s) = %s" % (item,type(item)); return item; def ZZ(z=0): '''Create JAS BigInteger as ring element. ''' if isinstance(z,RingElem): z = z.elem; r = BigInteger(z); return RingElem(r); def ZM(m,z=0,field=False): '''Create JAS ModInteger as ring element. ''' if isinstance(m,RingElem): m = m.elem; if isinstance(z,RingElem): z = z.elem; # if z != 0 and ( z == False ): # never true # field = z; # z = 0; if field: mf = ModIntegerRing(m,field); else: mf = ModIntegerRing(m); r = ModInteger(mf,z); return RingElem(r); def GF(m,z=0): '''Create JAS ModInteger as field element. ''' #print "m = %s" % m return ZM(m,z,True); def QQ(d=0,n=1): '''Create JAS BigRational as ring element. ''' if isinstance(d,PyTuple) or isinstance(d,PyList): if n != 1: print "%s ignored" % n; if len(d) > 1: n = d[1]; d = d[0]; if isinstance(d,RingElem): d = d.elem; if isinstance(n,RingElem): n = n.elem; if n == 1: if d == 0: r = BigRational(); else: r = BigRational(d); else: d = BigRational(d); n = BigRational(n); r = d.divide(n); # BigRational(d,n); only for short integers return RingElem(r); def CC(re=BigRational(),im=BigRational()): '''Create JAS BigComplex as ring element. ''' if re == 0: re = BigRational(); if im == 0: im = BigRational(); if isinstance(re,PyTuple) or isinstance(re,PyList): if isinstance(re[0],PyTuple) or isinstance(re[0],PyList): if len(re) > 1: im = QQ( re[1] ); re = QQ( re[0] ); else: re = QQ(re); # re = makeJasArith( re ); if isinstance(im,PyTuple) or isinstance(im,PyList): im = QQ( im ); # im = makeJasArith( im ); if isinstance(re,RingElem): re = re.elem; if isinstance(im,RingElem): im = im.elem; if im.isZERO(): if re.isZERO(): c = BigComplex(); else: c = BigComplex(re); else: c = BigComplex(re,im); return RingElem(c); def CR(re=BigRational(),im=BigRational(),ring=None): '''Create JAS generic Complex as ring element. ''' if re == 0: re = BigRational(); if im == 0: im = BigRational(); if isinstance(re,PyTuple) or isinstance(re,PyList): if isinstance(re[0],PyTuple) or isinstance(re[0],PyList): if len(re) > 1: im = QQ( re[1] ); re = QQ( re[0] ); else: re = QQ(re); # re = makeJasArith( re ); if isinstance(im,PyTuple) or isinstance(im,PyList): im = QQ( im ); # im = makeJasArith( im ); if isinstance(re,RingElem): re = re.elem; if isinstance(im,RingElem): im = im.elem; if ring == None: ring = re.factory(); r = ComplexRing(ring); #print "d type(%s) = %s" % (r,type(r)); if im.isZERO(): if re.isZERO(): c = Complex(r); else: c = Complex(r,re); else: c = Complex(r,re,im); #print "d type(%s) = %s" % (c,type(c)); return RingElem(c); def DD(d=0): '''Create JAS BigDecimal as ring element. ''' if isinstance(d,RingElem): d = d.elem; if isinstance(d,PyFloat): d = str(d); #print "d type(%s) = %s" % (d,type(d)); if d == 0: r = BigDecimal(); else: r = BigDecimal(d); return RingElem(r); def Quat(re=BigRational(),im=BigRational(),jm=BigRational(),km=BigRational()): '''Create JAS BigQuaternion as ring element. ''' if re == 0: re = BigRational(); if im == 0: im = BigRational(); if jm == 0: jm = BigRational(); if km == 0: km = BigRational(); if isinstance(re,PyTuple) or isinstance(re,PyList): if isinstance(re[0],PyTuple) or isinstance(re[0],PyList): if len(re) > 1: im = QQ( re[1] ); re = QQ( re[0] ); else: re = QQ(re); # re = makeJasArith( re ); if isinstance(im,PyTuple) or isinstance(im,PyList): im = QQ( im ); if isinstance(jm,PyTuple) or isinstance(jm,PyList): jm = QQ( jm ); if isinstance(km,PyTuple) or isinstance(km,PyList): kim = QQ( km ); # im = makeJasArith( im ); if isinstance(re,RingElem): re = re.elem; if isinstance(im,RingElem): im = im.elem; if isinstance(jm,RingElem): jm = jm.elem; if isinstance(km,RingElem): km = km.elem; c = BigQuaternion(re,im,jm,km); return RingElem(c); def Oct(ro=BigQuaternion(),io=BigQuaternion()): '''Create JAS BigOctonion as ring element. ''' if ro == 0: ro = BigQuaternion(); if io == 0: io = BigQuaternion(); if isinstance(ro,PyTuple) or isinstance(ro,PyList): if isinstance(ro[0],PyTuple) or isinstance(ro[0],PyList): if len(ro) > 1: io = QQ( ro[1] ); ro = QQ( ro[0] ); else: ro = QQ(ro); # re = makeJasArith( re ); if isinstance(io,PyTuple) or isinstance(io,PyList): io = QQ( io ); # im = makeJasArith( im ); if isinstance(ro,RingElem): ro = ro.elem; if isinstance(io,RingElem): io = io.elem; c = BigOctonion(ro,io); return RingElem(c); def AN(m,z=0,field=False,pr=None): '''Create JAS AlgebraicNumber as ring element. ''' if isinstance(m,RingElem): m = m.elem; if isinstance(z,RingElem): z = z.elem; # if z != 0 and ( z == True or z == False ): # not working # field = z; # z = 0; #print "m.getClass() = " + str(m.getClass().getName()); #print "field = " + str(field); if m.getClass().getSimpleName() == "AlgebraicNumber": mf = AlgebraicNumberRing(m.factory().modul,m.factory().isField()); else: if field: mf = AlgebraicNumberRing(m,field); else: mf = AlgebraicNumberRing(m); #print "mf = " + mf.toString(); if z == 0: r = AlgebraicNumber(mf); else: r = AlgebraicNumber(mf,z); return RingElem(r); def RealN(m,i,r=0): '''Create JAS RealAlgebraicNumber as ring element. ''' if isinstance(m,RingElem): m = m.elem; if isinstance(r,RingElem): r = r.elem; if isinstance(i,PyTuple) or isinstance(i,PyList): il = BigRational(i[0]); ir = BigRational(i[1]); i = Interval(il,ir); #print "m.getClass() = " + str(m.getClass().getName()); if m.getClass().getSimpleName() == "RealAlgebraicNumber": mf = RealAlgebraicRing(m.factory().algebraic.modul,i); else: mf = RealAlgebraicRing(m,i); if r == 0: rr = RealAlgebraicNumber(mf); else: rr = RealAlgebraicNumber(mf,r); return RingElem(rr); def RF(pr,d=0,n=1): '''Create JAS rational function Quotient as ring element. ''' if isinstance(d,PyTuple) or isinstance(d,PyList): if n != 1: print "%s ignored" % n; if len(d) > 1: n = d[1]; d = d[0]; if isinstance(d,RingElem): d = d.elem; if isinstance(n,RingElem): n = n.elem; if isinstance(pr,RingElem): pr = pr.elem; if isinstance(pr,Ring): pr = pr.ring; qr = QuotientRing(pr); if d == 0: r = Quotient(qr); else: if n == 1: r = Quotient(qr,d); else: r = Quotient(qr,d,n); return RingElem(r); def RC(ideal,r=0): '''Create JAS polynomial Residue as ring element. ''' if ideal == None: raise ValueError, "No ideal given." if isinstance(ideal,Ideal): ideal = jas.application.Ideal(ideal.pset); #ideal.doGB(); #print "ideal.getList().get(0).ring.ideal = %s" % ideal.getList().get(0).ring.ideal; if ideal.getList().get(0).ring.getClass().getSimpleName() == "ResidueRing": rc = ResidueRing( ideal.getList().get(0).ring.ideal ); else: rc = ResidueRing(ideal); if isinstance(r,RingElem): r = r.elem; if r == 0: r = Residue(rc); else: r = Residue(rc,r); return RingElem(r); def LC(ideal,d=0,n=1): '''Create JAS polynomial Local as ring element. ''' if ideal == None: raise ValueError, "No ideal given." if isinstance(ideal,Ideal): ideal = jas.application.Ideal(ideal.pset); #ideal.doGB(); #print "ideal.getList().get(0).ring.ideal = %s" % ideal.getList().get(0).ring.ideal; if ideal.getList().get(0).ring.getClass().getSimpleName() == "LocalRing": lc = LocalRing( ideal.getList().get(0).ring.ideal ); else: lc = LocalRing(ideal); if isinstance(d,PyTuple) or isinstance(d,PyList): if n != 1: print "%s ignored" % n; if len(d) > 1: n = d[1]; d = d[0]; if isinstance(d,RingElem): d = d.elem; if isinstance(n,RingElem): n = n.elem; if d == 0: r = Local(lc); else: if n == 1: r = Local(lc,d); else: r = Local(lc,d,n); return RingElem(r); def SRF(pr,d=0,n=1): '''Create JAS rational function SolvableQuotient as ring element. ''' if isinstance(d,PyTuple) or isinstance(d,PyList): if n != 1: print "%s ignored" % n; if len(d) > 1: n = d[1]; d = d[0]; if isinstance(d,RingElem): d = d.elem; if isinstance(n,RingElem): n = n.elem; if isinstance(pr,RingElem): pr = pr.elem; if isinstance(pr,Ring): pr = pr.ring; qr = SolvableQuotientRing(pr); if d == 0: r = SolvableQuotient(qr); else: if n == 1: r = SolvableQuotient(qr,d); else: r = SolvableQuotient(qr,d,n); return RingElem(r); def SRC(ideal,r=0): '''Create JAS polynomial SolvableResidue as ring element. ''' #print "ideal = " + str(ideal); if ideal == None: # does not work print "ideal = " + str(ideal); if False: raise ValueError, "No ideal given." if isinstance(ideal,SolvableIdeal): ideal = jas.application.SolvableIdeal(ideal.pset); #ideal.doGB(); #print "ideal.getList().get(0).ring.ideal = %s" % ideal.getList().get(0).ring.ideal; if ideal.getList().get(0).ring.getClass().getSimpleName() == "SolvableResidueRing": rc = SolvableResidueRing( ideal.getList().get(0).ring.ideal ); else: rc = SolvableResidueRing(ideal); if isinstance(r,RingElem): r = r.elem; if r == 0: r = SolvableResidue(rc); else: r = SolvableResidue(rc,r); return RingElem(r); def SLC(ideal,d=0,n=1): '''Create JAS polynomial SolvableLocal as ring element. ''' if ideal == None: #print "ideal = " + str(ideal); if False: raise ValueError, "No ideal given." if isinstance(ideal,SolvableIdeal): ideal = jas.application.SolvableIdeal(ideal.pset); #ideal.doGB(); #print "ideal.getList().get(0).ring.ideal = %s" % ideal.getList().get(0).ring.ideal; if ideal.getList().get(0).ring.getClass().getSimpleName() == "SolvableLocalRing": lc = SolvableLocalRing( ideal.getList().get(0).ring.ideal ); else: lc = SolvableLocalRing(ideal); if isinstance(d,PyTuple) or isinstance(d,PyList): if n != 1: print "%s ignored" % n; if len(d) > 1: n = d[1]; d = d[0]; if isinstance(d,RingElem): d = d.elem; if isinstance(n,RingElem): n = n.elem; if d == 0: r = SolvableLocal(lc); else: if n == 1: r = SolvableLocal(lc,d); else: r = SolvableLocal(lc,d,n); return RingElem(r); def SLR(ideal,d=0,n=1): '''Create JAS polynomial SolvableLocalResidue as ring element. ''' if ideal == None: #print "ideal = " + str(ideal); if False: raise ValueError, "No ideal given." if isinstance(ideal,SolvableIdeal): ideal = jas.application.SolvableIdeal(ideal.pset); #ideal.doGB(); #print "ideal.getList().get(0).ring.ideal = %s" % ideal.getList().get(0).ring.ideal; cfr = ideal.getList().get(0).ring; if cfr.getClass().getSimpleName() == "SolvableLocalResidueRing": lc = SolvableLocalResidueRing( cfr.ideal ); else: lc = SolvableLocalResidueRing(ideal); if isinstance(d,PyTuple) or isinstance(d,PyList): if n != 1: print "%s ignored" % n; if len(d) > 1: n = d[1]; d = d[0]; if isinstance(d,RingElem): d = d.elem; if isinstance(n,RingElem): n = n.elem; if d == 0: r = SolvableLocalResidue(lc); else: if n == 1: r = SolvableLocalResidue(lc,d); else: r = SolvableLocalResidue(lc,d,n); return RingElem(r); def RR(flist,n=1,r=0): '''Create JAS regular ring Product as ring element. ''' if not isinstance(n,PyInteger): r = n; n = 1; if flist == None: raise ValueError, "No list given." if isinstance(flist,PyList) or isinstance(flist,PyTuple): flist = pylist2arraylist( [ x.factory() for x in flist ], rec=1); ncop = 0; else: ncop = n; if isinstance(flist,RingElem): flist = flist.elem; flist = flist.factory(); ncop = n; #print "flist = " + str(flist); #print "ncop = " + str(ncop); if ncop == 0: pr = ProductRing(flist); else: pr = ProductRing(flist,ncop); #print "r type(%s) = %s" % (r,type(r)); if isinstance(r,RingElem): r = r.elem; try: #print "r.class() = %s" % r.getClass().getSimpleName(); if r.getClass().getSimpleName() == "Product": #print "r.val = %s" % r.val; r = r.val; except: pass; #print "r = " + str(r); if r == 0: r = Product(pr); else: r = Product(pr,r); return RingElem(r); def PS(cofac,name,f=None,truncate=None): '''Create JAS UnivPowerSeries as ring element. ''' cf = cofac; if isinstance(cofac,RingElem): cf = cofac.elem.factory(); if isinstance(cofac,Ring): cf = cofac.ring; if isinstance(truncate,RingElem): truncate = truncate.elem; if truncate == None: ps = UnivPowerSeriesRing(cf,name); else: ps = UnivPowerSeriesRing(cf,truncate,name); if f == None: r = ps.getZERO(); else: class Coeff( Coefficients ): def __init__(self,cofac): self.coFac = cofac; def generate(self,i): a = f(i); if isinstance(a,RingElem): a = a.elem; #print "a = " + str(a); return a; r = UnivPowerSeries(ps,Coeff(cf)); return RingElem(r); def MPS(cofac,names,f=None,truncate=None): '''Create JAS MultiVarPowerSeries as ring element. ''' cf = cofac; if isinstance(cofac,RingElem): cf = cofac.elem.factory(); if isinstance(cofac,Ring): cf = cofac.ring; vars = names; if isinstance(vars,PyString): vars = GenPolynomialTokenizer.variableList(vars); nv = len(vars); if isinstance(truncate,RingElem): truncate = truncate.elem; if truncate == None: ps = MultiVarPowerSeriesRing(cf,nv,vars); else: ps = MultiVarPowerSeriesRing(cf,nv,vars,truncate); if f == None: r = ps.getZERO(); else: class MCoeff( MultiVarCoefficients ): def __init__(self,r): MultiVarCoefficients.__init__(self,r); self.coFac = r.coFac; def generate(self,i): a = f(i); if isinstance(a,RingElem): a = a.elem; return a; r = MultiVarPowerSeries(ps,MCoeff(ps)); #print "r = " + str(r); return RingElem(r); def Vec(cofac,n,v=None): '''Create JAS GenVector ring element. ''' cf = cofac; if isinstance(cofac,RingElem): cf = cofac.elem.factory(); if isinstance(cofac,Ring): cf = cofac.ring; if isinstance(n,RingElem): n = n.elem; if isinstance(v,RingElem): v = v.elem; vr = GenVectorModul(cf,n); if v == None: r = GenVector(vr); else: r = GenVector(vr,v); return RingElem(r); def Mat(cofac,n,m,v=None): '''Create JAS GenMatrix ring element. ''' cf = cofac; if isinstance(cofac,RingElem): cf = cofac.elem.factory(); if isinstance(cofac,Ring): cf = cofac.ring; if isinstance(n,RingElem): n = n.elem; if isinstance(m,RingElem): m = m.elem; if isinstance(v,RingElem): v = v.elem; #print "cf type(%s) = %s" % (cf,type(cf)); mr = GenMatrixRing(cf,n,m); if v == None: r = GenMatrix(mr); else: r = GenMatrix(mr,v); return RingElem(r); def coercePair(a,b): '''Coerce type a to type b or type b to type a. ''' #print "a type(%s) = %s" % (a,type(a)); #print "b type(%s) = %s" % (b,type(b)); try: if not a.isPolynomial() and b.isPolynomial(): s = b.coerce(a); o = b; else: s = a; o = a.coerce(b); except: s = a; o = a.coerce(b); return (s,o); def isJavaInstance(a): '''Test if a is a Java instance. ''' #print "a type(%s) = %s" % (a,type(a)); try: c = a.getClass(); except: return False; return True; class RingElem: '''Proxy for JAS ring elements. Methods to be used as + - * ** / %. ''' def __init__(self,elem): '''Constructor for ring element. ''' if isinstance(elem,RingElem): self.elem = elem.elem; else: self.elem = elem; try: self.ring = self.elem.factory(); except: self.ring = self.elem; def __str__(self): '''Create a string representation. ''' return str(self.elem.toScript()); def zero(self): '''Zero element of this ring. ''' return RingElem( self.ring.getZERO() ); def isZERO(self): '''Test if this is the zero element of the ring. ''' return self.elem.isZERO(); def one(self): '''One element of this ring. ''' return RingElem( self.ring.getONE() ); def isONE(self): '''Test if this is the one element of the ring. ''' return self.elem.isONE(); def signum(self): '''Get the sign of this element. ''' return self.elem.signum(); def __abs__(self): '''Absolute value. ''' return RingElem( self.elem.abs() ); def __neg__(self): '''Negative value. ''' return RingElem( self.elem.negate() ); def __pos__(self): '''Positive value. ''' return self; def coerce(self,other): '''Coerce other to self. ''' #print "self type(%s) = %s" % (self,type(self)); #print "other type(%s) = %s" % (other,type(other)); #print "self.elem class(%s) = %s" % (self.elem,self.elem.getClass()); if self.elem.getClass().getSimpleName() == "GenVector": #print "self, other = %s, %s " % (self,other); if isinstance(other,PyTuple) or isinstance(other,PyList): o = pylist2arraylist(other,self.elem.factory().coFac,rec=1); o = GenVector(self.elem.factory(),o); return RingElem( o ); if self.elem.getClass().getSimpleName() == "GenMatrix": #print "self, other = %s, %s " % (type(self),type(other)); #print "o type(%s) = %s, str = %s" % (o,type(o),str(o)); if isinstance(other,PyTuple) or isinstance(other,PyList): o = pylist2arraylist(other,self.elem.factory().coFac,rec=2); o = GenMatrix(self.elem.factory(),o); return RingElem( o ); if self.elem.getClass().getSimpleName() == "GenPolynomial": #print "self, other = %s, %s " % (type(self),type(other)); #print "o type(%s) = %s, str = %s" % (o,type(o),str(o)); if isinstance(other,PyInteger) or isinstance(other,PyLong): o = self.ring.fromInteger(other); return RingElem( o ); if isinstance(other,RingElem): o = other.elem; else: o = other; if o == None: return RingElem( GenPolynomial(self.ring) ) if isJavaInstance(o): #print "self.elem, o = %s, %s " % (type(self.ring.coFac),type(o)); if o.getClass().getSimpleName() == "ExpVectorLong": # want startsWith or substring(0,8) == "ExpVector": o = GenPolynomial(self.ring,o); return RingElem( o ); if self.ring.coFac.getClass().getSimpleName() == o.getClass().getSimpleName(): o = GenPolynomial(self.ring,o); return RingElem( o ); if isinstance(other,RingElem): if self.isPolynomial() and not other.isPolynomial(): #print "self.ring = %s" % (self.ring); o = self.ring.parse( other.elem.toString() ); # not toScript() #print "o type(%s) = %s, str = %s" % (o,type(o),str(o)); return RingElem( o ); return other; #print "--1"; if isinstance(other,PyTuple) or isinstance(other,PyList): # assume BigRational or BigComplex # assume self will be compatible with them. todo: check this o = makeJasArith(other); #print "other class(%s) = %s" % (o,o.getClass()); if self.isPolynomial(): #print "other type(%s) = %s" % (o,type(o)); o = self.ring.parse( o.toString() ); # not toScript(); #o = o.elem; if self.elem.getClass().getSimpleName() == "BigComplex": #print "other type(%s) = %s" % (o,type(o)); o = CC( o ); o = o.elem; if self.elem.getClass().getSimpleName() == "BigQuaternion": #print "other type(%s) = %s" % (o,type(o)); o = Quat( o ); o = o.elem; if self.elem.getClass().getSimpleName() == "BigOctonion": #print "other type(%s) = %s" % (o,type(o)); o = Oct( Quat(o) ); o = o.elem; if self.elem.getClass().getSimpleName() == "Product": #print "other type(%s) = %s" % (o,type(o)); o = RR(self.ring, self.elem.multiply(o) ); # valueOf #print "o = %s" % o; o = o.elem; return RingElem(o); #print "--2"; # test if self.elem is a factory itself if self.isFactory(): if isinstance(other,PyInteger) or isinstance(other,PyLong): o = self.elem.fromInteger(other); else: if isinstance(other,PyFloat): # ?? what to do ?? o = self.elem.fromInteger( int(other) ); else: print "coerce_1: unknown other type(%s) = %s" % (other,type(other)); o = self.elem.parse( str(other) ); return RingElem(o); #print "--3"; #print "other type(%s) = %s" % (other,type(other)); # self.elem has a ring factory if isinstance(other,PyInteger) or isinstance(other,PyLong): o = self.elem.factory().fromInteger(other); else: if isinstance(other,PyFloat): # ?? what to do ?? #print "other type(%s) = %s" % (other,type(other)); #print "self type(%s) = %s" % (self.elem,self.elem.getClass().getName()); o = BigDecimal(other); if self.elem.getClass().getSimpleName() == "Product": o = RR(self.ring, self.elem.idempotent().multiply(o) ); # valueOf o = o.elem; else: o = self.elem.factory().getZERO().sum( o ); else: print "coerce_2: unknown other type(%s) = %s" % (other,type(other)); print "coerce_2: self type(%s) = %s" % (self,type(self)); o = self.elem.factory().parse( str(other) ); #print "--4"; return RingElem(o); def isFactory(self): '''Test if this is itself a ring factory. ''' f = self.elem.factory(); if self.elem == f: return True; else: return False; def isPolynomial(self): '''Test if this is a polynomial. ''' try: nv = self.elem.ring.nvar; except: return False; return True; def __cmp__(self,other): '''Compare two ring elements. ''' [s,o] = coercePair(self,other); return s.elem.compareTo( o.elem ); def __hash__(self): '''Hash value. ''' return self.elem.hashCode(); def __len__(self): '''Length of the element. ''' return self.elem.length(); def __mul__(self,other): '''Multiply two ring elements. ''' [s,o] = coercePair(self,other); #print "self type(%s) = %s" % (s,type(s)); #print "other type(%s) = %s" % (o,type(o)); return RingElem( s.elem.multiply( o.elem ) ); def __rmul__(self,other): '''Reverse multiply two ring elements. ''' [s,o] = coercePair(self,other); return o.__mul__(s); def __add__(self,other): '''Add two ring elements. ''' [s,o] = coercePair(self,other); return RingElem( s.elem.sum( o.elem ) ); def __radd__(self,other): '''Reverse add two ring elements. ''' [s,o] = coercePair(self,other); return o.__add__(s); def __sub__(self,other): '''Subtract two ring elements. ''' [s,o] = coercePair(self,other); return RingElem( s.elem.subtract( o.elem ) ); def __rsub__(self,other): '''Reverse subtract two ring elements. ''' [s,o] = coercePair(self,other); return o.__sub__(self); def __div__(self,other): '''Divide two ring elements. ''' [s,o] = coercePair(self,other); return RingElem( s.elem.divide( o.elem ) ); def __rdiv__(self,other): '''Reverse divide two ring elements. ''' [s,o] = coercePair(self,other); return o.__div__(s); def __mod__(self,other): '''Modular remainder of two ring elements. ''' [s,o] = coercePair(self,other); return RingElem( s.elem.remainder( o.elem ) ); def __xor__(self,other): '''Can not be used as power. ''' return None; def __pow__(self,other,n=None): '''Power of this to other. ''' #print "self type(%s) = %s" % (self,type(self)); #print "pow other type(%s) = %s" % (other,type(other)); if isinstance(other,PyInteger) or isinstance(other,PyLong): n = other; else: if isinstance(other,RingElem): n = other.elem; #if isinstance(n,BigRational): # does not work if n.getClass().getSimpleName() == "BigRational": n = n.numerator().intValue() / n.denominator().intValue(); #if isinstance(n,BigInteger): # does not work if n.getClass().getSimpleName() == "BigInteger": n = n.intValue(); if n == None: n = other; if self.isFactory(): p = Power(self.elem).power( self.elem, n ); else: p = Power(self.ring).power( self.elem, n ); return RingElem( p ); def __eq__(self,other): '''Test if two ring elements are equal. ''' if other == None: return False; [s,o] = coercePair(self,other); return s.elem.equals(o.elem) def __ne__(self,other): '''Test if two ring elements are not equal. ''' if other == None: return False; [s,o] = coercePair(self,other); return not self.elem.equals(o.elem) def __float__(self): '''Convert to Python float. ''' #print "self type(%s) = %s" % (self,type(self)); e = self.elem; if e.getClass().getSimpleName() == "BigInteger": e = BigRational(e); if e.getClass().getSimpleName() == "BigRational": e = BigDecimal(e); if e.getClass().getSimpleName() == "BigDecimal": e = e.toString(); e = float(e); return e; def factory(self): '''Get the factory of this element. ''' fac = self.elem.factory(); try: nv = fac.nvar; except: return RingElem(fac); #return PolyRing(fac.coFac,fac.getVars(),fac.tord); return RingElem(fac); def gens(self): '''Get the generators for the factory of this element. ''' L = self.elem.factory().generators(); #print "L = %s" % L; N = [ RingElem(e) for e in L ]; #print "N = %s" % N; return N; def inject_variables(self): '''Inject generators as variables into the main global namespace ''' inject_generators(self.gens()); def monic(self): '''Monic polynomial. ''' return RingElem( self.elem.monic() ); def evaluate(self,a): '''Evaluate at a for power series. ''' #print "self type(%s) = %s" % (self,type(self)); #print "a type(%s) = %s" % (a,type(a)); x = None; if isinstance(a,RingElem): x = a.elem; if isinstance(a,PyTuple) or isinstance(a,PyList): # assume BigRational or BigComplex # assume self will be compatible with them. todo: check this x = makeJasArith(a); try: e = self.elem.evaluate(x); except: e = 0; return RingElem( e ); def integrate(self,a=0,r=None): '''Integrate a power series with constant a or as rational function. a is the integration constant, r is for partial integration in variable r. ''' #print "self type(%s) = %s" % (self,type(self)); #print "a type(%s) = %s" % (a,type(a)); x = None; if isinstance(a,RingElem): x = a.elem; if isinstance(a,PyTuple) or isinstance(a,PyList): # assume BigRational or BigComplex # assume self will be compatible with them. todo: check this x = makeJasArith(a); try: if r != None: e = self.elem.integrate(x,r); else: e = self.elem.integrate(x); return RingElem( e ); except: pass; cf = self.elem.ring; try: cf = cf.ring; except: pass; integrator = ElementaryIntegration(cf.coFac); ei = integrator.integrate(self.elem); return ei; def differentiate(self,r=None): '''Differentiate a power series. r is for partial differentiation in variable r. ''' try: if r != None: e = self.elem.differentiate(r); else: e = self.elem.differentiate(); except: e = self.elem.factory().getZERO(); return RingElem( e ); def coefficients(self): '''Get the coefficients of a polynomial. ''' a = self.elem; #L = [ c.toScriptFactory() for c in a.coefficientIterator() ]; L = [ RingElem(c) for c in a.coefficientIterator() ]; return L #---------------- # Compatibility methods for Sage/Singular: # Note: the meaning of lt and lm is swapped compared to JAS. #---------------- def parent(self): '''Parent in Sage is factory in JAS. Compatibility method for Sage/Singular. ''' return self.factory(); def __call__(self,num): '''Apply this to num. ''' if num == 0: return self.zero(); if num == 1: return self.one(); return RingElem( self.ring.fromInteger(num) ); def lm(self): '''Leading monomial of a polynomial. Compatibility method for Sage/Singular. Note: the meaning of lt and lm is swapped compared to JAS. ''' ev = self.elem.leadingExpVector(); return ev; def lc(self): '''Leading coefficient of a polynomial. Compatibility method for Sage/Singular. ''' c = self.elem.leadingBaseCoefficient(); return RingElem(c); def lt(self): '''Leading term of a polynomial. Compatibility method for Sage/Singular. Note: the meaning of lt and lm is swapped compared to JAS. ''' ev = self.elem.leadingMonomial(); return Monomial(ev); def degree(self): '''Degree of a polynomial. ''' try: ev = self.elem.degree(); except: return None; return ev; def base_ring(self): '''Coefficient ring of a polynomial. ''' try: ev = self.elem.ring.coFac; except: return None; return RingElem(ev); def is_field(self): '''Test if this RingElem is field. ''' return self.elem.isField(); def monomials(self): '''All monomials of a polynomial. Compatibility method for Sage/Singular. ''' ev = self.elem.getMap().keySet(); return ev; def divides(self,other): '''Test if self divides other. Compatibility method for Sage/Singular. ''' [s,o] = coercePair(self,other); return o.elem.remainder( s.elem ).isZERO(); def ideal(self,list): '''Create an ideal. Compatibility method for Sage/Singular. ''' p = Ring("",ring=self.ring,fast=True); return p.ideal("",list=list); def monomial_quotient(self,a,b,coeff=False): '''Quotient of ExpVectors. Compatibility method for Sage/Singular. ''' if isinstance(a,RingElem): a = a.elem; if isinstance(b,RingElem): b = b.elem; if coeff == False: if a.getClass().getSimpleName() == "GenPolynomial": return RingElem( a.divide(b) ); else: return RingElem( GenPolynomial(self.ring, a.subtract(b)) ); else: # assume JAS Monomial c = a.coefficient().divide(b.coefficient()); e = a.exponent().subtract(b.exponent()) return RingElem( GenPolynomial(self.ring, c, e) ); def monomial_divides(self,a,b): '''Test divide of ExpVectors. Compatibility method for Sage/Singular. ''' #print "JAS a = " + str(a) + ", b = " + str(b); if isinstance(a,RingElem): a = a.elem; if a.getClass().getSimpleName() == "GenPolynomial": a = a.leadingExpVector(); if a.getClass().getSimpleName() != "ExpVectorLong": raise ValueError, "No ExpVector given " + str(a) + ", " + str(b) if b == None: return False; if isinstance(b,RingElem): b = b.elem; if b.getClass().getSimpleName() == "GenPolynomial": b = b.leadingExpVector(); if b.getClass().getSimpleName() != "ExpVectorLong": raise ValueError, "No ExpVector given " + str(a) + ", " + str(b) return a.divides(b); def monomial_pairwise_prime(self,e,f): '''Test if ExpVectors are pairwise prime. Compatibility method for Sage/Singular. ''' if isinstance(e,RingElem): e = e.elem; if isinstance(f,RingElem): f = f.elem; # assume JAS ExpVector c = e.gcd(f); return c.isZERO(); def monomial_lcm(self,e,f): '''Lcm of ExpVectors. Compatibility method for Sage/Singular. ''' if isinstance(e,RingElem): e = e.elem; if isinstance(f,RingElem): f = f.elem; # assume JAS ExpVector c = e.lcm(f); return c; def reduce(self,F): '''Compute a normal form of self with respect to F. Compatibility method for Sage/Singular. ''' s = self.elem; Fe = [ e.elem for e in F ]; n = ReductionSeq().normalform(Fe,s); return RingElem(n); #---------------- # End of compatibility methods #---------------- class PolyRing(Ring): '''Represents a JAS polynomial ring: GenPolynomialRing. Provides more convenient constructor. Then returns a Ring. ''' def __init__(self,coeff,vars,order=TermOrder(TermOrder.IGRLEX)): '''Ring constructor. coeff = factory for coefficients, vars = string with variable names, order = term order. ''' if coeff == None: raise ValueError, "No coefficient given." cf = coeff; if isinstance(coeff,RingElem): cf = coeff.elem.factory(); if isinstance(coeff,Ring): cf = coeff.ring; if vars == None: raise ValueError, "No variable names given." names = vars; if isinstance(vars,PyString): names = GenPolynomialTokenizer.variableList(vars); nv = len(names); to = PolyRing.lex; if isinstance(order,TermOrder): to = order; tring = GenPolynomialRing(cf,nv,to,names); #want: super(Ring,self).__init__(ring=tring) Ring.__init__(self,ring=tring) def __str__(self): '''Create a string representation. ''' return self.ring.toScript(); lex = TermOrder(TermOrder.INVLEX) grad = TermOrder(TermOrder.IGRLEX) class SolvPolyRing(SolvableRing): '''Represents a JAS solvable polynomial ring: GenSolvablePolynomialRing. Provides more convenient constructor. Then returns a Ring. ''' def __init__(self,coeff,vars,order=PolyRing.lex,rel=None): '''Ring constructor. coeff = factory for coefficients, vars = string with variable names, order = term order, rel = triple list of relations. (e,f,p,...) with e * f = p as relation and e, f and p are commutative polynomials. ''' if coeff == None: raise ValueError, "No coefficient given." cf = coeff; if isinstance(coeff,RingElem): cf = coeff.elem.factory(); if isinstance(coeff,Ring): cf = coeff.ring; if vars == None: raise ValueError, "No variable names given." names = vars; if isinstance(vars,PyString): names = GenPolynomialTokenizer.variableList(vars); nv = len(names); to = PolyRing.lex; if isinstance(order,TermOrder): to = order; L = []; for x in rel: if isinstance(x,RingElem): x = x.elem; L.append(x); constSolv = False; for i in range(0,len(L),3): #print "L[i+1] = " + str(L[i+1]); if L[i+1].isConstant(): constSolv = True; #print "cf = " + str(cf.getClass().getSimpleName()); recSolv = cf.getClass().getSimpleName() == "GenPolynomialRing"; quotSolv = cf.getClass().getSimpleName() == "SolvableQuotientRing"; resSolv = cf.getClass().getSimpleName() == "SolvableResidueRing"; locSolv = cf.getClass().getSimpleName() == "SolvableLocalRing"; locresSolv = cf.getClass().getSimpleName() == "SolvableLocalResidueRing"; if recSolv: ring = RecSolvablePolynomialRing(cf,nv,to,names); table = ring.table; coeffTable = ring.coeffTable; else: if resSolv: ring = ResidueSolvablePolynomialRing(cf,nv,to,names); table = ring.table; coeffTable = ring.polCoeff.coeffTable; else: if quotSolv: ring = QuotSolvablePolynomialRing(cf,nv,to,names); table = ring.table; coeffTable = ring.polCoeff.coeffTable; else: if locSolv: ring = LocalSolvablePolynomialRing(cf,nv,to,names); table = ring.table; coeffTable = ring.polCoeff.coeffTable; else: if locresSolv: ring = QLRSolvablePolynomialRing(cf,nv,to,names); table = ring.table; coeffTable = ring.polCoeff.coeffTable; else: ring = GenSolvablePolynomialRing(cf,nv,to,names); table = ring.table; coeffTable = table; if L != []: #print "rel = " + str(L); for i in range(0,len(L),3): #print "adding relation: " + str(L[i]) + " * " + str(L[i+1]) + " = " + str(L[i+2]); if recSolv and L[i+1].isConstant(): coeffTable.update( L[i], L[i+1], L[i+2] ); else: if resSolv and L[i+1].isConstant(): coeffTable.update(ring.toPolyCoefficients(L[i]), ring.toPolyCoefficients(L[i+1]), ring.toPolyCoefficients(L[i+2]) ); else: if quotSolv and L[i+1].isConstant(): coeffTable.update(ring.toPolyCoefficients(L[i]), ring.toPolyCoefficients(L[i+1]), ring.toPolyCoefficients(L[i+2]) ); else: if locSolv and L[i+1].isConstant(): coeffTable.update(ring.toPolyCoefficients(L[i]), ring.toPolyCoefficients(L[i+1]), ring.toPolyCoefficients(L[i+2]) ); else: if locresSolv and L[i+1].isConstant(): coeffTable.update(ring.toPolyCoefficients(L[i]), ring.toPolyCoefficients(L[i+1]), ring.toPolyCoefficients(L[i+2]) ); else: print "L[i], L[i+1], L[i+2]: " + str(L[i]) + ", " + str(L[i+1]) + ", " + str(L[i+2]); table.update( L[i], L[i+1], L[i+2] ); self.ring = ring; SolvableRing.__init__(self,ring=self.ring) def __str__(self): '''Create a string representation. ''' return self.ring.toScript(); class EF: '''Extension field builder. Construction of extension field towers according to the builder pattern. ''' def __init__(self,base): '''Constructor to set base field. ''' if isinstance(base,RingElem): #factory = base.elem; factory = base.ring; else: factory = base; try: factory = self.factory.factory(); except: pass print "extension field factory: " + factory.toScript(); # + " :: " + factory.toString(); #print "d type(%s) = %s" % (factory,type(factory)); if isinstance(factory,ExtensionFieldBuilder): self.builder = factory; else: self.builder = ExtensionFieldBuilder(factory); def __str__(self): '''Create a string representation. ''' return str(self.builder.toScript()); def extend(self,vars,algebraic=None): '''Create an extension field. If algebraic is given as string expression, then an algebraic extension field is constructed, else a transcendental extension field is constructed. ''' if algebraic == None: ef = self.builder.transcendentExtension(vars); else: ef = self.builder.algebraicExtension(vars,algebraic); return EF(ef.build()); def realExtend(self,vars,algebraic,interval): '''Create a real extension field. Construct a real algebraic extension field with an isolating interval for a real root. ''' ef = self.builder.realAlgebraicExtension(vars,algebraic,interval); return EF(ef.build()); def complexExtend(self,vars,algebraic,rectangle): '''Create a complex extension field. Construct a complex algebraic extension field with an isolating rectangle for a complex root. ''' ef = self.builder.complexAlgebraicExtension(vars,algebraic,rectangle); return EF(ef.build()); def polynomial(self,vars): '''Create an polynomial ring extension. ''' ef = self.builder.polynomialExtension(vars); return EF(ef.build()); def build(self): '''Get extension field tower. ''' rf = self.builder.build(); if isinstance(rf,GenPolynomialRing): return PolyRing(rf.coFac,rf.getVars(),rf.tord); else: return RingElem(rf.getZERO()); class WordRing(Ring): '''Represents a JAS free non-commutative polynomial ring: GenWordPolynomialRing. Has a method to create word ideals. <b>Note:</b> watch your step: check that jython does not reorder multiplication. ''' def __init__(self,ringstr="",ring=None): '''Word polynomial ring constructor. ''' if ring == None: raise ValueError, "parse of word polynomials not implemented" sr = StringReader( ringstr ); tok = GenPolynomialTokenizer(sr); self.pset = tok.nextWordPolynomialSet(); self.ring = self.pset.ring; else: self.ring = ring; #if not self.ring.isAssociative(): # print "warning: ring is not associative"; def __str__(self): '''Create a string representation. ''' return str(self.ring.toScript()); def ideal(self,ringstr="",list=None): '''Create a word ideal. ''' return WordIdeal(self,ringstr,list); def one(self): '''Get the one of the word polynomial ring. ''' return RingElem( self.ring.getONE() ); def zero(self): '''Get the zero of the word polynomial ring. ''' return RingElem( self.ring.getZERO() ); def random(self,n): '''Get a random word polynomial. ''' return RingElem( self.ring.random(n) ); def random(self,k,l,d): '''Get a random word polynomial. ''' return RingElem( self.ring.random(k,l,d) ); def element(self,poly): '''Create an element from a string or object. ''' if not isinstance(poly,str): try: if self.ring == poly.ring: return RingElem(poly); except Exception, e: pass poly = str(poly); I = WordIdeal(self, "( " + poly + " )"); list = I.list; if len(list) > 0: return RingElem( list[0] ); class WordPolyRing(WordRing): '''Represents a JAS free non-commutative polynomial ring: GenWordPolynomialRing. Provides more convenient constructor. Then returns a Ring. <b>Note:</b> watch your step: check that jython does not reorder multiplication. ''' def __init__(self,coeff,vars): '''Ring constructor. coeff = factory for coefficients, vars = string with variable names. ''' if coeff == None: raise ValueError, "No coefficient given." cf = coeff; if isinstance(coeff,RingElem): cf = coeff.elem.factory(); if isinstance(coeff,Ring): cf = coeff.ring; if vars == None: raise ValueError, "No variable names given." names = vars; if isinstance(vars,PyString): names = GenPolynomialTokenizer.variableList(vars); wf = WordFactory(names); ring = GenWordPolynomialRing(cf,wf); self.ring = ring; def __str__(self): '''Create a string representation. ''' return self.ring.toScript(); class WordIdeal: '''Represents a JAS word polynomial ideal. Methods for two-sided Groebner basees and others. <b>Note:</b> watch your step: check that jython does not reorder multiplication. ''' def __init__(self,ring,ringstr="",list=None): '''Constructor for an ideal in a word polynomial ring. ''' self.ring = ring; if list == None: raise ValueError, "parse of word polynomials not implemented" sr = StringReader( ringstr ); tok = GenPolynomialTokenizer(ring.ring,sr); self.list = tok.nextSolvablePolynomialList(); else: self.list = pylist2arraylist(list,rec=1); #self.pset = PolynomialList(ring.ring,self.list); def __str__(self): '''Create a string representation. ''' ll = [ e.toScript() for e in self.list ] return "( " + ", ".join(ll) + " )"; def __cmp__(self,other): '''Compare two ideals. ''' t = False; if not isinstance(other,WordIdeal): return t; t = self.list.equals(other.list); return t; def GB(self): '''Compute a two-sided Groebner base. ''' return self.twosidedGB(); def twosidedGB(self): '''Compute a two-sided Groebner base. ''' #s = self.pset; F = self.list; t = System.currentTimeMillis(); G = WordGroebnerBaseSeq().GB(F); t = System.currentTimeMillis() - t; print "executed twosidedGB in %s ms" % t; return WordIdeal(self.ring,"",G); def isGB(self): '''Test if this is a two-sided Groebner base. ''' return self.isTwosidedGB(); def isTwosidedGB(self): '''Test if this is a two-sided Groebner base. ''' #s = self.pset; F = self.list; t = System.currentTimeMillis(); b = WordGroebnerBaseSeq().isGB(F); t = System.currentTimeMillis() - t; print "isTwosidedGB executed in %s ms" % t; return b;
Python
# # jython examples for jas. # $Id$ # import sys from java.lang import System from java.lang import Integer from jas import Ring from jas import PolyRing from jas import Ideal from jas import QQ, AN, RF, EF from jas import terminate from jas import startLog # polynomial examples: Yr = EF(QQ()).extend("x,y").extend("z","z^2 + x^2 + y^2 - 1").build(); #print "Yr = " + str(Yr); #print [one,x,y,z] = Yr.gens(); print "one = " + str(one); print "x = " + str(x); print "y = " + str(y); print "z = " + str(z); print; f = (1+z)*(1-z); # / ( x**2 + y**2 ); print "f = " + str(f); print; g = f / (1 - z); print "g = " + str(g); print; #startLog(); terminate();
Python
# # jython examples for jas. # $Id$ # import sys from java.lang import System from java.lang import Integer from jas import Ring from jas import PolyRing from jas import Ideal from jas import QQ, AN, RF from jas import terminate from jas import startLog # polynomial examples: factorization over Q(sqrt(2))(x)(sqrt(x))[y] Q = PolyRing(QQ(),"w2",PolyRing.lex); print "Q = " + str(Q); [e,a] = Q.gens(); #print "e = " + str(e); print "a = " + str(a); root = a**2 - 2; print "root = " + str(root); Q2 = AN(root,field=True); print "Q2 = " + str(Q2.factory()); [one,w2] = Q2.gens(); #print "one = " + str(one); #print "w2 = " + str(w2); print; Qp = PolyRing(Q2,"x",PolyRing.lex); print "Qp = " + str(Qp); [ep,wp,ap] = Qp.gens(); #print "ep = " + str(ep); #print "wp = " + str(wp); #print "ap = " + str(ap); print; Qr = RF(Qp); print "Qr = " + str(Qr.factory()); [er,wr,ar] = Qr.gens(); #print "er = " + str(er); #print "wr = " + str(wr); #print "ar = " + str(ar); print; Qwx = PolyRing(Qr,"wx",PolyRing.lex); print "Qwx = " + str(Qwx); [ewx,wwx,ax,wx] = Qwx.gens(); #print "ewx = " + str(ewx); print "ax = " + str(ax); #print "wwx = " + str(wwx); print "wx = " + str(wx); print; rootx = wx**2 - ax; print "rootx = " + str(rootx); Q2x = AN(rootx,field=True); print "Q2x = " + str(Q2x.factory()); [ex2,w2x2,ax2,wx] = Q2x.gens(); #print "ex2 = " + str(ex2); #print "w2x2 = " + str(w2x2); #print "ax2 = " + str(ax2); #print "wx = " + str(wx); print; Yr = PolyRing(Q2x,"y",PolyRing.lex) print "Yr = " + str(Yr); [e,w2,x,wx,y] = Yr.gens(); print "e = " + str(e); print "w2 = " + str(w2); print "x = " + str(x); print "wx = " + str(wx); print "y = " + str(y); print; f = ( y**2 - x ) * ( y**2 - 2 ); #f = ( y**2 - x )**2 * ( y**2 - 2 )**3; #f = ( y**4 - x * 2 ); #f = ( y**7 - x * 2 ); #f = ( y**2 - 2 ); #f = ( y**2 - x ); #f = ( w2 * y**2 - 1 ); #f = ( y**2 - 1/x ); #f = ( y**2 - (1,2) ); #f = ( y**2 - 1/x ) * ( y**2 - (1,2) ); print "f = ", f; print; #sys.exit(); startLog(); t = System.currentTimeMillis(); G = Yr.factors(f); t = System.currentTimeMillis() - t; #print "G = ", G; #print "factor time =", t, "milliseconds"; #sys.exit(); print "f = ", f; g = one; for h, i in G.iteritems(): if i > 1: print "h**i = ", h, "**" + str(i); else: print "h = ", h; h = h**i; g = g*h; #print "g = ", g; if cmp(f,g) == 0: print "factor time =", t, "milliseconds,", "isFactors(f,g): true" ; else: print "factor time =", t, "milliseconds,", "isFactors(f,g): ", cmp(f,g); print; sys.exit(); t = System.currentTimeMillis(); G = Yr.factors(f); t = System.currentTimeMillis() - t; #print "G = ", G; print "2 factor time =", t, "milliseconds"; t = System.currentTimeMillis(); G = Yr.factors(f); t = System.currentTimeMillis() - t; #print "G = ", G; print "3 factor time =", t, "milliseconds"; #startLog(); terminate();
Python
# # read output of jas GB runs and prepare input for gnuplot # $Id$ # from sys import argv from sys import exit from time import strftime import re; import os from os import system hpat = re.compile(r'(m|d) = (\d+), ppn = (\d+), time = (\d+) milliseconds, (\d+) start-up'); dpat = re.compile(r'(m|d) = (\d+), time = (\d+) milliseconds, (\d+) start-up'); #hpat = re.compile(r'd = (\d+), ppn = (\d+), time = (\d+) milliseconds, (\d+) start-up'); #dpat = re.compile(r'd = (\d+), time = (\d+) milliseconds, (\d+) start-up'); ppat = re.compile(r'time = (\d+) milliseconds'); fpat = re.compile(r'p = (\d+), time = (\d+) milliseconds'); spat = re.compile(r'seq,'); ####fpat = re.compile(r'_p(\d+)\.'); ####spat = re.compile(r'_s\.'); #r0pat = re.compile(r'Pairlist\(#put=(\d+), #rem=(\d+), size=(\d+)\)'); rpat = re.compile(r'Pairlist\(#put=(\d+), #rem=(\d+)\)'); ####r1pat = re.compile(r'pairlist #put = (\d+) #rem = (\d+)'); res = {}; pairs = None; hybrid = False; dist = False; para = False; for fname in argv[1:]: dn = -1; print "file =", fname f = open(fname,"r"); for line in f: pm = rpat.search(line); # pairlist results if pm: print "pair: ", line, np = pm.group(1); nr = pm.group(2); if pairs == None: pairs = ( np, nr ); #print "put = " + np + ", rem = " + nr; continue; ## pm = r0pat.search(line); # pairlist results ## if pm: ## print "pair0: ", line, ## np = pm.group(1); ## nr = pm.group(2); ## if pairs != None: ## pairs = ( np, nr ); ## #print "put = " + np + ", rem = " + nr; ## continue; ma = hpat.search(line); # distributed hybrid results if ma: print "h: ", line, d_h = ma.group(1) print "d_h: ", d_h, dn = int( ma.group(2) ); pp = int( ma.group(3) ); tm = long( ma.group(4) ); su = long( ma.group(5) ); hybrid = True; if not dn in res: res[ dn ] = {}; if pp in res[ dn ]: if 't' in res[ dn ][ pp ]: tx = res[ dn ][ pp ][ 't' ]; if tx < tm: # minimum or maximum tm = tx; su = res[ dn ][ pp ][ 's' ] if 'p' in res[ dn ][ pp ] or 'r' in res[ dn ][ pp ]: pairs = ( res[ dn ][ pp ]['p'], res[ dn ][ pp ]['r'] ); res[ dn ][ pp ] = { 't': tm, 's': su }; if pairs != None: res[ dn ][ pp ]['p'] = pairs[0]; res[ dn ][ pp ]['r'] = pairs[1]; pairs = None; continue; ma = dpat.search(line); # distributed results if ma: print "d: ", line, d_h = ma.group(1) print "d_h: ", d_h, dn = int( ma.group(2) ); pp = 1; tm = long( ma.group(3) ); su = long( ma.group(4) ); dist = True; if not dn in res: res[ dn ] = {}; if pp in res[ dn ]: if 't' in res[ dn ][ pp ]: tx = res[ dn ][ pp ][ 't' ]; if tx < tm: # minimum or maximum tm = tx; su = res[ dn ][ pp ][ 's' ] if 'p' in res[ dn ][ pp ] or 'r' in res[ dn ][ pp ]: pairs = ( res[ dn ][ pp ]['p'], res[ dn ][ pp ]['r'] ); res[ dn ][ pp ] = { 't': tm, 's': su }; if pairs != None: res[ dn ][ pp ]['p'] = pairs[0]; res[ dn ][ pp ]['r'] = pairs[1]; pairs = None; continue; ma = ppat.search(line); # parallel and sequential results if ma: print "p: ", line, tm = long( ma.group(1) ); fm = fpat.search(line); if fm: #print fname dn = 1; pp = int( fm.group(1) ); para = True; else: sm = spat.search(line); if sm: dn = 1; pp = 0; else: print "invalid: ", line, dn = -1; pp = -1; if not dn in res: res[ dn ] = {}; if pp in res[ dn ]: if 't' in res[ dn ][ pp ]: tx = res[ dn ][ pp ][ 't' ]; if tx < tm: # minimum or maximum tm = tx; if 'p' in res[ dn ][ pp ] or 'r' in res[ dn ][ pp ]: pairs = ( res[ dn ][ pp ]['p'], res[ dn ][ pp ]['r'] ); res[ dn ][ pp ] = { 't': tm, 's': '0' }; if pairs != None: res[ dn ][ pp ]['p'] = pairs[0]; res[ dn ][ pp ]['r'] = pairs[1]; pairs = None; print "\nres = ", res; ks = res.keys(); #print "ks = ", ks; ks.sort(); print "ks = ", ks; kpp = []; for d in ks: kdd = res[d].keys(); for dd in kdd: if dd not in kpp: kpp.append(dd); kpp.sort(); print "kpp = ", kpp; for d in ks: rd = res[d].keys(); rd.sort(); for p in rd: print " " + str(d) + "," + str(p) + " & " + str(res[d][p]['t']) + " & " + str(res[d][p]['s']) s1 = ks[0]; if s1 == 0: rxx = res.keys(); rxr = rxx[1]; rk = res[rxr].keys(); rk.sort(); p1 = rk[0]; st = int( res[ rxr ][ p1 ]['t'] ); else: rk = res[s1].keys(); rk.sort(); p1 = rk[0]; st = int( res[ s1 ][ p1 ]['t'] ); print "s1 = ", s1; print "p1 = ", p1; print "st = ", st; speed = {}; for k in ks: speed[k] = {}; rk = res[k].keys(); rk.sort(); for p in rk: speed[k][p] = st / float(res[k][p]['t']); print "speed = ", speed; bname = "kat_"; tag = argv[1]; bname = tag; i = tag.find("/"); if i >= 0: bname = tag[:i]; i = bname.find(".out"); if i >= 0: bname = tag[:i]; print "bname = " + bname; # LaTex output: summary = "\n% run = " + tag + "\n"; summary += r"\begin{tabular}{|r|r|r|r|r|r|}" + "\n"; summary += r"\hline" + "\n"; summary += " nodes & ppn & time & speedup & put & rem \n"; summary += r"\\ \hline" + "\n"; for d in ks: rd = res[d].keys(); rd.sort(); for p in rd: #if res[d][p]['s'] != "0": # summary += " " + str(d) + " & " + str(p) + " & " + str(res[d][p]['t']) + " & " + str(res[d][p]['s']) + " & " + str(speed[d][p])[:4]; #else: # summary += " " + str(d) + " & " + str(p) + " & " + str(res[d][p]['t']) + " & " + " & " + str(speed[d][p])[:4]; summary += " " + str(d) + " & " + str(p) + " & " + str(res[d][p]['t']) + " & " + str(speed[d][p])[:4]; if 'p' in res[d][p] and 'r' in res[d][p]: summary += " & " + str(res[d][p]['p']) + " & " + str(res[d][p]['r']) + "\n" else: summary += " & " + " & " + "\n" summary += r"\\ \hline" + "\n"; summary += r"\end{tabular}" + "\n"; print summary; tname = bname+".tex"; tt=open(tname,"w"); tt.write(summary); tt.close(); # output for 2-d gnuplot: oname = bname+".po"; o=open(oname,"w"); ploting = "\n#nodes #ppn time speedup ideal\n"; for k in ks: rk = res[k].keys(); rk.sort(); for p in rk: ideals = k*p; if ideals == 0: ideals = 1; ploting += str(k) + " " + str(p) + " " + str(res[k][p]['t']) + " " + str(speed[k][p]) + " " + str(ideals) + "\n"; ploting += "\n"; print ploting; o.write(ploting); o.close(); # output for 1-d gnuplot, colums for nodes: oname = bname+"_p.po"; o=open(oname,"w"); ploting = "\n#ppn time p, time d1, time d2, ... \n"; for p in kpp: ploting += str(p); for k in ks: #print "p = " + str(p) + ", k = " + str(k) if res[k]: if p in res[k]: #ploting += " " + str(float(res[k][p]['t'])/1000.0); ploting += " " + str(speed[k][p]); else: ploting += " -"; ploting += "\n"; #ploting += "\n"; print ploting; o.write(ploting); o.close(); # output for 1-d gnuplot, colums for ppn: oname = bname+"_d.po"; o=open(oname,"w"); ploting = "\n#nodes time ppn1, time ppn2, time ppn3, ... \n"; for k in ks: ploting += str(k); for p in kpp: #print "p = " + str(p) + ", k = " + str(k) if res[k]: if p in res[k]: #ploting += " " + str(float(res[k][p]['t'])/1000.0); ploting += " " + str(speed[k][p]); else: ploting += " -"; ploting += "\n"; #ploting += "\n"; print ploting; o.write(ploting); o.close(); #exit(); #--------------------------------------- pscript_2d = """ set grid set terminal x11 set title "Groebner bases on a grid cluster, distributed hybrid version" set time set xlabel "number of nodes" set ylabel "threads per node" set xrange [0:7] set yrange [0:7] #reverse #set clip two set xtics 1.0 set ytics 1.0 set style data lines #set contour base #set surface #set pm3d set dgrid3d set hidden3d set multiplot set size 0.95,0.95 #set size 0.95,0.5 #set origin 0,0.5 set origin 0,0 set datafile missing "-" ##set zlabel "milliseconds" set zlabel "seconds" splot "%s.po" using 1:2:($3/1000) title '%s computing time', "%s.po" using 1:2:( (%s/1000)/($1*$2) ) every ::2 title '%s ideal' #set size 0.95,0.45 #set origin 0,0 #set zlabel "speedup" #splot "%s.po" using 1:2:4 title '%s speedup', "%s.po" using 1:2:(($1*$2)) title '%s ideal' ## every ::2 start from the second line ## smooth acsplines ##with linespoints ##with linespoints ## smooth bezier unset multiplot pause mouse set terminal postscript set output "%s.ps" replot """ #--------------------------------------- #--------------------------------------- pscript_1d = """ set grid set terminal x11 set title "Groebner bases on a grid cluster, distributed version" set time set xlabel "number of nodes" #set xrange [0:8] set xtics 1.0 set style data lines set multiplot set size 0.95,0.5 set origin 0,0.5 #set origin 0,0 ##set ylabel "milliseconds" set ylabel "seconds" # smooth acsplines plot "%s.po" using 1:($3/1000) title '%s computing time', "%s.po" using 1:( (%s/1000)/($5) ) title '%s ideal' #set size 0.95,0.45 set origin 0,0 set ylabel "speedup" # smooth bezier plot "%s.po" using 1:4 title '%s speedup', "%s.po" using 1:(($5)) title '%s ideal' #with linespoints #with linespoints unset multiplot pause mouse set terminal postscript set output "%s.ps" replot """ #--------------------------------------- #--------------------------------------- pscript_1p = """ set grid set terminal x11 set title "Groebner bases on a multi-core computer" set time set xlabel "number of threads" #set xrange [0:8] set xtics 1.0 set style data lines set multiplot set size 0.95,0.5 set origin 0,0.5 #set origin 0,0 ##set ylabel "milliseconds" set ylabel "seconds" # smooth acsplines plot "%s.po" using 2:($3/1000) title '%s computing time', "%s.po" using 2:( (%s/1000)/($5) ) title '%s ideal' #set size 0.95,0.45 set origin 0,0 set ylabel "speedup" # smooth bezier plot "%s.po" using 2:4 title '%s speedup', "%s.po" using 2:(($5)) title '%s ideal' #with linespoints #with linespoints unset multiplot pause mouse set terminal postscript set output "%s.ps" replot """ #--------------------------------------- #--------------------------------------- pscript_d = """ set grid set terminal x11 set title "Groebner bases on a grid cluster, distributed hybrid version" set time set xlabel "number of threads" #set xrange [0:8] set xtics 1.0 set style data lines #set multiplot #set size 0.95,0.5 #set origin 0,0.5 set origin 0,0 ##set ylabel "milliseconds" #set ylabel "seconds" set ylabel "speedup" # smooth acsplines plot "%s.po" using 1:2 title '%s, parallel, n = 1',\ "%s.po" using 1:3 title 'distributed, n = 2',\ "%s.po" using 1:4 title 'distributed, n = 3',\ "%s.po" using 1:5 title 'distributed, n = 4',\ "%s.po" using 1:6 title 'distributed, n = 5',\ "%s.po" using 1:7 title 'distributed, n = 6',\ "%s.po" using 1:8 title 'distributed, n = 7' #with linespoints #unset multiplot pause mouse set terminal postscript set output "%s.ps" replot """ #--------------------------------------- #--------------------------------------- pscript_dp = """ set grid set terminal x11 set title "Groebner bases on a grid cluster, distributed hybrid version" set time set xlabel "number of nodes" #set xrange [0:8] set xtics 1.0 set style data lines #set multiplot #set size 0.95,0.5 #set origin 0,0.5 set origin 0,0 ##set ylabel "milliseconds" #set ylabel "seconds" set ylabel "speedup" # smooth acsplines # 1:2 ignored plot "%s.po" using 1:3 title '%s, ppn = 1',\ "%s.po" using 1:4 title 'ppn = 2',\ "%s.po" using 1:5 title 'ppn = 3',\ "%s.po" using 1:6 title 'ppn = 4',\ "%s.po" using 1:7 title 'ppn = 5',\ "%s.po" using 1:8 title 'ppn = 6',\ "%s.po" using 1:9 title 'ppn = 7',\ "%s.po" using 1:10 title 'ppn = 8' #with linespoints #unset multiplot pause mouse set terminal postscript set output "%s.ps" replot """ #--------------------------------------- exam = bname; psname = bname + ".ps"; pname = "plotin.gp" p=open(pname,"w"); print p; sqt = st; print "seq time = ", sqt; #print "args: %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s. " % ("x11",bname,exam,bname,str(sqt),exam,bname,exam,bname,exam,bname); hyb2d = False; #hyb2d = True t2n = True; # thread to nodes #t2n = False if hybrid: if hyb2d: pscript = pscript_2d % (bname,exam,bname,str(sqt),exam,bname,exam,bname,exam,bname); else: if t2n: oname = bname+"_p"; pscript = pscript_d % (oname,exam,oname,oname,oname,oname,oname,oname,bname); else: oname = bname+"_d"; pscript = pscript_dp % (oname,exam,oname,oname,oname,oname,oname,oname,oname,bname); else: if dist: pscript = pscript_1d % (bname,exam,bname,bname,str(sqt),exam,bname,exam,bname,exam); else: if para: pscript = pscript_1p % (bname,exam,bname,bname,str(sqt),exam,bname,exam,bname,exam); p.write(pscript); p.close(); cmd = "gnuplot " + pname; print "cmd: " + cmd; os.system(cmd); # convert to pdf, better use pstopdf, embed all fonts #cmd = "ps2pdf " + psname; cmd = "epstopdf --autorotate=All --embed " + psname; print "cmd: " + cmd; os.system(cmd);
Python
# # jython examples for jas. # $Id$ # import sys; from jas import Ring from jas import Ideal from edu.jas.arith import ModIntegerRing # example from rose (modified) modular computation #r = Ring( "Mod 19 (U3,U4,A46) L" ); #r = Ring( "Mod 1152921504606846883 (U3,U4,A46) L" ); # 2^60-93 #r = Ring( "Quat(U3,U4,A46) L" ); #r = Ring( "Z(U3,U4,A46) L" ); #r = Ring( "C(U3,U4,A46) L" ); r = Ring( "Rat(A46,U3,U4) G" ); print "Ring: " + str(r); print; ps = """ ( ( U4^4 - 20/7 A46^2 ), ( A46^2 U3^4 + 7/10 A46 U3^4 + 7/48 U3^4 - 50/27 A46^2 - 35/27 A46 - 49/216 ), ( A46^5 U4^3 + 7/5 A46^4 U4^3 + 609/1000 A46^3 U4^3 + 49/1250 A46^2 U4^3 - 27391/800000 A46 U4^3 - 1029/160000 U4^3 + 3/7 A46^5 U3 U4^2 + 3/5 A46^6 U3 U4^2 + 63/200 A46^3 U3 U4^2 + 147/2000 A46^2 U3 U4^2 + 4137/800000 A46 U3 U4^2 - 7/20 A46^4 U3^2 U4 - 77/125 A46^3 U3^2 U4 - 23863/60000 A46^2 U3^2 U4 - 1078/9375 A46 U3^2 U4 - 24353/1920000 U3^2 U4 - 3/20 A46^4 U3^3 - 21/100 A46^3 U3^3 - 91/800 A46^2 U3^3 - 5887/200000 A46 U3^3 - 343/128000 U3^3 ) ) """; f = Ideal( r, ps ); print "Ideal: " + str(f); print; fi = f.toInteger(); print "Ideal: " + str(fi); print; # "1152921504606846883" mf = ModIntegerRing( str(2**60-93), True ); #mf = ModIntegerRing( str(19), True ); fm = fi.toModular( mf ); print "Ideal: " + str(fm); #sys.exit(); rm = fm.GB(); #print "seq Output:", rm; #print; #rg = f.GB(); #print "seq Output:", rg; #print; #rgm = rg.toInteger().toModular(mf); #print "seq Output:", rgm; #print; #e = rm == rgm; #print "e = " + str(e); sys.exit(); #for i in range(1,9): for i in range(1,3): rg = f.parGB(i); #print "par Output:", rg; #print; rg = f.parOldGB(i); #print "par-old Output:", rg; #print; #f.distClient(); # starts in background #rg = f.distGB(i); #print "dist Output:", rg; #print; #sys.exit();
Python
# # jython examples for jas. # $Id$ # import sys; from jas import Ring from jas import Ideal from jas import startLog from jas import terminate # chebyshev polynomial example # T(0) = 1 # T(1) = x # T(n) = 2 * x * T(n-1) - T(n-2) r = Ring( "Z(x) L" ); print "Ring: " + str(r); print; # sage like: with generators for the polynomial ring [one,x] = r.gens(); x2 = 2 * x; N = 10; T = [one,x]; for n in range(2,N): t = x2 * T[n-1] - T[n-2]; T.append( t ); for n in range(0,N): print "T[%s] = %s" % (n,T[n]); print; #sys.exit();
Python
# # jython examples for jas. # $Id$ # from java.lang import System from java.lang import Integer from jas import Ring, PolyRing from jas import terminate from jas import startLog from jas import QQ, DD # polynomial examples: zero dimensional ideals prime and primary decomposition #r = Ring( "Rat(x) L" ); #r = Ring( "Q(x) L" ); r = PolyRing(QQ(),"x,y,z",PolyRing.lex); print "Ring: " + str(r); print; [one,x,y,z] = r.gens(); f1 = (x**2 - 5)**2; f2 = y**2 - 5; f3 = z**3 - y * x ; print "f1 = ", f1; print "f2 = ", f2; print "f3 = ", f3; print; F = r.ideal( list=[f1,f2,f3] ); print "F = ", F; print; startLog(); t = System.currentTimeMillis(); Q = F.primaryDecomp(); t = System.currentTimeMillis() - t; print "Q = ", Q; print; print "primary decomp time =", t, "milliseconds"; print; print "F = ", F; print; #startLog(); terminate();
Python
# # jruby examples for jas. # $Id$ # #from java.lang import System #from java.lang import Integer from jas import SolvableRing, SolvPolyRing, PolyRing from jas import QQ, startLog, SRC, SRF # Weyl coefficient field example r = PolyRing(QQ(),"p1,q1"); #is automatic: [one,p1,q1] = p.gens(); relations = [q1, p1, p1 * q1 + 1 ]; print "relations: = " + str([ str(f) for f in relations ]); print; rp = SolvPolyRing(QQ(), "p1,q1", PolyRing.lex, relations); print "SolvPolyRing: " + str(rp); print; print "gens =" + str([ str(f) for f in rp.gens() ]); #is automatic: one,p1,q1 = rp.gens(); scp = SRF(rp); print "scp = " + str(scp); r2 = PolyRing(scp,"p2,q2"); #is automatic: [one,p1,q1,p2,q2] = r2.gens(); relations2 = [q2, p2, p2 * q2 + 1 ]; print "relations: = " + str([ str(f) for f in relations2 ]); print; rp2 = SolvPolyRing(scp, "p2,q2", PolyRing.lex, relations2); print "SolvPolyRing: " + str(rp2); print; print "gens =" + str([ str(f) for f in rp2.gens() ]); #is automatic: one,q1,p1,q2,p2 = rp2.gens(); f1 = p2 + p1; f2 = q2 - q1; print "f1 = " +str(f1); print "f2 = " +str(f2); f3 = f1 * f2; print "f3 = " +str(f3); f4 = f2 * f1; print "f4 = " +str(f4); ff = [ f4 , f3 ]; print "ff = [" + str([ str(f) for f in ff ]); print #exit(0); ii = rp2.ideal( "", ff ); print "SolvableIdeal: " + str(ii); print; rgl = ii.leftGB(); print "seq left GB: " + str(rgl); print "isLeftGB: " + str(rgl.isLeftGB()); print; rgr = ii.rightGB(); print "seq right GB: " + str(rgr); print "isRightGB: " + str(rgr.isRightGB()); print; #startLog(); rgt = ii.twosidedGB(); print "seq twosided GB: " + str(rgt); print "isTwosidedGB: " + str(rgt.isTwosidedGB()); print; urgt = rgt.univariates(); print "univariate polynomials: " + str([ str(f) for f in urgt ]); print; #h = q1; #h = q2; #h = p2; #h = q2 - p2; #h = q1 * q2 + p1 * p2 - p1 + q1**2 + 1; h = q1 * q2 + p1 * p2 + q1; print "polynomial: " + str(h); hi = rgt.inverse(h); print "inverse polynomial: " + str(hi); print; hhi = h * hi; print "h * hi: " + str(hhi); print "h * hi left-mod rgt: " + str(rgt.leftReduction(hhi)); print "h * hi right-mod rgt: " + str(rgt.rightReduction(hhi)); print;
Python
# # jython examples for jas. # $Id$ # import sys; from java.lang import System from java.lang import Integer from jas import Ring, PolyRing from jas import terminate from jas import startLog from jas import QQ, DD # polynomial examples: real roots over Q for zero dimensional ideal `cyclic5' #r = Ring( "Q(x) L" ); r = PolyRing(QQ(),"a,b,c,d,e",PolyRing.lex); print "Ring: " + str(r); print; [one,a,b,c,d,e] = r.gens(); f1 = a + b + c + d + e; f2 = a*b + b*c + c*d + d*e + e*a; f3 = a*b*c + b*c*d + c*d*e + d*e*a + e*a*b; f4 = a*b*c*d + b*c*d*e + c*d*e*a + d*e*a*b + e*a*b*c; f5 = a*b*c*d*e - 1; print "f1 = ", f1; print "f2 = ", f2; print "f3 = ", f3; print "f4 = ", f4; print "f5 = ", f5; print; F = r.ideal( list=[f1,f2,f3,f4,f5] ); print "F = ", F; print; startLog(); #G = F.GB(); #print "G = ", G; #print; #sys.exit(); t = System.currentTimeMillis(); R = F.realRoots(); t = System.currentTimeMillis() - t; print; print "R = ", R; print; print "real roots: "; F.realRootsPrint() print "real roots time =", t, "milliseconds"; print; print "F = ", F; print; #startLog(); terminate();
Python
# # jython examples for jas. # $Id$ # import sys; from jas import Ring from jas import Ideal from jas import startLog from jas import terminate # Nabashima, ISSAC 2007, example F8 # modified, take care # integral function coefficients #r = Ring( "IntFunc(d, b, a, c) (y,x,w,z) L" ); r = Ring( "IntFunc(d, b, a, c) (y,x,w,z) G" ); #r = Ring( "IntFunc(d, b, c, a) (w,z,y,x) G" ); #r = Ring( "IntFunc(b, c, a) (w,x,z,y) L" ); #r = Ring( "IntFunc(b, c) (z,y,w,x) L" ); #r = Ring( "IntFunc(b) (z,y,w,x) L" ); #r = Ring( "IntFunc(c) (z,y,w,x) L" ); #r = Ring( "IntFunc(c) (z,y,w,x) G" ); print "Ring: " + str(r); print; ps = """ ( ( { c } w^2 + z ), ( { a } x^2 + { b } y ), ( ( x - z )^2 + ( y - w)^2 ), ( { 2 d } x w - { 2 b } y ) ) """; ## ( { 1 } x^2 + { 1 } y ), ## ( { 1 } w^2 + z ), ## ( { 2 } x w - { 2 1 } y ) # ( { 1 } x^2 + { b } y ), # ( { c } w^2 + z ), # ( { a } x^2 + { b } y ), # ( { 2 d } x w - { 2 b } y ) #startLog(); f = r.paramideal( ps ); print "ParamIdeal: " + str(f); print; #startLog(); gs = f.CGBsystem(); gs = f.CGBsystem(); gs = f.CGBsystem(); gs = f.CGBsystem(); print "CGBsystem: " + str(gs); print; terminate(); sys.exit(); bg = gs.isCGBsystem(); if bg: print "isCGBsystem: true"; else: print "isCGBsystem: false"; print; gs = f.CGB(); print "CGB: " + str(gs); print; bg = gs.isCGB(); if bg: print "isCGB: true"; else: print "isCGB: false"; print; terminate(); #------------------------------------------ #sys.exit();
Python
#<A name="xxx"></A> import os.path z=z1=z2='' tree=[] row=[] tab=[] tabs=[] stabs=[] f = open('bookmarks.html', 'r') tSpace = 0 oldtSpace = 0 """ class MyTab: maxCol = 0 oldmaxCol = 0 tabName = '' tab = [] def reset(self): maxCol = 0 oldmaxCol = 0 tabName = '' tab = [] x = MyTab() """ maxCol = 0 oldmaxCol = 0 tabName = '' class MyTab(object): """__init__() functions as the class constructor""" def __init__(self, tabName=None, maxCol=None, tab=None): self.tabName = tabName self.maxCol = maxCol self.tab = tab MyTabList=[] def fx(linea,stringa,inizio,fine): #fx(line,s,0,len(line)) ls= len(stringa)+inizio z=linea[ls:fine].find(stringa) if z!=-1: return z def treeSpace(line): global tSpace,oldtSpace ssZero = '<DL>' zzZero = line.find(ssZero) if zzZero != -1: tSpace += 1 ssOne = '</DL>' zzOne = line.find(ssOne) if zzOne != -1: if tSpace >0: tSpace -= 1 if tree: tree.pop() def treeFolders(line): global tSpace,oldtSpace ssZero = '<DT><H3' zzZero = line.find(ssZero) if zzZero != -1: lssZero = zzZero + len(ssZero) ssOne = '>' zzOne = line[lssZero:].find(ssOne) if zzOne != -1: lssOne = lssZero + zzOne + len(ssOne) ssTwo = '<' zzTwo = line[lssOne:].find(ssTwo) if zzTwo != -1: lssTwo = lssOne + zzTwo #+ len(ssTwo) #print '<TH>'+'<A>' + line[lssOne:lssTwo]+'</A>'+'</TH>' tree.append(line[lssOne:lssTwo]) #for t in tree: #print t #print tSpace def treeLine(line): global row, tab, maxCol,oldmaxCol s='<DT><A HREF=\"' ls= len(s) z = line.find(s) if z != -1: ls= z+len(s) sOne='\"' z1=line[ls:].find(sOne) if z1 != -1: lsOne = ls+z1#+len(sOne) #print '<TR>'+'<TD HEIGHT=17 ALIGN=LEFT>' #print '<A HREF=\"' +line[ls:lsOne] + '\">' row.append(line[ls:lsOne])#url lsTwo = lsOne + len(sOne) sTwo = '>' z2 = line[lsTwo:].find(sTwo) if z2!=-1: lsThree = lsTwo+z2+len(sTwo) #print z,z1,z2,lsThree sThree='</A>' z3=line[lsThree:].find(sThree) if z3!=-1: lsFour = lsThree + z3 #+ len(sThree) #tSpaceTwo = ' '*tSpace #print tSpaceTwo,line[lsThree:lsFour] +'</A>'+'</TD>'+'</TR>' l = line[lsThree:lsFour] if l!='': row.append(l)#description else: row.append('empty') if len(tree)!=0: #categorie = bkm folders for t in range(0,len(tree)): row.append(tree[t]) tab.append(row) #print 'len riga: ' + str(len(row)) maxCol = len(row) if maxCol > oldmaxCol: oldmaxCol = maxCol else: maxCol=oldmaxCol row=[] def htmlparse(): global row, tab, tabName, tSpace while 1: line=f.readline() if not line: break #print line treeFolders(line) treeSpace(line) treeLine(line) if len(tree)==0: if len(tab)!=0: for t in tab: for r in range(len(t)): if r==2: #print 'nome tabella: ',t[r] tabName = t[r] #print 'maxCol: ' + str(maxCol) MyTabList.append(MyTab(tabName,maxCol,tab)) #x.tab=tab #stabs.append(x) #x.reset() #tabs.append(tab) tab = [] f.close() htmlparse() """ for tt in MyTabList: #for t in tt: print '\n' print tt.tabName print tt.maxCol for t in tt.tab: print 'divisore\n' for r in range(len(t)): print t[r] """ """ for tt in tabs: for t in tt: print '\n' for r in range(len(t)): if r==2: print 'nome tabella: ',t[r] else: print t[r] print 'divisore\n' """
Python
############################################################################## ## ## minjson.py implements JSON reading and writing in python. ## Copyright (c) 2005 Jim Washington and Contributors. ## ## 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA ## ############################################################################## # minjson.py # use python's parser to read minimal javascript objects. # str's objects and fixes the text to write javascript. # Thanks to Patrick Logan for starting the json-py project and making so many # good test cases. # Jim Washington 7 Aug 2005. from re import compile, sub, search, DOTALL # set to true if transmission size is much more important than speed # only affects writing, and makes a minimal difference in output size. alwaysStripWhiteSpace = False # add to this string if you wish to exclude additional math operators # from reading. badOperators = '*' ################################# # read JSON object # ################################# slashstarcomment = compile(r'/\*.*?\*/',DOTALL) doubleslashcomment = compile(r'//.*\n') def _Read(aString): """Use eval in a 'safe' way to turn javascript expression into a python expression. Allow only True, False, and None in global __builtins__, and since those map as true, false, null in javascript, pass those as locals """ try: result = eval(aString, {"__builtins__":{'True':True,'False':False,'None':None}}, {'null':None,'true':True,'false':False}) except NameError: raise ReadException, \ "Strings must be quoted. Could not read '%s'." % aString except SyntaxError: raise ReadException, \ "Syntax error. Could not read '%s'." % aString return result # badOperators is defined at the top of the module # generate the regexes for math detection regexes = {} for operator in badOperators: if operator in '+*': # '+' and '*' need to be escaped with \ in re regexes[operator,'numeric operation'] \ = compile(r"\d*\s*\%s|\%s\s*\d*" % (operator, operator)) else: regexes[operator,'numeric operation'] \ = compile(r"\d*\s*%s|%s\s*\d*" % (operator, operator)) def _getStringState(aSequence): """return the list of required quote closures if the end of aString needs them to close quotes. """ state = [] for k in aSequence: if k in ['"',"'"]: if state and k == state[-1]: state.pop() else: state.append(k) return state def _sanityCheckMath(aString): """just need to check that, if there is a math operator in the client's JSON, it is inside a quoted string. This is mainly to keep client from successfully sending 'D0S'*9**9**9**9... Return True if OK, False otherwise """ for operator in badOperators: #first check, is it a possible math operation? if regexes[(operator,'numeric operation')].search(aString) is not None: # OK. possible math operation. get the operator's locations getlocs = regexes[(operator,'numeric operation')].finditer(aString) locs = [item.span() for item in getlocs] halfStrLen = len(aString) / 2 #fortunately, this should be rare for loc in locs: exprStart = loc[0] exprEnd = loc[1] # We only need to know the char is within open quote # status. if exprStart <= halfStrLen: teststr = aString[:exprStart] else: teststr = list(aString[exprEnd+1:]) teststr.reverse() if not _getStringState(teststr): return False return True def safeRead(aString): """turn the js into happier python and check for bad operations before sending it to the interpreter """ # get rid of trailing null. Konqueror appends this, and the python # interpreter balks when it is there. CHR0 = chr(0) while aString.endswith(CHR0): aString = aString[:-1] # strip leading and trailing whitespace aString = aString.strip() # zap /* ... */ comments aString = slashstarcomment.sub('',aString) # zap // comments aString = doubleslashcomment.sub('',aString) # here, we only check for the * operator as a DOS problem by default; # additional operators may be excluded by editing badOperators # at the top of the module if _sanityCheckMath(aString): return _Read(aString) else: raise ReadException, 'Unacceptable JSON expression: %s' % aString read = safeRead ################################# # write object as JSON # ################################# #alwaysStripWhiteSpace is defined at the top of the module tfnTuple = (('True','true'),('False','false'),('None','null'),) def _replaceTrueFalseNone(aString): """replace True, False, and None with javascript counterparts""" for k in tfnTuple: if k[0] in aString: aString = aString.replace(k[0],k[1]) return aString def _handleCode(subStr,stripWhiteSpace): """replace True, False, and None with javascript counterparts if appropriate, remove unicode u's, fix long L's, make tuples lists, and strip white space if requested """ if 'e' in subStr: #True, False, and None have 'e' in them. :) subStr = (_replaceTrueFalseNone(subStr)) if stripWhiteSpace: # re.sub might do a better job, but takes longer. # Spaces are the majority of the whitespace, anyway... subStr = subStr.replace(' ','') if subStr[-1] in "uU": #remove unicode u's subStr = subStr[:-1] if "L" in subStr: #remove Ls from long ints subStr = subStr.replace("L",'') #do tuples as lists if "(" in subStr: subStr = subStr.replace("(",'[') if ")" in subStr: subStr = subStr.replace(")",']') return subStr # re for a double-quoted string that has a single-quote in it # but no double-quotes and python punctuation after: redoublequotedstring = compile(r'"[^"]*\'[^"]*"[,\]\}:\)]') escapedSingleQuote = r"\'" escapedDoubleQuote = r'\"' def doQuotesSwapping(aString): """rewrite doublequoted strings with single quotes as singlequoted strings with escaped single quotes""" s = [] foundlocs = redoublequotedstring.finditer(aString) prevend = 0 for loc in foundlocs: start,end = loc.span() s.append(aString[prevend:start]) tempstr = aString[start:end] endchar = tempstr[-1] ts1 = tempstr[1:-2] ts1 = ts1.replace("'",escapedSingleQuote) ts1 = "'%s'%s" % (ts1,endchar) s.append(ts1) prevend = end s.append(aString[prevend:]) return ''.join(s) def _pyexpr2jsexpr(aString, stripWhiteSpace): """Take advantage of python's formatting of string representations of objects. Python always uses "'" to delimit strings. Except it doesn't when there is ' in the string. Fix that, then, if we split on that delimiter, we have a list that alternates non-string text with string text. Since string text is already properly escaped, we only need to replace True, False, and None in non-string text and remove any unicode 'u's preceding string values. if stripWhiteSpace is True, remove spaces, etc from the non-string text. """ inSingleQuote = False inDoubleQuote = False #python will quote with " when there is a ' in the string, #so fix that first if redoublequotedstring.search(aString): aString = doQuotesSwapping(aString) marker = None if escapedSingleQuote in aString: #replace escaped single quotes with a marker marker = markerBase = '|' markerCount = 1 while marker in aString: #if the marker is already there, make it different markerCount += 1 marker = markerBase * markerCount aString = aString.replace(escapedSingleQuote,marker) #escape double-quotes aString = aString.replace('"',escapedDoubleQuote) #split the string on the real single-quotes splitStr = aString.split("'") outList = [] alt = True for subStr in splitStr: #if alt is True, non-string; do replacements if alt: subStr = _handleCode(subStr,stripWhiteSpace) outList.append(subStr) alt = not alt result = '"'.join(outList) if marker: #put the escaped single-quotes back as "'" result = result.replace(marker,"'") return result def write(obj, encoding="utf-8",stripWhiteSpace=alwaysStripWhiteSpace): """Represent the object as a string. Do any necessary fix-ups with pyexpr2jsexpr""" try: #not really sure encode does anything here aString = str(obj).encode(encoding) except UnicodeEncodeError: aString = obj.encode(encoding) if isinstance(obj,basestring): if '"' in aString: aString = aString.replace(escapedDoubleQuote,'"') result = '"%s"' % aString.replace('"',escapedDoubleQuote) else: result = '"%s"' % aString else: result = _pyexpr2jsexpr(aString,stripWhiteSpace).encode(encoding) return result class ReadException(Exception): pass class WriteException(Exception): pass
Python
import unittest ## Run the tests on minjson by changing the import... import json #import minjson as json ## jsontest.py implements tests for the json.py JSON ## (http://json.org) reader and writer. ## Copyright (C) 2005 Patrick D. Logan ## Contact mailto:patrickdlogan@stardecisions.com ## ## 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA # The object tests should be order-independent. They're not. # i.e. they should test for existence of keys and values # with read/write invariance. def _removeWhitespace(str): return str.replace(" ", "") class JsonTest(unittest.TestCase): def testReadEmptyObject(self): obj = json.read("{}") self.assertEqual({}, obj) def testWriteEmptyObject(self): s = json.write({}) self.assertEqual("{}", _removeWhitespace(s)) def testReadStringValue(self): obj = json.read('{ "name" : "Patrick" }') self.assertEqual({ "name" : "Patrick" }, obj) def testReadEscapedQuotationMark(self): obj = json.read(r'"\""') self.assertEqual(r'"', obj) def testReadEscapedSolidus(self): obj = json.read(r'"\/"') self.assertEqual(r'/', obj) def testReadEscapedReverseSolidus(self): obj = json.read(r'"\\"') self.assertEqual("\\", obj) def testReadEscapedBackspace(self): obj = json.read(r'"\b"') self.assertEqual("\b", obj) def testReadEscapedFormfeed(self): obj = json.read(r'"\f"') self.assertEqual("\f", obj) def testReadEscapedNewline(self): obj = json.read(r'"\n"') self.assertEqual("\n", obj) def testReadEscapedCarriageReturn(self): obj = json.read(r'"\r"') self.assertEqual("\r", obj) def testReadEscapedHorizontalTab(self): obj = json.read(r'"\t"') self.assertEqual("\t", obj) def testReadEscapedHexCharacter(self): obj = json.read(r'"\u000A"') self.assertEqual("\n", obj) obj = json.read(r'"\u1001"') self.assertEqual(u'\u1001', obj) def testWriteEscapedQuotationMark(self): s = json.write(r'"') self.assertEqual(r'"\""', _removeWhitespace(s)) def testWriteEscapedSolidus(self): s = json.write(r'/', escaped_forward_slash=True) self.assertEqual(r'"\/"', _removeWhitespace(s)) def testWriteNonEscapedSolidus(self): s = json.write(r'/') self.assertEqual(r'"/"', _removeWhitespace(s)) def testWriteEscapedReverseSolidus(self): s = json.write("\\") self.assertEqual(r'"\\"', _removeWhitespace(s)) def testWriteEscapedBackspace(self): s = json.write("\b") self.assertEqual(r'"\b"', _removeWhitespace(s)) def testWriteEscapedFormfeed(self): s = json.write("\f") self.assertEqual(r'"\f"', _removeWhitespace(s)) def testWriteEscapedNewline(self): s = json.write("\n") self.assertEqual(r'"\n"', _removeWhitespace(s)) def testWriteEscapedCarriageReturn(self): s = json.write("\r") self.assertEqual(r'"\r"', _removeWhitespace(s)) def testWriteEscapedHorizontalTab(self): s = json.write("\t") self.assertEqual(r'"\t"', _removeWhitespace(s)) def testWriteEscapedHexCharacter(self): s = json.write(u'\u1001') self.assertEqual(u'"\u1001"', _removeWhitespace(s)) def testReadBadEscapedHexCharacter(self): self.assertRaises(json.ReadException, self.doReadBadEscapedHexCharacter) def doReadBadEscapedHexCharacter(self): json.read('"\u10K5"') def testReadBadObjectKey(self): self.assertRaises(json.ReadException, self.doReadBadObjectKey) def doReadBadObjectKey(self): json.read('{ 44 : "age" }') def testReadBadArray(self): self.assertRaises(json.ReadException, self.doReadBadArray) def doReadBadArray(self): json.read('[1,2,3,,]') def testReadDoubleSolidusComment(self): obj = json.read("[1, 2, // This is a comment.\n 3]") self.assertEqual([1, 2, 3], obj) obj = json.read('[1, 2, // This is a comment.\n{"last":3}]') self.assertEqual([1, 2, {"last":3}], obj) def testReadBadDoubleSolidusComment(self): self.assertRaises(json.ReadException, self.doReadBadDoubleSolidusComment) def doReadBadDoubleSolidusComment(self): json.read("[1, 2, / This is not a comment.\n 3]") def testReadCStyleComment(self): obj = json.read("[1, 2, /* This is a comment. \n */ 3]") self.assertEqual([1, 2, 3], obj) obj = json.read('[1, 2, /* This is a comment. */{"last":3}]') self.assertEqual([1, 2, {"last":3}], obj) def testReadCStyleCommentWithoutEnd(self): self.assertRaises(json.ReadException, self.doReadCStyleCommentWithoutEnd) def testReadCStyleCommentWithSlashStar(self): self.assertRaises(json.ReadException, self.doReadCStyleCommentWithSlashStar) def doReadCStyleCommentWithoutEnd(self): json.read("[1, 2, /* This is not a comment./ 3]") def doReadCStyleCommentWithSlashStar(self): json.read("[1, 2, /* This is not a comment./* */ 3]") def testReadBadObjectSyntax(self): self.assertRaises(json.ReadException, self.doReadBadObjectSyntax) def doReadBadObjectSyntax(self): json.read('{"age", 44}') def testWriteStringValue(self): s = json.write({ "name" : "Patrick" }) self.assertEqual('{"name":"Patrick"}', _removeWhitespace(s)) def testReadIntegerValue(self): obj = json.read('{ "age" : 44 }') self.assertEqual({ "age" : 44 }, obj) def testReadNegativeIntegerValue(self): obj = json.read('{ "key" : -44 }') self.assertEqual({ "key" : -44 }, obj) def testReadFloatValue(self): obj = json.read('{ "age" : 44.5 }') self.assertEqual({ "age" : 44.5 }, obj) def testReadNegativeFloatValue(self): obj = json.read(' { "key" : -44.5 } ') self.assertEqual({ "key" : -44.5 }, obj) def testReadBadNumber(self): self.assertRaises(json.ReadException, self.doReadBadNumber) def doReadBadNumber(self): json.read('-44.4.4') def testReadSmallObject(self): obj = json.read('{ "name" : "Patrick", "age":44} ') self.assertEqual({ "age" : 44, "name" : "Patrick" }, obj) def testReadEmptyArray(self): obj = json.read('[]') self.assertEqual([], obj) def testWriteEmptyArray(self): self.assertEqual("[]", _removeWhitespace(json.write([]))) def testReadSmallArray(self): obj = json.read(' [ "a" , "b", "c" ] ') self.assertEqual(["a", "b", "c"], obj) def testWriteSmallArray(self): self.assertEqual('[1,2,3,4]', _removeWhitespace(json.write([1, 2, 3, 4]))) def testWriteSmallObject(self): s = json.write({ "name" : "Patrick", "age": 44 }) self.assertEqual('{"age":44,"name":"Patrick"}', _removeWhitespace(s)) def testWriteFloat(self): self.assertEqual("3.445567", _removeWhitespace(json.write(3.44556677))) def testReadTrue(self): self.assertEqual(True, json.read("true")) def testReadFalse(self): self.assertEqual(False, json.read("false")) def testReadNull(self): self.assertEqual(None, json.read("null")) def testWriteTrue(self): self.assertEqual("true", _removeWhitespace(json.write(True))) def testWriteFalse(self): self.assertEqual("false", _removeWhitespace(json.write(False))) def testWriteNull(self): self.assertEqual("null", _removeWhitespace(json.write(None))) def testReadArrayOfSymbols(self): self.assertEqual([True, False, None], json.read(" [ true, false,null] ")) def testWriteArrayOfSymbolsFromList(self): self.assertEqual("[true,false,null]", _removeWhitespace(json.write([True, False, None]))) def testWriteArrayOfSymbolsFromTuple(self): self.assertEqual("[true,false,null]", _removeWhitespace(json.write((True, False, None)))) def testReadComplexObject(self): src = ''' { "name": "Patrick", "age" : 44, "Employed?" : true, "Female?" : false, "grandchildren":null } ''' obj = json.read(src) self.assertEqual({"name":"Patrick","age":44,"Employed?":True,"Female?":False,"grandchildren":None}, obj) def testReadLongArray(self): src = '''[ "used", "abused", "confused", true, false, null, 1, 2, [3, 4, 5]] ''' obj = json.read(src) self.assertEqual(["used","abused","confused", True, False, None, 1,2,[3,4,5]], obj) def testReadIncompleteArray(self): self.assertRaises(json.ReadException, self.doReadIncompleteArray) def doReadIncompleteArray(self): json.read('[') def testReadComplexArray(self): src = ''' [ { "name": "Patrick", "age" : 44, "Employed?" : true, "Female?" : false, "grandchildren":null }, "used", "abused", "confused", 1, 2, [3, 4, 5] ] ''' obj = json.read(src) self.assertEqual([{"name":"Patrick","age":44,"Employed?":True,"Female?":False,"grandchildren":None}, "used","abused","confused", 1,2,[3,4,5]], obj) def testWriteComplexArray(self): obj = [{"name":"Patrick","age":44,"Employed?":True,"Female?":False,"grandchildren":None}, "used","abused","confused", 1,2,[3,4,5]] self.assertEqual('[{"Female?":false,"age":44,"name":"Patrick","grandchildren":null,"Employed?":true},"used","abused","confused",1,2,[3,4,5]]', _removeWhitespace(json.write(obj))) def testReadWriteCopies(self): orig_obj = {'a':' " '} json_str = json.write(orig_obj) copy_obj = json.read(json_str) self.assertEqual(orig_obj, copy_obj) self.assertEqual(True, orig_obj == copy_obj) self.assertEqual(False, orig_obj is copy_obj) def testStringEncoding(self): s = json.write([1, 2, 3]) self.assertEqual(unicode("[1,2,3]", "utf-8"), _removeWhitespace(s)) def testReadEmptyObjectAtEndOfArray(self): self.assertEqual(["a","b","c",{}], json.read('["a","b","c",{}]')) def testReadEmptyObjectMidArray(self): self.assertEqual(["a","b",{},"c"], json.read('["a","b",{},"c"]')) def testReadClosingObjectBracket(self): self.assertEqual({"a":[1,2,3]}, json.read('{"a":[1,2,3]}')) def testAnotherDoubleSlashComment(self): obj = json.read('[1 , // xzy\n2]') self.assertEqual(obj, [1, 2]) def testAnotherSlashStarComment(self): obj = json.read('[1,/* xzy */2]') self.assertEqual(obj, [1, 2]) def testEmptyObjectInList(self): obj = json.read('[{}]') self.assertEqual([{}], obj) def testObjectInListWithSlashStarComment(self): obj1 = json.read('[{} /*Comment*/]') self.assertEqual([{}], obj1) def testObjectWithEmptyList(self): obj = json.read('{"test": [] }') self.assertEqual({"test":[]}, obj) def testObjectWithNonEmptyList(self): obj = json.read('{"test": [3, 4, 5] }') self.assertEqual({"test":[3, 4, 5]}, obj) def testCommentInObjectWithListValue(self): obj2 = json.read('{"test": [] /*Comment*/}') self.assertEqual({"test":[]}, obj2) def testWriteLong(self): self.assertEqual("12345678901234567890", json.write(12345678901234567890)) def main(): unittest.main() if __name__ == '__main__': main()
Python
import string import types ## json.py implements a JSON (http://json.org) reader and writer. ## Copyright (C) 2005 Patrick D. Logan ## Contact mailto:patrickdlogan@stardecisions.com ## ## 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA class _StringGenerator(object): def __init__(self, string): self.string = string self.index = -1 def peek(self): i = self.index + 1 if i < len(self.string): return self.string[i] else: return None def next(self): self.index += 1 if self.index < len(self.string): return self.string[self.index] else: raise StopIteration def all(self): return self.string class WriteException(Exception): pass class ReadException(Exception): pass class JsonReader(object): hex_digits = {'A': 10,'B': 11,'C': 12,'D': 13,'E': 14,'F':15} escapes = {'t':'\t','n':'\n','f':'\f','r':'\r','b':'\b'} def read(self, s): self._generator = _StringGenerator(s) result = self._read() return result def _read(self): self._eatWhitespace() peek = self._peek() if peek is None: raise ReadException, "Nothing to read: '%s'" % self._generator.all() if peek == '{': return self._readObject() elif peek == '[': return self._readArray() elif peek == '"': return self._readString() elif peek == '-' or peek.isdigit(): return self._readNumber() elif peek == 't': return self._readTrue() elif peek == 'f': return self._readFalse() elif peek == 'n': return self._readNull() elif peek == '/': self._readComment() return self._read() else: raise ReadException, "Input is not valid JSON: '%s'" % self._generator.all() def _readTrue(self): self._assertNext('t', "true") self._assertNext('r', "true") self._assertNext('u', "true") self._assertNext('e', "true") return True def _readFalse(self): self._assertNext('f', "false") self._assertNext('a', "false") self._assertNext('l', "false") self._assertNext('s', "false") self._assertNext('e', "false") return False def _readNull(self): self._assertNext('n', "null") self._assertNext('u', "null") self._assertNext('l', "null") self._assertNext('l', "null") return None def _assertNext(self, ch, target): if self._next() != ch: raise ReadException, "Trying to read %s: '%s'" % (target, self._generator.all()) def _readNumber(self): isfloat = False result = self._next() peek = self._peek() while peek is not None and (peek.isdigit() or peek == "."): isfloat = isfloat or peek == "." result = result + self._next() peek = self._peek() try: if isfloat: return float(result) else: return int(result) except ValueError: raise ReadException, "Not a valid JSON number: '%s'" % result def _readString(self): result = "" assert self._next() == '"' try: while self._peek() != '"': ch = self._next() if ch == "\\": ch = self._next() if ch in 'brnft': ch = self.escapes[ch] elif ch == "u": ch4096 = self._next() ch256 = self._next() ch16 = self._next() ch1 = self._next() n = 4096 * self._hexDigitToInt(ch4096) n += 256 * self._hexDigitToInt(ch256) n += 16 * self._hexDigitToInt(ch16) n += self._hexDigitToInt(ch1) ch = unichr(n) elif ch not in '"/\\': raise ReadException, "Not a valid escaped JSON character: '%s' in %s" % (ch, self._generator.all()) result = result + ch except StopIteration: raise ReadException, "Not a valid JSON string: '%s'" % self._generator.all() assert self._next() == '"' return result def _hexDigitToInt(self, ch): try: result = self.hex_digits[ch.upper()] except KeyError: try: result = int(ch) except ValueError: raise ReadException, "The character %s is not a hex digit." % ch return result def _readComment(self): assert self._next() == "/" second = self._next() if second == "/": self._readDoubleSolidusComment() elif second == '*': self._readCStyleComment() else: raise ReadException, "Not a valid JSON comment: %s" % self._generator.all() def _readCStyleComment(self): try: done = False while not done: ch = self._next() done = (ch == "*" and self._peek() == "/") if not done and ch == "/" and self._peek() == "*": raise ReadException, "Not a valid JSON comment: %s, '/*' cannot be embedded in the comment." % self._generator.all() self._next() except StopIteration: raise ReadException, "Not a valid JSON comment: %s, expected */" % self._generator.all() def _readDoubleSolidusComment(self): try: ch = self._next() while ch != "\r" and ch != "\n": ch = self._next() except StopIteration: pass def _readArray(self): result = [] assert self._next() == '[' done = self._peek() == ']' while not done: item = self._read() result.append(item) self._eatWhitespace() done = self._peek() == ']' if not done: ch = self._next() if ch != ",": raise ReadException, "Not a valid JSON array: '%s' due to: '%s'" % (self._generator.all(), ch) assert ']' == self._next() return result def _readObject(self): result = {} assert self._next() == '{' done = self._peek() == '}' while not done: key = self._read() if type(key) is not types.StringType: raise ReadException, "Not a valid JSON object key (should be a string): %s" % key self._eatWhitespace() ch = self._next() if ch != ":": raise ReadException, "Not a valid JSON object: '%s' due to: '%s'" % (self._generator.all(), ch) self._eatWhitespace() val = self._read() result[key] = val self._eatWhitespace() done = self._peek() == '}' if not done: ch = self._next() if ch != ",": raise ReadException, "Not a valid JSON array: '%s' due to: '%s'" % (self._generator.all(), ch) assert self._next() == "}" return result def _eatWhitespace(self): p = self._peek() while p is not None and p in string.whitespace or p == '/': if p == '/': self._readComment() else: self._next() p = self._peek() def _peek(self): return self._generator.peek() def _next(self): return self._generator.next() class JsonWriter(object): def _append(self, s): self._results.append(s) def write(self, obj, escaped_forward_slash=False): self._escaped_forward_slash = escaped_forward_slash self._results = [] self._write(obj) return "".join(self._results) def _write(self, obj): ty = type(obj) if ty is types.DictType: n = len(obj) self._append("{") for k, v in obj.items(): self._write(k) self._append(":") self._write(v) n = n - 1 if n > 0: self._append(",") self._append("}") elif ty is types.ListType or ty is types.TupleType: n = len(obj) self._append("[") for item in obj: self._write(item) n = n - 1 if n > 0: self._append(",") self._append("]") elif ty is types.StringType or ty is types.UnicodeType: self._append('"') obj = obj.replace('\\', r'\\') if self._escaped_forward_slash: obj = obj.replace('/', r'\/') obj = obj.replace('"', r'\"') obj = obj.replace('\b', r'\b') obj = obj.replace('\f', r'\f') obj = obj.replace('\n', r'\n') obj = obj.replace('\r', r'\r') obj = obj.replace('\t', r'\t') self._append(obj) self._append('"') elif ty is types.IntType or ty is types.LongType: self._append(str(obj)) elif ty is types.FloatType: self._append("%f" % obj) elif obj is True: self._append("true") elif obj is False: self._append("false") elif obj is None: self._append("null") else: raise WriteException, "Cannot write in JSON: %s" % repr(obj) def write(obj, escaped_forward_slash=False): return JsonWriter().write(obj, escaped_forward_slash) def read(s): return JsonReader().read(s)
Python
from BitTorrent.bencode import bencode,bdecode from BitTorrent.download import download,defaults from BitTorrent.fmt import fmttime, fmtsize from threading import Thread, Event, Lock from sys import stdout from os.path import abspath, join, exists, getsize from time import sleep filecheck=Lock() class StatusUpdater: def __init__(self, id, params,output=[],threads={},save_path='',torrents={}): self.torrents=torrents self.torrent=self.torrents[id] self.output=output self.id=id self.output[id]=[] self.params = params self.myinfo = threads[self.id] self.done = 0 self.checking = 0 self.activity = 'starting' ## self.display() self.myinfo['errors'] = [] self.metafile=bdecode(open(self.torrents[self.id]['path'],'rb').read()) #trim pieces data del self.metafile['info']['pieces'] print "self.output=",self.output def download(self): ## print self.metafile download(self.params + ['--responsefile', self.torrent['path']], self.choose, self.display, self.finished, self.err, self.myinfo['kill'], 80) ## download(self.params, self.choose, self.display, self.finished, self.err, self.myinfo['kill'], 80) print 'Torrent %s stopped' % self.id stdout.flush() def finished(self): self.done = 1 self.myinfo['done'] = 1 self.activity = 'complete' self.display({'fractionDone' : 1, 'downRate' : 0}) def err(self, msg): self.myinfo['errors'].append(msg) self.display() def failed(self): self.activity = 'failed' self.display() ## def choose(self, default, size, saveas, dir): ## global filecheck ## self.myinfo['downfile'] = default ## self.myinfo['filesize'] = fmtsize(size) ## if saveas == '': ## saveas = default ## # it asks me where I want to save it before checking the file.. ## if exists(self.id[:-len(ext)]) and (getsize(self.id[:-len(ext)]) > 0): ## # file will get checked ## while (not filecheck.acquire(0) and not self.myinfo['kill'].isSet()): ## self.myinfo['status'] = 'disk wait' ## sleep(0.1) ## if not self.myinfo['kill'].isSet(): ## self.checking = 1 ## self.myinfo['checking'] = 1 ## self.myinfo['savefile'] = self.file[:-len(ext)] ## return self.file[:-len(ext)] def choose(self,default,size,saveas,dir): global filecheck print "choose default=",default,"size=",size,"saveas=",saveas,"dir=",dir self.myinfo['downfile'] = default self.myinfo['filesize'] = fmtsize(size) #full path to file save_path = self.torrent['save_path']+'/'+default if exists(save_path) and (getsize(save_path) > 0): print "CHECKING" while (not filecheck.acquire(0) and not self.myinfo['kill'].isSet()): print "disk wait" self.myinfo['status'] = 'disk wait' sleep(0.1) if not self.myinfo['kill'].isSet(): print 'SET CHECKING TO 1' self.checking=1 self.myinfo['checking']=1 self.myinfo['savefile']=save_path return save_path def display(self, dict = {}): fractionDone = dict.get('fractionDone', None) timeEst = dict.get('timeEst', None) activity = dict.get('activity', None) global status if activity is not None and not self.done: if activity == 'checking existing file': self.activity = 'disk check' elif activity == 'connecting to peers': self.activity = 'connecting' else: self.activity = activity elif timeEst is not None: self.activity = fmttime(timeEst, 1) if fractionDone is not None: self.myinfo['status'] = '%s %.0f%%' % (self.activity, fractionDone * 100) else: self.myinfo['status'] = self.activity if self.activity != 'checking existing file' and self.checking: # we finished checking our files. filecheck.release() self.checking = 0 self.myinfo['checking'] = 0 if dict.has_key('upRate'): self.myinfo['uprate'] = dict['upRate'] if dict.has_key('downRate'): self.myinfo['downrate'] = dict['downRate'] if dict.has_key('upTotal'): self.myinfo['uptotal'] = dict['upTotal'] if dict.has_key('downTotal'): self.myinfo['downtotal'] = dict['downTotal'] ## print "display=",self.myinfo
Python
#!/usr/bin/python #torrent stuff from BitTorrent.download import download,defaults from BitTorrent.fmt import fmttime, fmtsize from BitTorrent.bencode import bdecode,bencode from threading import Thread, Event, Lock from status import * #utils from os import listdir from os.path import abspath, join, exists, getsize from sys import argv, stdout, exit from time import sleep from copy import deepcopy import traceback import sha #server stuff import time import BaseHTTPServer import cgi from json.json import JsonWriter,JsonReader #global thread pool threads={} torrents={} ## torrents[id]={'id':id,'path':self.get_form['torrent'][0], ## 'save_path':self.get_form['save_path'][0]}) torrent_metas=[] main=None #messages sorted by id #each id points to a list of strings,which are json objects torrent_messages={} filecheck = Lock() started=False #keepgoing is an ugly hack used to shut this beast down keepgoing=True ###HTTPD server instance httpd=None server=None ##threads['id']={} ##StatusUpdater(None,None,'id',output=torrent_messages,threads=threads) ##initialize Json Stuff json_writer=JsonWriter() json_reader=JsonReader() def mainloop(params=[]): global torrents,threads,torrent_metas, torrent_messages print 'mainloop starting' ## print torrents deadtorrents=[] ## initialize_messages() ## print torrent_messages while True: #initialize torrents for key in torrents.keys(): if key not in threads.keys(): torrent_messages[key]['error'].append("New Torrent: %s" %key) threads[key]={'kill':Event(),'try': 1} threads[key]['thread']=Thread( target=StatusUpdater(key,params,output=torrent_messages[key],threads=threads, save_path=torrents[key]['save_path'],torrents=torrents).download, name=key ) threads[key]['thread'].start() ## print "threads=",threads ## print for name,threadinfo in threads.items(): if threadinfo.get('timeout')==0: threadinfo['try'] = threadinfo['try'] + 1 print name print threads if not threadinfo['kill'].isSet(): threadinfo['thread']=Thread( StatusUpdater(name,params,output=torrent_messages[name],threads=threads, save_path=torrents[name]['save_path'],torrents=torrents).download, name=name ) threadinfo['thread'].start() threadinfo['timeout'] = -1 else: del threads[name] del torrents[name] elif threadinfo.get('timeout') > 0: #decrement our counter by 1 threadinfo['timeout']=threadinfo['timeout'] - 1 elif not threadinfo['thread'].isAlive(): if threadinfo.get('checking',None): filecheck.release() if threadinfo.get('try') == 6: deadtorrents.append(name) torrent_messages[name]['error'].append("%s died 6 times, added to dead list" %name) del threads[name] else: del threadinfo['thread'] threadinfo['timeout']=10 #TODO: maybe deal the torrents that disapear. #or get canceled, for later in the devel cycle ## print torrent_messages print threads ## return sleep(1) def dropdir_mainloop(d, params): """ d=directory to look for torrents in params=a string passed from the command line """ deadfiles = [] global threads, status,keepgoing while keepgoing: files = listdir(d) # new files for file in files: if file[-len(ext):] == ext: if file not in threads.keys() + deadfiles: threads[file] = {'kill': Event(), 'try': 1} print 'New torrent: %s' % file stdout.flush() threads[file]['thread'] = Thread(target = StatusUpdater(join(d, file), params, file).download, name = file) threads[file]['thread'].start() # files with multiple tries for file, threadinfo in threads.items(): if threadinfo.get('timeout') == 0: # Zero seconds left, try and start the thing again. threadinfo['try'] = threadinfo['try'] + 1 threadinfo['thread'] = Thread(target = StatusUpdater(join(d, file), params, file).download, name = file) threadinfo['thread'].start() threadinfo['timeout'] = -1 elif threadinfo.get('timeout') > 0: # Decrement our counter by 1 threadinfo['timeout'] = threadinfo['timeout'] - 1 elif not threadinfo['thread'].isAlive(): # died without permission # if it was checking the file, it isn't anymore. if threadinfo.get('checking', None): filecheck.release() if threadinfo.get('try') == 6: # Died on the sixth try? You're dead. deadfiles.append(file) print '%s died 6 times, added to dead list' % fil stdout.flush() del threads[file] else: del threadinfo['thread'] threadinfo['timeout'] = 10 # dealing with files that dissapear if file not in files: print 'Torrent file dissapeared, killing %s' % file stdout.flush() if threadinfo.get('timeout', -1) == -1: threadinfo['kill'].set() threadinfo['thread'].join() # if this thread was filechecking, open it up if threadinfo.get('checking', None): filecheck.release() del threads[file] for file in deadfiles: # if the file dissapears, remove it from our dead list if file not in files: deadfiles.remove(file) sleep(1) class Handler(BaseHTTPServer.BaseHTTPRequestHandler): """ Request object that handles http requests, also does some torrent bookeeping all responses are in JSON serialized format as all messages are to be consumed by javascript """ def torrent_file(self,msg): global torrents,threads,torrent_metas #decode data file and put it in the torrent metas print "torrent_file decoded get=", self.get_form,"path=",self.path data=open(self.get_form['torrent'][0],'rb').read() id=sha.new() id.update(self.get_form['torrent'][0]) id=id.hexdigest() ##TODO: remove the pieces info and make sure the path is in there torrents[id]={'id':id,'path':self.get_form['torrent'][0], 'save_path':self.get_form['save_path'][0]} torrent_messages[id]=dict(error=[],status=str(),) self.wfile.write(json_writer.write(dict(id=id))) def get_dispatch(self): methods=dict( form=self.form, torrent_file=self.torrent_file, start=self.start, info_all=self.info_all, info=self.info, kill=self.kill, stop=self.stop, ) self.get_form=cgi.parse_qs(self.path.split('/')[-1][1::]) method=self.path.split('/')[1] return methods.get(method,self.bad_method)(method) def bad_method(self,msg): return self.wfile.write(json_writer.write(dict(error="no method found, %s" %msg))) def start(self,msg): print "starting torrents" global torrents,threads,torrent_metas global main,started if started: print "Service already started" return self.wfile.write(json_writer.write(dict(message='torrents started already'))) #crop the pieces info because it's not needed #will bloat memory ## for n,v in enumerate(torrent_metas): ## del torrent_metas[n]['info']['pieces'] params=[] started=True main=Thread(target=mainloop,name="mainloop",kwargs=dict(params=params)) main.start() if started: return self.wfile.write(json_writer.write(dict(message='All Torrents Started'))) def kill(self,msg): id=self.get_form['id'][0] threads[id]['kill'].set() threads[id]['thread'].join() self.wfile.write(json_writer.write(dict(message='%s killed' %id))) def stop(self,msg): global keepgoing,server,httpd print "*"*80 print 'STOPING'*3 print "*"*80 for k in threads.keys(): threads[k]['kill'].set() threads[k]['thread'].join() httpd.server_close() keepgoing=False; def info(self,msg): id=self.get_form['id'][0] self.wfile.write(json_writer.write(dict(status=threads[id]['status'], savefile=threads[id]['savefile'], downtotal=threads[id].get('downtotal',0), downfile=threads[id]['downfile'], errors=threads[id]['errors'], downrate=threads[id].get('downrate',0), uprate=threads[id].get('uprate',0), filesize=threads[id].get('filesize',0), uptotal=threads[id].get('uptotal',0) ))) def info_all(self,msg): ## print "info_all threads=",threads ret={} t=threads ## print t if len(t)>0: print "creating returnable info dict" for k in threads.keys(): row=dict(status=t[k]['status'], savefile=t[k].get('savefile',''), downtotal=t[k].get('downtotal',0), downfile=t[k].get('downfile',''), errors=t[k].get('errors',''), downrate=t[k].get('downrate',0), uprate=t[k].get('uprate',0), filesize=t[k].get('filesize',0), uptotal=t[k].get('uptotal',0) ) ret[k]=row ## print 'ret=',ret self.wfile.write(json_writer.write(ret)) def do_GET(self): """Respond to a GET request.""" return self.get_dispatch() def form(self,msg): self.html_header() self.wfile.write(open('index.html','r').read()) def plain_header(self): self.send_response(200) self.send_header("Content-type", "text/plain") self.end_headers() def html_header(self): self.send_response(200) self.send_header("Content-type", "text/html") self.end_headers() if __name__ == '__main__': print "argv=",argv global httpd,keepgoing,server port=int(argv[1]) server_class = BaseHTTPServer.HTTPServer httpd = server_class(('localhost', port), Handler) print time.asctime(), "Server Starts - %s:%s" % ('localhost', port) try: server=Thread(target=httpd.serve_forever,name='http_server') server.start() #to keep this from running off the end while keepgoing: sleep(1) except KeyboardInterrupt: pass httpd.server_close() print time.asctime(), "Server Stops - %s:%s" % ('localhost',port) exit(0)
Python
#!/usr/bin/python #torrent stuff from BitTorrent.download import download,defaults from BitTorrent.fmt import fmttime, fmtsize from BitTorrent.bencode import bdecode,bencode from threading import Thread, Event, Lock from status import * #utils from os import listdir from os.path import abspath, join, exists, getsize from sys import argv, stdout, exit from time import sleep from copy import deepcopy import traceback import sha #server stuff import time import BaseHTTPServer import cgi from json.json import JsonWriter,JsonReader #global thread pool threads={} torrents={} ## torrents[id]={'id':id,'path':self.get_form['torrent'][0], ## 'save_path':self.get_form['save_path'][0]}) torrent_metas=[] main=None #messages sorted by id #each id points to a list of strings,which are json objects torrent_messages={} filecheck = Lock() started=False #keepgoing is an ugly hack used to shut this beast down keepgoing=True ###HTTPD server instance httpd=None server=None ##threads['id']={} ##StatusUpdater(None,None,'id',output=torrent_messages,threads=threads) ##initialize Json Stuff json_writer=JsonWriter() json_reader=JsonReader() def mainloop(params=[]): global torrents,threads,torrent_metas, torrent_messages print 'mainloop starting' ## print torrents deadtorrents=[] ## initialize_messages() ## print torrent_messages while True: #initialize torrents for key in torrents.keys(): if key not in threads.keys(): torrent_messages[key]['error'].append("New Torrent: %s" %key) threads[key]={'kill':Event(),'try': 1} threads[key]['thread']=Thread( target=StatusUpdater(key,params,output=torrent_messages[key],threads=threads, save_path=torrents[key]['save_path'],torrents=torrents).download, name=key ) threads[key]['thread'].start() ## print "threads=",threads ## print for name,threadinfo in threads.items(): if threadinfo.get('timeout')==0: threadinfo['try'] = threadinfo['try'] + 1 print name print threads if not threadinfo['kill'].isSet(): threadinfo['thread']=Thread( StatusUpdater(name,params,output=torrent_messages[name],threads=threads, save_path=torrents[name]['save_path'],torrents=torrents).download, name=name ) threadinfo['thread'].start() threadinfo['timeout'] = -1 else: del threads[name] del torrents[name] elif threadinfo.get('timeout') > 0: #decrement our counter by 1 threadinfo['timeout']=threadinfo['timeout'] - 1 elif not threadinfo['thread'].isAlive(): if threadinfo.get('checking',None): filecheck.release() if threadinfo.get('try') == 6: deadtorrents.append(name) torrent_messages[name]['error'].append("%s died 6 times, added to dead list" %name) del threads[name] else: del threadinfo['thread'] threadinfo['timeout']=10 #TODO: maybe deal the torrents that disapear. #or get canceled, for later in the devel cycle ## print torrent_messages print threads ## return sleep(1) def dropdir_mainloop(d, params): """ d=directory to look for torrents in params=a string passed from the command line """ deadfiles = [] global threads, status,keepgoing while keepgoing: files = listdir(d) # new files for file in files: if file[-len(ext):] == ext: if file not in threads.keys() + deadfiles: threads[file] = {'kill': Event(), 'try': 1} print 'New torrent: %s' % file stdout.flush() threads[file]['thread'] = Thread(target = StatusUpdater(join(d, file), params, file).download, name = file) threads[file]['thread'].start() # files with multiple tries for file, threadinfo in threads.items(): if threadinfo.get('timeout') == 0: # Zero seconds left, try and start the thing again. threadinfo['try'] = threadinfo['try'] + 1 threadinfo['thread'] = Thread(target = StatusUpdater(join(d, file), params, file).download, name = file) threadinfo['thread'].start() threadinfo['timeout'] = -1 elif threadinfo.get('timeout') > 0: # Decrement our counter by 1 threadinfo['timeout'] = threadinfo['timeout'] - 1 elif not threadinfo['thread'].isAlive(): # died without permission # if it was checking the file, it isn't anymore. if threadinfo.get('checking', None): filecheck.release() if threadinfo.get('try') == 6: # Died on the sixth try? You're dead. deadfiles.append(file) print '%s died 6 times, added to dead list' % fil stdout.flush() del threads[file] else: del threadinfo['thread'] threadinfo['timeout'] = 10 # dealing with files that dissapear if file not in files: print 'Torrent file dissapeared, killing %s' % file stdout.flush() if threadinfo.get('timeout', -1) == -1: threadinfo['kill'].set() threadinfo['thread'].join() # if this thread was filechecking, open it up if threadinfo.get('checking', None): filecheck.release() del threads[file] for file in deadfiles: # if the file dissapears, remove it from our dead list if file not in files: deadfiles.remove(file) sleep(1) class Handler(BaseHTTPServer.BaseHTTPRequestHandler): """ Request object that handles http requests, also does some torrent bookeeping all responses are in JSON serialized format as all messages are to be consumed by javascript """ def torrent_file(self,msg): global torrents,threads,torrent_metas #decode data file and put it in the torrent metas print "torrent_file decoded get=", self.get_form,"path=",self.path data=open(self.get_form['torrent'][0],'rb').read() id=sha.new() id.update(self.get_form['torrent'][0]) id=id.hexdigest() ##TODO: remove the pieces info and make sure the path is in there torrents[id]={'id':id,'path':self.get_form['torrent'][0], 'save_path':self.get_form['save_path'][0]} torrent_messages[id]=dict(error=[],status=str(),) self.wfile.write(json_writer.write(dict(id=id))) def get_dispatch(self): methods=dict( form=self.form, torrent_file=self.torrent_file, start=self.start, info_all=self.info_all, info=self.info, kill=self.kill, stop=self.stop, ) self.get_form=cgi.parse_qs(self.path.split('/')[-1][1::]) method=self.path.split('/')[1] return methods.get(method,self.bad_method)(method) def bad_method(self,msg): return self.wfile.write(json_writer.write(dict(error="no method found, %s" %msg))) def start(self,msg): print "starting torrents" global torrents,threads,torrent_metas global main,started if started: print "Service already started" return self.wfile.write(json_writer.write(dict(message='torrents started already'))) #crop the pieces info because it's not needed #will bloat memory ## for n,v in enumerate(torrent_metas): ## del torrent_metas[n]['info']['pieces'] params=[] started=True main=Thread(target=mainloop,name="mainloop",kwargs=dict(params=params)) main.start() if started: return self.wfile.write(json_writer.write(dict(message='All Torrents Started'))) def kill(self,msg): id=self.get_form['id'][0] threads[id]['kill'].set() threads[id]['thread'].join() self.wfile.write(json_writer.write(dict(message='%s killed' %id))) def stop(self,msg): global keepgoing,server,httpd print "*"*80 print 'STOPING'*3 print "*"*80 for k in threads.keys(): threads[k]['kill'].set() threads[k]['thread'].join() httpd.server_close() keepgoing=False; def info(self,msg): id=self.get_form['id'][0] self.wfile.write(json_writer.write(dict(status=threads[id]['status'], savefile=threads[id]['savefile'], downtotal=threads[id].get('downtotal',0), downfile=threads[id]['downfile'], errors=threads[id]['errors'], downrate=threads[id].get('downrate',0), uprate=threads[id].get('uprate',0), filesize=threads[id].get('filesize',0), uptotal=threads[id].get('uptotal',0) ))) def info_all(self,msg): ## print "info_all threads=",threads ret={} t=threads ## print t if len(t)>0: print "creating returnable info dict" for k in threads.keys(): row=dict(status=t[k]['status'], savefile=t[k].get('savefile',''), downtotal=t[k].get('downtotal',0), downfile=t[k].get('downfile',''), errors=t[k].get('errors',''), downrate=t[k].get('downrate',0), uprate=t[k].get('uprate',0), filesize=t[k].get('filesize',0), uptotal=t[k].get('uptotal',0) ) ret[k]=row ## print 'ret=',ret self.wfile.write(json_writer.write(ret)) def do_GET(self): """Respond to a GET request.""" return self.get_dispatch() def form(self,msg): self.html_header() self.wfile.write(open('index.html','r').read()) def plain_header(self): self.send_response(200) self.send_header("Content-type", "text/plain") self.end_headers() def html_header(self): self.send_response(200) self.send_header("Content-type", "text/html") self.end_headers() if __name__ == '__main__': print "argv=",argv global httpd,keepgoing,server port=int(argv[1]) server_class = BaseHTTPServer.HTTPServer httpd = server_class(('localhost', port), Handler) print time.asctime(), "Server Starts - %s:%s" % ('localhost', port) try: server=Thread(target=httpd.serve_forever,name='http_server') server.start() #to keep this from running off the end while keepgoing: sleep(1) except KeyboardInterrupt: pass httpd.server_close() print time.asctime(), "Server Stops - %s:%s" % ('localhost',port) exit(0)
Python
#! /usr/bin/python # Written by Bram Cohen # see LICENSE.txt for license information from sys import argv from os.path import getsize, split, join, abspath, isdir from os import listdir from sha import sha from copy import copy from string import strip from BitTorrent.bencode import bencode from BitTorrent.btformats import check_info from BitTorrent.parseargs import parseargs, formatDefinitions from threading import Event from time import time defaults = [ ('piece_size_pow2', 18, "which power of 2 to set the piece size to"), ('comment', '', "optional human-readable comment to put in .torrent"), ('target', '', "optional target file for the torrent") ] ignore = ['core', 'CVS'] def dummy(v): pass def make_meta_file(file, url, piece_len_exp = 18, flag = Event(), progress = dummy, progress_percent=1, comment = None, target = None): if piece_len_exp == None: piece_len_exp = 18 piece_length = 2 ** piece_len_exp a, b = split(file) if not target: if b == '': f = a + '.torrent' else: f = join(a, b + '.torrent') else: f = target info = makeinfo(file, piece_length, flag, progress, progress_percent) if flag.isSet(): return check_info(info) h = open(f, 'wb') data = {'info': info, 'announce': strip(url), 'creation date': long(time())} if comment: data['comment'] = comment h.write(bencode(data)) h.close() def calcsize(file): if not isdir(file): return getsize(file) total = 0 for s in subfiles(abspath(file)): total += getsize(s[1]) return total def makeinfo(file, piece_length, flag, progress, progress_percent=1): file = abspath(file) if isdir(file): subs = subfiles(file) subs.sort() pieces = [] sh = sha() done = 0 fs = [] totalsize = 0.0 totalhashed = 0 for p, f in subs: totalsize += getsize(f) for p, f in subs: pos = 0 size = getsize(f) fs.append({'length': size, 'path': p}) h = open(f, 'rb') while pos < size: a = min(size - pos, piece_length - done) sh.update(h.read(a)) if flag.isSet(): return done += a pos += a totalhashed += a if done == piece_length: pieces.append(sh.digest()) done = 0 sh = sha() if progress_percent: progress(totalhashed / totalsize) else: progress(a) h.close() if done > 0: pieces.append(sh.digest()) return {'pieces': ''.join(pieces), 'piece length': piece_length, 'files': fs, 'name': split(file)[1]} else: size = getsize(file) pieces = [] p = 0 h = open(file, 'rb') while p < size: x = h.read(min(piece_length, size - p)) if flag.isSet(): return pieces.append(sha(x).digest()) p += piece_length if p > size: p = size if progress_percent: progress(float(p) / size) else: progress(min(piece_length, size - p)) h.close() return {'pieces': ''.join(pieces), 'piece length': piece_length, 'length': size, 'name': split(file)[1]} def subfiles(d): r = [] stack = [([], d)] while len(stack) > 0: p, n = stack.pop() if isdir(n): for s in listdir(n): if s not in ignore and s[:1] != '.': stack.append((copy(p) + [s], join(n, s))) else: r.append((p, n)) return r def prog(amount): print '%.1f%% complete\r' % (amount * 100), if __name__ == '__main__': if len(argv) < 3: print 'usage is -' print argv[0] + ' file trackerurl [params]' print print formatDefinitions(defaults, 80) else: try: config, args = parseargs(argv[3:], defaults, 0, 0) make_meta_file(argv[1], argv[2], config['piece_size_pow2'], progress = prog, comment = config['comment'], target = config['target']) except ValueError, e: print 'error: ' + str(e) print 'run with no args for parameter explanations'
Python
# Written by Bram Cohen, Uoti Urpala, and John Hoffman # see LICENSE.txt for license information try: True except: True = 1 False = 0 bool = lambda x: not not x try: sum([1]) negsum = lambda a: len(a)-sum(a) except: negsum = lambda a: reduce(lambda x,y: x+(not y), a, 0) def _int_to_booleans(x): r = [] for i in range(8): r.append(bool(x & 0x80)) x <<= 1 return tuple(r) lookup_table = [_int_to_booleans(i) for i in range(256)] reverse_lookup_table = {} for i in xrange(256): reverse_lookup_table[lookup_table[i]] = chr(i) class Bitfield: def __init__(self, length, bitstring = None): self.length = length if bitstring is not None: extra = len(bitstring) * 8 - length if extra < 0 or extra >= 8: raise ValueError t = lookup_table r = [] for c in bitstring: r.extend(t[ord(c)]) if extra > 0: if r[-extra:] != [0] * extra: raise ValueError del r[-extra:] self.array = r self.numfalse = negsum(r) else: self.array = [False] * length self.numfalse = length def __setitem__(self, index, val): val = bool(val) self.numfalse += self.array[index]-val self.array[index] = val def __getitem__(self, index): return self.array[index] def __len__(self): return self.length def tostring(self): booleans = self.array t = reverse_lookup_table s = len(booleans) % 8 r = [ t[tuple(booleans[x:x+8])] for x in xrange(0, len(booleans)-s, 8) ] if s: r += t[tuple(booleans[-s:] + ([0] * (8-s)))] return ''.join(r) def complete(self): return not self.numfalse def test_bitfield(): try: x = Bitfield(7, 'ab') assert False except ValueError: pass try: x = Bitfield(7, 'ab') assert False except ValueError: pass try: x = Bitfield(9, 'abc') assert False except ValueError: pass try: x = Bitfield(0, 'a') assert False except ValueError: pass try: x = Bitfield(1, '') assert False except ValueError: pass try: x = Bitfield(7, '') assert False except ValueError: pass try: x = Bitfield(8, '') assert False except ValueError: pass try: x = Bitfield(9, 'a') assert False except ValueError: pass try: x = Bitfield(7, chr(1)) assert False except ValueError: pass try: x = Bitfield(9, chr(0) + chr(0x40)) assert False except ValueError: pass assert Bitfield(0, '').tostring() == '' assert Bitfield(1, chr(0x80)).tostring() == chr(0x80) assert Bitfield(7, chr(0x02)).tostring() == chr(0x02) assert Bitfield(8, chr(0xFF)).tostring() == chr(0xFF) assert Bitfield(9, chr(0) + chr(0x80)).tostring() == chr(0) + chr(0x80) x = Bitfield(1) assert x.numfalse == 1 x[0] = 1 assert x.numfalse == 0 x[0] = 1 assert x.numfalse == 0 assert x.tostring() == chr(0x80) x = Bitfield(7) assert len(x) == 7 x[6] = 1 assert x.numfalse == 6 assert x.tostring() == chr(0x02) x = Bitfield(8) x[7] = 1 assert x.tostring() == chr(1) x = Bitfield(9) x[8] = 1 assert x.numfalse == 8 assert x.tostring() == chr(0) + chr(0x80) x = Bitfield(8, chr(0xC4)) assert len(x) == 8 assert x.numfalse == 5 assert x.tostring() == chr(0xC4)
Python
# Written by Bram Cohen # see LICENSE.txt for license information from string import join class FakeHandle: def __init__(self, name, fakeopen): self.name = name self.fakeopen = fakeopen self.pos = 0 def flush(self): pass def close(self): pass def seek(self, pos): self.pos = pos def read(self, amount = None): old = self.pos f = self.fakeopen.files[self.name] if self.pos >= len(f): return '' if amount is None: self.pos = len(f) return join(f[old:], '') else: self.pos = min(len(f), old + amount) return join(f[old:self.pos], '') def write(self, s): f = self.fakeopen.files[self.name] while len(f) < self.pos: f.append(chr(0)) self.fakeopen.files[self.name][self.pos : self.pos + len(s)] = list(s) self.pos += len(s) class FakeOpen: def __init__(self, initial = {}): self.files = {} for key, value in initial.items(): self.files[key] = list(value) def open(self, filename, mode): """currently treats everything as rw - doesn't support append""" self.files.setdefault(filename, []) return FakeHandle(filename, self) def exists(self, file): return self.files.has_key(file) def getsize(self, file): return len(self.files[file]) def test_normal(): f = FakeOpen({'f1': 'abcde'}) assert f.exists('f1') assert not f.exists('f2') assert f.getsize('f1') == 5 h = f.open('f1', 'rw') assert h.read(3) == 'abc' assert h.read(1) == 'd' assert h.read() == 'e' assert h.read(2) == '' h.write('fpq') h.seek(4) assert h.read(2) == 'ef' h.write('ghij') h.seek(0) assert h.read() == 'abcdefghij' h.seek(2) h.write('p') h.write('q') assert h.read(1) == 'e' h.seek(1) assert h.read(5) == 'bpqef' h2 = f.open('f2', 'rw') assert h2.read() == '' h2.write('mnop') h2.seek(1) assert h2.read() == 'nop' assert f.exists('f1') assert f.exists('f2') assert f.getsize('f1') == 10 assert f.getsize('f2') == 4
Python
# Written by Bram Cohen # see LICENSE.txt for license information from CurrentRateMeasure import Measure from random import shuffle from time import time from bitfield import Bitfield class SingleDownload: def __init__(self, downloader, connection): self.downloader = downloader self.connection = connection self.choked = True self.interested = False self.active_requests = [] self.measure = Measure(downloader.max_rate_period) self.have = Bitfield(downloader.numpieces) self.last = 0 self.example_interest = None def disconnected(self): self.downloader.downloads.remove(self) for i in xrange(len(self.have)): if self.have[i]: self.downloader.picker.lost_have(i) self._letgo() def _letgo(self): if not self.active_requests: return if self.downloader.storage.is_endgame(): self.active_requests = [] return lost = [] for index, begin, length in self.active_requests: self.downloader.storage.request_lost(index, begin, length) if index not in lost: lost.append(index) self.active_requests = [] ds = [d for d in self.downloader.downloads if not d.choked] shuffle(ds) for d in ds: d._request_more(lost) for d in self.downloader.downloads: if d.choked and not d.interested: for l in lost: if d.have[l] and self.downloader.storage.do_I_have_requests(l): d.interested = True d.connection.send_interested() break def got_choke(self): if not self.choked: self.choked = True self._letgo() def got_unchoke(self): if self.choked: self.choked = False if self.interested: self._request_more() def is_choked(self): return self.choked def is_interested(self): return self.interested def got_piece(self, index, begin, piece): try: self.active_requests.remove((index, begin, len(piece))) except ValueError: return False if self.downloader.storage.is_endgame(): self.downloader.all_requests.remove((index, begin, len(piece))) self.last = time() self.measure.update_rate(len(piece)) self.downloader.measurefunc(len(piece)) self.downloader.downmeasure.update_rate(len(piece)) if not self.downloader.storage.piece_came_in(index, begin, piece): if self.downloader.storage.is_endgame(): while self.downloader.storage.do_I_have_requests(index): nb, nl = self.downloader.storage.new_request(index) self.downloader.all_requests.append((index, nb, nl)) for d in self.downloader.downloads: d.fix_download_endgame() return False self.downloader.picker.bump(index) ds = [d for d in self.downloader.downloads if not d.choked] shuffle(ds) for d in ds: d._request_more([index]) return False if self.downloader.storage.do_I_have(index): self.downloader.picker.complete(index) if self.downloader.storage.is_endgame(): for d in self.downloader.downloads: if d is not self and d.interested: if d.choked: d.fix_download_endgame() else: try: d.active_requests.remove((index, begin, len(piece))) except ValueError: continue d.connection.send_cancel(index, begin, len(piece)) d.fix_download_endgame() self._request_more() if self.downloader.picker.am_I_complete(): for d in [i for i in self.downloader.downloads if i.have.numfalse == 0]: d.connection.close() return self.downloader.storage.do_I_have(index) def _want(self, index): return self.have[index] and self.downloader.storage.do_I_have_requests(index) def _request_more(self, indices = None): assert not self.choked if len(self.active_requests) == self.downloader.backlog: return if self.downloader.storage.is_endgame(): self.fix_download_endgame() return lost_interests = [] while len(self.active_requests) < self.downloader.backlog: if indices is None: interest = self.downloader.picker.next(self._want, self.have.numfalse == 0) else: interest = None for i in indices: if self.have[i] and self.downloader.storage.do_I_have_requests(i): interest = i break if interest is None: break if not self.interested: self.interested = True self.connection.send_interested() self.example_interest = interest begin, length = self.downloader.storage.new_request(interest) self.downloader.picker.requested(interest, self.have.numfalse == 0) self.active_requests.append((interest, begin, length)) self.connection.send_request(interest, begin, length) if not self.downloader.storage.do_I_have_requests(interest): lost_interests.append(interest) if not self.active_requests and self.interested: self.interested = False self.connection.send_not_interested() if lost_interests: for d in self.downloader.downloads: if d.active_requests or not d.interested: continue if d.example_interest is not None and self.downloader.storage.do_I_have_requests(d.example_interest): continue for lost in lost_interests: if d.have[lost]: break else: continue interest = self.downloader.picker.next(d._want, d.have.numfalse == 0) if interest is None: d.interested = False d.connection.send_not_interested() else: d.example_interest = interest if self.downloader.storage.is_endgame(): self.downloader.all_requests = [] for d in self.downloader.downloads: self.downloader.all_requests.extend(d.active_requests) for d in self.downloader.downloads: d.fix_download_endgame() def fix_download_endgame(self): want = [a for a in self.downloader.all_requests if self.have[a[0]] and a not in self.active_requests] if self.interested and not self.active_requests and not want: self.interested = False self.connection.send_not_interested() return if not self.interested and want: self.interested = True self.connection.send_interested() if self.choked: return shuffle(want) del want[self.downloader.backlog - len(self.active_requests):] self.active_requests.extend(want) for piece, begin, length in want: self.connection.send_request(piece, begin, length) def got_have(self, index): if self.have[index]: return self.have[index] = True self.downloader.picker.got_have(index) if self.downloader.picker.am_I_complete() and self.have.numfalse == 0: self.connection.close() return if self.downloader.storage.is_endgame(): self.fix_download_endgame() elif self.downloader.storage.do_I_have_requests(index): if not self.choked: self._request_more([index]) else: if not self.interested: self.interested = True self.connection.send_interested() def got_have_bitfield(self, have): self.have = have for i in xrange(len(self.have)): if self.have[i]: self.downloader.picker.got_have(i) if self.downloader.picker.am_I_complete() and self.have.numfalse == 0: self.connection.close() return if self.downloader.storage.is_endgame(): for piece, begin, length in self.downloader.all_requests: if self.have[piece]: self.interested = True self.connection.send_interested() return for i in xrange(len(self.have)): if self.have[i] and self.downloader.storage.do_I_have_requests(i): self.interested = True self.connection.send_interested() return def get_rate(self): return self.measure.get_rate() def is_snubbed(self): return time() - self.last > self.downloader.snub_time class Downloader: def __init__(self, storage, picker, backlog, max_rate_period, numpieces, downmeasure, snub_time, measurefunc = lambda x: None): self.storage = storage self.picker = picker self.backlog = backlog self.max_rate_period = max_rate_period self.downmeasure = downmeasure self.numpieces = numpieces self.snub_time = snub_time self.measurefunc = measurefunc self.downloads = [] def make_download(self, connection): self.downloads.append(SingleDownload(self, connection)) return self.downloads[-1] class DummyPicker: def __init__(self, num, r): self.stuff = range(num) self.r = r def next(self, wantfunc, seed): for i in self.stuff: if wantfunc(i): return i return None def lost_have(self, pos): self.r.append('lost have') def got_have(self, pos): self.r.append('got have') def requested(self, pos, seed): self.r.append('requested') def complete(self, pos): self.stuff.remove(pos) self.r.append('complete') def am_I_complete(self): return False def bump(self, i): pass class DummyStorage: def __init__(self, remaining, have_endgame = False, numpieces = 1): self.remaining = remaining self.active = [[] for i in xrange(numpieces)] self.endgame = False self.have_endgame = have_endgame def do_I_have_requests(self, index): return self.remaining[index] != [] def request_lost(self, index, begin, length): x = (begin, length) self.active[index].remove(x) self.remaining[index].append(x) self.remaining[index].sort() def piece_came_in(self, index, begin, piece): self.active[index].remove((begin, len(piece))) return True def do_I_have(self, index): return (self.remaining[index] == [] and self.active[index] == []) def new_request(self, index): x = self.remaining[index].pop() for i in self.remaining: if i: break else: self.endgame = True self.active[index].append(x) self.active[index].sort() return x def is_endgame(self): return self.have_endgame and self.endgame class DummyConnection: def __init__(self, events): self.events = events def send_interested(self): self.events.append('interested') def send_not_interested(self): self.events.append('not interested') def send_request(self, index, begin, length): self.events.append(('request', index, begin, length)) def send_cancel(self, index, begin, length): self.events.append(('cancel', index, begin, length)) def test_stops_at_backlog(): ds = DummyStorage([[(0, 2), (2, 2), (4, 2), (6, 2)]]) events = [] d = Downloader(ds, DummyPicker(len(ds.remaining), events), 2, 15, 1, Measure(15), 10) sd = d.make_download(DummyConnection(events)) assert events == [] assert ds.remaining == [[(0, 2), (2, 2), (4, 2), (6, 2)]] assert ds.active == [[]] sd.got_have_bitfield(Bitfield(1, chr(0x80))) assert events == ['got have', 'interested'] del events[:] assert ds.remaining == [[(0, 2), (2, 2), (4, 2), (6, 2)]] assert ds.active == [[]] sd.got_unchoke() assert events == ['requested', ('request', 0, 6, 2), 'requested', ('request', 0, 4, 2)] del events[:] assert ds.remaining == [[(0, 2), (2, 2)]] assert ds.active == [[(4, 2), (6, 2)]] sd.got_piece(0, 4, 'ab') assert events == ['requested', ('request', 0, 2, 2)] del events[:] assert ds.remaining == [[(0, 2)]] assert ds.active == [[(2, 2), (6, 2)]] def test_got_have_single(): ds = DummyStorage([[(0, 2)]]) events = [] d = Downloader(ds, DummyPicker(len(ds.remaining), events), 2, 15, 1, Measure(15), 10) sd = d.make_download(DummyConnection(events)) assert events == [] assert ds.remaining == [[(0, 2)]] assert ds.active == [[]] sd.got_unchoke() assert events == [] assert ds.remaining == [[(0, 2)]] assert ds.active == [[]] sd.got_have(0) assert events == ['got have', 'interested', 'requested', ('request', 0, 0, 2)] del events[:] assert ds.remaining == [[]] assert ds.active == [[(0, 2)]] sd.disconnected() assert events == ['lost have'] def test_choke_clears_active(): ds = DummyStorage([[(0, 2)]]) events = [] d = Downloader(ds, DummyPicker(len(ds.remaining), events), 2, 15, 1, Measure(15), 10) sd1 = d.make_download(DummyConnection(events)) sd2 = d.make_download(DummyConnection(events)) assert events == [] assert ds.remaining == [[(0, 2)]] assert ds.active == [[]] sd1.got_unchoke() sd1.got_have(0) assert events == ['got have', 'interested', 'requested', ('request', 0, 0, 2)] del events[:] assert ds.remaining == [[]] assert ds.active == [[(0, 2)]] sd2.got_unchoke() sd2.got_have(0) assert events == ['got have'] del events[:] assert ds.remaining == [[]] assert ds.active == [[(0, 2)]] sd1.got_choke() assert events == ['interested', 'requested', ('request', 0, 0, 2), 'not interested'] del events[:] assert ds.remaining == [[]] assert ds.active == [[(0, 2)]] sd2.got_piece(0, 0, 'ab') assert events == ['complete', 'not interested'] del events[:] assert ds.remaining == [[]] assert ds.active == [[]] def test_endgame(): ds = DummyStorage([[(0, 2)], [(0, 2)], [(0, 2)]], True, 3) events = [] d = Downloader(ds, DummyPicker(len(ds.remaining), events), 10, 15, 3, Measure(15), 10) ev1 = [] ev2 = [] ev3 = [] ev4 = [] sd1 = d.make_download(DummyConnection(ev1)) sd2 = d.make_download(DummyConnection(ev2)) sd3 = d.make_download(DummyConnection(ev3)) sd1.got_unchoke() sd1.got_have(0) assert ev1 == ['interested', ('request', 0, 0, 2)] del ev1[:] sd2.got_unchoke() sd2.got_have(0) sd2.got_have(1) assert ev2 == ['interested', ('request', 1, 0, 2)] del ev2[:] sd3.got_unchoke() sd3.got_have(0) sd3.got_have(1) sd3.got_have(2) assert (ev3 == ['interested', ('request', 2, 0, 2), ('request', 0, 0, 2), ('request', 1, 0, 2)] or ev3 == ['interested', ('request', 2, 0, 2), ('request', 1, 0, 2), ('request', 0, 0, 2)]) del ev3[:] assert ev2 == [('request', 0, 0, 2)] del ev2[:] sd2.got_piece(0, 0, 'ab') assert ev1 == [('cancel', 0, 0, 2), 'not interested'] del ev1[:] assert ev2 == [] assert ev3 == [('cancel', 0, 0, 2)] del ev3[:] sd3.got_choke() assert ev1 == [] assert ev2 == [] assert ev3 == [] sd3.got_unchoke() assert (ev3 == [('request', 2, 0, 2), ('request', 1, 0, 2)] or ev3 == [('request', 1, 0, 2), ('request', 2, 0, 2)]) del ev3[:] assert ev1 == [] assert ev2 == [] sd4 = d.make_download(DummyConnection(ev4)) sd4.got_have_bitfield([True, True, True]) assert ev4 == ['interested'] del ev4[:] sd4.got_unchoke() assert (ev4 == [('request', 2, 0, 2), ('request', 1, 0, 2)] or ev4 == [('request', 1, 0, 2), ('request', 2, 0, 2)]) assert ev1 == [] assert ev2 == [] assert ev3 == [] def test_stops_at_backlog_endgame(): ds = DummyStorage([[(2, 2), (0, 2)], [(2, 2), (0, 2)], [(0, 2)]], True, 3) events = [] d = Downloader(ds, DummyPicker(len(ds.remaining), events), 3, 15, 3, Measure(15), 10) ev1 = [] ev2 = [] ev3 = [] sd1 = d.make_download(DummyConnection(ev1)) sd2 = d.make_download(DummyConnection(ev2)) sd3 = d.make_download(DummyConnection(ev3)) sd1.got_unchoke() sd1.got_have(0) assert ev1 == ['interested', ('request', 0, 0, 2), ('request', 0, 2, 2)] del ev1[:] sd2.got_unchoke() sd2.got_have(0) assert ev2 == [] sd2.got_have(1) assert ev2 == ['interested', ('request', 1, 0, 2), ('request', 1, 2, 2)] del ev2[:] sd3.got_unchoke() sd3.got_have(2) assert (ev2 == [('request', 0, 0, 2)] or ev2 == [('request', 0, 2, 2)]) n = ev2[0][2] del ev2[:] sd1.got_piece(0, n, 'ab') assert ev1 == [] assert ev2 == [('cancel', 0, n, 2), ('request', 0, 2-n, 2)]
Python
# Written by Bram Cohen # see LICENSE.txt for license information from random import randrange class Choker: def __init__(self, max_uploads, schedule, done = lambda: False, min_uploads = None): self.max_uploads = max_uploads if min_uploads is None: min_uploads = max_uploads self.min_uploads = min_uploads self.schedule = schedule self.connections = [] self.count = 0 self.done = done schedule(self._round_robin, 10) def _round_robin(self): self.schedule(self._round_robin, 10) self.count += 1 if self.count % 3 == 0: for i in xrange(len(self.connections)): u = self.connections[i].get_upload() if u.is_choked() and u.is_interested(): self.connections = self.connections[i:] + self.connections[:i] break self._rechoke() def _snubbed(self, c): if self.done(): return False return c.get_download().is_snubbed() def _rate(self, c): if self.done(): return c.get_upload().get_rate() else: return c.get_download().get_rate() def _rechoke(self): preferred = [] for c in self.connections: if not self._snubbed(c) and c.get_upload().is_interested(): preferred.append((-self._rate(c), c)) preferred.sort() del preferred[self.max_uploads - 1:] preferred = [x[1] for x in preferred] count = len(preferred) hit = False for c in self.connections: u = c.get_upload() if c in preferred: u.unchoke() else: if count < self.min_uploads or not hit: u.unchoke() if u.is_interested(): count += 1 hit = True else: u.choke() def connection_made(self, connection, p = None): if p is None: p = randrange(-2, len(self.connections) + 1) self.connections.insert(max(p, 0), connection) self._rechoke() def connection_lost(self, connection): self.connections.remove(connection) if connection.get_upload().is_interested() and not connection.get_upload().is_choked(): self._rechoke() def interested(self, connection): if not connection.get_upload().is_choked(): self._rechoke() def not_interested(self, connection): if not connection.get_upload().is_choked(): self._rechoke() def change_max_uploads(self, newval): def foo(self=self, newval=newval): self._change_max_uploads(newval) self.schedule(foo, 0); def _change_max_uploads(self, newval): self.max_uploads = newval self._rechoke() class DummyScheduler: def __init__(self): self.s = [] def __call__(self, func, delay): self.s.append((func, delay)) class DummyConnection: def __init__(self, v = 0): self.u = DummyUploader() self.d = DummyDownloader(self) self.v = v def get_upload(self): return self.u def get_download(self): return self.d class DummyDownloader: def __init__(self, c): self.s = False self.c = c def is_snubbed(self): return self.s def get_rate(self): return self.c.v class DummyUploader: def __init__(self): self.i = False self.c = True def choke(self): if not self.c: self.c = True def unchoke(self): if self.c: self.c = False def is_choked(self): return self.c def is_interested(self): return self.i def test_round_robin_with_no_downloads(): s = DummyScheduler() Choker(2, s) assert len(s.s) == 1 assert s.s[0][1] == 10 s.s[0][0]() del s.s[0] assert len(s.s) == 1 assert s.s[0][1] == 10 s.s[0][0]() del s.s[0] s.s[0][0]() del s.s[0] s.s[0][0]() del s.s[0] def test_resort(): s = DummyScheduler() choker = Choker(1, s) c1 = DummyConnection() c2 = DummyConnection(1) c3 = DummyConnection(2) c4 = DummyConnection(3) c2.u.i = True c3.u.i = True choker.connection_made(c1) assert not c1.u.c choker.connection_made(c2, 1) assert not c1.u.c assert not c2.u.c choker.connection_made(c3, 1) assert not c1.u.c assert c2.u.c assert not c3.u.c c2.v = 2 c3.v = 1 choker.connection_made(c4, 1) assert not c1.u.c assert c2.u.c assert not c3.u.c assert not c4.u.c choker.connection_lost(c4) assert not c1.u.c assert c2.u.c assert not c3.u.c s.s[0][0]() assert not c1.u.c assert c2.u.c assert not c3.u.c def test_interest(): s = DummyScheduler() choker = Choker(1, s) c1 = DummyConnection() c2 = DummyConnection(1) c3 = DummyConnection(2) c2.u.i = True c3.u.i = True choker.connection_made(c1) assert not c1.u.c choker.connection_made(c2, 1) assert not c1.u.c assert not c2.u.c choker.connection_made(c3, 1) assert not c1.u.c assert c2.u.c assert not c3.u.c c3.u.i = False choker.not_interested(c3) assert not c1.u.c assert not c2.u.c assert not c3.u.c c3.u.i = True choker.interested(c3) assert not c1.u.c assert c2.u.c assert not c3.u.c choker.connection_lost(c3) assert not c1.u.c assert not c2.u.c def test_robin_interest(): s = DummyScheduler() choker = Choker(1, s) c1 = DummyConnection(0) c2 = DummyConnection(1) c1.u.i = True choker.connection_made(c2) assert not c2.u.c choker.connection_made(c1, 0) assert not c1.u.c assert c2.u.c c1.u.i = False choker.not_interested(c1) assert not c1.u.c assert not c2.u.c c1.u.i = True choker.interested(c1) assert not c1.u.c assert c2.u.c choker.connection_lost(c1) assert not c2.u.c def test_skip_not_interested(): s = DummyScheduler() choker = Choker(1, s) c1 = DummyConnection(0) c2 = DummyConnection(1) c3 = DummyConnection(2) c1.u.i = True c3.u.i = True choker.connection_made(c2) assert not c2.u.c choker.connection_made(c1, 0) assert not c1.u.c assert c2.u.c choker.connection_made(c3, 2) assert not c1.u.c assert c2.u.c assert c3.u.c f = s.s[0][0] f() assert not c1.u.c assert c2.u.c assert c3.u.c f() assert not c1.u.c assert c2.u.c assert c3.u.c f() assert c1.u.c assert c2.u.c assert not c3.u.c def test_connection_lost_no_interrupt(): s = DummyScheduler() choker = Choker(1, s) c1 = DummyConnection(0) c2 = DummyConnection(1) c3 = DummyConnection(2) c1.u.i = True c2.u.i = True c3.u.i = True choker.connection_made(c1) choker.connection_made(c2, 1) choker.connection_made(c3, 2) f = s.s[0][0] f() assert not c1.u.c assert c2.u.c assert c3.u.c f() assert not c1.u.c assert c2.u.c assert c3.u.c f() assert c1.u.c assert not c2.u.c assert c3.u.c f() assert c1.u.c assert not c2.u.c assert c3.u.c f() assert c1.u.c assert not c2.u.c assert c3.u.c choker.connection_lost(c3) assert c1.u.c assert not c2.u.c f() assert not c1.u.c assert c2.u.c choker.connection_lost(c2) assert not c1.u.c def test_connection_made_no_interrupt(): s = DummyScheduler() choker = Choker(1, s) c1 = DummyConnection(0) c2 = DummyConnection(1) c3 = DummyConnection(2) c1.u.i = True c2.u.i = True c3.u.i = True choker.connection_made(c1) choker.connection_made(c2, 1) f = s.s[0][0] assert not c1.u.c assert c2.u.c f() assert not c1.u.c assert c2.u.c f() assert not c1.u.c assert c2.u.c choker.connection_made(c3, 1) assert not c1.u.c assert c2.u.c assert c3.u.c f() assert c1.u.c assert c2.u.c assert not c3.u.c def test_round_robin(): s = DummyScheduler() choker = Choker(1, s) c1 = DummyConnection(0) c2 = DummyConnection(1) c1.u.i = True c2.u.i = True choker.connection_made(c1) choker.connection_made(c2, 1) f = s.s[0][0] assert not c1.u.c assert c2.u.c f() assert not c1.u.c assert c2.u.c f() assert not c1.u.c assert c2.u.c f() assert c1.u.c assert not c2.u.c f() assert c1.u.c assert not c2.u.c f() assert c1.u.c assert not c2.u.c f() assert not c1.u.c assert c2.u.c def test_multi(): s = DummyScheduler() choker = Choker(4, s) c1 = DummyConnection(0) c2 = DummyConnection(0) c3 = DummyConnection(0) c4 = DummyConnection(8) c5 = DummyConnection(0) c6 = DummyConnection(0) c7 = DummyConnection(6) c8 = DummyConnection(0) c9 = DummyConnection(9) c10 = DummyConnection(7) c11 = DummyConnection(10) choker.connection_made(c1, 0) choker.connection_made(c2, 1) choker.connection_made(c3, 2) choker.connection_made(c4, 3) choker.connection_made(c5, 4) choker.connection_made(c6, 5) choker.connection_made(c7, 6) choker.connection_made(c8, 7) choker.connection_made(c9, 8) choker.connection_made(c10, 9) choker.connection_made(c11, 10) c2.u.i = True c4.u.i = True c6.u.i = True c8.u.i = True c10.u.i = True c2.d.s = True c6.d.s = True c8.d.s = True s.s[0][0]() assert not c1.u.c assert not c2.u.c assert not c3.u.c assert not c4.u.c assert not c5.u.c assert not c6.u.c assert c7.u.c assert c8.u.c assert c9.u.c assert not c10.u.c assert c11.u.c
Python
# Written by Bram Cohen # see LICENSE.txt for license information from bisect import insort import socket from cStringIO import StringIO from traceback import print_exc from errno import EWOULDBLOCK, ENOBUFS try: from select import poll, error, POLLIN, POLLOUT, POLLERR, POLLHUP timemult = 1000 except ImportError: from selectpoll import poll, error, POLLIN, POLLOUT, POLLERR, POLLHUP timemult = 1 from threading import Thread, Event from time import time, sleep import sys from random import randrange all = POLLIN | POLLOUT class SingleSocket: def __init__(self, raw_server, sock, handler): self.raw_server = raw_server self.socket = sock self.handler = handler self.buffer = [] self.last_hit = time() self.fileno = sock.fileno() self.connected = False def get_ip(self): try: return self.socket.getpeername()[0] except socket.error: return 'no connection' def close(self): sock = self.socket self.socket = None self.buffer = [] del self.raw_server.single_sockets[self.fileno] self.raw_server.poll.unregister(sock) sock.close() def shutdown(self, val): self.socket.shutdown(val) def is_flushed(self): return len(self.buffer) == 0 def write(self, s): assert self.socket is not None self.buffer.append(s) if len(self.buffer) == 1: self.try_write() def try_write(self): if self.connected: try: while self.buffer != []: amount = self.socket.send(self.buffer[0]) if amount != len(self.buffer[0]): if amount != 0: self.buffer[0] = self.buffer[0][amount:] break del self.buffer[0] except socket.error, e: code, msg = e if code != EWOULDBLOCK: self.raw_server.dead_from_write.append(self) return if self.buffer == []: self.raw_server.poll.register(self.socket, POLLIN) else: self.raw_server.poll.register(self.socket, all) def default_error_handler(x): print x class RawServer: def __init__(self, doneflag, timeout_check_interval, timeout, noisy = True, errorfunc = default_error_handler, maxconnects = 55): self.timeout_check_interval = timeout_check_interval self.timeout = timeout self.poll = poll() # {socket: SingleSocket} self.single_sockets = {} self.dead_from_write = [] self.doneflag = doneflag self.noisy = noisy self.errorfunc = errorfunc self.maxconnects = maxconnects self.funcs = [] self.unscheduled_tasks = [] self.add_task(self.scan_for_timeouts, timeout_check_interval) def add_task(self, func, delay): self.unscheduled_tasks.append((func, delay)) def scan_for_timeouts(self): self.add_task(self.scan_for_timeouts, self.timeout_check_interval) t = time() - self.timeout tokill = [] for s in self.single_sockets.values(): if s.last_hit < t: tokill.append(s) for k in tokill: if k.socket is not None: self._close_socket(k) def bind(self, port, bind = '', reuse = False): self.bindaddr = bind server = socket.socket(socket.AF_INET, socket.SOCK_STREAM) if reuse: server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) server.setblocking(0) try: server.setsockopt(socket.IPPROTO_IP, socket.IP_TOS, 32) except: pass server.bind((bind, port)) server.listen(5) self.poll.register(server, POLLIN) self.server = server def start_connection(self, dns, handler = None): if handler is None: handler = self.handler sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.setblocking(0) try: sock.setsockopt(socket.IPPROTO_IP, socket.IP_TOS, 32) except: pass sock.bind((self.bindaddr, 0)) try: sock.connect_ex(dns) except socket.error: raise except Exception, e: raise socket.error(str(e)) self.poll.register(sock, POLLIN) s = SingleSocket(self, sock, handler) self.single_sockets[sock.fileno()] = s return s def handle_events(self, events): for sock, event in events: if sock == self.server.fileno(): if event & (POLLHUP | POLLERR) != 0: self.poll.unregister(self.server) self.server.close() self.errorfunc('lost server socket') else: try: newsock, addr = self.server.accept() newsock.setblocking(0) if len(self.single_sockets) >= self.maxconnects: newsock.close() continue nss = SingleSocket(self, newsock, self.handler) self.single_sockets[newsock.fileno()] = nss self.poll.register(newsock, POLLIN) self.handler.external_connection_made(nss) except socket.error: sleep(1) else: s = self.single_sockets.get(sock) if s is None: continue s.connected = True if (event & (POLLHUP | POLLERR)) != 0: self._close_socket(s) continue if (event & POLLIN) != 0: try: s.last_hit = time() data = s.socket.recv(100000) if data == '': self._close_socket(s) else: s.handler.data_came_in(s, data) except socket.error, e: code, msg = e if code != EWOULDBLOCK: self._close_socket(s) continue if (event & POLLOUT) != 0 and s.socket is not None and not s.is_flushed(): s.try_write() if s.is_flushed(): s.handler.connection_flushed(s) def pop_unscheduled(self): try: while True: (func, delay) = self.unscheduled_tasks.pop() insort(self.funcs, (time() + delay, func)) except IndexError: pass def listen_forever(self, handler): self.handler = handler try: while not self.doneflag.isSet(): try: self.pop_unscheduled() if len(self.funcs) == 0: period = 2 ** 30 else: period = self.funcs[0][0] - time() if period < 0: period = 0 events = self.poll.poll(period * timemult) if self.doneflag.isSet(): return while len(self.funcs) > 0 and self.funcs[0][0] <= time(): garbage, func = self.funcs[0] del self.funcs[0] try: func() except KeyboardInterrupt: print_exc() return except: if self.noisy: data = StringIO() print_exc(file = data) self.errorfunc(data.getvalue()) self._close_dead() self.handle_events(events) if self.doneflag.isSet(): return self._close_dead() except error, e: if self.doneflag.isSet(): return # I can't find a coherent explanation for what the behavior should be here, # and people report conflicting behavior, so I'll just try all the possibilities try: code, msg, desc = e except: try: code, msg = e except: code = ENOBUFS if code == ENOBUFS: self.errorfunc("Have to exit due to the TCP stack flaking out") return except KeyboardInterrupt: print_exc() return except: data = StringIO() print_exc(file = data) self.errorfunc(data.getvalue()) finally: for ss in self.single_sockets.values(): ss.close() self.server.close() def _close_dead(self): while len(self.dead_from_write) > 0: old = self.dead_from_write self.dead_from_write = [] for s in old: if s.socket is not None: self._close_socket(s) def _close_socket(self, s): sock = s.socket.fileno() s.socket.close() self.poll.unregister(sock) del self.single_sockets[sock] s.socket = None s.handler.connection_lost(s) # everything below is for testing class DummyHandler: def __init__(self): self.external_made = [] self.data_in = [] self.lost = [] def external_connection_made(self, s): self.external_made.append(s) def data_came_in(self, s, data): self.data_in.append((s, data)) def connection_lost(self, s): self.lost.append(s) def connection_flushed(self, s): pass def sl(rs, handler, port): rs.bind(port) Thread(target = rs.listen_forever, args = [handler]).start() def loop(rs): x = [] def r(rs = rs, x = x): rs.add_task(x[0], .1) x.append(r) rs.add_task(r, .1) beginport = 5000 + randrange(10000) def test_starting_side_close(): try: fa = Event() fb = Event() da = DummyHandler() sa = RawServer(fa, 100, 100) loop(sa) sl(sa, da, beginport) db = DummyHandler() sb = RawServer(fb, 100, 100) loop(sb) sl(sb, db, beginport + 1) sleep(.5) ca = sa.start_connection(('127.0.0.1', beginport + 1)) sleep(1) assert da.external_made == [] assert da.data_in == [] assert da.lost == [] assert len(db.external_made) == 1 cb = db.external_made[0] del db.external_made[:] assert db.data_in == [] assert db.lost == [] ca.write('aaa') cb.write('bbb') sleep(1) assert da.external_made == [] assert da.data_in == [(ca, 'bbb')] del da.data_in[:] assert da.lost == [] assert db.external_made == [] assert db.data_in == [(cb, 'aaa')] del db.data_in[:] assert db.lost == [] ca.write('ccc') cb.write('ddd') sleep(1) assert da.external_made == [] assert da.data_in == [(ca, 'ddd')] del da.data_in[:] assert da.lost == [] assert db.external_made == [] assert db.data_in == [(cb, 'ccc')] del db.data_in[:] assert db.lost == [] ca.close() sleep(1) assert da.external_made == [] assert da.data_in == [] assert da.lost == [] assert db.external_made == [] assert db.data_in == [] assert db.lost == [cb] del db.lost[:] finally: fa.set() fb.set() def test_receiving_side_close(): try: da = DummyHandler() fa = Event() sa = RawServer(fa, 100, 100) loop(sa) sl(sa, da, beginport + 2) db = DummyHandler() fb = Event() sb = RawServer(fb, 100, 100) loop(sb) sl(sb, db, beginport + 3) sleep(.5) ca = sa.start_connection(('127.0.0.1', beginport + 3)) sleep(1) assert da.external_made == [] assert da.data_in == [] assert da.lost == [] assert len(db.external_made) == 1 cb = db.external_made[0] del db.external_made[:] assert db.data_in == [] assert db.lost == [] ca.write('aaa') cb.write('bbb') sleep(1) assert da.external_made == [] assert da.data_in == [(ca, 'bbb')] del da.data_in[:] assert da.lost == [] assert db.external_made == [] assert db.data_in == [(cb, 'aaa')] del db.data_in[:] assert db.lost == [] ca.write('ccc') cb.write('ddd') sleep(1) assert da.external_made == [] assert da.data_in == [(ca, 'ddd')] del da.data_in[:] assert da.lost == [] assert db.external_made == [] assert db.data_in == [(cb, 'ccc')] del db.data_in[:] assert db.lost == [] cb.close() sleep(1) assert da.external_made == [] assert da.data_in == [] assert da.lost == [ca] del da.lost[:] assert db.external_made == [] assert db.data_in == [] assert db.lost == [] finally: fa.set() fb.set() def test_connection_refused(): try: da = DummyHandler() fa = Event() sa = RawServer(fa, 100, 100) loop(sa) sl(sa, da, beginport + 6) sleep(.5) ca = sa.start_connection(('127.0.0.1', beginport + 15)) sleep(1) assert da.external_made == [] assert da.data_in == [] assert da.lost == [ca] del da.lost[:] finally: fa.set() def test_both_close(): try: da = DummyHandler() fa = Event() sa = RawServer(fa, 100, 100) loop(sa) sl(sa, da, beginport + 4) sleep(1) db = DummyHandler() fb = Event() sb = RawServer(fb, 100, 100) loop(sb) sl(sb, db, beginport + 5) sleep(.5) ca = sa.start_connection(('127.0.0.1', beginport + 5)) sleep(1) assert da.external_made == [] assert da.data_in == [] assert da.lost == [] assert len(db.external_made) == 1 cb = db.external_made[0] del db.external_made[:] assert db.data_in == [] assert db.lost == [] ca.write('aaa') cb.write('bbb') sleep(1) assert da.external_made == [] assert da.data_in == [(ca, 'bbb')] del da.data_in[:] assert da.lost == [] assert db.external_made == [] assert db.data_in == [(cb, 'aaa')] del db.data_in[:] assert db.lost == [] ca.write('ccc') cb.write('ddd') sleep(1) assert da.external_made == [] assert da.data_in == [(ca, 'ddd')] del da.data_in[:] assert da.lost == [] assert db.external_made == [] assert db.data_in == [(cb, 'ccc')] del db.data_in[:] assert db.lost == [] ca.close() cb.close() sleep(1) assert da.external_made == [] assert da.data_in == [] assert da.lost == [] assert db.external_made == [] assert db.data_in == [] assert db.lost == [] finally: fa.set() fb.set() def test_normal(): l = [] f = Event() s = RawServer(f, 100, 100) loop(s) sl(s, DummyHandler(), beginport + 7) s.add_task(lambda l = l: l.append('b'), 2) s.add_task(lambda l = l: l.append('a'), 1) s.add_task(lambda l = l: l.append('d'), 4) sleep(1.5) s.add_task(lambda l = l: l.append('c'), 1.5) sleep(3) assert l == ['a', 'b', 'c', 'd'] f.set() def test_catch_exception(): l = [] f = Event() s = RawServer(f, 100, 100, False) loop(s) sl(s, DummyHandler(), beginport + 9) s.add_task(lambda l = l: l.append('b'), 2) s.add_task(lambda: 4/0, 1) sleep(3) assert l == ['b'] f.set() def test_closes_if_not_hit(): try: da = DummyHandler() fa = Event() sa = RawServer(fa, 2, 2) loop(sa) sl(sa, da, beginport + 14) sleep(1) db = DummyHandler() fb = Event() sb = RawServer(fb, 100, 100) loop(sb) sl(sb, db, beginport + 13) sleep(.5) sa.start_connection(('127.0.0.1', beginport + 13)) sleep(1) assert da.external_made == [] assert da.data_in == [] assert da.lost == [] assert len(db.external_made) == 1 del db.external_made[:] assert db.data_in == [] assert db.lost == [] sleep(3.1) assert len(da.lost) == 1 assert len(db.lost) == 1 finally: fa.set() fb.set() def test_does_not_close_if_hit(): try: fa = Event() fb = Event() da = DummyHandler() sa = RawServer(fa, 2, 2) loop(sa) sl(sa, da, beginport + 12) sleep(1) db = DummyHandler() sb = RawServer(fb, 100, 100) loop(sb) sl(sb, db, beginport + 13) sleep(.5) sa.start_connection(('127.0.0.1', beginport + 13)) sleep(1) assert da.external_made == [] assert da.data_in == [] assert da.lost == [] assert len(db.external_made) == 1 cb = db.external_made[0] del db.external_made[:] assert db.data_in == [] assert db.lost == [] cb.write('bbb') sleep(.5) assert da.lost == [] assert db.lost == [] finally: fa.set() fb.set()
Python
# Written by Bram Cohen # see LICENSE.txt for license information from select import select, error from time import sleep from types import IntType from bisect import bisect POLLIN = 1 POLLOUT = 2 POLLERR = 8 POLLHUP = 16 class poll: def __init__(self): self.rlist = [] self.wlist = [] def register(self, f, t): if type(f) != IntType: f = f.fileno() if (t & POLLIN) != 0: insert(self.rlist, f) else: remove(self.rlist, f) if (t & POLLOUT) != 0: insert(self.wlist, f) else: remove(self.wlist, f) def unregister(self, f): if type(f) != IntType: f = f.fileno() remove(self.rlist, f) remove(self.wlist, f) def poll(self, timeout = None): if self.rlist != [] or self.wlist != []: r, w, e = select(self.rlist, self.wlist, [], timeout) else: sleep(timeout) return [] result = [] for s in r: result.append((s, POLLIN)) for s in w: result.append((s, POLLOUT)) return result def remove(list, item): i = bisect(list, item) if i > 0 and list[i-1] == item: del list[i-1] def insert(list, item): i = bisect(list, item) if i == 0 or list[i-1] != item: list.insert(i, item) def test_remove(): x = [2, 4, 6] remove(x, 2) assert x == [4, 6] x = [2, 4, 6] remove(x, 4) assert x == [2, 6] x = [2, 4, 6] remove(x, 6) assert x == [2, 4] x = [2, 4, 6] remove(x, 5) assert x == [2, 4, 6] x = [2, 4, 6] remove(x, 1) assert x == [2, 4, 6] x = [2, 4, 6] remove(x, 7) assert x == [2, 4, 6] x = [2, 4, 6] remove(x, 5) assert x == [2, 4, 6] x = [] remove(x, 3) assert x == [] def test_insert(): x = [2, 4] insert(x, 1) assert x == [1, 2, 4] x = [2, 4] insert(x, 3) assert x == [2, 3, 4] x = [2, 4] insert(x, 5) assert x == [2, 4, 5] x = [2, 4] insert(x, 2) assert x == [2, 4] x = [2, 4] insert(x, 4) assert x == [2, 4] x = [2, 3, 4] insert(x, 3) assert x == [2, 3, 4] x = [] insert(x, 3) assert x == [3]
Python
# Written by Bram Cohen # see LICENSE.txt for license information from cStringIO import StringIO from binascii import b2a_hex from socket import error as socketerror protocol_name = 'BitTorrent protocol' def toint(s): return long(b2a_hex(s), 16) def tobinary(i): return (chr(i >> 24) + chr((i >> 16) & 0xFF) + chr((i >> 8) & 0xFF) + chr(i & 0xFF)) # header, reserved, download id, my id, [length, message] class Connection: def __init__(self, Encoder, connection, id, is_local): self.encoder = Encoder self.connection = connection self.id = id self.locally_initiated = is_local self.complete = False self.closed = False self.buffer = StringIO() self.next_len = 1 self.next_func = self.read_header_len if self.locally_initiated: connection.write(chr(len(protocol_name)) + protocol_name + (chr(0) * 8) + self.encoder.download_id) if self.id is not None: connection.write(self.encoder.my_id) def get_ip(self): return self.connection.get_ip() def get_id(self): return self.id def is_locally_initiated(self): return self.locally_initiated def is_flushed(self): return self.connection.is_flushed() def read_header_len(self, s): if ord(s) != len(protocol_name): return None return len(protocol_name), self.read_header def read_header(self, s): if s != protocol_name: return None return 8, self.read_reserved def read_reserved(self, s): return 20, self.read_download_id def read_download_id(self, s): if s != self.encoder.download_id: return None if not self.locally_initiated: self.connection.write(chr(len(protocol_name)) + protocol_name + (chr(0) * 8) + self.encoder.download_id + self.encoder.my_id) return 20, self.read_peer_id def read_peer_id(self, s): if not self.id: if s == self.encoder.my_id: return None for v in self.encoder.connections.values(): if s and v.id == s: return None self.id = s if self.locally_initiated: self.connection.write(self.encoder.my_id) else: self.encoder.everinc = True else: if s != self.id: return None self.complete = True self.encoder.connecter.connection_made(self) return 4, self.read_len def read_len(self, s): l = toint(s) if l > self.encoder.max_len: return None return l, self.read_message def read_message(self, s): if s != '': self.encoder.connecter.got_message(self, s) return 4, self.read_len def read_dead(self, s): return None def close(self): if not self.closed: self.connection.close() self.sever() def sever(self): self.closed = True del self.encoder.connections[self.connection] if self.complete: self.encoder.connecter.connection_lost(self) def send_message(self, message): self.connection.write(tobinary(len(message)) + message) def data_came_in(self, s): while True: if self.closed: return i = self.next_len - self.buffer.tell() if i > len(s): self.buffer.write(s) return self.buffer.write(s[:i]) s = s[i:] m = self.buffer.getvalue() self.buffer.reset() self.buffer.truncate() try: x = self.next_func(m) except: self.next_len, self.next_func = 1, self.read_dead raise if x is None: self.close() return self.next_len, self.next_func = x class Encoder: def __init__(self, connecter, raw_server, my_id, max_len, schedulefunc, keepalive_delay, download_id, max_initiate = 40): self.raw_server = raw_server self.connecter = connecter self.my_id = my_id self.max_len = max_len self.schedulefunc = schedulefunc self.keepalive_delay = keepalive_delay self.download_id = download_id self.max_initiate = max_initiate self.everinc = False self.connections = {} self.spares = [] schedulefunc(self.send_keepalives, keepalive_delay) def send_keepalives(self): self.schedulefunc(self.send_keepalives, self.keepalive_delay) for c in self.connections.values(): if c.complete: c.send_message('') def start_connection(self, dns, id): if id: if id == self.my_id: return for v in self.connections.values(): if v.id == id: return if len(self.connections) >= self.max_initiate: if len(self.spares) < self.max_initiate and dns not in self.spares: self.spares.append(dns) return try: c = self.raw_server.start_connection(dns) self.connections[c] = Connection(self, c, id, True) except socketerror: pass def _start_connection(self, dns, id): def foo(self=self, dns=dns, id=id): self.start_connection(dns, id) self.schedulefunc(foo, 0) def got_id(self, connection): for v in self.connections.values(): if connection is not v and connection.id == v.id: connection.close() return self.connecter.connection_made(connection) def ever_got_incoming(self): return self.everinc def external_connection_made(self, connection): self.connections[connection] = Connection(self, connection, None, False) def connection_flushed(self, connection): c = self.connections[connection] if c.complete: self.connecter.connection_flushed(c) def connection_lost(self, connection): self.connections[connection].sever() while len(self.connections) < self.max_initiate and self.spares: self.start_connection(self.spares.pop(), None) def data_came_in(self, connection, data): self.connections[connection].data_came_in(data) # everything below is for testing class DummyConnecter: def __init__(self): self.log = [] self.close_next = False def connection_made(self, connection): self.log.append(('made', connection)) def connection_lost(self, connection): self.log.append(('lost', connection)) def connection_flushed(self, connection): self.log.append(('flushed', connection)) def got_message(self, connection, message): self.log.append(('got', connection, message)) if self.close_next: connection.close() class DummyRawServer: def __init__(self): self.connects = [] def start_connection(self, dns): c = DummyRawConnection() self.connects.append((dns, c)) return c class DummyRawConnection: def __init__(self): self.closed = False self.data = [] self.flushed = True def get_ip(self): return 'fake.ip' def is_flushed(self): return self.flushed def write(self, data): assert not self.closed self.data.append(data) def close(self): assert not self.closed self.closed = True def pop(self): r = ''.join(self.data) del self.data[:] return r def dummyschedule(a, b): pass def test_messages_in_and_out(): c = DummyConnecter() rs = DummyRawServer() e = Encoder(c, rs, 'a' * 20, 500, dummyschedule, 30, 'd' * 20) c1 = DummyRawConnection() e.external_connection_made(c1) assert c1.pop() == '' assert c.log == [] assert rs.connects == [] assert not c1.closed e.data_came_in(c1, chr(len(protocol_name)) + protocol_name + \ chr(0) * 8 + 'd' * 20) assert c1.pop() == chr(len(protocol_name)) + protocol_name + \ chr(0) * 8 + 'd' * 20 + 'a' * 20 assert c.log == [] assert rs.connects == [] assert not c1.closed e.data_came_in(c1, 'b' * 20) assert c1.pop() == '' assert len(c.log) == 1 assert c.log[0][0] == 'made' ch = c.log[0][1] del c.log[:] assert rs.connects == [] assert not c1.closed assert ch.get_ip() == 'fake.ip' ch.send_message('abc') assert c1.pop() == chr(0) * 3 + chr(3) + 'abc' assert c.log == [] assert rs.connects == [] assert not c1.closed e.data_came_in(c1, chr(0) * 3 + chr(3) + 'def') assert c1.pop() == '' assert c.log == [('got', ch, 'def')] del c.log[:] assert rs.connects == [] assert not c1.closed def test_flushed(): c = DummyConnecter() rs = DummyRawServer() e = Encoder(c, rs, 'a' * 20, 500, dummyschedule, 30, 'd' * 20) c1 = DummyRawConnection() e.external_connection_made(c1) assert c1.pop() == '' assert c.log == [] assert rs.connects == [] assert not c1.closed e.data_came_in(c1, chr(len(protocol_name)) + protocol_name + \ chr(0) * 8 + 'd' * 20) assert c1.pop() == chr(len(protocol_name)) + protocol_name + \ chr(0) * 8 + 'd' * 20 + 'a' * 20 assert c1.pop() == '' assert c.log == [] assert rs.connects == [] assert not c1.closed e.connection_flushed(c1) assert c1.pop() == '' assert c.log == [] assert rs.connects == [] assert not c1.closed e.data_came_in(c1, 'b' * 20) assert c1.pop() == '' assert len(c.log) == 1 assert c.log[0][0] == 'made' ch = c.log[0][1] del c.log[:] assert rs.connects == [] assert not c1.closed assert ch.is_flushed() e.connection_flushed(c1) assert c1.pop() == '' assert c.log == [('flushed', ch)] assert rs.connects == [] assert not c1.closed c1.flushed = False assert not ch.is_flushed() def test_wrong_header_length(): c = DummyConnecter() rs = DummyRawServer() e = Encoder(c, rs, 'a' * 20, 500, dummyschedule, 30, 'd' * 20) c1 = DummyRawConnection() e.external_connection_made(c1) assert c1.pop() == '' assert c.log == [] assert rs.connects == [] assert not c1.closed e.data_came_in(c1, chr(5) * 30) assert c.log == [] assert c1.closed def test_wrong_header(): c = DummyConnecter() rs = DummyRawServer() e = Encoder(c, rs, 'a' * 20, 500, dummyschedule, 30, 'd' * 20) c1 = DummyRawConnection() e.external_connection_made(c1) assert c1.pop() == '' assert c.log == [] assert rs.connects == [] assert not c1.closed e.data_came_in(c1, chr(len(protocol_name)) + 'a' * len(protocol_name)) assert c.log == [] assert c1.closed def test_wrong_download_id(): c = DummyConnecter() rs = DummyRawServer() e = Encoder(c, rs, 'a' * 20, 500, dummyschedule, 30, 'd' * 20) c1 = DummyRawConnection() e.external_connection_made(c1) assert c1.pop() == '' assert c.log == [] assert rs.connects == [] assert not c1.closed e.data_came_in(c1, chr(len(protocol_name)) + protocol_name + chr(0) * 8 + 'e' * 20) assert c1.pop() == '' assert c.log == [] assert c1.closed def test_wrong_other_id(): c = DummyConnecter() rs = DummyRawServer() e = Encoder(c, rs, 'a' * 20, 500, dummyschedule, 30, 'd' * 20) e.start_connection('dns', 'o' * 20) assert c.log == [] assert len(rs.connects) == 1 assert rs.connects[0][0] == 'dns' c1 = rs.connects[0][1] del rs.connects[:] assert c1.pop() == chr(len(protocol_name)) + protocol_name + \ chr(0) * 8 + 'd' * 20 + 'a' * 20 assert not c1.closed e.data_came_in(c1, chr(len(protocol_name)) + protocol_name + chr(0) * 8 + 'd' * 20 + 'b' * 20) assert c.log == [] assert c1.closed def test_over_max_len(): c = DummyConnecter() rs = DummyRawServer() e = Encoder(c, rs, 'a' * 20, 500, dummyschedule, 30, 'd' * 20) c1 = DummyRawConnection() e.external_connection_made(c1) assert c1.pop() == '' assert c.log == [] assert rs.connects == [] assert not c1.closed e.data_came_in(c1, chr(len(protocol_name)) + protocol_name + chr(0) * 8 + 'd' * 20 + 'o' * 20) assert c1.pop() == chr(len(protocol_name)) + protocol_name + \ chr(0) * 8 + 'd' * 20 + 'a' * 20 assert len(c.log) == 1 and c.log[0][0] == 'made' ch = c.log[0][1] del c.log[:] assert not c1.closed e.data_came_in(c1, chr(1) + chr(0) * 3) assert c.log == [('lost', ch)] assert c1.closed def test_keepalive(): s = [] def sched(interval, thing, s = s): s.append((interval, thing)) c = DummyConnecter() rs = DummyRawServer() e = Encoder(c, rs, 'a' * 20, 500, sched, 30, 'd' * 20) assert len(s) == 1 assert s[0][1] == 30 kfunc = s[0][0] del s[:] c1 = DummyRawConnection() e.external_connection_made(c1) assert c1.pop() == '' assert c.log == [] assert not c1.closed kfunc() assert c1.pop() == '' assert c.log == [] assert not c1.closed assert s == [(kfunc, 30)] del s[:] e.data_came_in(c1, chr(len(protocol_name)) + protocol_name + chr(0) * 8 + 'd' * 20 + 'o' * 20) assert len(c.log) == 1 and c.log[0][0] == 'made' del c.log[:] assert c1.pop() == chr(len(protocol_name)) + protocol_name + \ chr(0) * 8 + 'd' * 20 + 'a' * 20 assert not c1.closed kfunc() assert c1.pop() == chr(0) * 4 assert c.log == [] assert not c1.closed def test_swallow_keepalive(): c = DummyConnecter() rs = DummyRawServer() e = Encoder(c, rs, 'a' * 20, 500, dummyschedule, 30, 'd' * 20) c1 = DummyRawConnection() e.external_connection_made(c1) assert c1.pop() == '' assert c.log == [] assert rs.connects == [] assert not c1.closed e.data_came_in(c1, chr(len(protocol_name)) + protocol_name + chr(0) * 8 + 'd' * 20 + 'o' * 20) assert c1.pop() == chr(len(protocol_name)) + protocol_name + \ chr(0) * 8 + 'd' * 20 + 'a' * 20 assert len(c.log) == 1 and c.log[0][0] == 'made' del c.log[:] assert not c1.closed e.data_came_in(c1, chr(0) * 4) assert c.log == [] assert not c1.closed def test_local_close(): c = DummyConnecter() rs = DummyRawServer() e = Encoder(c, rs, 'a' * 20, 500, dummyschedule, 30, 'd' * 20) c1 = DummyRawConnection() e.external_connection_made(c1) assert c1.pop() == '' assert c.log == [] assert rs.connects == [] assert not c1.closed e.data_came_in(c1, chr(len(protocol_name)) + protocol_name + chr(0) * 8 + 'd' * 20 + 'o' * 20) assert c1.pop() == chr(len(protocol_name)) + protocol_name + \ chr(0) * 8 + 'd' * 20 + 'a' * 20 assert len(c.log) == 1 and c.log[0][0] == 'made' ch = c.log[0][1] del c.log[:] assert not c1.closed ch.close() assert c.log == [('lost', ch)] del c.log[:] assert c1.closed def test_local_close_in_message_receive(): c = DummyConnecter() rs = DummyRawServer() e = Encoder(c, rs, 'a' * 20, 500, dummyschedule, 30, 'd' * 20) c1 = DummyRawConnection() e.external_connection_made(c1) assert c1.pop() == '' assert c.log == [] assert rs.connects == [] assert not c1.closed e.data_came_in(c1, chr(len(protocol_name)) + protocol_name + chr(0) * 8 + 'd' * 20 + 'o' * 20) assert c1.pop() == chr(len(protocol_name)) + protocol_name + \ chr(0) * 8 + 'd' * 20 + 'a' * 20 assert len(c.log) == 1 and c.log[0][0] == 'made' ch = c.log[0][1] del c.log[:] assert not c1.closed c.close_next = True e.data_came_in(c1, chr(0) * 3 + chr(4) + 'abcd') assert c.log == [('got', ch, 'abcd'), ('lost', ch)] assert c1.closed def test_remote_close(): c = DummyConnecter() rs = DummyRawServer() e = Encoder(c, rs, 'a' * 20, 500, dummyschedule, 30, 'd' * 20) c1 = DummyRawConnection() e.external_connection_made(c1) assert c1.pop() == '' assert c.log == [] assert rs.connects == [] assert not c1.closed e.data_came_in(c1, chr(len(protocol_name)) + protocol_name + chr(0) * 8 + 'd' * 20 + 'o' * 20) assert c1.pop() == chr(len(protocol_name)) + protocol_name + \ chr(0) * 8 + 'd' * 20 + 'a' * 20 assert len(c.log) == 1 and c.log[0][0] == 'made' ch = c.log[0][1] del c.log[:] assert not c1.closed e.connection_lost(c1) assert c.log == [('lost', ch)] assert not c1.closed def test_partial_data_in(): c = DummyConnecter() rs = DummyRawServer() e = Encoder(c, rs, 'a' * 20, 500, dummyschedule, 30, 'd' * 20) c1 = DummyRawConnection() e.external_connection_made(c1) assert c1.pop() == '' assert c.log == [] assert rs.connects == [] assert not c1.closed e.data_came_in(c1, chr(len(protocol_name)) + protocol_name + chr(0) * 4) e.data_came_in(c1, chr(0) * 4 + 'd' * 20 + 'c' * 10) e.data_came_in(c1, 'c' * 10) assert c1.pop() == chr(len(protocol_name)) + protocol_name + \ chr(0) * 8 + 'd' * 20 + 'a' * 20 assert len(c.log) == 1 and c.log[0][0] == 'made' del c.log[:] assert not c1.closed def test_ignore_connect_of_extant(): c = DummyConnecter() rs = DummyRawServer() e = Encoder(c, rs, 'a' * 20, 500, dummyschedule, 30, 'd' * 20) c1 = DummyRawConnection() e.external_connection_made(c1) assert c1.pop() == '' assert c.log == [] assert rs.connects == [] assert not c1.closed e.data_came_in(c1, chr(len(protocol_name)) + protocol_name + chr(0) * 8 + 'd' * 20 + 'o' * 20) assert c1.pop() == chr(len(protocol_name)) + protocol_name + \ chr(0) * 8 + 'd' * 20 + 'a' * 20 assert len(c.log) == 1 and c.log[0][0] == 'made' del c.log[:] assert not c1.closed e.start_connection('dns', 'o' * 20) assert c.log == [] assert rs.connects == [] assert not c1.closed def test_ignore_connect_to_self(): c = DummyConnecter() rs = DummyRawServer() e = Encoder(c, rs, 'a' * 20, 500, dummyschedule, 30, 'd' * 20) c1 = DummyRawConnection() e.start_connection('dns', 'a' * 20) assert c.log == [] assert rs.connects == [] assert not c1.closed def test_conversion(): assert toint(tobinary(50000)) == 50000
Python
# Written by Bram Cohen # see LICENSE.txt for license information from time import time class DownloaderFeedback: def __init__(self, choker, add_task, statusfunc, upfunc, downfunc, uptotal, downtotal, remainingfunc, leftfunc, file_length, finflag, interval, spewflag): self.choker = choker self.add_task = add_task self.statusfunc = statusfunc self.upfunc = upfunc self.downfunc = downfunc self.uptotal = uptotal self.downtotal = downtotal self.remainingfunc = remainingfunc self.leftfunc = leftfunc self.file_length = file_length self.finflag = finflag self.interval = interval self.spewflag = spewflag self.lastids = [] self.display() def _rotate(self): cs = self.choker.connections for id in self.lastids: for i in xrange(len(cs)): if cs[i].get_id() == id: return cs[i:] + cs[:i] return cs def collect_spew(self): l = [ ] cs = self._rotate() self.lastids = [c.get_id() for c in cs] for c in cs: rec = {} rec["ip"] = c.get_ip() if c is self.choker.connections[0]: rec["is_optimistic_unchoke"] = 1 else: rec["is_optimistic_unchoke"] = 0 if c.is_locally_initiated(): rec["initiation"] = "local" else: rec["initiation"] = "remote" u = c.get_upload() rec["upload"] = (int(u.measure.get_rate()), u.is_interested(), u.is_choked()) d = c.get_download() rec["download"] = (int(d.measure.get_rate()), d.is_interested(), d.is_choked(), d.is_snubbed()) l.append(rec) return l def display(self): self.add_task(self.display, self.interval) spew = [] if self.finflag.isSet(): status = {"upRate" : self.upfunc(), "upTotal" : self.uptotal() / 1048576.0} if self.spewflag.isSet(): status['spew'] = self.collect_spew() self.statusfunc(status) return timeEst = self.remainingfunc() if self.file_length > 0: fractionDone = (self.file_length - self.leftfunc()) / float(self.file_length) else: fractionDone = 1 status = { "fractionDone" : fractionDone, "downRate" : self.downfunc(), "upRate" : self.upfunc(), "upTotal" : self.uptotal() / 1048576.0, "downTotal" : self.downtotal() / 1048576.0 } if timeEst is not None: status['timeEst'] = timeEst if self.spewflag.isSet(): status['spew'] = self.collect_spew() self.statusfunc(status)
Python
# Written by Bram Cohen # see LICENSE.txt for license information from sha import sha from bisect import bisect_right class Storage: def __init__(self, files, open, exists, getsize): # can raise IOError and ValueError self.ranges = [] total = 0l so_far = 0l for file, length in files: if length != 0: self.ranges.append((total, total + length, file)) total += length if exists(file): l = getsize(file) if l > length: l = length so_far += l elif not exists(file): open(file, 'wb').close() self.begins = [i[0] for i in self.ranges] self.total_length = total self.handles = {} self.whandles = {} self.tops = {} for file, length in files: if exists(file): l = getsize(file) if l != length: self.handles[file] = open(file, 'rb+') self.whandles[file] = 1 if l > length: self.handles[file].truncate(length) else: self.handles[file] = open(file, 'rb') self.tops[file] = l else: self.handles[file] = open(file, 'wb+') self.whandles[file] = 1 def was_preallocated(self, pos, length): for file, begin, end in self._intervals(pos, length): if self.tops.get(file, 0) < end: return False return True def set_readonly(self): # may raise IOError or OSError for file in self.whandles.keys(): old = self.handles[file] old.flush() old.close() self.handles[file] = open(file, 'rb') def get_total_length(self): return self.total_length def _intervals(self, pos, amount): r = [] stop = pos + amount p = bisect_right(self.begins, pos) - 1 while p < len(self.ranges) and self.ranges[p][0] < stop: begin, end, file = self.ranges[p] r.append((file, max(pos, begin) - begin, min(end, stop) - begin)) p += 1 return r def read(self, pos, amount): r = [] for file, pos, end in self._intervals(pos, amount): h = self.handles[file] h.seek(pos) r.append(h.read(end - pos)) return ''.join(r) def write(self, pos, s): # might raise an IOError total = 0 for file, begin, end in self._intervals(pos, len(s)): if not self.whandles.has_key(file): self.handles[file].close() self.handles[file] = open(file, 'rb+') self.whandles[file] = 1 h = self.handles[file] h.seek(begin) h.write(s[total: total + end - begin]) total += end - begin def close(self): for h in self.handles.values(): h.close() def lrange(a, b, c): r = [] while a < b: r.append(a) a += c return r # everything below is for testing from fakeopen import FakeOpen def test_Storage_simple(): f = FakeOpen() m = Storage([('a', 5)], f.open, f.exists, f.getsize) assert f.files.keys() == ['a'] m.write(0, 'abc') assert m.read(0, 3) == 'abc' m.write(2, 'abc') assert m.read(2, 3) == 'abc' m.write(1, 'abc') assert m.read(0, 5) == 'aabcc' def test_Storage_multiple(): f = FakeOpen() m = Storage([('a', 5), ('2', 4), ('c', 3)], f.open, f.exists, f.getsize) x = f.files.keys() x.sort() assert x == ['2', 'a', 'c'] m.write(3, 'abc') assert m.read(3, 3) == 'abc' m.write(5, 'ab') assert m.read(4, 3) == 'bab' m.write(3, 'pqrstuvw') assert m.read(3, 8) == 'pqrstuvw' m.write(3, 'abcdef') assert m.read(3, 7) == 'abcdefv' def test_Storage_zero(): f = FakeOpen() Storage([('a', 0)], f.open, f.exists, f.getsize) assert f.files == {'a': []} def test_resume_zero(): f = FakeOpen({'a': ''}) Storage([('a', 0)], f.open, f.exists, f.getsize) assert f.files == {'a': []} def test_Storage_with_zero(): f = FakeOpen() m = Storage([('a', 3), ('b', 0), ('c', 3)], f.open, f.exists, f.getsize) m.write(2, 'abc') assert m.read(2, 3) == 'abc' x = f.files.keys() x.sort() assert x == ['a', 'b', 'c'] assert len(f.files['a']) == 3 assert len(f.files['b']) == 0 def test_Storage_resume(): f = FakeOpen({'a': 'abc'}) m = Storage([('a', 4)], f.open, f.exists, f.getsize) assert f.files.keys() == ['a'] assert m.read(0, 3) == 'abc' def test_Storage_mixed_resume(): f = FakeOpen({'b': 'abc'}) m = Storage([('a', 3), ('b', 4)], f.open, f.exists, f.getsize) x = f.files.keys() x.sort() assert x == ['a', 'b'] assert m.read(3, 3) == 'abc'
Python
""" A much simpler testing framework than PyUnit tests a module by running all functions in it whose name starts with 'test' a test fails if it raises an exception, otherwise it passes functions are try_all and try_single """ # Written by Bram Cohen # see LICENSE.txt for license information from traceback import print_exc from sys import modules def try_all(excludes = [], excluded_paths=[]): """ tests all imported modules takes an optional list of module names and/or module objects to skip over. modules from files under under any of excluded_paths are also skipped. """ failed = [] for modulename, module in modules.items(): # skip builtins if not hasattr(module, '__file__'): continue # skip modules under any of excluded_paths if [p for p in excluded_paths if module.__file__.startswith(p)]: continue if modulename not in excludes and module not in excludes: try_module(module, modulename, failed) print_failed(failed) def try_single(m): """ tests a single module accepts either a module object or a module name in string form """ if type(m) is str: modulename = m module = __import__(m) else: modulename = str(m) module = m failed = [] try_module(module, modulename, failed) print_failed(failed) def try_module(module, modulename, failed): if not hasattr(module, '__dict__'): return for n, func in module.__dict__.items(): if not callable(func) or n[:4] != 'test': continue name = modulename + '.' + n try: print 'trying ' + name func() print 'passed ' + name except: print_exc() failed.append(name) print 'failed ' + name def print_failed(failed): print if len(failed) == 0: print 'everything passed' else: print 'the following tests failed:' for i in failed: print i
Python
# Written by Bram Cohen # see LICENSE.txt for license information from time import time class Measure: def __init__(self, max_rate_period, fudge = 1): self.max_rate_period = max_rate_period self.ratesince = time() - fudge self.last = self.ratesince self.rate = 0.0 self.total = 0l def update_rate(self, amount): self.total += amount t = time() self.rate = (self.rate * (self.last - self.ratesince) + amount) / (t - self.ratesince) self.last = t if self.ratesince < t - self.max_rate_period: self.ratesince = t - self.max_rate_period def get_rate(self): self.update_rate(0) return self.rate def get_rate_noupdate(self): return self.rate def time_until_rate(self, newrate): if self.rate <= newrate: return 0 t = time() - self.ratesince return ((self.rate * t) / newrate) - t def get_total(self): return self.total
Python
# Written by Petru Paler # see LICENSE.txt for license information def decode_int(x, f): f += 1 newf = x.index('e', f) try: n = int(x[f:newf]) except (OverflowError, ValueError): n = long(x[f:newf]) if x[f] == '-': if x[f + 1] == '0': raise ValueError elif x[f] == '0' and newf != f+1: raise ValueError return (n, newf+1) def decode_string(x, f): colon = x.index(':', f) try: n = int(x[f:colon]) except (OverflowError, ValueError): n = long(x[f:colon]) if x[f] == '0' and colon != f+1: raise ValueError colon += 1 return (x[colon:colon+n], colon+n) def decode_list(x, f): r, f = [], f+1 while x[f] != 'e': v, f = decode_func[x[f]](x, f) r.append(v) return (r, f + 1) def decode_dict(x, f): r, f = {}, f+1 lastkey = None while x[f] != 'e': k, f = decode_string(x, f) if lastkey >= k: raise ValueError lastkey = k r[k], f = decode_func[x[f]](x, f) return (r, f + 1) decode_func = {} decode_func['l'] = decode_list decode_func['d'] = decode_dict decode_func['i'] = decode_int decode_func['0'] = decode_string decode_func['1'] = decode_string decode_func['2'] = decode_string decode_func['3'] = decode_string decode_func['4'] = decode_string decode_func['5'] = decode_string decode_func['6'] = decode_string decode_func['7'] = decode_string decode_func['8'] = decode_string decode_func['9'] = decode_string def bdecode(x): try: r, l = decode_func[x[0]](x, 0) except (IndexError, KeyError): raise ValueError if l != len(x): raise ValueError return r def test_bdecode(): try: bdecode('0:0:') assert 0 except ValueError: pass try: bdecode('ie') assert 0 except ValueError: pass try: bdecode('i341foo382e') assert 0 except ValueError: pass assert bdecode('i4e') == 4L assert bdecode('i0e') == 0L assert bdecode('i123456789e') == 123456789L assert bdecode('i-10e') == -10L try: bdecode('i-0e') assert 0 except ValueError: pass try: bdecode('i123') assert 0 except ValueError: pass try: bdecode('') assert 0 except ValueError: pass try: bdecode('i6easd') assert 0 except ValueError: pass try: bdecode('35208734823ljdahflajhdf') assert 0 except ValueError: pass try: bdecode('2:abfdjslhfld') assert 0 except ValueError: pass assert bdecode('0:') == '' assert bdecode('3:abc') == 'abc' assert bdecode('10:1234567890') == '1234567890' try: bdecode('02:xy') assert 0 except ValueError: pass try: bdecode('l') assert 0 except ValueError: pass assert bdecode('le') == [] try: bdecode('leanfdldjfh') assert 0 except ValueError: pass assert bdecode('l0:0:0:e') == ['', '', ''] try: bdecode('relwjhrlewjh') assert 0 except ValueError: pass assert bdecode('li1ei2ei3ee') == [1, 2, 3] assert bdecode('l3:asd2:xye') == ['asd', 'xy'] assert bdecode('ll5:Alice3:Bobeli2ei3eee') == [['Alice', 'Bob'], [2, 3]] try: bdecode('d') assert 0 except ValueError: pass try: bdecode('defoobar') assert 0 except ValueError: pass assert bdecode('de') == {} assert bdecode('d3:agei25e4:eyes4:bluee') == {'age': 25, 'eyes': 'blue'} assert bdecode('d8:spam.mp3d6:author5:Alice6:lengthi100000eee') == {'spam.mp3': {'author': 'Alice', 'length': 100000}} try: bdecode('d3:fooe') assert 0 except ValueError: pass try: bdecode('di1e0:e') assert 0 except ValueError: pass try: bdecode('d1:b0:1:a0:e') assert 0 except ValueError: pass try: bdecode('d1:a0:1:a0:e') assert 0 except ValueError: pass try: bdecode('i03e') assert 0 except ValueError: pass try: bdecode('l01:ae') assert 0 except ValueError: pass try: bdecode('9999:x') assert 0 except ValueError: pass try: bdecode('l0:') assert 0 except ValueError: pass try: bdecode('d0:0:') assert 0 except ValueError: pass try: bdecode('d0:') assert 0 except ValueError: pass try: bdecode('00:') assert 0 except ValueError: pass try: bdecode('l-3:e') assert 0 except ValueError: pass try: bdecode('i-03e') assert 0 except ValueError: pass bdecode('d0:i3ee') from types import StringType, IntType, LongType, DictType, ListType, TupleType class Bencached(object): __slots__ = ['bencoded'] def __init__(self, s): self.bencoded = s def encode_bencached(x,r): r.append(x.bencoded) def encode_int(x, r): r.extend(('i', str(x), 'e')) def encode_string(x, r): r.extend((str(len(x)), ':', x)) def encode_list(x, r): r.append('l') for i in x: encode_func[type(i)](i, r) r.append('e') def encode_dict(x,r): r.append('d') ilist = x.items() ilist.sort() for k, v in ilist: r.extend((str(len(k)), ':', k)) encode_func[type(v)](v, r) r.append('e') encode_func = {} encode_func[type(Bencached(0))] = encode_bencached encode_func[IntType] = encode_int encode_func[LongType] = encode_int encode_func[StringType] = encode_string encode_func[ListType] = encode_list encode_func[TupleType] = encode_list encode_func[DictType] = encode_dict try: from types import BooleanType encode_func[BooleanType] = encode_int except ImportError: pass def bencode(x): r = [] encode_func[type(x)](x, r) return ''.join(r) def test_bencode(): assert bencode(4) == 'i4e' assert bencode(0) == 'i0e' assert bencode(-10) == 'i-10e' assert bencode(12345678901234567890L) == 'i12345678901234567890e' assert bencode('') == '0:' assert bencode('abc') == '3:abc' assert bencode('1234567890') == '10:1234567890' assert bencode([]) == 'le' assert bencode([1, 2, 3]) == 'li1ei2ei3ee' assert bencode([['Alice', 'Bob'], [2, 3]]) == 'll5:Alice3:Bobeli2ei3eee' assert bencode({}) == 'de' assert bencode({'age': 25, 'eyes': 'blue'}) == 'd3:agei25e4:eyes4:bluee' assert bencode({'spam.mp3': {'author': 'Alice', 'length': 100000}}) == 'd8:spam.mp3d6:author5:Alice6:lengthi100000eee' assert bencode(Bencached(bencode(3))) == 'i3e' try: bencode({1: 'foo'}) except TypeError: return assert 0 try: import psyco psyco.bind(bdecode) psyco.bind(bencode) except ImportError: pass
Python
# Written by Bram Cohen # see LICENSE.txt for license information from bitfield import Bitfield from binascii import b2a_hex from CurrentRateMeasure import Measure def toint(s): return long(b2a_hex(s), 16) def tobinary(i): return (chr(i >> 24) + chr((i >> 16) & 0xFF) + chr((i >> 8) & 0xFF) + chr(i & 0xFF)) CHOKE = chr(0) UNCHOKE = chr(1) INTERESTED = chr(2) NOT_INTERESTED = chr(3) # index HAVE = chr(4) # index, bitfield BITFIELD = chr(5) # index, begin, length REQUEST = chr(6) # index, begin, piece PIECE = chr(7) # index, begin, piece CANCEL = chr(8) class Connection: def __init__(self, connection, connecter): self.connection = connection self.connecter = connecter self.got_anything = False def get_ip(self): return self.connection.get_ip() def get_id(self): return self.connection.get_id() def close(self): self.connection.close() def is_flushed(self): if self.connecter.rate_capped: return False return self.connection.is_flushed() def is_locally_initiated(self): return self.connection.is_locally_initiated() def send_interested(self): self.connection.send_message(INTERESTED) def send_not_interested(self): self.connection.send_message(NOT_INTERESTED) def send_choke(self): self.connection.send_message(CHOKE) def send_unchoke(self): self.connection.send_message(UNCHOKE) def send_request(self, index, begin, length): self.connection.send_message(REQUEST + tobinary(index) + tobinary(begin) + tobinary(length)) def send_cancel(self, index, begin, length): self.connection.send_message(CANCEL + tobinary(index) + tobinary(begin) + tobinary(length)) def send_piece(self, index, begin, piece): assert not self.connecter.rate_capped self.connecter._update_upload_rate(len(piece)) self.connection.send_message(PIECE + tobinary(index) + tobinary(begin) + piece) def send_bitfield(self, bitfield): self.connection.send_message(BITFIELD + bitfield) def send_have(self, index): self.connection.send_message(HAVE + tobinary(index)) def get_upload(self): return self.upload def get_download(self): return self.download class Connecter: def __init__(self, make_upload, downloader, choker, numpieces, totalup, max_upload_rate = 0, sched = None): self.downloader = downloader self.make_upload = make_upload self.choker = choker self.numpieces = numpieces self.max_upload_rate = max_upload_rate self.sched = sched self.totalup = totalup self.rate_capped = False self.connections = {} def _update_upload_rate(self, amount): self.totalup.update_rate(amount) if self.max_upload_rate > 0 and self.totalup.get_rate_noupdate() > self.max_upload_rate: self.rate_capped = True self.sched(self._uncap, self.totalup.time_until_rate(self.max_upload_rate)) def _uncap(self): self.rate_capped = False while not self.rate_capped: up = None minrate = None for i in self.connections.values(): if not i.upload.is_choked() and i.upload.has_queries() and i.connection.is_flushed(): rate = i.upload.get_rate() if up is None or rate < minrate: up = i.upload minrate = rate if up is None: break up.flushed() if self.totalup.get_rate_noupdate() > self.max_upload_rate: break def change_max_upload_rate(self, newval): def foo(self=self, newval=newval): self._change_max_upload_rate(newval) self.sched(foo, 0); def _change_max_upload_rate(self, newval): self.max_upload_rate = newval self._uncap() def how_many_connections(self): return len(self.connections) def connection_made(self, connection): c = Connection(connection, self) self.connections[connection] = c c.upload = self.make_upload(c) c.download = self.downloader.make_download(c) self.choker.connection_made(c) def connection_lost(self, connection): c = self.connections[connection] d = c.download del self.connections[connection] d.disconnected() self.choker.connection_lost(c) def connection_flushed(self, connection): self.connections[connection].upload.flushed() def got_message(self, connection, message): c = self.connections[connection] t = message[0] if t == BITFIELD and c.got_anything: connection.close() return c.got_anything = True if (t in [CHOKE, UNCHOKE, INTERESTED, NOT_INTERESTED] and len(message) != 1): connection.close() return if t == CHOKE: c.download.got_choke() elif t == UNCHOKE: c.download.got_unchoke() elif t == INTERESTED: c.upload.got_interested() elif t == NOT_INTERESTED: c.upload.got_not_interested() elif t == HAVE: if len(message) != 5: connection.close() return i = toint(message[1:]) if i >= self.numpieces: connection.close() return c.download.got_have(i) elif t == BITFIELD: try: b = Bitfield(self.numpieces, message[1:]) except ValueError: connection.close() return c.download.got_have_bitfield(b) elif t == REQUEST: if len(message) != 13: connection.close() return i = toint(message[1:5]) if i >= self.numpieces: connection.close() return c.upload.got_request(i, toint(message[5:9]), toint(message[9:])) elif t == CANCEL: if len(message) != 13: connection.close() return i = toint(message[1:5]) if i >= self.numpieces: connection.close() return c.upload.got_cancel(i, toint(message[5:9]), toint(message[9:])) elif t == PIECE: if len(message) <= 9: connection.close() return i = toint(message[1:5]) if i >= self.numpieces: connection.close() return if c.download.got_piece(i, toint(message[5:9]), message[9:]): for co in self.connections.values(): co.send_have(i) else: connection.close() class DummyUpload: def __init__(self, events): self.events = events events.append('made upload') def flushed(self): self.events.append('flushed') def got_interested(self): self.events.append('interested') def got_not_interested(self): self.events.append('not interested') def got_request(self, index, begin, length): self.events.append(('request', index, begin, length)) def got_cancel(self, index, begin, length): self.events.append(('cancel', index, begin, length)) class DummyDownload: def __init__(self, events): self.events = events events.append('made download') self.hit = 0 def disconnected(self): self.events.append('disconnected') def got_choke(self): self.events.append('choke') def got_unchoke(self): self.events.append('unchoke') def got_have(self, i): self.events.append(('have', i)) def got_have_bitfield(self, bitfield): self.events.append(('bitfield', bitfield.tostring())) def got_piece(self, index, begin, piece): self.events.append(('piece', index, begin, piece)) self.hit += 1 return self.hit > 1 class DummyDownloader: def __init__(self, events): self.events = events def make_download(self, connection): return DummyDownload(self.events) class DummyConnection: def __init__(self, events): self.events = events def send_message(self, message): self.events.append(('m', message)) class DummyChoker: def __init__(self, events, cs): self.events = events self.cs = cs def connection_made(self, c): self.events.append('made') self.cs.append(c) def connection_lost(self, c): self.events.append('lost') def test_operation(): events = [] cs = [] co = Connecter(lambda c, events = events: DummyUpload(events), DummyDownloader(events), DummyChoker(events, cs), 3, Measure(10)) assert events == [] assert cs == [] dc = DummyConnection(events) co.connection_made(dc) assert len(cs) == 1 cc = cs[0] co.got_message(dc, BITFIELD + chr(0xc0)) co.got_message(dc, CHOKE) co.got_message(dc, UNCHOKE) co.got_message(dc, INTERESTED) co.got_message(dc, NOT_INTERESTED) co.got_message(dc, HAVE + tobinary(2)) co.got_message(dc, REQUEST + tobinary(1) + tobinary(5) + tobinary(6)) co.got_message(dc, CANCEL + tobinary(2) + tobinary(3) + tobinary(4)) co.got_message(dc, PIECE + tobinary(1) + tobinary(0) + 'abc') co.got_message(dc, PIECE + tobinary(1) + tobinary(3) + 'def') co.connection_flushed(dc) cc.send_bitfield(chr(0x60)) cc.send_interested() cc.send_not_interested() cc.send_choke() cc.send_unchoke() cc.send_have(4) cc.send_request(0, 2, 1) cc.send_cancel(1, 2, 3) cc.send_piece(1, 2, 'abc') co.connection_lost(dc) x = ['made upload', 'made download', 'made', ('bitfield', chr(0xC0)), 'choke', 'unchoke', 'interested', 'not interested', ('have', 2), ('request', 1, 5, 6), ('cancel', 2, 3, 4), ('piece', 1, 0, 'abc'), ('piece', 1, 3, 'def'), ('m', HAVE + tobinary(1)), 'flushed', ('m', BITFIELD + chr(0x60)), ('m', INTERESTED), ('m', NOT_INTERESTED), ('m', CHOKE), ('m', UNCHOKE), ('m', HAVE + tobinary(4)), ('m', REQUEST + tobinary(0) + tobinary(2) + tobinary(1)), ('m', CANCEL + tobinary(1) + tobinary(2) + tobinary(3)), ('m', PIECE + tobinary(1) + tobinary(2) + 'abc'), 'disconnected', 'lost'] for a, b in zip (events, x): assert a == b, repr((a, b)) def test_conversion(): assert toint(tobinary(50000)) == 50000
Python
# Written by Bill Bumgarner and Bram Cohen # see LICENSE.txt for license information from types import * from cStringIO import StringIO def formatDefinitions(options, COLS): s = StringIO() indent = " " * 10 width = COLS - 11 if width < 15: width = COLS - 2 indent = " " for (longname, default, doc) in options: s.write('--' + longname + ' <arg>\n') if default is not None: doc += ' (defaults to ' + repr(default) + ')' i = 0 for word in doc.split(): if i == 0: s.write(indent + word) i = len(word) elif i + len(word) >= width: s.write('\n' + indent + word) i = len(word) else: s.write(' ' + word) i += len(word) + 1 s.write('\n\n') return s.getvalue() def usage(str): raise ValueError(str) def parseargs(argv, options, minargs = None, maxargs = None): config = {} longkeyed = {} for option in options: longname, default, doc = option longkeyed[longname] = option config[longname] = default options = [] args = [] pos = 0 while pos < len(argv): if argv[pos][:2] != '--': args.append(argv[pos]) pos += 1 else: if pos == len(argv) - 1: usage('parameter passed in at end with no value') key, value = argv[pos][2:], argv[pos+1] pos += 2 if not longkeyed.has_key(key): usage('unknown key --' + key) longname, default, doc = longkeyed[key] try: t = type(config[longname]) if t is NoneType or t is StringType: config[longname] = value elif t in (IntType, LongType): config[longname] = long(value) elif t is FloatType: config[longname] = float(value) else: assert 0 except ValueError, e: usage('wrong format of --%s - %s' % (key, str(e))) for key, value in config.items(): if value is None: usage("Option --%s is required." % key) if minargs is not None and len(args) < minargs: usage("Must supply at least %d args." % minargs) if maxargs is not None and len(args) > maxargs: usage("Too many args - %d max." % maxargs) return (config, args) def test_parseargs(): assert parseargs(('d', '--a', 'pq', 'e', '--b', '3', '--c', '4.5', 'f'), (('a', 'x', ''), ('b', 1, ''), ('c', 2.3, ''))) == ({'a': 'pq', 'b': 3, 'c': 4.5}, ['d', 'e', 'f']) assert parseargs([], [('a', 'x', '')]) == ({'a': 'x'}, []) assert parseargs(['--a', 'x', '--a', 'y'], [('a', '', '')]) == ({'a': 'y'}, []) try: parseargs([], [('a', 'x', '')]) except ValueError: pass try: parseargs(['--a', 'x'], []) except ValueError: pass try: parseargs(['--a'], [('a', 'x', '')]) except ValueError: pass try: parseargs([], [], 1, 2) except ValueError: pass assert parseargs(['x'], [], 1, 2) == ({}, ['x']) assert parseargs(['x', 'y'], [], 1, 2) == ({}, ['x', 'y']) try: parseargs(['x', 'y', 'z'], [], 1, 2) except ValueError: pass try: parseargs(['--a', '2.0'], [('a', 3, '')]) except ValueError: pass try: parseargs(['--a', 'z'], [('a', 2.1, '')]) except ValueError: pass
Python
#! /usr/bin/python # Written by Bram Cohen # see LICENSE.txt for license information from os.path import join, split from threading import Event from traceback import print_exc from sys import argv from BitTorrent.btmakemetafile import calcsize, make_meta_file, ignore def dummy(x): pass def completedir(files, url, flag = Event(), vc = dummy, fc = dummy, piece_len_pow2 = None): files.sort() ext = '.torrent' togen = [] for f in files: if f[-len(ext):] != ext: togen.append(f) total = 0 for i in togen: total += calcsize(i) subtotal = [0] def callback(x, subtotal = subtotal, total = total, vc = vc): subtotal[0] += x vc(float(subtotal[0]) / total) for i in togen: t = split(i) if t[1] == '': i = t[0] fc(i) try: make_meta_file(i, url, flag = flag, progress = callback, progress_percent=0, piece_len_exp = piece_len_pow2) except ValueError: print_exc() def dc(v): print v if __name__ == '__main__': completedir(argv[2:], argv[1], fc = dc)
Python
#! /usr/bin/python # Written by Bram Cohen # see LICENSE.txt for license information from sys import argv from os.path import getsize, split, join, abspath, isdir from os import listdir from sha import sha from copy import copy from string import strip from BitTorrent.bencode import bencode from BitTorrent.btformats import check_info from BitTorrent.parseargs import parseargs, formatDefinitions from threading import Event from time import time defaults = [ ('piece_size_pow2', 18, "which power of 2 to set the piece size to"), ('comment', '', "optional human-readable comment to put in .torrent"), ('target', '', "optional target file for the torrent") ] ignore = ['core', 'CVS'] def dummy(v): pass def make_meta_file(file, url, piece_len_exp = 18, flag = Event(), progress = dummy, progress_percent=1, comment = None, target = None): if piece_len_exp == None: piece_len_exp = 18 piece_length = 2 ** piece_len_exp a, b = split(file) if not target: if b == '': f = a + '.torrent' else: f = join(a, b + '.torrent') else: f = target info = makeinfo(file, piece_length, flag, progress, progress_percent) if flag.isSet(): return check_info(info) h = open(f, 'wb') data = {'info': info, 'announce': strip(url), 'creation date': long(time())} if comment: data['comment'] = comment h.write(bencode(data)) h.close() def calcsize(file): if not isdir(file): return getsize(file) total = 0 for s in subfiles(abspath(file)): total += getsize(s[1]) return total def makeinfo(file, piece_length, flag, progress, progress_percent=1): file = abspath(file) if isdir(file): subs = subfiles(file) subs.sort() pieces = [] sh = sha() done = 0 fs = [] totalsize = 0.0 totalhashed = 0 for p, f in subs: totalsize += getsize(f) for p, f in subs: pos = 0 size = getsize(f) fs.append({'length': size, 'path': p}) h = open(f, 'rb') while pos < size: a = min(size - pos, piece_length - done) sh.update(h.read(a)) if flag.isSet(): return done += a pos += a totalhashed += a if done == piece_length: pieces.append(sh.digest()) done = 0 sh = sha() if progress_percent: progress(totalhashed / totalsize) else: progress(a) h.close() if done > 0: pieces.append(sh.digest()) return {'pieces': ''.join(pieces), 'piece length': piece_length, 'files': fs, 'name': split(file)[1]} else: size = getsize(file) pieces = [] p = 0 h = open(file, 'rb') while p < size: x = h.read(min(piece_length, size - p)) if flag.isSet(): return pieces.append(sha(x).digest()) p += piece_length if p > size: p = size if progress_percent: progress(float(p) / size) else: progress(min(piece_length, size - p)) h.close() return {'pieces': ''.join(pieces), 'piece length': piece_length, 'length': size, 'name': split(file)[1]} def subfiles(d): r = [] stack = [([], d)] while len(stack) > 0: p, n = stack.pop() if isdir(n): for s in listdir(n): if s not in ignore and s[:1] != '.': stack.append((copy(p) + [s], join(n, s))) else: r.append((p, n)) return r def prog(amount): print '%.1f%% complete\r' % (amount * 100), if __name__ == '__main__': if len(argv) < 3: print 'usage is -' print argv[0] + ' file trackerurl [params]' print print formatDefinitions(defaults, 80) else: try: config, args = parseargs(argv[3:], defaults, 0, 0) make_meta_file(argv[1], argv[2], config['piece_size_pow2'], progress = prog, comment = config['comment'], target = config['target']) except ValueError, e: print 'error: ' + str(e) print 'run with no args for parameter explanations'
Python
# Written by Bram Cohen # see LICENSE.txt for license information from cStringIO import StringIO from sys import stdout import time from gzip import GzipFile DEBUG = False weekdays = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'] months = [None, 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'] class HTTPConnection: def __init__(self, handler, connection): self.handler = handler self.connection = connection self.buf = '' self.closed = False self.done = False self.donereading = False self.next_func = self.read_type def get_ip(self): return self.connection.get_ip() def data_came_in(self, data): if self.donereading or self.next_func is None: return True self.buf += data while True: try: i = self.buf.index('\n') except ValueError: return True val = self.buf[:i] self.buf = self.buf[i+1:] self.next_func = self.next_func(val) if self.donereading: return True if self.next_func is None or self.closed: return False def read_type(self, data): self.header = data.strip() words = data.split() if len(words) == 3: self.command, self.path, garbage = words self.pre1 = False elif len(words) == 2: self.command, self.path = words self.pre1 = True if self.command != 'GET': return None else: return None if self.command not in ('HEAD', 'GET'): return None self.headers = {} return self.read_header def read_header(self, data): data = data.strip() if data == '': self.donereading = True # check for Accept-Encoding: header, pick a if self.headers.has_key('accept-encoding'): ae = self.headers['accept-encoding'] if DEBUG: print "Got Accept-Encoding: " + ae + "\n" else: #identity assumed if no header ae = 'identity' # this eventually needs to support multple acceptable types # q-values and all that fancy HTTP crap # for now assume we're only communicating with our own client if ae.find('gzip') != -1: self.encoding = 'gzip' else: #default to identity. self.encoding = 'identity' r = self.handler.getfunc(self, self.path, self.headers) if r is not None: self.answer(r) return None try: i = data.index(':') except ValueError: return None self.headers[data[:i].strip().lower()] = data[i+1:].strip() if DEBUG: print data[:i].strip() + ": " + data[i+1:].strip() return self.read_header def answer(self, (responsecode, responsestring, headers, data)): if self.closed: return if self.encoding == 'gzip': #transform data using gzip compression #this is nasty but i'm unsure of a better way at the moment compressed = StringIO() gz = GzipFile(fileobj = compressed, mode = 'wb', compresslevel = 9) gz.write(data) gz.close() compressed.seek(0,0) cdata = compressed.read() compressed.close() if len(cdata) >= len(data): self.encoding = 'identity' else: if DEBUG: print "Compressed: %i Uncompressed: %i\n" % (len(cdata),len(data)) data = cdata headers['Content-Encoding'] = 'gzip' # i'm abusing the identd field here, but this should be ok if self.encoding == 'identity': ident = '-' else: ident = self.encoding username = '-' referer = self.headers.get('referer','-') useragent = self.headers.get('user-agent','-') year, month, day, hour, minute, second, a, b, c = time.localtime(time.time()) print '%s %s %s [%02d/%3s/%04d:%02d:%02d:%02d] "%s" %i %i "%s" "%s"' % ( self.connection.get_ip(), ident, username, day, months[month], year, hour, minute, second, self.header, responsecode, len(data), referer, useragent) t = time.time() if t - self.handler.lastflush > self.handler.minflush: self.handler.lastflush = t stdout.flush() self.done = True r = StringIO() r.write('HTTP/1.0 ' + str(responsecode) + ' ' + responsestring + '\r\n') if not self.pre1: headers['Content-Length'] = len(data) for key, value in headers.items(): r.write(key + ': ' + str(value) + '\r\n') r.write('\r\n') if self.command != 'HEAD': r.write(data) self.connection.write(r.getvalue()) if self.connection.is_flushed(): self.connection.shutdown(1) class HTTPHandler: def __init__(self, getfunc, minflush): self.connections = {} self.getfunc = getfunc self.minflush = minflush self.lastflush = time.time() def external_connection_made(self, connection): self.connections[connection] = HTTPConnection(self, connection) def connection_flushed(self, connection): if self.connections[connection].done: connection.shutdown(1) def connection_lost(self, connection): ec = self.connections[connection] ec.closed = True del ec.connection del ec.next_func del self.connections[connection] def data_came_in(self, connection, data): c = self.connections[connection] if not c.data_came_in(data) and not c.closed: c.connection.shutdown(1)
Python
# Written by Bram Cohen # see LICENSE.txt for license information from random import randrange, shuffle, choice class PiecePicker: def __init__(self, numpieces, rarest_first_cutoff = 1): self.rarest_first_cutoff = rarest_first_cutoff self.numpieces = numpieces self.interests = [range(numpieces)] self.pos_in_interests = range(numpieces) self.numinterests = [0] * numpieces self.started = [] self.seedstarted = [] self.numgot = 0 self.scrambled = range(numpieces) shuffle(self.scrambled) def got_have(self, piece): if self.numinterests[piece] is None: return numint = self.numinterests[piece] if numint == len(self.interests) - 1: self.interests.append([]) self.numinterests[piece] += 1 self._shift_over(piece, self.interests[numint], self.interests[numint + 1]) def lost_have(self, piece): if self.numinterests[piece] is None: return numint = self.numinterests[piece] self.numinterests[piece] -= 1 self._shift_over(piece, self.interests[numint], self.interests[numint - 1]) def _shift_over(self, piece, l1, l2): p = self.pos_in_interests[piece] l1[p] = l1[-1] self.pos_in_interests[l1[-1]] = p del l1[-1] newp = randrange(len(l2) + 1) if newp == len(l2): self.pos_in_interests[piece] = len(l2) l2.append(piece) else: old = l2[newp] self.pos_in_interests[old] = len(l2) l2.append(old) l2[newp] = piece self.pos_in_interests[piece] = newp def requested(self, piece, seed = False): if piece not in self.started: self.started.append(piece) if seed and piece not in self.seedstarted: self.seedstarted.append(piece) def complete(self, piece): assert self.numinterests[piece] is not None self.numgot += 1 l = self.interests[self.numinterests[piece]] p = self.pos_in_interests[piece] l[p] = l[-1] self.pos_in_interests[l[-1]] = p del l[-1] self.numinterests[piece] = None try: self.started.remove(piece) self.seedstarted.remove(piece) except ValueError: pass def next(self, havefunc, seed = False): bests = None bestnum = 2 ** 30 if seed: s = self.seedstarted else: s = self.started for i in s: if havefunc(i): if self.numinterests[i] < bestnum: bests = [i] bestnum = self.numinterests[i] elif self.numinterests[i] == bestnum: bests.append(i) if bests: return choice(bests) if self.numgot < self.rarest_first_cutoff: for i in self.scrambled: if havefunc(i): return i return None for i in xrange(1, min(bestnum, len(self.interests))): for j in self.interests[i]: if havefunc(j): return j return None def am_I_complete(self): return self.numgot == self.numpieces def bump(self, piece): l = self.interests[self.numinterests[piece]] pos = self.pos_in_interests[piece] del l[pos] l.append(piece) for i in range(pos,len(l)): self.pos_in_interests[l[i]] = i def test_requested(): p = PiecePicker(9) p.complete(8) p.got_have(0) p.got_have(2) p.got_have(4) p.got_have(6) p.requested(1) p.requested(1) p.requested(3) p.requested(0) p.requested(6) v = _pull(p) assert v[:2] == [1, 3] or v[:2] == [3, 1] assert v[2:4] == [0, 6] or v[2:4] == [6, 0] assert v[4:] == [2, 4] or v[4:] == [4, 2] def test_change_interest(): p = PiecePicker(9) p.complete(8) p.got_have(0) p.got_have(2) p.got_have(4) p.got_have(6) p.lost_have(2) p.lost_have(6) v = _pull(p) assert v == [0, 4] or v == [4, 0] def test_change_interest2(): p = PiecePicker(9) p.complete(8) p.got_have(0) p.got_have(2) p.got_have(4) p.got_have(6) p.lost_have(2) p.lost_have(6) v = _pull(p) assert v == [0, 4] or v == [4, 0] def test_complete(): p = PiecePicker(1) p.got_have(0) p.complete(0) assert _pull(p) == [] p.got_have(0) p.lost_have(0) def test_rarer_in_started_takes_priority(): p = PiecePicker(3) p.complete(2) p.requested(0) p.requested(1) p.got_have(1) p.got_have(0) p.got_have(0) assert _pull(p) == [1, 0] def test_zero(): assert _pull(PiecePicker(0)) == [] def _pull(pp): r = [] def want(p, r = r): return p not in r while True: n = pp.next(want) if n is None: break r.append(n) return r
Python
# This file created for Debian because btdownloadcurses can't # find btdownloadheadless because we rename it. def print_spew(spew): s = StringIO() s.write('\n\n\n') for c in spew: s.write('%20s ' % c['ip']) if c['initiation'] == 'local': s.write('l') else: s.write('r') rate, interested, choked = c['upload'] s.write(' %10s ' % str(int(rate))) if c['is_optimistic_unchoke']: s.write('*') else: s.write(' ') if interested: s.write('i') else: s.write(' ') if choked: s.write('c') else: s.write(' ') rate, interested, choked, snubbed = c['download'] s.write(' %10s ' % str(int(rate))) if interested: s.write('i') else: s.write(' ') if choked: s.write('c') else: s.write(' ') if snubbed: s.write('s') else: s.write(' ') s.write('\n') print s.getvalue()
Python
# # zurllib.py # # This is (hopefully) a drop-in for urllib which will request gzip/deflate # compression and then decompress the output if a compressed response is # received while maintaining the API. # # by Robert Stone 2/22/2003 # from urllib import * from urllib2 import * from gzip import GzipFile from StringIO import StringIO from __init__ import version import pprint DEBUG=0 class HTTPContentEncodingHandler(HTTPHandler): """Inherit and add gzip/deflate/etc support to HTTP gets.""" def http_open(self, req): # add the Accept-Encoding header to the request # support gzip encoding (identity is assumed) req.add_header("Accept-Encoding","gzip") req.add_header('User-Agent', 'BitTorrent/' + version) if DEBUG: print "Sending:" print req.headers print "\n" fp = HTTPHandler.http_open(self,req) headers = fp.headers if DEBUG: pprint.pprint(headers.dict) url = fp.url resp = addinfourldecompress(fp, headers, url) # As of Python 2.4 http_open response also has 'code' and 'msg' # members, and HTTPErrorProcessor breaks if they don't exist. if 'code' in dir(fp): resp.code = fp.code if 'msg' in dir(fp): resp.msg = fp.msg return resp class addinfourldecompress(addinfourl): """Do gzip decompression if necessary. Do addinfourl stuff too.""" def __init__(self, fp, headers, url): # we need to do something more sophisticated here to deal with # multiple values? What about other weird crap like q-values? # basically this only works for the most simplistic case and will # break in some other cases, but for now we only care about making # this work with the BT tracker so.... if headers.has_key('content-encoding') and headers['content-encoding'] == 'gzip': if DEBUG: print "Contents of Content-encoding: " + headers['Content-encoding'] + "\n" self.gzip = 1 self.rawfp = fp fp = GzipStream(fp) else: self.gzip = 0 return addinfourl.__init__(self, fp, headers, url) def close(self): self.fp.close() if self.gzip: self.rawfp.close() def iscompressed(self): return self.gzip class GzipStream(StringIO): """Magically decompress a file object. This is not the most efficient way to do this but GzipFile() wants to seek, etc, which won't work for a stream such as that from a socket. So we copy the whole shebang info a StringIO object, decompress that then let people access the decompressed output as a StringIO object. The disadvantage is memory use and the advantage is random access. Will mess with fixing this later. """ def __init__(self,fp): self.fp = fp # this is nasty and needs to be fixed at some point # copy everything into a StringIO (compressed) compressed = StringIO() r = fp.read() while r: compressed.write(r) r = fp.read() # now, unzip (gz) the StringIO to a string compressed.seek(0,0) gz = GzipFile(fileobj = compressed) str = '' r = gz.read() while r: str += r r = gz.read() # close our utility files compressed.close() gz.close() # init our stringio selves with the string StringIO.__init__(self, str) del str def close(self): self.fp.close() return StringIO.close(self) def test(): """Test this module. At the moment this is lame. """ print "Running unit tests.\n" def printcomp(fp): try: if fp.iscompressed(): print "GET was compressed.\n" else: print "GET was uncompressed.\n" except: print "no iscompressed function! this shouldn't happen" print "Trying to GET a compressed document...\n" fp = urlopen('http://a.scarywater.net/hng/index.shtml') print fp.read() printcomp(fp) fp.close() print "Trying to GET an unknown document...\n" fp = urlopen('http://www.otaku.org/') print fp.read() printcomp(fp) fp.close() # # Install the HTTPContentEncodingHandler that we've defined above. # install_opener(build_opener(HTTPContentEncodingHandler)) if __name__ == '__main__': test()
Python
#! /usr/bin/python # Written by Bram Cohen # see LICENSE.txt for license information from os.path import join, split from threading import Event from traceback import print_exc from sys import argv from BitTorrent.btmakemetafile import calcsize, make_meta_file, ignore def dummy(x): pass def completedir(files, url, flag = Event(), vc = dummy, fc = dummy, piece_len_pow2 = None): files.sort() ext = '.torrent' togen = [] for f in files: if f[-len(ext):] != ext: togen.append(f) total = 0 for i in togen: total += calcsize(i) subtotal = [0] def callback(x, subtotal = subtotal, total = total, vc = vc): subtotal[0] += x vc(float(subtotal[0]) / total) for i in togen: t = split(i) if t[1] == '': i = t[0] fc(i) try: make_meta_file(i, url, flag = flag, progress = callback, progress_percent=0, piece_len_exp = piece_len_pow2) except ValueError: print_exc() def dc(v): print v if __name__ == '__main__': completedir(argv[2:], argv[1], fc = dc)
Python