Module jas
[hide private]
[frames] | no frames]

Source Code for Module jas

   1  '''jython interface to JAS. 
   2  ''' 
   3   
   4  # $Id: jas.py 4262 2012-10-21 13:24:47Z kredel $ 
   5   
   6  from java.lang           import System 
   7  from java.io             import StringReader 
   8  from java.util           import ArrayList, List, Collections 
   9   
  10  from org.apache.log4j    import BasicConfigurator; 
  11   
  12  from edu.jas.structure   import RingElem, RingFactory, Power 
  13  from edu.jas.arith       import BigInteger, BigRational, BigComplex, BigDecimal,\ 
  14                                  ModInteger, ModIntegerRing, BigQuaternion, BigOctonion,\ 
  15                                  Product, ProductRing, PrimeList 
  16  from edu.jas.poly        import GenPolynomial, GenPolynomialRing, Monomial,\ 
  17                                  GenSolvablePolynomial, GenSolvablePolynomialRing,\ 
  18                                  GenWordPolynomial, GenWordPolynomialRing,\ 
  19                                  Word, WordFactory,\ 
  20                                  GenPolynomialTokenizer, OrderedPolynomialList, PolyUtil,\ 
  21                                  TermOrderOptimization, TermOrder, PolynomialList,\ 
  22                                  AlgebraicNumber, AlgebraicNumberRing,\ 
  23                                  OrderedModuleList, ModuleList,\ 
  24                                  Complex, ComplexRing 
  25  from edu.jas.ps          import UnivPowerSeries, UnivPowerSeriesRing,\ 
  26                                  UnivPowerSeriesMap, Coefficients, \ 
  27                                  MultiVarPowerSeries, MultiVarPowerSeriesRing,\ 
  28                                  MultiVarPowerSeriesMap, MultiVarCoefficients,\ 
  29                                  StandardBaseSeq 
  30  from edu.jas.gb          import EReductionSeq, DGroebnerBaseSeq, EGroebnerBaseSeq,\ 
  31                                  GroebnerBaseDistributedEC, GroebnerBaseDistributedHybridEC,\ 
  32                                  GroebnerBaseSeq, GroebnerBaseSeqPairSeq,\ 
  33                                  OrderedPairlist, OrderedSyzPairlist,\ 
  34                                  ReductionSeq, GroebnerBaseParallel, GroebnerBaseSeqPairParallel,\ 
  35                                  SolvableGroebnerBaseParallel, SolvableGroebnerBaseSeq,\ 
  36                                  WordGroebnerBaseSeq 
  37  from edu.jas.gbufd       import GroebnerBasePseudoRecSeq, GroebnerBasePseudoSeq,\ 
  38                                  RGroebnerBasePseudoSeq, RGroebnerBaseSeq, RReductionSeq,\ 
  39                                  CharacteristicSetWu 
  40  from edu.jas.gbmod       import ModGroebnerBaseAbstract, ModSolvableGroebnerBaseAbstract,\ 
  41                                  SolvableSyzygyAbstract, SyzygyAbstract 
  42  from edu.jas.vector      import GenVector, GenVectorModul,\ 
  43                                  GenMatrix, GenMatrixRing 
  44  from edu.jas.application import PolyUtilApp, Residue, ResidueRing, Ideal,\ 
  45                                  Local, LocalRing, IdealWithRealAlgebraicRoots,\ 
  46                                  ComprehensiveGroebnerBaseSeq, ExtensionFieldBuilder 
  47  from edu.jas.kern        import ComputerThreads, StringUtil, Scripting 
  48  from edu.jas.ufd         import GreatestCommonDivisor, PolyUfdUtil, GCDFactory,\ 
  49                                  FactorFactory, SquarefreeFactory, Quotient, QuotientRing 
  50  from edu.jas.root        import RealRootsSturm, Interval, RealAlgebraicNumber, RealAlgebraicRing,\ 
  51                                  ComplexRootsSturm, Rectangle, RootFactory 
  52  from edu.jas.integrate   import ElementaryIntegration 
  53  from edu.jas.util        import ExecutableServer 
  54  from edu.jas             import structure, arith, poly, ps, gb, gbmod, vector,\ 
  55                                  application, util, ufd 
  56  from edu                 import jas 
  57  #PrettyPrint.setInternal(); 
  58   
  59  from org.python.core     import PyInstance, PyList, PyTuple,\ 
  60                                  PyInteger, PyLong, PyFloat, PyString 
  61   
  62  # set output to Python scripting 
  63  Scripting.setLang(Scripting.Lang.Python); 
  64   
65 -def startLog():
66 '''Configure the log4j system and start logging. 67 ''' 68 BasicConfigurator.configure();
69
70 -def terminate():
71 '''Terminate the running thread pools. 72 ''' 73 ComputerThreads.terminate();
74
75 -def noThreads():
76 '''Turn off automatic parallel threads usage. 77 ''' 78 print "nt = ", ComputerThreads.NO_THREADS; 79 ComputerThreads.setNoThreads(); #NO_THREADS = #0; #1; #True; 80 print "nt = ", ComputerThreads.NO_THREADS;
81 82 auto_inject = True 83
84 -def inject_variable(name, value):
85 '''Inject a variable into the main global namespace 86 87 INPUT: 88 - "name" - a string 89 - "value" - anything 90 91 Found in Sage. 92 AUTHORS: 93 - William Stein 94 ''' 95 assert type(name) is str 96 import sys 97 depth = 0 98 while True: 99 G = sys._getframe(depth).f_globals 100 #print "G = `%s` " % G; 101 depth += 1 102 if depth > 100: 103 print "depth limit %s reached " % depth; 104 break 105 if G is None: 106 continue 107 # orig: if G["__name__"] == "__main__" and G["__package__"] is None: 108 try: 109 if G["__name__"] is None: 110 break 111 except: 112 #print "G[__name__] undefined"; 113 break 114 if G["__name__"] == "__main__": 115 try: 116 if G["__package__"] is None: 117 break 118 except: 119 break 120 if G is None: 121 print "error at G no global environment found for `%s` = `%s` " % (name, value); 122 return 123 if name in G: 124 print "redefining global variable `%s` from `%s` " % (name, G[name]); 125 G[name] = value
126
127 -def inject_generators(gens):
128 '''Inject generators as variables into the main global namespace 129 130 INPUT: 131 - "gens" - generators 132 ''' 133 for v in gens: 134 #print "vars = " + str(v); 135 if str(v) == "1": 136 inject_variable("one",v) 137 else: 138 inject_variable(str(v),v)
139 140
141 -class Ring:
142 '''Represents a JAS polynomial ring: GenPolynomialRing. 143 144 Methods to create ideals and ideals with parametric coefficients. 145 ''' 146
147 - def __init__(self,ringstr="",ring=None,fast=False):
148 '''Ring constructor. 149 ''' 150 if ring == None: 151 sr = StringReader( ringstr ); 152 tok = GenPolynomialTokenizer(sr); 153 self.pset = tok.nextPolynomialSet(); 154 self.ring = self.pset.ring; 155 else: 156 self.ring = ring; 157 if fast: 158 return; 159 self.engine = GCDFactory.getProxy(self.ring.coFac); 160 try: 161 self.sqf = SquarefreeFactory.getImplementation(self.ring.coFac); 162 # print "sqf: ", self.sqf; 163 # except Exception, e: 164 # print "error " + str(e) 165 except: 166 pass 167 try: 168 self.factor = FactorFactory.getImplementation(self.ring.coFac); 169 #print "factor: ", self.factor; 170 except: 171 pass 172 # except Exception, e: 173 # print "error " + str(e) 174 #print "dict: " + str(self.__dict__) 175 vns = "" 176 for v in self.ring.generators(): 177 #print "vars = " + str(v); 178 vs = str(v); 179 vr = RingElem(v); 180 vs = vs.replace(" ",""); 181 if vs == "1": 182 vs='one'; 183 if vs.find("(") >= 0: 184 vs = vs.replace("(",""); 185 vs = vs.replace(")",""); 186 if vs.find("{") >= 0: 187 vs = vs.replace("{",""); 188 vs = vs.replace("}",""); 189 try: 190 if self.__dict__[vs] is None: 191 self.__dict__[vs] = vr; 192 else: 193 print vs + " not redefined to " + str(v); 194 except: 195 self.__dict__[vs] = vr; 196 if auto_inject: 197 inject_variable(vs,vr) 198 vns = vns + vs + " " 199 if auto_inject: 200 print "globally defined variables: " + vns
201 #print "dict: " + str(self.__dict__) 202
203 - def __str__(self):
204 '''Create a string representation. 205 ''' 206 return str(self.ring.toScript());
207
208 - def ideal(self,ringstr="",list=None):
209 '''Create an ideal. 210 ''' 211 return Ideal(self,ringstr,list=list);
212
213 - def paramideal(self,ringstr="",list=None,gbsys=None):
214 '''Create an ideal in a polynomial ring with parameter coefficients. 215 ''' 216 return ParamIdeal(self,ringstr,list,gbsys);
217
218 - def gens(self):
219 '''Get list of generators of the polynomial ring. 220 ''' 221 L = self.ring.generators(); 222 N = [ RingElem(e) for e in L ]; 223 return N;
224
225 - def inject_variables(self):
226 '''Inject generators as variables into the main global namespace 227 ''' 228 inject_generators(self.gens());
229
230 - def one(self):
231 '''Get the one of the polynomial ring. 232 ''' 233 return RingElem( self.ring.getONE() );
234
235 - def zero(self):
236 '''Get the zero of the polynomial ring. 237 ''' 238 return RingElem( self.ring.getZERO() );
239
240 - def random(self,k=5,l=7,d=3,q=0.3):
241 '''Get a random polynomial. 242 ''' 243 r = self.ring.random(k,l,d,q); 244 if self.ring.coFac.isField(): 245 r = r.monic(); 246 return RingElem( r );
247
248 - def element(self,poly):
249 '''Create an element from a string or object. 250 ''' 251 if not isinstance(poly,str): 252 try: 253 if self.ring == poly.ring: 254 return RingElem(poly); 255 except Exception, e: 256 pass 257 poly = str(poly); 258 I = Ideal(self, "( " + poly + " )"); 259 list = I.pset.list; 260 if len(list) > 0: 261 return RingElem( list[0] );
262
263 - def gcd(self,a,b):
264 '''Compute the greatest common divisor of a and b. 265 ''' 266 if isinstance(a,RingElem): 267 a = a.elem; 268 else: 269 a = self.element( a ); 270 a = a.elem; 271 if isinstance(b,RingElem): 272 b = b.elem; 273 else: 274 b = self.element( b ); 275 b = b.elem; 276 return RingElem( self.engine.gcd(a,b) );
277
278 - def squarefreeFactors(self,a):
279 '''Compute squarefree factors of polynomial. 280 ''' 281 if isinstance(a,RingElem): 282 a = a.elem; 283 else: 284 a = self.element( a ); 285 a = a.elem; 286 cf = self.ring.coFac; 287 if cf.getClass().getSimpleName() == "GenPolynomialRing": 288 e = self.sqf.recursiveSquarefreeFactors( a ); 289 else: 290 e = self.sqf.squarefreeFactors( a ); 291 L = {}; 292 for a in e.keySet(): 293 i = e.get(a); 294 L[ RingElem( a ) ] = i; 295 return L;
296
297 - def factors(self,a):
298 '''Compute irreducible factorization for modular, integer, 299 rational number and algebriac number coefficients. 300 ''' 301 if isinstance(a,RingElem): 302 a = a.elem; 303 else: 304 a = self.element( a ); 305 a = a.elem; 306 try: 307 cf = self.ring.coFac; 308 if cf.getClass().getSimpleName() == "GenPolynomialRing": 309 e = self.factor.recursiveFactors( a ); 310 else: 311 e = self.factor.factors( a ); 312 L = {}; 313 for a in e.keySet(): 314 i = e.get(a); 315 L[ RingElem( a ) ] = i; 316 return L; 317 except Exception, e: 318 print "error " + str(e) 319 return None
320
321 - def factorsAbsolute(self,a):
322 '''Compute absolute irreducible factorization for (modular,) 323 rational number coefficients. 324 ''' 325 if isinstance(a,RingElem): 326 a = a.elem; 327 else: 328 a = self.element( a ); 329 a = a.elem; 330 try: 331 L = self.factor.factorsAbsolute( a ); 332 ## L = {}; 333 ## for a in e.keySet(): 334 ## i = e.get(a); 335 ## L[ RingElem( a ) ] = i; 336 return L; 337 except Exception, e: 338 print "error in factorsAbsolute " + str(e) 339 return None
340
341 - def realRoots(self,a,eps=None):
342 '''Compute real roots of univariate polynomial. 343 ''' 344 if isinstance(a,RingElem): 345 a = a.elem; 346 else: 347 a = self.element( a ); 348 a = a.elem; 349 if isinstance(eps,RingElem): 350 eps = eps.elem; 351 try: 352 if eps == None: 353 #R = RealRootsSturm().realRoots( a ); 354 R = RootFactory.realAlgebraicNumbers( a ); 355 else: 356 R = RootFactory.realAlgebraicNumbers( a, eps ); 357 R = [ RingElem(r) for r in R ]; 358 #R = [ RingElem(BigDecimal(r.getRational())) for r in R ]; 359 return R; 360 except Exception, e: 361 print "error " + str(e) 362 return None
363
364 - def complexRoots(self,a,eps=None):
365 '''Compute complex roots of univariate polynomial. 366 ''' 367 if isinstance(a,RingElem): 368 a = a.elem; 369 else: 370 a = self.element( a ); 371 a = a.elem; 372 if isinstance(eps,RingElem): 373 eps = eps.elem; 374 cmplx = False; 375 try: 376 x = a.ring.coFac.getONE().getRe(); 377 cmplx = True; 378 except Exception, e: 379 pass; 380 try: 381 if eps == None: 382 if cmplx: 383 R = RootFactory.complexAlgebraicNumbersComplex(a); 384 else: 385 R = RootFactory.complexAlgebraicNumbers(a); 386 # R = ComplexRootsSturm(a.ring.coFac).complexRoots( a ); 387 # R = [ r.centerApprox() for r in R ]; 388 # R = [ r.ring.getRoot() for r in R ]; 389 R = [ RingElem(r) for r in R ]; 390 else: 391 if cmplx: 392 R = RootFactory.complexAlgebraicNumbersComplex(a,eps); 393 else: 394 R = RootFactory.complexAlgebraicNumbers(a,eps); 395 R = [ RingElem(r) for r in R ]; 396 # R = [ r.decimalMagnitude() for r in R ]; 397 # R = ComplexRootsSturm(a.ring.coFac).complexRoots( a, eps ); 398 # R = ComplexRootsSturm(a.ring.coFac).approximateRoots( a, eps ); 399 return R; 400 except Exception, e: 401 print "error " + str(e) 402 return None
403
404 - def integrate(self,a):
405 '''Integrate (univariate) rational function. 406 ''' 407 if isinstance(a,RingElem): 408 a = a.elem; 409 else: 410 a = self.element( a ); 411 a = a.elem; 412 cf = self.ring; 413 try: 414 cf = cf.ring; 415 except: 416 pass; 417 integrator = ElementaryIntegration(cf.coFac); 418 ei = integrator.integrate(a); 419 return ei;
420
421 - def powerseriesRing(self):
422 '''Get a power series ring from this ring. 423 ''' 424 pr = MultiVarPowerSeriesRing(self.ring); 425 return MultiSeriesRing(ring=pr);
426 427
428 -class Ideal:
429 '''Represents a JAS polynomial ideal: PolynomialList and Ideal. 430 431 Methods for Groebner bases, ideal sum, intersection and others. 432 ''' 433
434 - def __init__(self,ring,polystr="",list=None):
435 '''Ideal constructor. 436 ''' 437 self.ring = ring; 438 if list == None: 439 sr = StringReader( polystr ); 440 tok = GenPolynomialTokenizer(ring.ring,sr); 441 self.list = tok.nextPolynomialList(); 442 else: 443 self.list = pylist2arraylist(list,rec=1); 444 self.pset = OrderedPolynomialList(ring.ring,self.list); 445 self.roots = None; 446 self.croots = None; 447 self.prime = None; 448 self.primary = None;
449
450 - def __str__(self):
451 '''Create a string representation. 452 ''' 453 return str(self.pset.toScript());
454
455 - def __eq__(self,other):
456 '''Test if two ideals are equal. 457 ''' 458 o = other; 459 if isinstance(other,Ideal): 460 o = other.pset; 461 return self.pset.equals(o)
462
463 - def paramideal(self):
464 '''Create an ideal in a polynomial ring with parameter coefficients. 465 ''' 466 return ParamIdeal(self.ring,"",self.list);
467
468 - def GB(self):
469 '''Compute a Groebner base. 470 ''' 471 s = self.pset; 472 cofac = s.ring.coFac; 473 F = s.list; 474 t = System.currentTimeMillis(); 475 if cofac.isField(): 476 G = GroebnerBaseSeq(ReductionSeq(),OrderedSyzPairlist()).GB(F); 477 #G = GroebnerBaseSeq().GB(F); 478 else: 479 v = None; 480 try: 481 v = cofac.vars; 482 except: 483 pass 484 if v == None: 485 G = GroebnerBasePseudoSeq(cofac).GB(F); 486 else: 487 G = GroebnerBasePseudoRecSeq(cofac).GB(F); 488 t = System.currentTimeMillis() - t; 489 print "sequential GB executed in %s ms" % t; 490 return Ideal(self.ring,"",G);
491
492 - def isGB(self):
493 '''Test if this is a Groebner base. 494 ''' 495 s = self.pset; 496 cofac = s.ring.coFac; 497 F = s.list; 498 t = System.currentTimeMillis(); 499 if cofac.isField(): 500 b = GroebnerBaseSeq().isGB(F); 501 else: 502 v = None; 503 try: 504 v = cofac.vars; 505 except: 506 pass 507 if v == None: 508 b = GroebnerBasePseudoSeq(cofac).isGB(F); 509 else: 510 b = GroebnerBasePseudoRecSeq(cofac).isGB(F); 511 t = System.currentTimeMillis() - t; 512 #print "isGB executed in %s ms" % t; 513 return b;
514
515 - def eGB(self):
516 '''Compute an e-Groebner base. 517 ''' 518 s = self.pset; 519 cofac = s.ring.coFac; 520 F = s.list; 521 t = System.currentTimeMillis(); 522 G = EGroebnerBaseSeq().GB(F) 523 t = System.currentTimeMillis() - t; 524 print "sequential e-GB executed in %s ms" % t; 525 return Ideal(self.ring,"",G);
526
527 - def iseGB(self):
528 '''Test if this is an e-Groebner base. 529 ''' 530 s = self.pset; 531 cofac = s.ring.coFac; 532 F = s.list; 533 t = System.currentTimeMillis(); 534 b = EGroebnerBaseSeq().isGB(F) 535 t = System.currentTimeMillis() - t; 536 print "is e-GB test executed in %s ms" % t; 537 return b;
538
539 - def dGB(self):
540 '''Compute an d-Groebner base. 541 ''' 542 s = self.pset; 543 cofac = s.ring.coFac; 544 F = s.list; 545 t = System.currentTimeMillis(); 546 G = DGroebnerBaseSeq().GB(F) 547 t = System.currentTimeMillis() - t; 548 print "sequential d-GB executed in %s ms" % t; 549 return Ideal(self.ring,"",G);
550
551 - def isdGB(self):
552 '''Test if this is a d-Groebner base. 553 ''' 554 s = self.pset; 555 cofac = s.ring.coFac; 556 F = s.list; 557 t = System.currentTimeMillis(); 558 b = DGroebnerBaseSeq().isGB(F) 559 t = System.currentTimeMillis() - t; 560 print "is d-GB test executed in %s ms" % t; 561 return b;
562
563 - def parNewGB(self,th):
564 '''Compute in parallel a Groebner base. 565 ''' 566 s = self.pset; 567 F = s.list; 568 bbpar = GroebnerBaseSeqPairParallel(th); 569 t = System.currentTimeMillis(); 570 G = bbpar.GB(F); 571 t = System.currentTimeMillis() - t; 572 bbpar.terminate(); 573 print "parallel-new %s executed in %s ms" % (th, t); 574 return Ideal(self.ring,"",G);
575
576 - def parGB(self,th):
577 '''Compute in parallel a Groebner base. 578 ''' 579 s = self.pset; 580 F = s.list; 581 bbpar = GroebnerBaseParallel(th); 582 t = System.currentTimeMillis(); 583 G = bbpar.GB(F); 584 t = System.currentTimeMillis() - t; 585 bbpar.terminate(); 586 print "parallel %s executed in %s ms" % (th, t); 587 return Ideal(self.ring,"",G);
588
589 - def distGB(self,th=2,machine="examples/machines.localhost",port=55711):
590 '''Compute on a distributed system a Groebner base. 591 ''' 592 s = self.pset; 593 F = s.list; 594 t = System.currentTimeMillis(); 595 #old: gbd = GBDist(th,machine,port); 596 gbd = GroebnerBaseDistributedEC(machine,th,port); 597 #gbd = GroebnerBaseDistributedHybridEC(machine,th,port); 598 t1 = System.currentTimeMillis(); 599 G = gbd.GB(F); 600 t1 = System.currentTimeMillis() - t1; 601 gbd.terminate(); 602 t = System.currentTimeMillis() - t; 603 print "distributed %s executed in %s ms (%s ms start-up)" % (th,t1,t-t1); 604 return Ideal(self.ring,"",G);
605
606 - def distClient(self,port=4711): #8114
607 '''Client for a distributed computation. 608 ''' 609 s = self.pset; 610 es = ExecutableServer( port ); 611 es.init(); 612 es = ExecutableServer( port+1 ); 613 es.init(); 614 return None;
615
616 - def eReduction(self,p):
617 '''Compute a e-normal form of p with respect to this ideal. 618 ''' 619 s = self.pset; 620 G = s.list; 621 if isinstance(p,RingElem): 622 p = p.elem; 623 t = System.currentTimeMillis(); 624 n = EReductionSeq().normalform(G,p); 625 t = System.currentTimeMillis() - t; 626 print "sequential eReduction executed in %s ms" % t; 627 return RingElem(n);
628
629 - def reduction(self,p):
630 '''Compute a normal form of p with respect to this ideal. 631 ''' 632 s = self.pset; 633 G = s.list; 634 if isinstance(p,RingElem): 635 p = p.elem; 636 t = System.currentTimeMillis(); 637 n = ReductionSeq().normalform(G,p); 638 t = System.currentTimeMillis() - t; 639 print "sequential reduction executed in %s ms" % t; 640 return RingElem(n);
641
642 - def NF(self,reducer):
643 '''Compute a normal form of this ideal with respect to reducer. 644 ''' 645 s = self.pset; 646 F = s.list; 647 G = reducer.list; 648 t = System.currentTimeMillis(); 649 N = ReductionSeq().normalform(G,F); 650 t = System.currentTimeMillis() - t; 651 print "sequential NF executed in %s ms" % t; 652 return Ideal(self.ring,"",N);
653
654 - def interreduced_basis(self):
655 '''Compute a interreduced ideal basis of this. 656 657 Compatibility method for Sage/Singular. 658 ''' 659 F = self.pset.list; 660 N = ReductionSeq().irreducibleSet(F); 661 #N = GroebnerBaseSeq().minimalGB(F); 662 return [ RingElem(n) for n in N ];
663
664 - def intersectRing(self,ring):
665 '''Compute the intersection of this and the given polynomial ring. 666 ''' 667 s = jas.application.Ideal(self.pset); 668 N = s.intersect(ring.ring); 669 return Ideal(ring,"",N.getList());
670
671 - def intersect(self,id2):
672 '''Compute the intersection of this and the given ideal id2. 673 ''' 674 s1 = jas.application.Ideal(self.pset); 675 s2 = jas.application.Ideal(id2.pset); 676 N = s1.intersect(s2); 677 return Ideal(self.ring,"",N.getList());
678
679 - def eliminateRing(self,ring):
680 '''Compute the elimination ideal of this and the given polynomial ring. 681 ''' 682 s = jas.application.Ideal(self.pset); 683 N = s.eliminate(ring.ring); 684 r = Ring( ring=N.getRing() ); 685 return Ideal(r,"",N.getList());
686
687 - def sat(self,id2):
688 '''Compute the saturation of this with respect to given ideal id2. 689 ''' 690 s1 = jas.application.Ideal(self.pset); 691 s2 = jas.application.Ideal(id2.pset); 692 #Q = s1.infiniteQuotient(s2); 693 Q = s1.infiniteQuotientRab(s2); 694 return Ideal(self.ring,"",Q.getList());
695
696 - def sum(self,other):
697 '''Compute the sum of this and the ideal. 698 ''' 699 s = jas.application.Ideal(self.pset); 700 t = jas.application.Ideal(other.pset); 701 N = s.sum( t ); 702 return Ideal(self.ring,"",N.getList());
703
704 - def optimize(self):
705 '''Optimize the term order on the variables. 706 ''' 707 p = self.pset; 708 o = TermOrderOptimization.optimizeTermOrder(p); 709 r = Ring("",o.ring); 710 return Ideal(r,"",o.list);
711
712 - def realRoots(self):
713 '''Compute real roots of 0-dim ideal. 714 ''' 715 I = jas.application.Ideal(self.pset); 716 self.roots = jas.application.PolyUtilApp.realAlgebraicRoots(I); 717 for R in self.roots: 718 R.doDecimalApproximation(); 719 return self.roots;
720
721 - def realRootsPrint(self):
722 '''Print decimal approximation of real roots of 0-dim ideal. 723 ''' 724 if self.roots == None: 725 I = jas.application.Ideal(self.pset); 726 self.roots = jas.application.PolyUtilApp.realAlgebraicRoots(I); 727 for R in self.roots: 728 R.doDecimalApproximation(); 729 for Ir in self.roots: 730 for Dr in Ir.decimalApproximation(): 731 print str(Dr); 732 print;
733
734 - def radicalDecomp(self):
735 '''Compute radical decomposition of this ideal. 736 ''' 737 I = jas.application.Ideal(self.pset); 738 self.radical = I.radicalDecomposition(); 739 return self.radical;
740
741 - def decomposition(self):
742 '''Compute irreducible decomposition of this ideal. 743 ''' 744 I = jas.application.Ideal(self.pset); 745 self.irrdec = I.decomposition(); 746 return self.irrdec;
747
748 - def complexRoots(self):
749 '''Compute complex roots of 0-dim ideal. 750 ''' 751 I = jas.application.Ideal(self.pset); 752 self.croots = jas.application.PolyUtilApp.complexAlgebraicRoots(I); 753 for R in self.croots: 754 R.doDecimalApproximation(); 755 return self.croots;
756
757 - def complexRootsPrint(self):
758 '''Print decimal approximation of complex roots of 0-dim ideal. 759 ''' 760 if self.croots == None: 761 I = jas.application.Ideal(self.pset); 762 self.croots = jas.application.PolyUtilApp.realAlgebraicRoots(I); 763 for R in self.croots: 764 R.doDecimalApproximation(); 765 for Ic in self.croots: 766 for Dc in Ic.decimalApproximation(): 767 print str(Dc); 768 print;
769
770 - def primeDecomp(self):
771 '''Compute prime decomposition of this ideal. 772 ''' 773 I = jas.application.Ideal(self.pset); 774 self.prime = I.primeDecomposition(); 775 return self.prime;
776
777 - def primaryDecomp(self):
778 '''Compute primary decomposition of this ideal. 779 ''' 780 I = jas.application.Ideal(self.pset); 781 ## if self.prime == None: 782 ## self.prime = I.primeDecomposition(); 783 self.primary = I.primaryDecomposition(); 784 return self.primary;
785
786 - def toInteger(self):
787 '''Convert rational coefficients to integer coefficients. 788 ''' 789 p = self.pset; 790 l = p.list; 791 r = p.ring; 792 ri = GenPolynomialRing( BigInteger(), r.nvar, r.tord, r.vars ); 793 pi = PolyUtil.integerFromRationalCoefficients(ri,l); 794 r = Ring("",ri); 795 return Ideal(r,"",pi);
796
797 - def toModular(self,mf):
798 '''Convert integer coefficients to modular coefficients. 799 ''' 800 p = self.pset; 801 l = p.list; 802 r = p.ring; 803 rm = GenPolynomialRing( mf, r.nvar, r.tord, r.vars ); 804 pm = PolyUtil.fromIntegerCoefficients(rm,l); 805 r = Ring("",rm); 806 return Ideal(r,"",pm);
807
808 - def CS(self):
809 '''Compute a Characteristic Set. 810 ''' 811 s = self.pset; 812 cofac = s.ring.coFac; 813 F = s.list; 814 t = System.currentTimeMillis(); 815 if cofac.isField(): 816 G = CharacteristicSetWu().characteristicSet(F); 817 else: 818 print "CS not implemented for coefficients %s" % cofac.toScriptFactory(); 819 G = None; 820 t = System.currentTimeMillis() - t; 821 print "sequential CS executed in %s ms" % t; 822 return Ideal(self.ring,"",G);
823
824 - def isCS(self):
825 '''Test for Characteristic Set. 826 ''' 827 s = self.pset; 828 cofac = s.ring.coFac; 829 F = s.list.clone(); 830 Collections.reverse(F); # todo 831 t = System.currentTimeMillis(); 832 if cofac.isField(): 833 b = CharacteristicSetWu().isCharacteristicSet(F); 834 else: 835 print "isCS not implemented for coefficients %s" % cofac.toScriptFactory(); 836 b = False; 837 t = System.currentTimeMillis() - t; 838 return b;
839
840 - def csReduction(self,p):
841 '''Compute a normal form of p with respect to this characteristic set. 842 ''' 843 s = self.pset; 844 F = s.list.clone(); 845 Collections.reverse(F); # todo 846 if isinstance(p,RingElem): 847 p = p.elem; 848 t = System.currentTimeMillis(); 849 n = CharacteristicSetWu().characteristicSetReduction(F,p); 850 t = System.currentTimeMillis() - t; 851 #print "sequential char set reduction executed in %s ms" % t; 852 return RingElem(n);
853 854 855 ## def syzygy(self): 856 ## '''Syzygy of generating polynomials. 857 ## ''' 858 ## p = self.pset; 859 ## l = p.list; 860 ## s = SyzygyAbstract().zeroRelations( l ); 861 ## m = Module("",p.ring); 862 ## return SubModule(m,"",s); 863 864
865 -class ParamIdeal:
866 '''Represents a JAS polynomial ideal with polynomial coefficients. 867 868 Methods to compute comprehensive Groebner bases. 869 ''' 870
871 - def __init__(self,ring,polystr="",list=None,gbsys=None):
872 '''Parametric ideal constructor. 873 ''' 874 self.ring = ring; 875 if list == None and polystr != None: 876 sr = StringReader( polystr ); 877 tok = GenPolynomialTokenizer(ring.ring,sr); 878 self.list = tok.nextPolynomialList(); 879 else: 880 self.list = pylist2arraylist(list,rec=1); 881 self.gbsys = gbsys; 882 self.pset = OrderedPolynomialList(ring.ring,self.list);
883
884 - def __str__(self):
885 '''Create a string representation. 886 ''' 887 if self.gbsys == None: 888 return self.pset.toScript(); 889 else: 890 return self.gbsys.toString(); # toScript() not available
891 # return self.pset.toScript() + "\n" + self.gbsys.toScript(); 892
893 - def optimizeCoeff(self):
894 '''Optimize the term order on the variables of the coefficients. 895 ''' 896 p = self.pset; 897 o = TermOrderOptimization.optimizeTermOrderOnCoefficients(p); 898 r = Ring("",o.ring); 899 return ParamIdeal(r,"",o.list);
900
901 - def optimizeCoeffQuot(self):
902 '''Optimize the term order on the variables of the quotient coefficients. 903 ''' 904 p = self.pset; 905 l = p.list; 906 r = p.ring; 907 q = r.coFac; 908 c = q.ring; 909 rc = GenPolynomialRing( c, r.nvar, r.tord, r.vars ); 910 #print "rc = ", rc; 911 lp = PolyUfdUtil.integralFromQuotientCoefficients(rc,l); 912 #print "lp = ", lp; 913 pp = PolynomialList(rc,lp); 914 #print "pp = ", pp; 915 oq = TermOrderOptimization.optimizeTermOrderOnCoefficients(pp); 916 oor = oq.ring; 917 qo = oor.coFac; 918 cq = QuotientRing( qo ); 919 rq = GenPolynomialRing( cq, r.nvar, r.tord, r.vars ); 920 #print "rq = ", rq; 921 o = PolyUfdUtil.quotientFromIntegralCoefficients(rq,oq.list); 922 r = Ring("",rq); 923 return ParamIdeal(r,"",o);
924
925 - def toIntegralCoeff(self):
926 '''Convert rational function coefficients to integral function coefficients. 927 ''' 928 p = self.pset; 929 l = p.list; 930 r = p.ring; 931 q = r.coFac; 932 c = q.ring; 933 rc = GenPolynomialRing( c, r.nvar, r.tord, r.vars ); 934 #print "rc = ", rc; 935 lp = PolyUfdUtil.integralFromQuotientCoefficients(rc,l); 936 #print "lp = ", lp; 937 r = Ring("",rc); 938 return ParamIdeal(r,"",lp);
939
940 - def toModularCoeff(self,mf):
941 '''Convert integral function coefficients to modular function coefficients. 942 ''' 943 p = self.pset; 944 l = p.list; 945 r = p.ring; 946 c = r.coFac; 947 #print "c = ", c; 948 cm = GenPolynomialRing( mf, c.nvar, c.tord, c.vars ); 949 #print "cm = ", cm; 950 rm = GenPolynomialRing( cm, r.nvar, r.tord, r.vars ); 951 #print "rm = ", rm; 952 pm = PolyUfdUtil.fromIntegerCoefficients(rm,l); 953 r = Ring("",rm); 954 return ParamIdeal(r,"",pm);
955
956 - def toQuotientCoeff(self):
957 '''Convert integral function coefficients to rational function coefficients. 958 ''' 959 p = self.pset; 960 l = p.list; 961 r = p.ring; 962 c = r.coFac; 963 #print "c = ", c; 964 q = QuotientRing(c); 965 #print "q = ", q; 966 qm = GenPolynomialRing( q, r.nvar, r.tord, r.vars ); 967 #print "qm = ", qm; 968 pm = PolyUfdUtil.quotientFromIntegralCoefficients(qm,l); 969 r = Ring("",qm); 970 return ParamIdeal(r,"",pm);
971
972 - def GB(self):
973 '''Compute a Groebner base. 974 ''' 975 I = Ideal(self.ring,"",self.pset.list); 976 g = I.GB(); 977 return ParamIdeal(g.ring,"",g.pset.list);
978
979 - def isGB(self):
980 '''Test if this is a Groebner base. 981 ''' 982 I = Ideal(self.ring,"",self.pset.list); 983 return I.isGB();
984
985 - def CGB(self):
986 '''Compute a comprehensive Groebner base. 987 ''' 988 s = self.pset; 989 F = s.list; 990 t = System.currentTimeMillis(); 991 if self.gbsys == None: 992 self.gbsys = ComprehensiveGroebnerBaseSeq(self.ring.ring.coFac).GBsys(F); 993 G = self.gbsys.getCGB(); 994 t = System.currentTimeMillis() - t; 995 print "sequential comprehensive executed in %s ms" % t; 996 return ParamIdeal(self.ring,"",G,self.gbsys);
997
998 - def CGBsystem(self):
999 '''Compute a comprehensive Groebner system. 1000 ''' 1001 s = self.pset; 1002 F = s.list; 1003 t = System.currentTimeMillis(); 1004 S = ComprehensiveGroebnerBaseSeq(self.ring.ring.coFac).GBsys(F); 1005 t = System.currentTimeMillis() - t; 1006 print "sequential comprehensive system executed in %s ms" % t; 1007 return ParamIdeal(self.ring,None,F,S);
1008
1009 - def isCGB(self):
1010 '''Test if this is a comprehensive Groebner base. 1011 ''' 1012 s = self.pset; 1013 F = s.list; 1014 t = System.currentTimeMillis(); 1015 b = ComprehensiveGroebnerBaseSeq(self.ring.ring.coFac).isGB(F); 1016 t = System.currentTimeMillis() - t; 1017 print "isCGB executed in %s ms" % t; 1018 return b;
1019
1020 - def isCGBsystem(self):
1021 '''Test if this is a comprehensive Groebner system. 1022 ''' 1023 s = self.pset; 1024 S = self.gbsys; 1025 t = System.currentTimeMillis(); 1026 b = ComprehensiveGroebnerBaseSeq(self.ring.ring.coFac).isGBsys(S); 1027 t = System.currentTimeMillis() - t; 1028 print "isCGBsystem executed in %s ms" % t; 1029 return b;
1030
1031 - def regularRepresentation(self):
1032 '''Convert Groebner system to a representation with regular ring coefficents. 1033 ''' 1034 if self.gbsys == None: 1035 return None; 1036 G = PolyUtilApp.toProductRes(self.gbsys.list); 1037 ring = Ring(None,G[0].ring); 1038 return ParamIdeal(ring,None,G);
1039
1040 - def regularRepresentationBC(self):
1041 '''Convert Groebner system to a boolean closed representation with regular ring coefficents. 1042 ''' 1043 if self.gbsys == None: 1044 return None; 1045 G = PolyUtilApp.toProductRes(self.gbsys.list); 1046 ring = Ring(None,G[0].ring); 1047 res = RReductionSeq(); 1048 G = res.booleanClosure(G); 1049 return ParamIdeal(ring,None,G);
1050
1051 - def regularGB(self):
1052 '''Compute a Groebner base over a regular ring. 1053 ''' 1054 s = self.pset; 1055 F = s.list; 1056 t = System.currentTimeMillis(); 1057 G = RGroebnerBasePseudoSeq(self.ring.ring.coFac).GB(F); 1058 t = System.currentTimeMillis() - t; 1059 print "sequential regular GB executed in %s ms" % t; 1060 return ParamIdeal(self.ring,None,G);
1061
1062 - def isRegularGB(self):
1063 '''Test if this is Groebner base over a regular ring. 1064 ''' 1065 s = self.pset; 1066 F = s.list; 1067 t = System.currentTimeMillis(); 1068 b = RGroebnerBasePseudoSeq(self.ring.ring.coFac).isGB(F); 1069 t = System.currentTimeMillis() - t; 1070 print "isRegularGB executed in %s ms" % t; 1071 return b;
1072
1073 - def stringSlice(self):
1074 '''Get each component (slice) of regular ring coefficients separate. 1075 ''' 1076 s = self.pset; 1077 b = PolyUtilApp.productToString(s); 1078 return b;
1079 1080
1081 -class SolvableRing(Ring):
1082 '''Represents a JAS solvable polynomial ring: GenSolvablePolynomialRing. 1083 1084 Has a method to create solvable ideals. 1085 ''' 1086
1087 - def __init__(self,ringstr="",ring=None):
1088 '''Solvable polynomial ring constructor. 1089 ''' 1090 if ring == None: 1091 sr = StringReader( ringstr ); 1092 tok = GenPolynomialTokenizer(sr); 1093 self.pset = tok.nextSolvablePolynomialSet(); 1094 self.ring = self.pset.ring; 1095 else: 1096 self.ring = ring; 1097 if not self.ring.isAssociative(): 1098 print "warning: ring is not associative"; 1099 Ring.__init__(self,ring=self.ring)
1100
1101 - def __str__(self):
1102 '''Create a string representation. 1103 ''' 1104 return str(self.ring.toScript());
1105
1106 - def ideal(self,ringstr="",list=None):
1107 '''Create a solvable ideal. 1108 ''' 1109 return SolvableIdeal(self,ringstr,list);
1110
1111 - def one(self):
1112 '''Get the one of the solvable polynomial ring. 1113 ''' 1114 return RingElem( self.ring.getONE() );
1115
1116 - def zero(self):
1117 '''Get the zero of the solvable polynomial ring. 1118 ''' 1119 return RingElem( self.ring.getZERO() );
1120
1121 - def element(self,poly):
1122 '''Create an element from a string or object. 1123 ''' 1124 if not isinstance(poly,str): 1125 try: 1126 if self.ring == poly.ring: 1127 return RingElem(poly); 1128 except Exception, e: 1129 pass 1130 poly = str(poly); 1131 I = SolvableIdeal(self, "( " + poly + " )"); 1132 list = I.pset.list; 1133 if len(list) > 0: 1134 return RingElem( list[0] );
1135 1136
1137 -class SolvableIdeal:
1138 '''Represents a JAS solvable polynomial ideal. 1139 1140 Methods for left, right two-sided Groebner basees and others. 1141 ''' 1142
1143 - def __init__(self,ring,ringstr="",list=None):
1144 '''Constructor for an ideal in a solvable polynomial ring. 1145 ''' 1146 self.ring = ring; 1147 if list == None: 1148 sr = StringReader( ringstr ); 1149 tok = GenPolynomialTokenizer(ring.ring,sr); 1150 self.list = tok.nextSolvablePolynomialList(); 1151 else: 1152 self.list = pylist2arraylist(list,rec=1); 1153 self.pset = OrderedPolynomialList(ring.ring,self.list);
1154
1155 - def __str__(self):
1156 '''Create a string representation. 1157 ''' 1158 return str(self.pset.toScript());
1159
1160 - def __cmp__(self,other):
1161 '''Compare two ideals. 1162 ''' 1163 t = False; 1164 if not isinstance(other,WordIdeal): 1165 return t; 1166 t = self.list.equals(other.list); 1167 return t;
1168
1169 - def leftGB(self):
1170 '''Compute a left Groebner base. 1171 ''' 1172 s = self.pset; 1173 F = s.list; 1174 t = System.currentTimeMillis(); 1175 G = SolvableGroebnerBaseSeq().leftGB(F); 1176 t = System.currentTimeMillis() - t; 1177 print "executed leftGB in %s ms" % t; 1178 return SolvableIdeal(self.ring,"",G);
1179
1180 - def isLeftGB(self):
1181 '''Test if this is a left Groebner base. 1182 ''' 1183 s = self.pset; 1184 F = s.list; 1185 t = System.currentTimeMillis(); 1186 b = SolvableGroebnerBaseSeq().isLeftGB(F); 1187 t = System.currentTimeMillis() - t; 1188 print "isLeftGB executed in %s ms" % t; 1189 return b;
1190
1191 - def twosidedGB(self):
1192 '''Compute a two-sided Groebner base. 1193 ''' 1194 s = self.pset; 1195 F = s.list; 1196 t = System.currentTimeMillis(); 1197 G = SolvableGroebnerBaseSeq().twosidedGB(F); 1198 t = System.currentTimeMillis() - t; 1199 print "executed twosidedGB in %s ms" % t; 1200 return SolvableIdeal(self.ring,"",G);
1201
1202 - def isTwosidedGB(self):
1203 '''Test if this is a two-sided Groebner base. 1204 ''' 1205 s = self.pset; 1206 F = s.list; 1207 t = System.currentTimeMillis(); 1208 b = SolvableGroebnerBaseSeq().isTwosidedGB(F); 1209 t = System.currentTimeMillis() - t; 1210 print "isTwosidedGB executed in %s ms" % t; 1211 return b;
1212
1213 - def rightGB(self):
1214 '''Compute a right Groebner base. 1215 ''' 1216 s = self.pset; 1217 F = s.list; 1218 t = System.currentTimeMillis(); 1219 G = SolvableGroebnerBaseSeq().rightGB(F); 1220 t = System.currentTimeMillis() - t; 1221 print "executed rightGB in %s ms" % t; 1222 return SolvableIdeal(self.ring,"",G);
1223
1224 - def isRightGB(self):
1225 '''Test if this is a right Groebner base. 1226 ''' 1227 s = self.pset; 1228 F = s.list; 1229 t = System.currentTimeMillis(); 1230 b = SolvableGroebnerBaseSeq().isRightGB(F); 1231 t = System.currentTimeMillis() - t; 1232 print "isRightGB executed in %s ms" % t; 1233 return b;
1234
1235 - def intersect(self,ring):
1236 '''Compute the intersection of this and the polynomial ring. 1237 ''' 1238 s = jas.application.SolvableIdeal(self.pset); 1239 N = s.intersect(ring.ring); 1240 return SolvableIdeal(self.ring,"",N.getList());
1241
1242 - def sum(self,other):
1243 '''Compute the sum of this and the other ideal. 1244 ''' 1245 s = jas.application.SolvableIdeal(self.pset); 1246 t = jas.application.SolvableIdeal(other.pset); 1247 N = s.sum( t ); 1248 return SolvableIdeal(self.ring,"",N.getList());
1249
1250 - def parLeftGB(self,th):
1251 '''Compute a left Groebner base in parallel. 1252 ''' 1253 s = self.pset; 1254 F = s.list; 1255 bbpar = SolvableGroebnerBaseParallel(th); 1256 t = System.currentTimeMillis(); 1257 G = bbpar.leftGB(F); 1258 t = System.currentTimeMillis() - t; 1259 bbpar.terminate(); 1260 print "parallel %s leftGB executed in %s ms" % (th, t); 1261 return SolvableIdeal(self.ring,"",G);
1262
1263 - def parTwosidedGB(self,th):
1264 '''Compute a two-sided Groebner base in parallel. 1265 ''' 1266 s = self.pset; 1267 F = s.list; 1268 bbpar = SolvableGroebnerBaseParallel(th); 1269 t = System.currentTimeMillis(); 1270 G = bbpar.twosidedGB(F); 1271 t = System.currentTimeMillis() - t; 1272 bbpar.terminate(); 1273 print "parallel %s twosidedGB executed in %s ms" % (th, t); 1274 return SolvableIdeal(self.ring,"",G);
1275 1276
1277 -class Module:
1278 '''Represents a JAS module over a polynomial ring. 1279 1280 Method to create sub-modules. 1281 ''' 1282
1283 - def __init__(self,modstr="",ring=None,cols=0):
1284 '''Module constructor. 1285 ''' 1286 if ring == None: 1287 sr = StringReader( modstr ); 1288 tok = GenPolynomialTokenizer(sr); 1289 self.mset = tok.nextSubModuleSet(); 1290 if self.mset.cols >= 0: 1291 self.cols = self.mset.cols; 1292 else: 1293 self.cols = cols; 1294 else: 1295 self.mset = ModuleList(ring.ring,None); 1296 self.cols = cols; 1297 self.ring = self.mset.ring;
1298
1299 - def __str__(self):
1300 '''Create a string representation. 1301 ''' 1302 return str(self.mset.toScript());
1303
1304 - def submodul(self,modstr="",list=None):
1305 '''Create a sub-module. 1306 ''' 1307 return SubModule(self,modstr,list);
1308
1309 - def element(self,poly):
1310 '''Create an element from a string or object. 1311 ''' 1312 if not isinstance(poly,str): 1313 try: 1314 if self.ring == poly.ring: 1315 return RingElem(poly); 1316 except Exception, e: 1317 pass 1318 poly = str(poly); 1319 I = SubModule(self, "( " + poly + " )"); 1320 list = I.mset.list; 1321 if len(list) > 0: 1322 return RingElem( list[0] );
1323
1324 - def gens(self):
1325 '''Get the generators of this module. 1326 ''' 1327 gm = GenVectorModul(self.ring,self.cols); 1328 L = gm.generators(); 1329 #for g in L: 1330 # print "g = ", str(g); 1331 N = [ RingElem(e) for e in L ]; # want use val here, but can not 1332 return N;
1333
1334 - def inject_variables(self):
1335 '''Inject generators as variables into the main global namespace 1336 ''' 1337 inject_generators(self.gens());
1338 1339
1340 -class SubModule:
1341 '''Represents a JAS sub-module over a polynomial ring. 1342 1343 Methods to compute Groebner bases. 1344 ''' 1345
1346 - def __init__(self,module,modstr="",list=None):
1347 '''Constructor for a sub-module. 1348 ''' 1349 self.module = module; 1350 if list == None: 1351 sr = StringReader( modstr ); 1352 tok = GenPolynomialTokenizer(module.ring,sr); 1353 self.list = tok.nextSubModuleList(); 1354 else: 1355 if isinstance(list,PyList) or isinstance(list,PyTuple): 1356 if len(list) != 0: 1357 if isinstance(list[0],RingElem): 1358 list = [ re.elem for re in list ]; 1359 self.list = pylist2arraylist(list,self.module.ring,rec=2); 1360 else: 1361 self.list = list; 1362 #print "list = ", str(list); 1363 #e = self.list[0]; 1364 #print "e = ", e; 1365 self.mset = OrderedModuleList(module.ring,self.list); 1366 self.cols = self.mset.cols; 1367 self.rows = self.mset.rows; 1368 #print "list = %s" % self.list; 1369 #print "cols = %s" % self.cols; 1370 #print "mset = %s" % self.mset.toString(); 1371 #print "mset = %s" % self.mset.toScript(); 1372 self.pset = self.mset.getPolynomialList();
1373
1374 - def __str__(self):
1375 '''Create a string representation. 1376 ''' 1377 return str(self.mset.toScript()); # + "\n\n" + str(self.pset);
1378
1379 - def GB(self):
1380 '''Compute a Groebner base. 1381 ''' 1382 t = System.currentTimeMillis(); 1383 G = ModGroebnerBaseAbstract().GB(self.mset); 1384 t = System.currentTimeMillis() - t; 1385 print "executed module GB in %s ms" % t; 1386 return SubModule(self.module,"",G.list);
1387
1388 - def isGB(self):
1389 '''Test if this is a Groebner base. 1390 ''' 1391 t = System.currentTimeMillis(); 1392 b = ModGroebnerBaseAbstract().isGB(self.mset); 1393 t = System.currentTimeMillis() - t; 1394 print "module isGB executed in %s ms" % t; 1395 return b;
1396 1397 ## def isSyzygy(self,g): 1398 ## '''Test if this is a syzygy of the polynomials in g. 1399 ## ''' 1400 ## l = self.list; 1401 ## print "l = %s" % l; 1402 ## print "g = %s" % g; 1403 ## t = System.currentTimeMillis(); 1404 ## z = SyzygyAbstract().isZeroRelation( l, g.list ); 1405 ## t = System.currentTimeMillis() - t; 1406 ## print "executed isSyzygy in %s ms" % t; 1407 ## return z; 1408 1409
1410 -class SolvableModule(Module):
1411 '''Represents a JAS module over a solvable polynomial ring. 1412 1413 Method to create solvable sub-modules. 1414 ''' 1415
1416 - def __init__(self,modstr="",ring=None,cols=0):
1417 '''Solvable module constructor. 1418 ''' 1419 if ring == None: 1420 sr = StringReader( modstr ); 1421 tok = GenPolynomialTokenizer(sr); 1422 self.mset = tok.nextSolvableSubModuleSet(); 1423 if self.mset.cols >= 0: 1424 self.cols = self.mset.cols; 1425 else: 1426 self.mset = ModuleList(ring.ring,None); 1427 self.cols = cols; 1428 self.ring = self.mset.ring;
1429
1430 - def __str__(self):
1431 '''Create a string representation. 1432 ''' 1433 return str(self.mset.toScript());
1434
1435 - def submodul(self,modstr="",list=None):
1436 '''Create a solvable sub-module. 1437 ''' 1438 return SolvableSubModule(self,modstr,list);
1439
1440 - def element(self,poly):
1441 '''Create an element from a string or object. 1442 ''' 1443 if not isinstance(poly,str): 1444 try: 1445 if self.ring == poly.ring: 1446 return RingElem(poly); 1447 except Exception, e: 1448 pass 1449 poly = str(poly); 1450 I = SolvableSubModule(self, "( " + poly + " )"); 1451 list = I.mset.list; 1452 if len(list) > 0: 1453 return RingElem( list[0] );
1454 1455
1456 -class SolvableSubModule:
1457 '''Represents a JAS sub-module over a solvable polynomial ring. 1458 1459 Methods to compute left, right and two-sided Groebner bases. 1460 ''' 1461
1462 - def __init__(self,module,modstr="",list=None):
1463 '''Constructor for sub-module over a solvable polynomial ring. 1464 ''' 1465 self.module = module; 1466 if list == None: 1467 sr = StringReader( modstr ); 1468 tok = GenPolynomialTokenizer(module.ring,sr); 1469 self.list = tok.nextSolvableSubModuleList(); 1470 else: 1471 if isinstance(list,PyList) or isinstance(list,PyTuple): 1472 self.list = pylist2arraylist(list,self.module.ring,rec=2); 1473 else: 1474 self.list = list; 1475 self.mset = OrderedModuleList(module.ring,self.list); 1476 self.cols = self.mset.cols; 1477 self.rows = self.mset.rows;
1478
1479 - def __str__(self):
1480 '''Create a string representation. 1481 ''' 1482 return str(self.mset.toScript()); # + "\n\n" + str(self.pset);
1483
1484 - def leftGB(self):
1485 '''Compute a left Groebner base. 1486 ''' 1487 t = System.currentTimeMillis(); 1488 G = ModSolvableGroebnerBaseAbstract().leftGB(self.mset); 1489 t = System.currentTimeMillis() - t; 1490 print "executed left module GB in %s ms" % t; 1491 return SolvableSubModule(self.module,"",G.list);
1492
1493 - def isLeftGB(self):
1494 '''Test if this is a left Groebner base. 1495 ''' 1496 t = System.currentTimeMillis(); 1497 b = ModSolvableGroebnerBaseAbstract().isLeftGB(self.mset); 1498 t = System.currentTimeMillis() - t; 1499 print "module isLeftGB executed in %s ms" % t; 1500 return b;
1501
1502 - def twosidedGB(self):
1503 '''Compute a two-sided Groebner base. 1504 ''' 1505 t = System.currentTimeMillis(); 1506 G = ModSolvableGroebnerBaseAbstract().twosidedGB(self.mset); 1507 t = System.currentTimeMillis() - t; 1508 print "executed in %s ms" % t; 1509 return SolvableSubModule(self.module,"",G.list);
1510
1511 - def isTwosidedGB(self):
1512 '''Test if this is a two-sided Groebner base. 1513 ''' 1514 t = System.currentTimeMillis(); 1515 b = ModSolvableGroebnerBaseAbstract().isTwosidedGB(self.mset); 1516 t = System.currentTimeMillis() - t; 1517 print "module isTwosidedGB executed in %s ms" % t; 1518 return b;
1519
1520 - def rightGB(self):
1521 '''Compute a right Groebner base. 1522 ''' 1523 t = System.currentTimeMillis(); 1524 G = ModSolvableGroebnerBaseAbstract().rightGB(self.mset); 1525 t = System.currentTimeMillis() - t; 1526 print "executed module rightGB in %s ms" % t; 1527 return SolvableSubModule(self.module,"",G.list);
1528
1529 - def isRightGB(self):
1530 '''Test if this is a right Groebner base. 1531 ''' 1532 t = System.currentTimeMillis(); 1533 b = ModSolvableGroebnerBaseAbstract().isRightGB(self.mset); 1534 t = System.currentTimeMillis() - t; 1535 print "module isRightGB executed in %s ms" % t; 1536 return b;
1537 1538
1539 -class SeriesRing:
1540 '''Represents a JAS power series ring: UnivPowerSeriesRing. 1541 1542 Methods for univariate power series arithmetic. 1543 ''' 1544
1545 - def __init__(self,ringstr="",truncate=None,ring=None,cofac=None,name="z"):
1546 '''Ring constructor. 1547 ''' 1548 if ring == None: 1549 if len(ringstr) > 0: 1550 sr = StringReader( ringstr ); 1551 tok = GenPolynomialTokenizer(sr); 1552 pset = tok.nextPolynomialSet(); 1553 ring = pset.ring; 1554 vname = ring.vars; 1555 name = vname[0]; 1556 cofac = ring.coFac; 1557 if isinstance(cofac,RingElem): 1558 cofac = cofac.elem; 1559 if truncate == None: 1560 self.ring = UnivPowerSeriesRing(cofac,name); 1561 else: 1562 self.ring = UnivPowerSeriesRing(cofac,truncate,name); 1563 else: 1564 self.ring = ring;
1565
1566 - def __str__(self):
1567 '''Create a string representation. 1568 ''' 1569 return str(self.ring.toScript());
1570
1571 - def gens(self):
1572 '''Get the generators of the power series ring. 1573 ''' 1574 L = self.ring.generators(); 1575 N = [ RingElem(e) for e in L ]; 1576 return N;
1577
1578 - def inject_variables(self):
1579 '''Inject generators as variables into the main global namespace 1580 ''' 1581 inject_generators(self.gens());
1582
1583 - def one(self):
1584 '''Get the one of the power series ring. 1585 ''' 1586 return RingElem( self.ring.getONE() );
1587
1588 - def zero(self):
1589 '''Get the zero of the power series ring. 1590 ''' 1591 return RingElem( self.ring.getZERO() );
1592
1593 - def random(self,n):
1594 '''Get a random power series. 1595 ''' 1596 return RingElem( self.ring.random(n) );
1597
1598 - def exp(self):
1599 '''Get the exponential power series. 1600 ''' 1601 return RingElem( self.ring.getEXP() );
1602
1603 - def sin(self):
1604 '''Get the sinus power series. 1605 ''' 1606 return RingElem( self.ring.getSIN() );
1607
1608 - def cos(self):
1609 '''Get the cosinus power series. 1610 ''' 1611 return RingElem( self.ring.getCOS() );
1612
1613 - def tan(self):
1614 '''Get the tangens power series. 1615 ''' 1616 return RingElem( self.ring.getTAN() );
1617
1618 - def create(self,ifunc=None,jfunc=None,clazz=None):
1619 '''Create a power series with given generating function. 1620 1621 ifunc(int i) must return a value which is used in RingFactory.fromInteger(). 1622 jfunc(int i) must return a value of type ring.coFac. 1623 clazz must implement the Coefficients abstract class. 1624 ''' 1625 class coeff( Coefficients ): 1626 def __init__(self,cofac): 1627 self.coFac = cofac;
1628 def generate(self,i): 1629 if jfunc == None: 1630 return self.coFac.fromInteger( ifunc(i) ); 1631 else: 1632 return jfunc(i);
1633 if clazz == None: 1634 ps = UnivPowerSeries( self.ring, coeff(self.ring.coFac) ); 1635 else: 1636 ps = UnivPowerSeries( self.ring, clazz ); 1637 return RingElem( ps ); 1638
1639 - def fixPoint(self,psmap):
1640 '''Create a power series as fixed point of the given mapping. 1641 1642 psmap must implement the UnivPowerSeriesMap interface. 1643 ''' 1644 ps = self.ring.fixPoint( psmap ); 1645 return RingElem( ps );
1646
1647 - def gcd(self,a,b):
1648 '''Compute the greatest common divisor of a and b. 1649 ''' 1650 if isinstance(a,RingElem): 1651 a = a.elem; 1652 if isinstance(b,RingElem): 1653 b = b.elem; 1654 return RingElem( a.gcd(b) );
1655
1656 - def fromPoly(self,a):
1657 '''Convert a GenPolynomial to a power series. 1658 ''' 1659 if isinstance(a,RingElem): 1660 a = a.elem; 1661 return RingElem( self.ring.fromPolynomial(a) );
1662 1663
1664 -class MultiSeriesRing:
1665 '''Represents a JAS power series ring: MultiVarPowerSeriesRing. 1666 1667 Methods for multivariate power series arithmetic. 1668 ''' 1669
1670 - def __init__(self,ringstr="",truncate=None,ring=None,cofac=None,names=None):
1671 '''Ring constructor. 1672 ''' 1673 if ring == None: 1674 if len(ringstr) > 0: 1675 sr = StringReader( ringstr ); 1676 tok = GenPolynomialTokenizer(sr); 1677 pset = tok.nextPolynomialSet(); 1678 ring = pset.ring; 1679 names = ring.vars; 1680 cofac = ring.coFac; 1681 if isinstance(cofac,RingElem): 1682 cofac = cofac.elem; 1683 if truncate == None: 1684 self.ring = MultiVarPowerSeriesRing(cofac,names); 1685 else: 1686 self.ring = MultiVarPowerSeriesRing(cofac,len(names),truncate,names); 1687 else: 1688 self.ring = ring;
1689
1690 - def __str__(self):
1691 '''Create a string representation. 1692 ''' 1693 return str(self.ring.toScript());
1694
1695 - def gens(self):
1696 '''Get the generators of the power series ring. 1697 ''' 1698 L = self.ring.generators(); 1699 N = [ RingElem(e) for e in L ]; 1700 return N;
1701
1702 - def inject_variables(self):
1703 '''Inject generators as variables into the main global namespace 1704 ''' 1705 inject_generators(self.gens());
1706
1707 - def one(self):
1708 '''Get the one of the power series ring. 1709 ''' 1710 return RingElem( self.ring.getONE() );
1711
1712 - def zero(self):
1713 '''Get the zero of the power series ring. 1714 ''' 1715 return RingElem( self.ring.getZERO() );
1716
1717 - def random(self,n):
1718 '''Get a random power series. 1719 ''' 1720 return RingElem( self.ring.random(n) );
1721
1722 - def exp(self,r):
1723 '''Get the exponential power series, var r. 1724 ''' 1725 return RingElem( self.ring.getEXP(r) );
1726
1727 - def sin(self,r):
1728 '''Get the sinus power series, var r. 1729 ''' 1730 return RingElem( self.ring.getSIN(r) );
1731
1732 - def cos(self,r):
1733 '''Get the cosinus power series, var r. 1734 ''' 1735 return RingElem( self.ring.getCOS(r) );
1736
1737 - def tan(self,r):
1738 '''Get the tangens power series, var r. 1739 ''' 1740 return RingElem( self.ring.getTAN(r) );
1741
1742 - def create(self,ifunc=None,jfunc=None,clazz=None):
1743 '''Create a power series with given generating function. 1744 1745 ifunc(int i) must return a value which is used in RingFactory.fromInteger(). 1746 jfunc(int i) must return a value of type ring.coFac. 1747 clazz must implement the Coefficients abstract class. 1748 ''' 1749 class coeff( MultiVarCoefficients ): 1750 def __init__(self,r): 1751 MultiVarCoefficients.__init__(self,r); 1752 self.coFac = r.coFac;
1753 def generate(self,i): 1754 if jfunc == None: 1755 return self.coFac.fromInteger( ifunc(i) ); 1756 else: 1757 return jfunc(i);
1758 #print "ifunc" 1759 if clazz == None: 1760 ps = MultiVarPowerSeries( self.ring, coeff(self.ring) ); 1761 else: 1762 ps = MultiVarPowerSeries( self.ring, clazz ); 1763 #print "ps ", ps.toScript(); 1764 return RingElem( ps ); 1765
1766 - def fixPoint(self,psmap):
1767 '''Create a power series as fixed point of the given mapping. 1768 1769 psmap must implement the UnivPowerSeriesMap interface. 1770 ''' 1771 ps = self.ring.fixPoint( psmap ); 1772 return RingElem( ps );
1773
1774 - def gcd(self,a,b):
1775 '''Compute the greatest common divisor of a and b. 1776 ''' 1777 if isinstance(a,RingElem): 1778 a = a.elem; 1779 if isinstance(b,RingElem): 1780 b = b.elem; 1781 return RingElem( a.gcd(b) );
1782
1783 - def fromPoly(self,a):
1784 '''Convert a GenPolynomial to a power series. 1785 ''' 1786 if isinstance(a,RingElem): 1787 a = a.elem; 1788 return RingElem( self.ring.fromPolynomial(a) );
1789 1790
1791 -class PSIdeal:
1792 '''Represents a JAS power series ideal. 1793 1794 Method for Standard bases. 1795 ''' 1796
1797 - def __init__(self,ring,polylist,ideal=None,list=None):
1798 '''PSIdeal constructor. 1799 ''' 1800 if isinstance(ring,Ring) or isinstance(ring,PolyRing): 1801 ring = MultiVarPowerSeriesRing(ring.ring); 1802 if isinstance(ring,MultiSeriesRing): 1803 ring = ring.ring; 1804 self.ring = ring; 1805 #print "ring = ", ring.toScript(); 1806 if ideal != None: 1807 polylist = ideal.pset.list; 1808 if list == None: 1809 self.polylist = pylist2arraylist( [ a.elem for a in polylist ] ); 1810 #print "polylist = ", self.polylist; 1811 self.list = self.ring.fromPolynomial(self.polylist); 1812 else: 1813 self.polylist = None; 1814 self.list = pylist2arraylist( [ a.elem for a in list ] );
1815
1816 - def __str__(self):
1817 '''Create a string representation. 1818 ''' 1819 ll = [ e.toScript() for e in self.list ] 1820 return "( " + ", ".join(ll) + " )";
1821
1822 - def STD(self,trunc=None):
1823 '''Compute a standard base. 1824 ''' 1825 pr = self.ring; 1826 if trunc != None: 1827 pr.setTruncate(trunc); 1828 #print "pr = ", pr.toScript(); 1829 F = self.list; 1830 #print "F = ", F; 1831 tm = StandardBaseSeq(); 1832 t = System.currentTimeMillis(); 1833 S = tm.STD(F); 1834 t = System.currentTimeMillis() - t; 1835 print "sequential standard base executed in %s ms" % t; 1836 #Sp = [ RingElem(a.asPolynomial()) for a in S ]; 1837 Sp = [ RingElem(a) for a in S ]; 1838 #return Sp; 1839 return PSIdeal(self.ring,None,list=Sp);
1840 1841
1842 -def pylist2arraylist(list,fac=None,rec=1):
1843 '''Convert a Python list to a Java ArrayList. 1844 1845 If list is a Python list, it is converted, else list is left unchanged. 1846 ''' 1847 #print "list type(%s) = %s" % (list,type(list)); 1848 if isinstance(list,PyList) or isinstance(list,PyTuple): 1849 L = ArrayList(); 1850 for e in list: 1851 t = True; 1852 if isinstance(e,RingElem): 1853 t = False; 1854 e = e.elem; 1855 if isinstance(e,PyList) or isinstance(e,PyTuple): 1856 if rec <= 1: 1857 e = makeJasArith(e); 1858 else: 1859 t = False; 1860 e = pylist2arraylist(e,fac,rec-1); 1861 try: 1862 n = e.getClass().getSimpleName(); 1863 if n == "ArrayList": 1864 t = False; 1865 except: 1866 pass; 1867 if t and fac != None: 1868 #print "e.p(%s) = %s" % (e,e.getClass().getName()); 1869 e = fac.parse( str(e) ); #or makeJasArith(e) ? 1870 L.add(e); 1871 list = L; 1872 #print "list type(%s) = %s" % (list,type(list)); 1873 return list
1874 1875
1876 -def arraylist2pylist(list,rec=1):
1877 '''Convert a Java ArrayList to a Python list. 1878 1879 If list is a Java ArrayList list, it is converted, else list is left unchanged. 1880 ''' 1881 #print "list type(%s) = %s" % (list,type(list)); 1882 if isinstance(list,List): 1883 L = []; 1884 for e in list: 1885 if not isinstance(e,RingElem): 1886 e = RingElem(e); 1887 L.append(e); 1888 list = L; 1889 #print "list type(%s) = %s" % (list,type(list)); 1890 return list
1891 1892
1893 -def makeJasArith(item):
1894 '''Construct a jas.arith object. 1895 If item is a python tuple or list then a BigRational, BigComplex is constructed. 1896 If item is a python float then a BigDecimal is constructed. 1897 ''' 1898 #print "item type(%s) = %s" % (item,type(item)); 1899 if isinstance(item,PyInteger) or isinstance(item,PyLong): 1900 return BigInteger( item ); 1901 if isinstance(item,PyFloat): # ?? what to do ?? 1902 return BigDecimal( str(item) ); 1903 if isinstance(item,PyTuple) or isinstance(item,PyList): 1904 if len(item) > 2: 1905 print "len(item) > 2, remaining items ignored"; 1906 #print "item[0] type(%s) = %s" % (item[0],type(item[0])); 1907 isc = isinstance(item[0],PyTuple) or isinstance(item[0],PyList) 1908 if len(item) > 1: 1909 isc = isc or isinstance(item[1],PyTuple) or isinstance(item[1],PyList); 1910 if isc: 1911 if len(item) > 1: 1912 re = makeJasArith( item[0] ); 1913 if not re.isField(): 1914 re = BigRational( re.val ); 1915 im = makeJasArith( item[1] ); 1916 if not im.isField(): 1917 im = BigRational( im.val ); 1918 jasArith = BigComplex( re, im ); 1919 else: 1920 re = makeJasArith( item[0] ); 1921 jasArith = BigComplex( re ); 1922 else: 1923 if len(item) > 1: 1924 jasArith = BigRational( item[0] ).divide( BigRational( item[1] ) ); 1925 else: 1926 jasArith = BigRational( item[0] ); 1927 return jasArith; 1928 print "makeJasArith: unknown item type(%s) = %s" % (item,type(item)); 1929 return item;
1930 1931
1932 -def ZZ(z=0):
1933 '''Create JAS BigInteger as ring element. 1934 ''' 1935 if isinstance(z,RingElem): 1936 z = z.elem; 1937 r = BigInteger(z); 1938 return RingElem(r);
1939
1940 -def ZM(m,z=0,field=False):
1941 '''Create JAS ModInteger as ring element. 1942 ''' 1943 if isinstance(m,RingElem): 1944 m = m.elem; 1945 if isinstance(z,RingElem): 1946 z = z.elem; 1947 # if z != 0 and ( z == False ): # never true 1948 # field = z; 1949 # z = 0; 1950 if field: 1951 mf = ModIntegerRing(m,field); 1952 else: 1953 mf = ModIntegerRing(m); 1954 r = ModInteger(mf,z); 1955 return RingElem(r);
1956 1957
1958 -def GF(m,z=0):
1959 '''Create JAS ModInteger as field element. 1960 ''' 1961 #print "m = %s" % m 1962 return ZM(m,z,True);
1963 1964
1965 -def QQ(d=0,n=1):
1966 '''Create JAS BigRational as ring element. 1967 ''' 1968 if isinstance(d,PyTuple) or isinstance(d,PyList): 1969 if n != 1: 1970 print "%s ignored" % n; 1971 if len(d) > 1: 1972 n = d[1]; 1973 d = d[0]; 1974 if isinstance(d,RingElem): 1975 d = d.elem; 1976 if isinstance(n,RingElem): 1977 n = n.elem; 1978 if n == 1: 1979 if d == 0: 1980 r = BigRational(); 1981 else: 1982 r = BigRational(d); 1983 else: 1984 d = BigRational(d); 1985 n = BigRational(n); 1986 r = d.divide(n); # BigRational(d,n); only for short integers 1987 return RingElem(r);
1988 1989
1990 -def CC(re=BigRational(),im=BigRational()):
1991 '''Create JAS BigComplex as ring element. 1992 ''' 1993 if re == 0: 1994 re = BigRational(); 1995 if im == 0: 1996 im = BigRational(); 1997 if isinstance(re,PyTuple) or isinstance(re,PyList): 1998 if isinstance(re[0],PyTuple) or isinstance(re[0],PyList): 1999 if len(re) > 1: 2000 im = QQ( re[1] ); 2001 re = QQ( re[0] ); 2002 else: 2003 re = QQ(re); 2004 # re = makeJasArith( re ); 2005 if isinstance(im,PyTuple) or isinstance(im,PyList): 2006 im = QQ( im ); 2007 # im = makeJasArith( im ); 2008 if isinstance(re,RingElem): 2009 re = re.elem; 2010 if isinstance(im,RingElem): 2011 im = im.elem; 2012 if im.isZERO(): 2013 if re.isZERO(): 2014 c = BigComplex(); 2015 else: 2016 c = BigComplex(re); 2017 else: 2018 c = BigComplex(re,im); 2019 return RingElem(c);
2020 2021
2022 -def CR(re=BigRational(),im=BigRational(),ring=None):
2023 '''Create JAS generic Complex as ring element. 2024 ''' 2025 if re == 0: 2026 re = BigRational(); 2027 if im == 0: 2028 im = BigRational(); 2029 if isinstance(re,PyTuple) or isinstance(re,PyList): 2030 if isinstance(re[0],PyTuple) or isinstance(re[0],PyList): 2031 if len(re) > 1: 2032 im = QQ( re[1] ); 2033 re = QQ( re[0] ); 2034 else: 2035 re = QQ(re); 2036 # re = makeJasArith( re ); 2037 if isinstance(im,PyTuple) or isinstance(im,PyList): 2038 im = QQ( im ); 2039 # im = makeJasArith( im ); 2040 if isinstance(re,RingElem): 2041 re = re.elem; 2042 if isinstance(im,RingElem): 2043 im = im.elem; 2044 if ring == None: 2045 ring = re.factory(); 2046 r = ComplexRing(ring); 2047 #print "d type(%s) = %s" % (r,type(r)); 2048 if im.isZERO(): 2049 if re.isZERO(): 2050 c = Complex(r); 2051 else: 2052 c = Complex(r,re); 2053 else: 2054 c = Complex(r,re,im); 2055 #print "d type(%s) = %s" % (c,type(c)); 2056 return RingElem(c);
2057 2058
2059 -def DD(d=0):
2060 '''Create JAS BigDecimal as ring element. 2061 ''' 2062 if isinstance(d,RingElem): 2063 d = d.elem; 2064 if isinstance(d,PyFloat): 2065 d = str(d); 2066 #print "d type(%s) = %s" % (d,type(d)); 2067 if d == 0: 2068 r = BigDecimal(); 2069 else: 2070 r = BigDecimal(d); 2071 return RingElem(r);
2072 2073
2074 -def Quat(re=BigRational(),im=BigRational(),jm=BigRational(),km=BigRational()):
2075 '''Create JAS BigQuaternion as ring element. 2076 ''' 2077 if re == 0: 2078 re = BigRational(); 2079 if im == 0: 2080 im = BigRational(); 2081 if jm == 0: 2082 jm = BigRational(); 2083 if km == 0: 2084 km = BigRational(); 2085 if isinstance(re,PyTuple) or isinstance(re,PyList): 2086 if isinstance(re[0],PyTuple) or isinstance(re[0],PyList): 2087 if len(re) > 1: 2088 im = QQ( re[1] ); 2089 re = QQ( re[0] ); 2090 else: 2091 re = QQ(re); 2092 # re = makeJasArith( re ); 2093 if isinstance(im,PyTuple) or isinstance(im,PyList): 2094 im = QQ( im ); 2095 if isinstance(jm,PyTuple) or isinstance(jm,PyList): 2096 jm = QQ( jm ); 2097 if isinstance(km,PyTuple) or isinstance(km,PyList): 2098 kim = QQ( km ); 2099 # im = makeJasArith( im ); 2100 if isinstance(re,RingElem): 2101 re = re.elem; 2102 if isinstance(im,RingElem): 2103 im = im.elem; 2104 if isinstance(jm,RingElem): 2105 jm = jm.elem; 2106 if isinstance(km,RingElem): 2107 km = km.elem; 2108 c = BigQuaternion(re,im,jm,km); 2109 return RingElem(c);
2110 2111
2112 -def Oct(ro=BigQuaternion(),io=BigQuaternion()):
2113 '''Create JAS BigOctonion as ring element. 2114 ''' 2115 if ro == 0: 2116 ro = BigQuaternion(); 2117 if io == 0: 2118 io = BigQuaternion(); 2119 if isinstance(ro,PyTuple) or isinstance(ro,PyList): 2120 if isinstance(ro[0],PyTuple) or isinstance(ro[0],PyList): 2121 if len(ro) > 1: 2122 io = QQ( ro[1] ); 2123 ro = QQ( ro[0] ); 2124 else: 2125 ro = QQ(ro); 2126 # re = makeJasArith( re ); 2127 if isinstance(io,PyTuple) or isinstance(io,PyList): 2128 io = QQ( io ); 2129 # im = makeJasArith( im ); 2130 if isinstance(ro,RingElem): 2131 ro = ro.elem; 2132 if isinstance(io,RingElem): 2133 io = io.elem; 2134 c = BigOctonion(ro,io); 2135 return RingElem(c);
2136 2137
2138 -def AN(m,z=0,field=False,pr=None):
2139 '''Create JAS AlgebraicNumber as ring element. 2140 ''' 2141 if isinstance(m,RingElem): 2142 m = m.elem; 2143 if isinstance(z,RingElem): 2144 z = z.elem; 2145 # if z != 0 and ( z == True or z == False ): # not working 2146 # field = z; 2147 # z = 0; 2148 #print "m.getClass() = " + str(m.getClass().getName()); 2149 #print "field = " + str(field); 2150 if m.getClass().getSimpleName() == "AlgebraicNumber": 2151 mf = AlgebraicNumberRing(m.factory().modul,m.factory().isField()); 2152 else: 2153 if field: 2154 mf = AlgebraicNumberRing(m,field); 2155 else: 2156 mf = AlgebraicNumberRing(m); 2157 #print "mf = " + mf.toString(); 2158 if z == 0: 2159 r = AlgebraicNumber(mf); 2160 else: 2161 r = AlgebraicNumber(mf,z); 2162 return RingElem(r);
2163 2164
2165 -def RealN(m,i,r=0):
2166 '''Create JAS RealAlgebraicNumber as ring element. 2167 ''' 2168 if isinstance(m,RingElem): 2169 m = m.elem; 2170 if isinstance(r,RingElem): 2171 r = r.elem; 2172 if isinstance(i,PyTuple) or isinstance(i,PyList): 2173 il = BigRational(i[0]); 2174 ir = BigRational(i[1]); 2175 i = Interval(il,ir); 2176 #print "m.getClass() = " + str(m.getClass().getName()); 2177 if m.getClass().getSimpleName() == "RealAlgebraicNumber": 2178 mf = RealAlgebraicRing(m.factory().algebraic.modul,i); 2179 else: 2180 mf = RealAlgebraicRing(m,i); 2181 if r == 0: 2182 rr = RealAlgebraicNumber(mf); 2183 else: 2184 rr = RealAlgebraicNumber(mf,r); 2185 return RingElem(rr);
2186 2187
2188 -def RF(pr,d=0,n=1):
2189 '''Create JAS rational function Quotient as ring element. 2190 ''' 2191 if isinstance(d,PyTuple) or isinstance(d,PyList): 2192 if n != 1: 2193 print "%s ignored" % n; 2194 if len(d) > 1: 2195 n = d[1]; 2196 d = d[0]; 2197 if isinstance(d,RingElem): 2198 d = d.elem; 2199 if isinstance(n,RingElem): 2200 n = n.elem; 2201 if isinstance(pr,RingElem): 2202 pr = pr.elem; 2203 if isinstance(pr,Ring): 2204 pr = pr.ring; 2205 qr = QuotientRing(pr); 2206 if d == 0: 2207 r = Quotient(qr); 2208 else: 2209 if n == 1: 2210 r = Quotient(qr,d); 2211 else: 2212 r = Quotient(qr,d,n); 2213 return RingElem(r);
2214 2215
2216 -def RC(ideal,r=0):
2217 '''Create JAS polynomial Residue as ring element. 2218 ''' 2219 if ideal == None: 2220 raise ValueError, "No ideal given." 2221 if isinstance(ideal,Ideal): 2222 ideal = jas.application.Ideal(ideal.pset); 2223 #ideal.doGB(); 2224 #print "ideal.getList().get(0).ring.ideal = %s" % ideal.getList().get(0).ring.ideal; 2225 if ideal.getList().get(0).ring.getClass().getSimpleName() == "ResidueRing": 2226 rc = ResidueRing( ideal.getList().get(0).ring.ideal ); 2227 else: 2228 rc = ResidueRing(ideal); 2229 if isinstance(r,RingElem): 2230 r = r.elem; 2231 if r == 0: 2232 r = Residue(rc); 2233 else: 2234 r = Residue(rc,r); 2235 return RingElem(r);
2236 2237
2238 -def LC(ideal,d=0,n=1):
2239 '''Create JAS polynomial Local as ring element. 2240 ''' 2241 if ideal == None: 2242 raise ValueError, "No ideal given." 2243 if isinstance(ideal,Ideal): 2244 ideal = jas.application.Ideal(ideal.pset); 2245 #ideal.doGB(); 2246 #print "ideal.getList().get(0).ring.ideal = %s" % ideal.getList().get(0).ring.ideal; 2247 if ideal.getList().get(0).ring.getClass().getSimpleName() == "LocalRing": 2248 lc = LocalRing( ideal.getList().get(0).ring.ideal ); 2249 else: 2250 lc = LocalRing(ideal); 2251 if isinstance(d,PyTuple) or isinstance(d,PyList): 2252 if n != 1: 2253 print "%s ignored" % n; 2254 if len(d) > 1: 2255 n = d[1]; 2256 d = d[0]; 2257 if isinstance(d,RingElem): 2258 d = d.elem; 2259 if isinstance(n,RingElem): 2260 n = n.elem; 2261 if d == 0: 2262 r = Local(lc); 2263 else: 2264 if n == 1: 2265 r = Local(lc,d); 2266 else: 2267 r = Local(lc,d,n); 2268 return RingElem(r);
2269 2270
2271 -def RR(flist,n=1,r=0):
2272 '''Create JAS regular ring Product as ring element. 2273 ''' 2274 if not isinstance(n,PyInteger): 2275 r = n; 2276 n = 1; 2277 if flist == None: 2278 raise ValueError, "No list given." 2279 if isinstance(flist,PyList) or isinstance(flist,PyTuple): 2280 flist = pylist2arraylist( [ x.factory() for x in flist ], rec=1); 2281 ncop = 0; 2282 else: 2283 ncop = n; 2284 if isinstance(flist,RingElem): 2285 flist = flist.elem; 2286 flist = flist.factory(); 2287 ncop = n; 2288 #print "flist = " + str(flist); 2289 #print "ncop = " + str(ncop); 2290 if ncop == 0: 2291 pr = ProductRing(flist); 2292 else: 2293 pr = ProductRing(flist,ncop); 2294 #print "r type(%s) = %s" % (r,type(r)); 2295 if isinstance(r,RingElem): 2296 r = r.elem; 2297 try: 2298 #print "r.class() = %s" % r.getClass().getSimpleName(); 2299 if r.getClass().getSimpleName() == "Product": 2300 #print "r.val = %s" % r.val; 2301 r = r.val; 2302 except: 2303 pass; 2304 #print "r = " + str(r); 2305 if r == 0: 2306 r = Product(pr); 2307 else: 2308 r = Product(pr,r); 2309 return RingElem(r);
2310 2311
2312 -def PS(cofac,name,f=None,truncate=None):
2313 '''Create JAS UnivPowerSeries as ring element. 2314 ''' 2315 cf = cofac; 2316 if isinstance(cofac,RingElem): 2317 cf = cofac.elem.factory(); 2318 if isinstance(cofac,Ring): 2319 cf = cofac.ring; 2320 if isinstance(truncate,RingElem): 2321 truncate = truncate.elem; 2322 if truncate == None: 2323 ps = UnivPowerSeriesRing(cf,name); 2324 else: 2325 ps = UnivPowerSeriesRing(cf,truncate,name); 2326 if f == None: 2327 r = ps.getZERO(); 2328 else: 2329 class Coeff( Coefficients ): 2330 def __init__(self,cofac): 2331 self.coFac = cofac;
2332 def generate(self,i): 2333 a = f(i); 2334 if isinstance(a,RingElem): 2335 a = a.elem; 2336 #print "a = " + str(a); 2337 return a; 2338 r = UnivPowerSeries(ps,Coeff(cf)); 2339 return RingElem(r); 2340 2341
2342 -def MPS(cofac,names,f=None,truncate=None):
2343 '''Create JAS MultiVarPowerSeries as ring element. 2344 ''' 2345 cf = cofac; 2346 if isinstance(cofac,RingElem): 2347 cf = cofac.elem.factory(); 2348 if isinstance(cofac,Ring): 2349 cf = cofac.ring; 2350 vars = names; 2351 if isinstance(vars,PyString): 2352 vars = GenPolynomialTokenizer.variableList(vars); 2353 nv = len(vars); 2354 if isinstance(truncate,RingElem): 2355 truncate = truncate.elem; 2356 if truncate == None: 2357 ps = MultiVarPowerSeriesRing(cf,nv,vars); 2358 else: 2359 ps = MultiVarPowerSeriesRing(cf,nv,vars,truncate); 2360 if f == None: 2361 r = ps.getZERO(); 2362 else: 2363 class MCoeff( MultiVarCoefficients ): 2364 def __init__(self,r): 2365 MultiVarCoefficients.__init__(self,r); 2366 self.coFac = r.coFac;
2367 def generate(self,i): 2368 a = f(i); 2369 if isinstance(a,RingElem): 2370 a = a.elem; 2371 return a; 2372 r = MultiVarPowerSeries(ps,MCoeff(ps)); 2373 #print "r = " + str(r); 2374 return RingElem(r); 2375 2376
2377 -def Vec(cofac,n,v=None):
2378 '''Create JAS GenVector ring element. 2379 ''' 2380 cf = cofac; 2381 if isinstance(cofac,RingElem): 2382 cf = cofac.elem.factory(); 2383 if isinstance(cofac,Ring): 2384 cf = cofac.ring; 2385 if isinstance(n,RingElem): 2386 n = n.elem; 2387 if isinstance(v,RingElem): 2388 v = v.elem; 2389 vr = GenVectorModul(cf,n); 2390 if v == None: 2391 r = GenVector(vr); 2392 else: 2393 r = GenVector(vr,v); 2394 return RingElem(r);
2395 2396
2397 -def Mat(cofac,n,m,v=None):
2398 '''Create JAS GenMatrix ring element. 2399 ''' 2400 cf = cofac; 2401 if isinstance(cofac,RingElem): 2402 cf = cofac.elem.factory(); 2403 if isinstance(cofac,Ring): 2404 cf = cofac.ring; 2405 if isinstance(n,RingElem): 2406 n = n.elem; 2407 if isinstance(m,RingElem): 2408 m = m.elem; 2409 if isinstance(v,RingElem): 2410 v = v.elem; 2411 #print "cf type(%s) = %s" % (cf,type(cf)); 2412 mr = GenMatrixRing(cf,n,m); 2413 if v == None: 2414 r = GenMatrix(mr); 2415 else: 2416 r = GenMatrix(mr,v); 2417 return RingElem(r);
2418 2419
2420 -def coercePair(a,b):
2421 '''Coerce type a to type b or type b to type a. 2422 ''' 2423 #print "a type(%s) = %s" % (a,type(a)); 2424 #print "b type(%s) = %s" % (b,type(b)); 2425 try: 2426 if not a.isPolynomial() and b.isPolynomial(): 2427 s = b.coerce(a); 2428 o = b; 2429 else: 2430 s = a; 2431 o = a.coerce(b); 2432 except: 2433 s = a; 2434 o = a.coerce(b); 2435 return (s,o);
2436 2437
2438 -def isJavaInstance(a):
2439 '''Test if a is a Java instance. 2440 ''' 2441 #print "a type(%s) = %s" % (a,type(a)); 2442 try: 2443 c = a.getClass(); 2444 except: 2445 return False; 2446 return True;
2447 2448
2449 -class RingElem:
2450 '''Proxy for JAS ring elements. 2451 2452 Methods to be used as + - * ** / %. 2453 ''' 2454
2455 - def __init__(self,elem):
2456 '''Constructor for ring element. 2457 ''' 2458 if isinstance(elem,RingElem): 2459 self.elem = elem.elem; 2460 else: 2461 self.elem = elem; 2462 try: 2463 self.ring = self.elem.factory(); 2464 except: 2465 self.ring = self.elem;
2466
2467 - def __str__(self):
2468 '''Create a string representation. 2469 ''' 2470 return str(self.elem.toScript());
2471
2472 - def zero(self):
2473 '''Zero element of this ring. 2474 ''' 2475 return RingElem( self.ring.getZERO() );
2476
2477 - def isZERO(self):
2478 '''Test if this is the zero element of the ring. 2479 ''' 2480 return self.elem.isZERO();
2481
2482 - def one(self):
2483 '''One element of this ring. 2484 ''' 2485 return RingElem( self.ring.getONE() );
2486
2487 - def isONE(self):
2488 '''Test if this is the one element of the ring. 2489 ''' 2490 return self.elem.isONE();
2491
2492 - def signum(self):
2493 '''Get the sign of this element. 2494 ''' 2495 return self.elem.signum();
2496
2497 - def __abs__(self):
2498 '''Absolute value. 2499 ''' 2500 return RingElem( self.elem.abs() );
2501
2502 - def __neg__(self):
2503 '''Negative value. 2504 ''' 2505 return RingElem( self.elem.negate() );
2506
2507 - def __pos__(self):
2508 '''Positive value. 2509 ''' 2510 return self;
2511
2512 - def coerce(self,other):
2513 '''Coerce other to self. 2514 ''' 2515 #print "self type(%s) = %s" % (self,type(self)); 2516 #print "other type(%s) = %s" % (other,type(other)); 2517 #print "self.elem class(%s) = %s" % (self.elem,self.elem.getClass()); 2518 if self.elem.getClass().getSimpleName() == "GenVector": 2519 #print "self, other = %s, %s " % (self,other); 2520 if isinstance(other,PyTuple) or isinstance(other,PyList): 2521 o = pylist2arraylist(other,self.elem.factory().coFac,rec=1); 2522 o = GenVector(self.elem.factory(),o); 2523 return RingElem( o ); 2524 if self.elem.getClass().getSimpleName() == "GenMatrix": 2525 #print "self, other = %s, %s " % (type(self),type(other)); 2526 #print "o type(%s) = %s, str = %s" % (o,type(o),str(o)); 2527 if isinstance(other,PyTuple) or isinstance(other,PyList): 2528 o = pylist2arraylist(other,self.elem.factory().coFac,rec=2); 2529 o = GenMatrix(self.elem.factory(),o); 2530 return RingElem( o ); 2531 if self.elem.getClass().getSimpleName() == "GenPolynomial": 2532 #print "self, other = %s, %s " % (type(self),type(other)); 2533 #print "o type(%s) = %s, str = %s" % (o,type(o),str(o)); 2534 if isinstance(other,PyInteger) or isinstance(other,PyLong): 2535 o = self.ring.fromInteger(other); 2536 return RingElem( o ); 2537 if isinstance(other,RingElem): 2538 o = other.elem; 2539 else: 2540 o = other; 2541 if o == None: 2542 return RingElem( GenPolynomial(self.ring) ) 2543 if isJavaInstance(o): 2544 #print "self.elem, o = %s, %s " % (type(self.ring.coFac),type(o)); 2545 if o.getClass().getSimpleName() == "ExpVectorLong": # want startsWith or substring(0,8) == "ExpVector": 2546 o = GenPolynomial(self.ring,o); 2547 return RingElem( o ); 2548 if self.ring.coFac.getClass().getSimpleName() == o.getClass().getSimpleName(): 2549 o = GenPolynomial(self.ring,o); 2550 return RingElem( o ); 2551 if isinstance(other,RingElem): 2552 if self.isPolynomial() and not other.isPolynomial(): 2553 #print "self.ring = %s" % (self.ring); 2554 o = self.ring.parse( other.elem.toString() ); # not toScript() 2555 #print "o type(%s) = %s, str = %s" % (o,type(o),str(o)); 2556 return RingElem( o ); 2557 return other; 2558 #print "--1"; 2559 if isinstance(other,PyTuple) or isinstance(other,PyList): 2560 # assume BigRational or BigComplex 2561 # assume self will be compatible with them. todo: check this 2562 o = makeJasArith(other); 2563 #print "other class(%s) = %s" % (o,o.getClass()); 2564 if self.isPolynomial(): 2565 #print "other type(%s) = %s" % (o,type(o)); 2566 o = self.ring.parse( o.toString() ); # not toScript(); 2567 #o = o.elem; 2568 if self.elem.getClass().getSimpleName() == "BigComplex": 2569 #print "other type(%s) = %s" % (o,type(o)); 2570 o = CC( o ); 2571 o = o.elem; 2572 if self.elem.getClass().getSimpleName() == "BigQuaternion": 2573 #print "other type(%s) = %s" % (o,type(o)); 2574 o = Quat( o ); 2575 o = o.elem; 2576 if self.elem.getClass().getSimpleName() == "BigOctonion": 2577 #print "other type(%s) = %s" % (o,type(o)); 2578 o = Oct( Quat(o) ); 2579 o = o.elem; 2580 if self.elem.getClass().getSimpleName() == "Product": 2581 #print "other type(%s) = %s" % (o,type(o)); 2582 o = RR(self.ring, self.elem.multiply(o) ); # valueOf 2583 #print "o = %s" % o; 2584 o = o.elem; 2585 return RingElem(o); 2586 #print "--2"; 2587 # test if self.elem is a factory itself 2588 if self.isFactory(): 2589 if isinstance(other,PyInteger) or isinstance(other,PyLong): 2590 o = self.elem.fromInteger(other); 2591 else: 2592 if isinstance(other,PyFloat): # ?? what to do ?? 2593 o = self.elem.fromInteger( int(other) ); 2594 else: 2595 print "coerce_1: unknown other type(%s) = %s" % (other,type(other)); 2596 o = self.elem.parse( str(other) ); 2597 return RingElem(o); 2598 #print "--3"; 2599 #print "other type(%s) = %s" % (other,type(other)); 2600 # self.elem has a ring factory 2601 if isinstance(other,PyInteger) or isinstance(other,PyLong): 2602 o = self.elem.factory().fromInteger(other); 2603 else: 2604 if isinstance(other,PyFloat): # ?? what to do ?? 2605 #print "other type(%s) = %s" % (other,type(other)); 2606 #print "self type(%s) = %s" % (self.elem,self.elem.getClass().getName()); 2607 o = BigDecimal(other); 2608 if self.elem.getClass().getSimpleName() == "Product": 2609 o = RR(self.ring, self.elem.idempotent().multiply(o) ); # valueOf 2610 o = o.elem; 2611 else: 2612 o = self.elem.factory().getZERO().sum( o ); 2613 else: 2614 print "coerce_2: unknown other type(%s) = %s" % (other,type(other)); 2615 print "coerce_2: self type(%s) = %s" % (self,type(self)); 2616 o = self.elem.factory().parse( str(other) ); 2617 #print "--4"; 2618 return RingElem(o);
2619
2620 - def isFactory(self):
2621 '''Test if this is itself a ring factory. 2622 ''' 2623 f = self.elem.factory(); 2624 if self.elem == f: 2625 return True; 2626 else: 2627 return False;
2628
2629 - def isPolynomial(self):
2630 '''Test if this is a polynomial. 2631 ''' 2632 try: 2633 nv = self.elem.ring.nvar; 2634 except: 2635 return False; 2636 return True;
2637
2638 - def __cmp__(self,other):
2639 '''Compare two ring elements. 2640 ''' 2641 [s,o] = coercePair(self,other); 2642 return s.elem.compareTo( o.elem );
2643
2644 - def __hash__(self):
2645 '''Hash value. 2646 ''' 2647 return self.elem.hashCode();
2648
2649 - def __len__(self):
2650 '''Length of the element. 2651 ''' 2652 return self.elem.length();
2653
2654 - def __mul__(self,other):
2655 '''Multiply two ring elements. 2656 ''' 2657 [s,o] = coercePair(self,other); 2658 #print "self type(%s) = %s" % (s,type(s)); 2659 #print "other type(%s) = %s" % (o,type(o)); 2660 return RingElem( s.elem.multiply( o.elem ) );
2661
2662 - def __rmul__(self,other):
2663 '''Reverse multiply two ring elements. 2664 ''' 2665 [s,o] = coercePair(self,other); 2666 return o.__mul__(s);
2667
2668 - def __add__(self,other):
2669 '''Add two ring elements. 2670 ''' 2671 [s,o] = coercePair(self,other); 2672 return RingElem( s.elem.sum( o.elem ) );
2673
2674 - def __radd__(self,other):
2675 '''Reverse add two ring elements. 2676 ''' 2677 [s,o] = coercePair(self,other); 2678 return o.__add__(s);
2679
2680 - def __sub__(self,other):
2681 '''Subtract two ring elements. 2682 ''' 2683 [s,o] = coercePair(self,other); 2684 return RingElem( s.elem.subtract( o.elem ) );
2685
2686 - def __rsub__(self,other):
2687 '''Reverse subtract two ring elements. 2688 ''' 2689 [s,o] = coercePair(self,other); 2690 return o.__sub__(self);
2691
2692 - def __div__(self,other):
2693 '''Divide two ring elements. 2694 ''' 2695 [s,o] = coercePair(self,other); 2696 return RingElem( s.elem.divide( o.elem ) );
2697
2698 - def __rdiv__(self,other):
2699 '''Reverse divide two ring elements. 2700 ''' 2701 [s,o] = coercePair(self,other); 2702 return o.__div__(s);
2703
2704 - def __mod__(self,other):
2705 '''Modular remainder of two ring elements. 2706 ''' 2707 [s,o] = coercePair(self,other); 2708 return RingElem( s.elem.remainder( o.elem ) );
2709
2710 - def __xor__(self,other):
2711 '''Can not be used as power. 2712 ''' 2713 return None;
2714
2715 - def __pow__(self,other,n=None):
2716 '''Power of this to other. 2717 ''' 2718 #print "self type(%s) = %s" % (self,type(self)); 2719 #print "pow other type(%s) = %s" % (other,type(other)); 2720 if isinstance(other,PyInteger) or isinstance(other,PyLong): 2721 n = other; 2722 else: 2723 if isinstance(other,RingElem): 2724 n = other.elem; 2725 #if isinstance(n,BigRational): # does not work 2726 if n.getClass().getSimpleName() == "BigRational": 2727 n = n.numerator().intValue() / n.denominator().intValue(); 2728 #if isinstance(n,BigInteger): # does not work 2729 if n.getClass().getSimpleName() == "BigInteger": 2730 n = n.intValue(); 2731 if n == None: 2732 n = other; 2733 if self.isFactory(): 2734 p = Power(self.elem).power( self.elem, n ); 2735 else: 2736 p = Power(self.ring).power( self.elem, n ); 2737 return RingElem( p );
2738
2739 - def __eq__(self,other):
2740 '''Test if two ring elements are equal. 2741 ''' 2742 if other == None: 2743 return False; 2744 [s,o] = coercePair(self,other); 2745 return s.elem.equals(o.elem)
2746
2747 - def __ne__(self,other):
2748 '''Test if two ring elements are not equal. 2749 ''' 2750 if other == None: 2751 return False; 2752 [s,o] = coercePair(self,other); 2753 return not self.elem.equals(o.elem)
2754
2755 - def __float__(self):
2756 '''Convert to Python float. 2757 ''' 2758 #print "self type(%s) = %s" % (self,type(self)); 2759 e = self.elem; 2760 if e.getClass().getSimpleName() == "BigInteger": 2761 e = BigRational(e); 2762 if e.getClass().getSimpleName() == "BigRational": 2763 e = BigDecimal(e); 2764 if e.getClass().getSimpleName() == "BigDecimal": 2765 e = e.toString(); 2766 e = float(e); 2767 return e;
2768
2769 - def factory(self):
2770 '''Get the factory of this element. 2771 ''' 2772 fac = self.elem.factory(); 2773 try: 2774 nv = fac.nvar; 2775 except: 2776 return RingElem(fac); 2777 #return PolyRing(fac.coFac,fac.getVars(),fac.tord); 2778 return RingElem(fac);
2779
2780 - def gens(self):
2781 '''Get the generators for the factory of this element. 2782 ''' 2783 L = self.elem.factory().generators(); 2784 #print "L = %s" % L; 2785 N = [ RingElem(e) for e in L ]; 2786 #print "N = %s" % N; 2787 return N;
2788
2789 - def inject_variables(self):
2790 '''Inject generators as variables into the main global namespace 2791 ''' 2792 inject_generators(self.gens());
2793
2794 - def monic(self):
2795 '''Monic polynomial. 2796 ''' 2797 return RingElem( self.elem.monic() );
2798
2799 - def evaluate(self,a):
2800 '''Evaluate at a for power series. 2801 ''' 2802 #print "self type(%s) = %s" % (self,type(self)); 2803 #print "a type(%s) = %s" % (a,type(a)); 2804 x = None; 2805 if isinstance(a,RingElem): 2806 x = a.elem; 2807 if isinstance(a,PyTuple) or isinstance(a,PyList): 2808 # assume BigRational or BigComplex 2809 # assume self will be compatible with them. todo: check this 2810 x = makeJasArith(a); 2811 try: 2812 e = self.elem.evaluate(x); 2813 except: 2814 e = 0; 2815 return RingElem( e );
2816
2817 - def integrate(self,a=0,r=None):
2818 '''Integrate a power series with constant a or as rational function. 2819 2820 a is the integration constant, r is for partial integration in variable r. 2821 ''' 2822 #print "self type(%s) = %s" % (self,type(self)); 2823 #print "a type(%s) = %s" % (a,type(a)); 2824 x = None; 2825 if isinstance(a,RingElem): 2826 x = a.elem; 2827 if isinstance(a,PyTuple) or isinstance(a,PyList): 2828 # assume BigRational or BigComplex 2829 # assume self will be compatible with them. todo: check this 2830 x = makeJasArith(a); 2831 try: 2832 if r != None: 2833 e = self.elem.integrate(x,r); 2834 else: 2835 e = self.elem.integrate(x); 2836 return RingElem( e ); 2837 except: 2838 pass; 2839 cf = self.elem.ring; 2840 try: 2841 cf = cf.ring; 2842 except: 2843 pass; 2844 integrator = ElementaryIntegration(cf.coFac); 2845 ei = integrator.integrate(self.elem); 2846 return ei;
2847
2848 - def differentiate(self,r=None):
2849 '''Differentiate a power series. 2850 2851 r is for partial differentiation in variable r. 2852 ''' 2853 try: 2854 if r != None: 2855 e = self.elem.differentiate(r); 2856 else: 2857 e = self.elem.differentiate(); 2858 except: 2859 e = self.elem.factory().getZERO(); 2860 return RingElem( e );
2861
2862 - def coefficients(self):
2863 '''Get the coefficients of a polynomial. 2864 ''' 2865 a = self.elem; 2866 #L = [ c.toScriptFactory() for c in a.coefficientIterator() ]; 2867 L = [ RingElem(c) for c in a.coefficientIterator() ]; 2868 return L
2869 2870 #---------------- 2871 # Compatibility methods for Sage/Singular: 2872 # Note: the meaning of lt and lm is swapped compared to JAS. 2873 #---------------- 2874
2875 - def parent(self):
2876 '''Parent in Sage is factory in JAS. 2877 2878 Compatibility method for Sage/Singular. 2879 ''' 2880 return self.factory();
2881
2882 - def __call__(self,num):
2883 '''Apply this to num. 2884 ''' 2885 if num == 0: 2886 return self.zero(); 2887 if num == 1: 2888 return self.one(); 2889 return RingElem( self.ring.fromInteger(num) );
2890
2891 - def lm(self):
2892 '''Leading monomial of a polynomial. 2893 2894 Compatibility method for Sage/Singular. 2895 Note: the meaning of lt and lm is swapped compared to JAS. 2896 ''' 2897 ev = self.elem.leadingExpVector(); 2898 return ev;
2899
2900 - def lc(self):
2901 '''Leading coefficient of a polynomial. 2902 2903 Compatibility method for Sage/Singular. 2904 ''' 2905 c = self.elem.leadingBaseCoefficient(); 2906 return RingElem(c);
2907
2908 - def lt(self):
2909 '''Leading term of a polynomial. 2910 2911 Compatibility method for Sage/Singular. 2912 Note: the meaning of lt and lm is swapped compared to JAS. 2913 ''' 2914 ev = self.elem.leadingMonomial(); 2915 return Monomial(ev);
2916
2917 - def degree(self):
2918 '''Degree of a polynomial. 2919 ''' 2920 try: 2921 ev = self.elem.degree(); 2922 except: 2923 return None; 2924 return ev;
2925
2926 - def base_ring(self):
2927 '''Coefficient ring of a polynomial. 2928 ''' 2929 try: 2930 ev = self.elem.ring.coFac; 2931 except: 2932 return None; 2933 return RingElem(ev);
2934
2935 - def is_field(self):
2936 '''Test if this RingElem is field. 2937 ''' 2938 return self.elem.isField();
2939
2940 - def monomials(self):
2941 '''All monomials of a polynomial. 2942 2943 Compatibility method for Sage/Singular. 2944 ''' 2945 ev = self.elem.getMap().keySet(); 2946 return ev;
2947
2948 - def divides(self,other):
2949 '''Test if self divides other. 2950 2951 Compatibility method for Sage/Singular. 2952 ''' 2953 [s,o] = coercePair(self,other); 2954 return o.elem.remainder( s.elem ).isZERO();
2955
2956 - def ideal(self,list):
2957 '''Create an ideal. 2958 2959 Compatibility method for Sage/Singular. 2960 ''' 2961 p = Ring("",ring=self.ring,fast=True); 2962 return p.ideal("",list=list);
2963
2964 - def monomial_quotient(self,a,b,coeff=False):
2965 '''Quotient of ExpVectors. 2966 2967 Compatibility method for Sage/Singular. 2968 ''' 2969 if isinstance(a,RingElem): 2970 a = a.elem; 2971 if isinstance(b,RingElem): 2972 b = b.elem; 2973 if coeff == False: 2974 if a.getClass().getSimpleName() == "GenPolynomial": 2975 return RingElem( a.divide(b) ); 2976 else: 2977 return RingElem( GenPolynomial(self.ring, a.subtract(b)) ); 2978 else: 2979 # assume JAS Monomial 2980 c = a.coefficient().divide(b.coefficient()); 2981 e = a.exponent().subtract(b.exponent()) 2982 return RingElem( GenPolynomial(self.ring, c, e) );
2983
2984 - def monomial_divides(self,a,b):
2985 '''Test divide of ExpVectors. 2986 2987 Compatibility method for Sage/Singular. 2988 ''' 2989 #print "JAS a = " + str(a) + ", b = " + str(b); 2990 if isinstance(a,RingElem): 2991 a = a.elem; 2992 if a.getClass().getSimpleName() == "GenPolynomial": 2993 a = a.leadingExpVector(); 2994 if a.getClass().getSimpleName() != "ExpVectorLong": 2995 raise ValueError, "No ExpVector given " + str(a) + ", " + str(b) 2996 if b == None: 2997 return False; 2998 if isinstance(b,RingElem): 2999 b = b.elem; 3000 if b.getClass().getSimpleName() == "GenPolynomial": 3001 b = b.leadingExpVector(); 3002 if b.getClass().getSimpleName() != "ExpVectorLong": 3003 raise ValueError, "No ExpVector given " + str(a) + ", " + str(b) 3004 return a.divides(b);
3005
3006 - def monomial_pairwise_prime(self,e,f):
3007 '''Test if ExpVectors are pairwise prime. 3008 3009 Compatibility method for Sage/Singular. 3010 ''' 3011 if isinstance(e,RingElem): 3012 e = e.elem; 3013 if isinstance(f,RingElem): 3014 f = f.elem; 3015 # assume JAS ExpVector 3016 c = e.gcd(f); 3017 return c.isZERO();
3018
3019 - def monomial_lcm(self,e,f):
3020 '''Lcm of ExpVectors. 3021 3022 Compatibility method for Sage/Singular. 3023 ''' 3024 if isinstance(e,RingElem): 3025 e = e.elem; 3026 if isinstance(f,RingElem): 3027 f = f.elem; 3028 # assume JAS ExpVector 3029 c = e.lcm(f); 3030 return c;
3031
3032 - def reduce(self,F):
3033 '''Compute a normal form of self with respect to F. 3034 3035 Compatibility method for Sage/Singular. 3036 ''' 3037 s = self.elem; 3038 Fe = [ e.elem for e in F ]; 3039 n = ReductionSeq().normalform(Fe,s); 3040 return RingElem(n);
3041 3042 #---------------- 3043 # End of compatibility methods 3044 #---------------- 3045 3046
3047 -class PolyRing(Ring):
3048 '''Represents a JAS polynomial ring: GenPolynomialRing. 3049 3050 Provides more convenient constructor. 3051 Then returns a Ring. 3052 ''' 3053
3054 - def __init__(self,coeff,vars,order=TermOrder(TermOrder.IGRLEX)):
3055 '''Ring constructor. 3056 3057 coeff = factory for coefficients, 3058 vars = string with variable names, 3059 order = term order. 3060 ''' 3061 if coeff == None: 3062 raise ValueError, "No coefficient given." 3063 cf = coeff; 3064 if isinstance(coeff,RingElem): 3065 cf = coeff.elem.factory(); 3066 if isinstance(coeff,Ring): 3067 cf = coeff.ring; 3068 if vars == None: 3069 raise ValueError, "No variable names given." 3070 names = vars; 3071 if isinstance(vars,PyString): 3072 names = GenPolynomialTokenizer.variableList(vars); 3073 nv = len(names); 3074 to = PolyRing.lex; 3075 if isinstance(order,TermOrder): 3076 to = order; 3077 tring = GenPolynomialRing(cf,nv,to,names); 3078 #want: super(Ring,self).__init__(ring=tring) 3079 Ring.__init__(self,ring=tring)
3080
3081 - def __str__(self):
3082 '''Create a string representation. 3083 ''' 3084 return self.ring.toScript();
3085 3086 lex = TermOrder(TermOrder.INVLEX) 3087 3088 grad = TermOrder(TermOrder.IGRLEX)
3089 3090
3091 -class SolvPolyRing(SolvableRing):
3092 '''Represents a JAS solvable polynomial ring: GenSolvablePolynomialRing. 3093 3094 Provides more convenient constructor. 3095 Then returns a Ring. 3096 ''' 3097
3098 - def __init__(self,coeff,vars,order=PolyRing.lex,rel=None):
3099 '''Ring constructor. 3100 3101 coeff = factory for coefficients, 3102 vars = string with variable names, 3103 order = term order, 3104 rel = triple list of relations. (e,f,p,...) with e * f = p as relation 3105 and e, f and p are commutative polynomials. 3106 ''' 3107 if coeff == None: 3108 raise ValueError, "No coefficient given." 3109 cf = coeff; 3110 if isinstance(coeff,RingElem): 3111 cf = coeff.elem.factory(); 3112 if isinstance(coeff,Ring): 3113 cf = coeff.ring; 3114 if vars == None: 3115 raise ValueError, "No variable names given." 3116 names = vars; 3117 if isinstance(vars,PyString): 3118 names = GenPolynomialTokenizer.variableList(vars); 3119 nv = len(names); 3120 to = PolyRing.lex; 3121 if isinstance(order,TermOrder): 3122 to = order; 3123 ring = GenSolvablePolynomialRing(cf,nv,to,names); 3124 if rel != None: 3125 #print "rel = " + str(rel); 3126 table = ring.table; 3127 L = []; 3128 for x in rel: 3129 if isinstance(x,RingElem): 3130 x = x.elem; 3131 L.append(x); 3132 #print "rel = " + str(L); 3133 for i in range(0,len(L),3): 3134 #print "adding relation: " + str(L[i]) + " * " + str(L[i+1]) + " = " + str(L[i+2]); 3135 table.update( L[i], L[i+1], L[i+2] ); 3136 self.ring = ring; 3137 SolvableRing.__init__(self,ring=self.ring)
3138
3139 - def __str__(self):
3140 '''Create a string representation. 3141 ''' 3142 return self.ring.toScript();
3143 3144
3145 -class EF:
3146 '''Extension field builder. 3147 3148 Construction of extension field towers according to the builder pattern. 3149 ''' 3150
3151 - def __init__(self,base):
3152 '''Constructor to set base field. 3153 ''' 3154 if isinstance(base,RingElem): 3155 #factory = base.elem; 3156 factory = base.ring; 3157 else: 3158 factory = base; 3159 try: 3160 factory = self.factory.factory(); 3161 except: 3162 pass 3163 print "extension field factory: " + factory.toScript(); # + " :: " + factory.toString(); 3164 #print "d type(%s) = %s" % (factory,type(factory)); 3165 if isinstance(factory,ExtensionFieldBuilder): 3166 self.builder = factory; 3167 else: 3168 self.builder = ExtensionFieldBuilder(factory);
3169
3170 - def __str__(self):
3171 '''Create a string representation. 3172 ''' 3173 return str(self.builder.toScript());
3174
3175 - def extend(self,vars,algebraic=None):
3176 '''Create an extension field. 3177 3178 If algebraic is given as string expression, then an algebraic 3179 extension field is constructed, else a transcendental 3180 extension field is constructed. 3181 ''' 3182 if algebraic == None: 3183 ef = self.builder.transcendentExtension(vars); 3184 else: 3185 ef = self.builder.algebraicExtension(vars,algebraic); 3186 return EF(ef.build());
3187
3188 - def realExtend(self,vars,algebraic,interval):
3189 '''Create a real extension field. 3190 3191 Construct a real algebraic extension field with an isolating interval for a real root. 3192 ''' 3193 ef = self.builder.realAlgebraicExtension(vars,algebraic,interval); 3194 return EF(ef.build());
3195
3196 - def complexExtend(self,vars,algebraic,rectangle):
3197 '''Create a complex extension field. 3198 3199 Construct a complex algebraic extension field with an isolating rectangle for a complex root. 3200 ''' 3201 ef = self.builder.complexAlgebraicExtension(vars,algebraic,rectangle); 3202 return EF(ef.build());
3203
3204 - def polynomial(self,vars):
3205 '''Create an polynomial ring extension. 3206 ''' 3207 ef = self.builder.polynomialExtension(vars); 3208 return EF(ef.build());
3209
3210 - def build(self):
3211 '''Get extension field tower. 3212 3213 ''' 3214 rf = self.builder.build(); 3215 if isinstance(rf,GenPolynomialRing): 3216 return PolyRing(rf.coFac,rf.getVars(),rf.tord); 3217 else: 3218 return RingElem(rf.getZERO());
3219 3220
3221 -class WordRing(Ring):
3222 '''Represents a JAS free non-commutative polynomial ring: GenWordPolynomialRing. 3223 3224 Has a method to create word ideals. 3225 <b>Note:</b> watch your step: check that jython does not reorder multiplication. 3226 ''' 3227
3228 - def __init__(self,ringstr="",ring=None):
3229 '''Word polynomial ring constructor. 3230 ''' 3231 if ring == None: 3232 raise ValueError, "parse of word polynomials not implemented" 3233 sr = StringReader( ringstr ); 3234 tok = GenPolynomialTokenizer(sr); 3235 self.pset = tok.nextWordPolynomialSet(); 3236 self.ring = self.pset.ring; 3237 else: 3238 self.ring = ring; 3239 if not self.ring.isAssociative(): 3240 print "warning: ring is not associative";
3241
3242 - def __str__(self):
3243 '''Create a string representation. 3244 ''' 3245 return str(self.ring.toScript());
3246
3247 - def ideal(self,ringstr="",list=None):
3248 '''Create a word ideal. 3249 ''' 3250 return WordIdeal(self,ringstr,list);
3251
3252 - def one(self):
3253 '''Get the one of the word polynomial ring. 3254 ''' 3255 return RingElem( self.ring.getONE() );
3256
3257 - def zero(self):
3258 '''Get the zero of the word polynomial ring. 3259 ''' 3260 return RingElem( self.ring.getZERO() );
3261
3262 - def random(self,n):
3263 '''Get a random word polynomial. 3264 ''' 3265 return RingElem( self.ring.random(n) );
3266
3267 - def random(self,k,l,d):
3268 '''Get a random word polynomial. 3269 ''' 3270 return RingElem( self.ring.random(k,l,d) );
3271
3272 - def element(self,poly):
3273 '''Create an element from a string or object. 3274 ''' 3275 if not isinstance(poly,str): 3276 try: 3277 if self.ring == poly.ring: 3278 return RingElem(poly); 3279 except Exception, e: 3280 pass 3281 poly = str(poly); 3282 I = WordIdeal(self, "( " + poly + " )"); 3283 list = I.list; 3284 if len(list) > 0: 3285 return RingElem( list[0] );
3286 3287
3288 -class WordPolyRing(WordRing):
3289 '''Represents a JAS free non-commutative polynomial ring: GenWordPolynomialRing. 3290 3291 Provides more convenient constructor. 3292 Then returns a Ring. 3293 <b>Note:</b> watch your step: check that jython does not reorder multiplication. 3294 ''' 3295
3296 - def __init__(self,coeff,vars):
3297 '''Ring constructor. 3298 3299 coeff = factory for coefficients, 3300 vars = string with variable names. 3301 ''' 3302 if coeff == None: 3303 raise ValueError, "No coefficient given." 3304 cf = coeff; 3305 if isinstance(coeff,RingElem): 3306 cf = coeff.elem.factory(); 3307 if isinstance(coeff,Ring): 3308 cf = coeff.ring; 3309 if vars == None: 3310 raise ValueError, "No variable names given." 3311 names = vars; 3312 if isinstance(vars,PyString): 3313 names = GenPolynomialTokenizer.variableList(vars); 3314 wf = WordFactory(names); 3315 ring = GenWordPolynomialRing(cf,wf); 3316 self.ring = ring;
3317
3318 - def __str__(self):
3319 '''Create a string representation. 3320 ''' 3321 return self.ring.toScript();
3322 3323
3324 -class WordIdeal:
3325 '''Represents a JAS word polynomial ideal. 3326 3327 Methods for two-sided Groebner basees and others. 3328 <b>Note:</b> watch your step: check that jython does not reorder multiplication. 3329 ''' 3330
3331 - def __init__(self,ring,ringstr="",list=None):
3332 '''Constructor for an ideal in a word polynomial ring. 3333 ''' 3334 self.ring = ring; 3335 if list == None: 3336 raise ValueError, "parse of word polynomials not implemented" 3337 sr = StringReader( ringstr ); 3338 tok = GenPolynomialTokenizer(ring.ring,sr); 3339 self.list = tok.nextSolvablePolynomialList(); 3340 else: 3341 self.list = pylist2arraylist(list,rec=1);
3342 #self.pset = PolynomialList(ring.ring,self.list); 3343
3344 - def __str__(self):
3345 '''Create a string representation. 3346 ''' 3347 ll = [ e.toScript() for e in self.list ] 3348 return "( " + ", ".join(ll) + " )";
3349
3350 - def __cmp__(self,other):
3351 '''Compare two ideals. 3352 ''' 3353 t = False; 3354 if not isinstance(other,WordIdeal): 3355 return t; 3356 t = self.list.equals(other.list); 3357 return t;
3358
3359 - def GB(self):
3360 '''Compute a two-sided Groebner base. 3361 ''' 3362 return self.twosidedGB();
3363
3364 - def twosidedGB(self):
3365 '''Compute a two-sided Groebner base. 3366 ''' 3367 #s = self.pset; 3368 F = self.list; 3369 t = System.currentTimeMillis(); 3370 G = WordGroebnerBaseSeq().GB(F); 3371 t = System.currentTimeMillis() - t; 3372 print "executed twosidedGB in %s ms" % t; 3373 return WordIdeal(self.ring,"",G);
3374
3375 - def isGB(self):
3376 '''Test if this is a two-sided Groebner base. 3377 ''' 3378 return self.isTwosidedGB();
3379
3380 - def isTwosidedGB(self):
3381 '''Test if this is a two-sided Groebner base. 3382 ''' 3383 #s = self.pset; 3384 F = self.list; 3385 t = System.currentTimeMillis(); 3386 b = WordGroebnerBaseSeq().isGB(F); 3387 t = System.currentTimeMillis() - t; 3388 print "isTwosidedGB executed in %s ms" % t; 3389 return b;
3390