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

Source Code for Module jas

   1  '''jython interface to JAS. 
   2  ''' 
   3   
   4  # $Id$ 
   5   
   6  from java.lang           import System 
   7  from java.io             import StringReader 
   8  from java.util           import ArrayList, List, Collections 
   9   
  10  from edu.jas.structure   import RingElem, RingFactory, Power 
  11  from edu.jas.arith       import BigInteger, BigRational, BigComplex, BigDecimal,\ 
  12                                  ModInteger, ModIntegerRing, ModLong, ModLongRing, ModInt, ModIntRing,\ 
  13                                  BigQuaternion, BigQuaternionRing, BigOctonion,\ 
  14                                  Product, ProductRing, PrimeList, PrimeInteger 
  15  from edu.jas.poly        import GenPolynomial, GenPolynomialRing, Monomial,\ 
  16                                  GenSolvablePolynomial, GenSolvablePolynomialRing,\ 
  17                                  RecSolvablePolynomial, RecSolvablePolynomialRing,\ 
  18                                  RecSolvableWordPolynomial, RecSolvableWordPolynomialRing,\ 
  19                                  QLRSolvablePolynomial, QLRSolvablePolynomialRing,\ 
  20                                  GenWordPolynomial, GenWordPolynomialRing,\ 
  21                                  ExpVector,\ 
  22                                  Word, WordFactory,\ 
  23                                  GenPolynomialTokenizer, OrderedPolynomialList, PolyUtil,\ 
  24                                  TermOrderOptimization, TermOrder, TermOrderByName,\ 
  25                                  PolynomialList, AlgebraicNumber, AlgebraicNumberRing,\ 
  26                                  OrderedModuleList, ModuleList,\ 
  27                                  Complex, ComplexRing 
  28  from edu.jas.ps          import UnivPowerSeries, UnivPowerSeriesRing,\ 
  29                                  UnivPowerSeriesMap, Coefficients, \ 
  30                                  MultiVarPowerSeries, MultiVarPowerSeriesRing,\ 
  31                                  MultiVarPowerSeriesMap, MultiVarCoefficients,\ 
  32                                  StandardBaseSeq 
  33  from edu.jas.gb          import EReductionSeq, DGroebnerBaseSeq, EGroebnerBaseSeq,\ 
  34                                  GroebnerBaseDistributedEC, GroebnerBaseDistributedHybridEC,\ 
  35                                  GroebnerBaseSeq, GroebnerBaseSeqIter, GroebnerBaseSeqPairSeq,\ 
  36                                  OrderedPairlist, OrderedSyzPairlist, ReductionSeq,\ 
  37                                  GroebnerBaseParallel, GroebnerBaseSeqPairParallel,\ 
  38                                  SolvableGroebnerBaseParallel, SolvableGroebnerBaseSeq,\ 
  39                                  SolvableReductionSeq, WordGroebnerBaseSeq 
  40  from edu.jas.gbufd       import GroebnerBasePseudoRecSeq, GroebnerBasePseudoSeq,\ 
  41                                  SolvableGroebnerBasePseudoSeq, SolvablePseudoReductionSeq,\ 
  42                                  PseudoReductionSeq, GroebnerBasePseudoParallel,\ 
  43                                  WordGroebnerBasePseudoSeq, WordPseudoReductionSeq,\ 
  44                                  SolvableGroebnerBasePseudoRecSeq, WordGroebnerBasePseudoRecSeq,\ 
  45                                  RGroebnerBasePseudoSeq, RGroebnerBaseSeq, RReductionSeq,\ 
  46                                  GroebnerBaseFGLM, GroebnerBaseWalk,\ 
  47                                  CharacteristicSetWu, PolyGBUtil,\ 
  48                                  SolvableSyzygySeq, SyzygySeq 
  49  #from edu.jas.gbmod       import ModGroebnerBaseSeq, ModSolvableGroebnerBaseSeq 
  50  from edu.jas.vector      import GenVector, GenVectorModul,\ 
  51                                  GenMatrix, GenMatrixRing 
  52  from edu.jas.application import FactorFactory, PolyUtilApp, RingFactoryTokenizer,\ 
  53                                  Residue, ResidueRing, Ideal,\ 
  54                                  Local, LocalRing, IdealWithRealAlgebraicRoots,\ 
  55                                  SolvableIdeal, SolvableResidue, SolvableResidueRing,\ 
  56                                  SolvableLocal, SolvableLocalRing,\ 
  57                                  SolvableLocalResidue, SolvableLocalResidueRing,\ 
  58                                  ResidueSolvablePolynomial, ResidueSolvablePolynomialRing,\ 
  59                                  LocalSolvablePolynomial, LocalSolvablePolynomialRing,\ 
  60                                  WordIdeal, WordResidue, WordResidueRing,\ 
  61                                  AlgebraicRootsPrimElem, RootFactoryApp,\ 
  62                                  ComprehensiveGroebnerBaseSeq, ExtensionFieldBuilder 
  63  from edu.jas.kern        import ComputerThreads, StringUtil, Scripting 
  64  from edu.jas.ufd         import GreatestCommonDivisor, PolyUfdUtil, GCDFactory,\ 
  65                                  SquarefreeFactory, Quotient, QuotientRing 
  66  from edu.jas.fd          import SolvableQuotient, SolvableQuotientRing,\ 
  67                                  QuotSolvablePolynomial, QuotSolvablePolynomialRing 
  68  from edu.jas.root        import RealRootsSturm, Interval, RealAlgebraicNumber, RealAlgebraicRing,\ 
  69                                  ComplexRootsSturm, Rectangle, RootFactory 
  70  from edu.jas.integrate   import ElementaryIntegration 
  71  from edu.jas.util        import ExecutableServer 
  72  #from edu.jas             import structure, arith, poly, ps, gb, gbmod, vector,\ 
  73  #                                application, util, ufd 
  74  from edu                 import jas 
  75  #PrettyPrint.setInternal(); 
  76   
  77  from org.python.core     import PyInstance, PyList, PyTuple,\ 
  78                                  PyInteger, PyLong, PyFloat, PyString 
  79  # not suitable PySequence 
  80   
  81  # set output to Python scripting 
  82  Scripting.setLang(Scripting.Lang.Python); 
  83   
84 -def startLog():
85 '''Configure the log4j system and start logging. 86 87 BasicConfigurator from log4j version 1 is no more supported, please use log4j2 configuration. 88 '''
89 #print "BasicConfigurator from log4j version 1 is no more supported, please use log4j2 configuration"; 90 91 print "Java Algebra System (JAS) version 2.7" 92
93 -def terminate():
94 '''Terminate the running thread pools. 95 ''' 96 ComputerThreads.terminate();
97
98 -def noThreads():
99 '''Turn off automatic parallel threads usage. 100 ''' 101 print "nt = ", ComputerThreads.NO_THREADS; 102 ComputerThreads.setNoThreads(); #NO_THREADS = #0; #1; #True; 103 print "nt = ", ComputerThreads.NO_THREADS;
104 105 auto_inject = True 106 '''Define variables automatically in the global namespace. 107 ''' 108
109 -def inject_variable(name, value):
110 '''Inject a variable into the main global namespace 111 112 INPUT: 113 - "name" - a string 114 - "value" - anything 115 116 Found in Sage. 117 AUTHORS: 118 - William Stein 119 ''' 120 assert type(name) is str 121 import sys 122 depth = 0 123 redef = None 124 while True: 125 G = sys._getframe(depth).f_globals 126 #print "G = `%s` " % G; 127 depth += 1 128 if depth > 100: 129 print "depth limit %s reached " % depth; 130 break 131 if G is None: 132 continue 133 # orig: if G["__name__"] == "__main__" and G["__package__"] is None: 134 try: 135 if G["__name__"] is None: 136 break 137 except: 138 #print "G[__name__] undefined"; 139 break 140 if G["__name__"] == "__main__": 141 try: 142 if G["__package__"] is None: 143 break 144 except: 145 break 146 if G is None: 147 print "error at G no global environment found for `%s` = `%s` " % (name, value); 148 return 149 if name in G: 150 redef = name; 151 #print "redefining global variable `%s` from `%s` " % (name, G[name]); 152 G[name] = value 153 return redef
154
155 -def inject_generators(gens):
156 '''Inject generators as variables into the main global namespace 157 158 INPUT: 159 - "gens" - generators 160 ''' 161 for v in gens: 162 #print "vars = " + str(v); 163 redef = []; 164 s = str(v); 165 if s.find("/") < 0 and s.find("(") < 0 and s.find(",") < 0 and s.find("{") < 0 and s.find("[") < 0 and s.find("|") < 0: 166 if s[0:1] == "1": 167 s = "one" + s[1:] 168 #print "var = " + s; 169 rd = inject_variable(s,v) 170 if rd != None: 171 redef.append(rd); 172 if redef != []: 173 print "WARN: redefined variables " + ", ".join(redef);
174
175 -def nameFromValue(v):
176 '''Get a meaningful name from a value. 177 178 INPUT: 179 - "v" - the given value. 180 ''' 181 import re; 182 ri = re.compile(r'\A[0-9].*'); 183 vs = str(v); 184 vs = vs.replace(" ",""); 185 vs = vs.replace("\n",""); 186 if vs.find("(") >= 0: 187 vs = vs.replace("(",""); 188 vs = vs.replace(")",""); 189 if vs.find("{") >= 0: 190 vs = vs.replace("{",""); 191 vs = vs.replace("}",""); 192 if vs.find("[") >= 0: 193 vs = vs.replace("[",""); 194 vs = vs.replace("]",""); 195 if vs.find(",") >= 0: 196 vs = vs.replace(",",""); 197 #if vs.find("|") >= 0: 198 # vs = vs.replace("|","div"); # case "1"? 199 if vs.find("/") >= 0: 200 vs = vs.replace("/","div"); 201 if vs[0:1] == "1" and not ri.match(vs): 202 vs = 'one' + vs[1:]; 203 if vs == "1": 204 vs = "one"; 205 if vs == "0i1" or vs == "0I1": 206 vs = "I"; 207 if vs.find("|") >= 0 or ri.match(vs): 208 #print "0vs = " + str(vs); 209 return None; 210 return vs;
211 212
213 -class Ring:
214 '''Represents a JAS polynomial ring: GenPolynomialRing. 215 216 Methods to create ideals and ideals with parametric coefficients. 217 ''' 218
219 - def __init__(self,ringstr="",ring=None,fast=False):
220 '''Ring constructor. 221 222 ringstr string representation to be parsed. 223 ring JAS ring object. 224 ''' 225 if ring == None: 226 sr = StringReader( ringstr ); 227 tok = RingFactoryTokenizer(sr); 228 pfac = tok.nextPolynomialRing(); 229 #tok = GenPolynomialTokenizer(pfac,sr); 230 #plist = tok.nextPolynomialList(); 231 #self.pset = PolynomialList(pfac,plist); 232 self.ring = pfac; 233 else: 234 if isinstance(ring,Ring): 235 self.ring = ring.ring; 236 else: 237 self.ring = ring; 238 if fast: 239 return; 240 self.engine = Ring.getEngineGcd(self.ring); 241 self.sqf = Ring.getEngineSqf(self.ring); 242 self.factor = Ring.getEngineFactor(self.ring); 243 self.variable_generators();
244
245 - def getEngineGcd(r):
246 '''Get the polynomial gcd engine implementation. 247 248 r is the given polynomial ring. 249 ''' 250 if isinstance(r,RingElem): 251 r = r.elem; 252 if not isinstance(r,GenPolynomialRing): 253 return None; 254 try: 255 i = GCDFactory.getProxy(r.coFac); 256 except: 257 i = None 258 return i;
259 260 getEngineGcd = staticmethod(getEngineGcd); 261
262 - def getEngineSqf(r):
263 '''Get the polynomial squarefree engine implementation. 264 265 r is the given polynomial ring. 266 ''' 267 if isinstance(r,RingElem): 268 r = r.elem; 269 if not isinstance(r,GenPolynomialRing): 270 return None; 271 try: 272 i = SquarefreeFactory.getImplementation(r.coFac); 273 except: 274 i = None 275 return i;
276 277 getEngineSqf = staticmethod(getEngineSqf); 278
279 - def getEngineFactor(r):
280 '''Get the polynomial factorization engine implementation. 281 282 r is the given polynomial ring. 283 ''' 284 if isinstance(r,RingElem): 285 r = r.elem; 286 if not isinstance(r,GenPolynomialRing): 287 return None; 288 try: 289 i = FactorFactory.getImplementation(r.coFac); 290 except: 291 i = None 292 return i;
293 294 getEngineFactor = staticmethod(getEngineFactor); 295
296 - def variable_generators(self):
297 '''Define instance variables for generators. 298 ''' 299 vns = [] 300 redef = [] 301 #print "dict: " + str(self.__dict__) 302 for v in self.gens(): #ring.generators(): 303 #vr = RingElem(v); 304 #print "vars = " + str(v); 305 vs = nameFromValue(v); 306 if vs is None: 307 #print "0vs = " + str(vs); 308 continue; 309 try: 310 if self.__dict__[vs] is None: 311 self.__dict__[vs] = v; 312 else: 313 print vs + " not redefined to " + str(v); 314 except: 315 self.__dict__[vs] = v; 316 if auto_inject: 317 rd = inject_variable(vs,v) 318 vns.append(vs) 319 if rd != None: 320 redef.append(rd); 321 if auto_inject: 322 print "globally defined variables: " + ", ".join(vns) 323 if redef != []: 324 print "WARN: redefined global variables: " + ", ".join(redef);
325 #print "dict: " + str(self.__dict__) 326
327 - def __str__(self):
328 '''Create a string representation. 329 ''' 330 return str(self.ring.toScript());
331
332 - def __eq__(self,other):
333 '''Test if two rings are equal. 334 ''' 335 if not isinstance(other, Ring): 336 return False; 337 s = self.ring; 338 t = other.ring; 339 return s.equals(t)
340
341 - def ideal(self,ringstr="",list=None):
342 '''Create an ideal. 343 ''' 344 return Ideal(self,ringstr,list=list);
345
346 - def paramideal(self,ringstr="",list=None,gbsys=None):
347 '''Create an ideal in a polynomial ring with parameter coefficients. 348 ''' 349 return ParamIdeal(self,ringstr,list,gbsys);
350
351 - def powerseriesRing(self):
352 '''Get a power series ring from this ring. 353 ''' 354 pr = MultiVarPowerSeriesRing(self.ring); 355 return MultiSeriesRing(ring=pr);
356
357 - def gens(self):
358 '''Get list of generators of the polynomial ring. 359 ''' 360 L = self.ring.generators(); 361 N = [ RingElem(e) for e in L ]; 362 return N;
363
364 - def inject_variables(self):
365 '''Inject generators as variables into the main global namespace 366 ''' 367 inject_generators(self.gens());
368
369 - def one(self):
370 '''Get the one of the polynomial ring. 371 ''' 372 return RingElem( self.ring.getONE() );
373
374 - def zero(self):
375 '''Get the zero of the polynomial ring. 376 ''' 377 return RingElem( self.ring.getZERO() );
378
379 - def random(self,k=5,l=7,d=3,q=0.3):
380 '''Get a random polynomial. 381 ''' 382 r = self.ring.random(k,l,d,q); 383 if self.ring.coFac.isField(): 384 r = r.monic(); 385 return RingElem( r );
386
387 - def element(self,poly):
388 '''Create an element from a string or object. 389 ''' 390 if not isinstance(poly,str): 391 try: 392 if self.ring == poly.ring: 393 return RingElem(poly); 394 except Exception, e: 395 pass 396 poly = str(poly); 397 I = Ideal(self, "( " + poly + " )"); 398 list = I.pset.list; 399 if len(list) > 0: 400 return RingElem( list[0] );
401
402 - def gcd(self,a,b):
403 '''Compute the greatest common divisor of a and b. 404 ''' 405 if isinstance(a,RingElem): 406 a = a.elem; 407 else: 408 a = self.element( a ); 409 a = a.elem; 410 if isinstance(b,RingElem): 411 b = b.elem; 412 else: 413 b = self.element( b ); 414 b = b.elem; 415 return RingElem( self.engine.gcd(a,b) );
416
417 - def squarefreeFactors(self,a):
418 '''Compute squarefree factors of polynomial. 419 ''' 420 if isinstance(a,RingElem): 421 a = a.elem; 422 else: 423 a = self.element( a ); 424 a = a.elem; 425 cf = self.ring.coFac; 426 if isinstance(cf,GenPolynomialRing): 427 e = self.sqf.recursiveSquarefreeFactors( a ); 428 else: 429 e = self.sqf.squarefreeFactors( a ); 430 L = {}; 431 for a in e.keySet(): 432 i = e.get(a); 433 L[ RingElem( a ) ] = i; 434 return L;
435
436 - def factors(self,a):
437 '''Compute irreducible factorization for modular, integer, 438 rational number and algebriac number coefficients. 439 ''' 440 if isinstance(a,RingElem): 441 a = a.elem; 442 else: 443 a = self.element( a ); 444 a = a.elem; 445 try: 446 cf = self.ring.coFac; 447 if isinstance(cf,GenPolynomialRing) and cf.isCommutative(): 448 e = self.factor.recursiveFactors( a ); 449 else: 450 e = self.factor.factors( a ); 451 L = {}; 452 for a in e.keySet(): 453 i = e.get(a); 454 L[ RingElem( a ) ] = i; 455 return L; 456 except Exception, e: 457 print "error " + str(e) 458 return None
459
460 - def factorsAbsolute(self,a):
461 '''Compute absolute irreducible factorization for (modular,) 462 rational number coefficients. 463 ''' 464 if isinstance(a,RingElem): 465 a = a.elem; 466 else: 467 a = self.element( a ); 468 a = a.elem; 469 try: 470 L = self.factor.factorsAbsolute( a ); 471 ## L = {}; 472 ## for a in e.keySet(): 473 ## i = e.get(a); 474 ## L[ RingElem( a ) ] = i; 475 return L; 476 except Exception, e: 477 print "error in factorsAbsolute " + str(e) 478 return None
479
480 - def realRoots(self,a,eps=None):
481 '''Compute real roots of univariate polynomial. 482 ''' 483 if not isinstance(a,RingElem): 484 a = RingElem(a); 485 return a.realRoots(eps);
486
487 - def complexRoots(self,a,eps=None):
488 '''Compute complex roots of univariate polynomial. 489 ''' 490 if not isinstance(a,RingElem): 491 a = RingElem(a); 492 return a.complexRoots(eps);
493
494 - def algebraicRoots(self,a,eps=None):
495 '''Algebraic real and Compute complex roots of univariate polynomial. 496 ''' 497 if not isinstance(a,RingElem): 498 a = RingElem(a); 499 return a.algebraicRoots(eps);
500
501 - def rootRefine(self,a,eps=None):
502 '''Compute algebraic roots refinement. 503 ''' 504 if not isinstance(a,RingElem): 505 a = RingElem(a); 506 return a.rootRefine(eps);
507
508 - def decimalRoots(self,a,eps=None):
509 '''Compute decimal approximation of real and complex roots of univariate polynomial. 510 ''' 511 if not isinstance(a,RingElem): 512 a = RingElem(a); 513 return a.decimalRoots(eps);
514
515 - def rootsOfUnity(self,a):
516 '''Roots of unity of real and complex algebraic numbers. 517 ''' 518 if not isinstance(a,RingElem): 519 a = RingElem(a); 520 return a.rootsOfUnity();
521
522 - def rootReduce(self,a, b):
523 '''Root reduce of real and complex algebraic numbers. 524 Compute an extension field with a primitive element. 525 ''' 526 if not isinstance(a,RingElem): 527 a = RingElem(a); 528 return a.rootReduce(b);
529
530 - def integrate(self,a):
531 '''Integrate rational function or power series. 532 ''' 533 if not isinstance(a,RingElem): 534 a = RingElem(a); 535 return a.integrate();
536
537 - def subring(self,polystr="",list=None):
538 '''Sub ring generators as Groebner base. 539 ''' 540 if list == None: 541 sr = StringReader( polystr ); 542 tok = GenPolynomialTokenizer(self.ring,sr); 543 self.list = tok.nextPolynomialList(); 544 else: 545 self.list = pylist2arraylist(list,rec=1); 546 sr = PolyGBUtil.subRing(self.list); 547 srr = [ RingElem(a) for a in sr ]; 548 return srr;
549
550 - def subringmember(self, list, a):
551 '''Sub ring member test. list is a Groebner base. 552 Test if a \in K[list]. 553 ''' 554 sr = [ p.elem for p in list]; 555 if isinstance(a,RingElem): 556 a = a.elem; 557 b = PolyGBUtil.subRingMember(sr, a); 558 return b;
559
560 - def CRT(self,polystr="", list=None, rem=None):
561 '''Chinese remainder theorem. 562 ''' 563 if list == None: 564 sr = StringReader( polystr ); 565 tok = GenPolynomialTokenizer(self.ring,sr); 566 self.list = tok.nextPolynomialList(); 567 else: 568 self.list = pylist2arraylist(list,rec=2); 569 if rem == None: 570 raise ValueError, "No remainders given." 571 else: 572 self.remlist = pylist2arraylist(rem,rec=1); 573 #print "list = " + str(self.list); 574 #print "remlist = " + str(self.remlist); 575 #print 576 h = PolyGBUtil.chineseRemainderTheorem(self.list, self.remlist); 577 if h != None: 578 h = RingElem(h); 579 return h;
580
581 - def CRTinterpol(self,polystr="", list=None, rem=None):
582 '''Chinese remainder theorem, interpolation. 583 ''' 584 if list == None: 585 sr = StringReader( polystr ); 586 tok = GenPolynomialTokenizer(self.ring,sr); 587 self.list = tok.nextPolynomialList(); 588 else: 589 self.list = pylist2arraylist(list,rec=2); 590 if rem == None: 591 raise ValueError, "No remainders given." 592 else: 593 self.remlist = pylist2arraylist(rem,rec=1); 594 #print "ring = " + str(self.ring); 595 #print "list = " + str(self.list); 596 #print "remlist = " + str(self.remlist); 597 #print 598 h = PolyGBUtil.CRTInterpolation(self.ring, self.list, self.remlist); 599 if h != None: 600 h = RingElem(h); 601 return h;
602 603
604 -class Ideal:
605 '''Represents a JAS polynomial ideal: PolynomialList and Ideal. 606 607 Methods for Groebner bases, ideal sum, intersection and others. 608 ''' 609
610 - def __init__(self,ring,polystr="",list=None):
611 '''Ideal constructor. 612 ''' 613 self.ring = ring; 614 if list == None: 615 sr = StringReader( polystr ); 616 tok = GenPolynomialTokenizer(ring.ring,sr); 617 self.list = tok.nextPolynomialList(); 618 else: 619 self.list = pylist2arraylist(list,rec=1); 620 self.pset = OrderedPolynomialList(ring.ring,self.list); 621 self.roots = None; 622 self.croots = None; 623 self.prime = None; 624 self.primary = None;
625
626 - def __str__(self):
627 '''Create a string representation. 628 ''' 629 return str(self.pset.toScript());
630
631 - def __eq__(self,other):
632 '''Test if two ideals are equal. 633 ''' 634 o = other; 635 if isinstance(other,Ideal): 636 o = other.pset; 637 return self.pset.equals(o)
638
639 - def paramideal(self):
640 '''Create an ideal in a polynomial ring with parameter coefficients. 641 ''' 642 return ParamIdeal(self.ring,"",self.list);
643
644 - def GB(self):
645 '''Compute a Groebner base. 646 ''' 647 s = self.pset; 648 cofac = s.ring.coFac; 649 F = s.list; 650 kind = ""; 651 t = System.currentTimeMillis(); 652 if cofac.isField(): 653 G = GroebnerBaseSeq(ReductionSeq(),OrderedSyzPairlist()).GB(F); 654 #G = GroebnerBaseSeqIter(ReductionSeq(),OrderedSyzPairlist()).GB(F); 655 #G = GroebnerBaseSeq().GB(F); 656 kind = "field" 657 else: 658 if isinstance(cofac,GenPolynomialRing) and cofac.isCommutative(): 659 G = GroebnerBasePseudoRecSeq(cofac).GB(F); 660 kind = "pseudorec" 661 else: 662 G = GroebnerBasePseudoSeq(cofac).GB(F); 663 kind = "pseudo" 664 t = System.currentTimeMillis() - t; 665 print "sequential(%s) GB executed in %s ms" % (kind, t); 666 return Ideal(self.ring,"",G);
667
668 - def isGB(self):
669 '''Test if this is a Groebner base. 670 ''' 671 s = self.pset; 672 cofac = s.ring.coFac; 673 F = s.list; 674 t = System.currentTimeMillis(); 675 if cofac.isField(): 676 b = GroebnerBaseSeq().isGB(F); 677 else: 678 if isinstance(cofac,GenPolynomialRing) and cofac.isCommutative(): 679 b = GroebnerBasePseudoRecSeq(cofac).isGB(F); 680 else: 681 b = GroebnerBasePseudoSeq(cofac).isGB(F); 682 t = System.currentTimeMillis() - t; 683 #print "isGB executed in %s ms" % t; 684 return b;
685
686 - def eGB(self):
687 '''Compute an e-Groebner base. 688 ''' 689 s = self.pset; 690 cofac = s.ring.coFac; 691 F = s.list; 692 t = System.currentTimeMillis(); 693 G = EGroebnerBaseSeq().GB(F) 694 t = System.currentTimeMillis() - t; 695 print "sequential e-GB executed in %s ms" % t; 696 return Ideal(self.ring,"",G);
697
698 - def iseGB(self):
699 '''Test if this is an e-Groebner base. 700 ''' 701 s = self.pset; 702 cofac = s.ring.coFac; 703 F = s.list; 704 t = System.currentTimeMillis(); 705 b = EGroebnerBaseSeq().isGB(F) 706 t = System.currentTimeMillis() - t; 707 print "is e-GB test executed in %s ms" % t; 708 return b;
709
710 - def dGB(self):
711 '''Compute an d-Groebner base. 712 ''' 713 s = self.pset; 714 cofac = s.ring.coFac; 715 F = s.list; 716 t = System.currentTimeMillis(); 717 G = DGroebnerBaseSeq().GB(F) 718 t = System.currentTimeMillis() - t; 719 print "sequential d-GB executed in %s ms" % t; 720 return Ideal(self.ring,"",G);
721
722 - def isdGB(self):
723 '''Test if this is a d-Groebner base. 724 ''' 725 s = self.pset; 726 cofac = s.ring.coFac; 727 F = s.list; 728 t = System.currentTimeMillis(); 729 b = DGroebnerBaseSeq().isGB(F) 730 t = System.currentTimeMillis() - t; 731 print "is d-GB test executed in %s ms" % t; 732 return b;
733
734 - def parNewGB(self,th):
735 '''Compute in parallel a Groebner base. 736 ''' 737 s = self.pset; 738 F = s.list; 739 bbpar = GroebnerBaseSeqPairParallel(th); 740 t = System.currentTimeMillis(); 741 G = bbpar.GB(F); 742 t = System.currentTimeMillis() - t; 743 bbpar.terminate(); 744 print "parallel-new %s executed in %s ms" % (th, t); 745 return Ideal(self.ring,"",G);
746
747 - def parGB(self,th):
748 '''Compute in parallel a Groebner base. 749 ''' 750 s = self.pset; 751 F = s.list; 752 cofac = s.ring.coFac; 753 if cofac.isField(): 754 bbpar = GroebnerBaseParallel(th); 755 else: 756 bbpar = GroebnerBasePseudoParallel(th,cofac); 757 t = System.currentTimeMillis(); 758 G = bbpar.GB(F); 759 t = System.currentTimeMillis() - t; 760 bbpar.terminate(); 761 print "parallel %s executed in %s ms" % (th, t); 762 return Ideal(self.ring,"",G);
763
764 - def distGB(self,th=2,machine="examples/machines.localhost",port=55711):
765 '''Compute on a distributed system a Groebner base. 766 ''' 767 s = self.pset; 768 F = s.list; 769 t = System.currentTimeMillis(); 770 #old: gbd = GBDist(th,machine,port); 771 gbd = GroebnerBaseDistributedEC(machine,th,port); 772 #gbd = GroebnerBaseDistributedHybridEC(machine,th,port); 773 t1 = System.currentTimeMillis(); 774 G = gbd.GB(F); 775 t1 = System.currentTimeMillis() - t1; 776 gbd.terminate(); 777 t = System.currentTimeMillis() - t; 778 print "distributed %s executed in %s ms (%s ms start-up)" % (th,t1,t-t1); 779 return Ideal(self.ring,"",G);
780
781 - def distClient(self,port=4711): #8114
782 '''Client for a distributed computation. 783 ''' 784 e1 = ExecutableServer( port ); 785 e1.init(); 786 e2 = ExecutableServer( port+1 ); 787 e2.init(); 788 self.exers = [e1,e2]; 789 return None;
790
791 - def distClientStop(self):
792 '''Stop client for a distributed computation. 793 ''' 794 for es in self.exers: 795 es.terminate(); 796 return None;
797
798 - def eReduction(self,p):
799 '''Compute a e-normal form of p with respect to this ideal. 800 ''' 801 s = self.pset; 802 G = s.list; 803 if isinstance(p,RingElem): 804 p = p.elem; 805 t = System.currentTimeMillis(); 806 n = EReductionSeq().normalform(G,p); 807 t = System.currentTimeMillis() - t; 808 print "sequential eReduction executed in %s ms" % t; 809 return RingElem(n);
810
811 - def reduction(self,p):
812 '''Compute a normal form of p with respect to this ideal. 813 ''' 814 s = self.pset; 815 G = s.list; 816 if isinstance(p,RingElem): 817 p = p.elem; 818 if self.ring.ring.coFac.isField(): 819 n = ReductionSeq().normalform(G,p); 820 else: 821 n = PseudoReductionSeq().normalform(G,p); 822 #F = PseudoReductionSeq().normalformFactor(G,p); 823 #print "F.multiplicator = " + str(F.multiplicator) 824 #n = F.pol 825 return RingElem(n);
826
827 - def NF(self,reducer):
828 '''Compute a normal form of this ideal with respect to reducer. 829 ''' 830 s = self.pset; 831 F = s.list; 832 G = reducer.list; 833 t = System.currentTimeMillis(); 834 N = ReductionSeq().normalform(G,F); 835 t = System.currentTimeMillis() - t; 836 print "sequential NF executed in %s ms" % t; 837 return Ideal(self.ring,"",N);
838
839 - def lift(self,p):
840 '''Represent p as element of this ideal. 841 ''' 842 G = self.pset.list; 843 z = self.ring.ring.getZERO(); 844 R = [ z for x in G]; 845 if isinstance(p,RingElem): 846 p = p.elem; 847 if self.ring.ring.coFac.isField(): 848 n = ReductionSeq().normalform(R,G,p); 849 else: 850 n = PseudoReductionSeq().normalform(R,G,p); 851 if not n.isZERO(): 852 raise ValueError, "p ist not a member of the ideal" 853 return [ RingElem(f) for f in R ];
854
855 - def interreduced_basis(self):
856 '''Compute a interreduced ideal basis of this. 857 858 Compatibility method for Sage/Singular. 859 ''' 860 F = self.pset.list; 861 if self.ring.ring.coFac.isField(): 862 N = ReductionSeq().irreducibleSet(F); 863 else: 864 N = PseudoReductionSeq().irreducibleSet(F); 865 #N = GroebnerBaseSeq().minimalGB(F); 866 return [ RingElem(n) for n in N ];
867
868 - def intersectRing(self,ring):
869 '''Compute the intersection of this and the given polynomial ring. 870 ''' 871 s = jas.application.Ideal(self.pset); 872 N = s.intersect(ring.ring); 873 return Ideal(ring,"",N.getList());
874
875 - def intersect(self,id2):
876 '''Compute the intersection of this and the given ideal id2. 877 ''' 878 s1 = jas.application.Ideal(self.pset); 879 s2 = jas.application.Ideal(id2.pset); 880 N = s1.intersect(s2); 881 return Ideal(self.ring,"",N.getList());
882
883 - def eliminateRing(self,ring):
884 '''Compute the elimination ideal of this and the given polynomial ring. 885 ''' 886 s = jas.application.Ideal(self.pset); 887 N = s.eliminate(ring.ring); 888 r = Ring( ring=N.getRing() ); 889 return Ideal(r,"",N.getList());
890
891 - def sat(self,id2):
892 '''Compute the saturation of this with respect to given ideal id2. 893 ''' 894 s1 = jas.application.Ideal(self.pset); 895 s2 = jas.application.Ideal(id2.pset); 896 #Q = s1.infiniteQuotient(s2); 897 Q = s1.infiniteQuotientRab(s2); 898 return Ideal(self.ring,"",Q.getList());
899
900 - def sum(self,other):
901 '''Compute the sum of this and the ideal. 902 ''' 903 s = jas.application.Ideal(self.pset); 904 t = jas.application.Ideal(other.pset); 905 N = s.sum( t ); 906 return Ideal(self.ring,"",N.getList());
907
908 - def univariates(self):
909 '''Compute the univariate polynomials in each variable of this ideal. 910 ''' 911 s = jas.application.Ideal(self.pset); 912 L = s.constructUnivariate(); 913 N = [ RingElem(e) for e in L ]; 914 return N;
915
916 - def inverse(self,p):
917 '''Compute the inverse polynomial modulo this ideal, if it exists. 918 ''' 919 s = jas.application.Ideal(self.pset); 920 if isinstance(p,RingElem): 921 p = p.elem; 922 i = s.inverse(p); 923 return RingElem(i);
924 925
926 - def optimize(self):
927 '''Optimize the term order on the variables. 928 ''' 929 p = self.pset; 930 o = TermOrderOptimization.optimizeTermOrder(p); 931 r = Ring("",o.ring); 932 return Ideal(r,"",o.list);
933
934 - def realRoots(self):
935 '''Compute real roots of 0-dim ideal. 936 ''' 937 I = jas.application.Ideal(self.pset); 938 self.roots = jas.application.PolyUtilApp.realAlgebraicRoots(I); 939 for R in self.roots: 940 R.doDecimalApproximation(); 941 return self.roots;
942
943 - def realRootsPrint(self):
944 '''Print decimal approximation of real roots of 0-dim ideal. 945 ''' 946 if self.roots == None: 947 I = jas.application.Ideal(self.pset); 948 self.roots = jas.application.PolyUtilApp.realAlgebraicRoots(I); 949 for R in self.roots: 950 R.doDecimalApproximation(); 951 for Ir in self.roots: 952 for Dr in Ir.decimalApproximation(): 953 print str(Dr); 954 print;
955
956 - def radicalDecomp(self):
957 '''Compute radical decomposition of this ideal. 958 ''' 959 I = jas.application.Ideal(self.pset); 960 self.radical = I.radicalDecomposition(); 961 return self.radical;
962
963 - def decomposition(self):
964 '''Compute irreducible decomposition of this ideal. 965 ''' 966 I = jas.application.Ideal(self.pset); 967 self.irrdec = I.decomposition(); 968 return self.irrdec;
969
970 - def complexRoots(self):
971 '''Compute complex roots of 0-dim ideal. 972 ''' 973 I = jas.application.Ideal(self.pset); 974 self.croots = jas.application.PolyUtilApp.complexAlgebraicRoots(I); 975 for R in self.croots: 976 R.doDecimalApproximation(); 977 return self.croots;
978
979 - def complexRootsPrint(self):
980 '''Print decimal approximation of complex roots of 0-dim ideal. 981 ''' 982 if self.croots == None: 983 I = jas.application.Ideal(self.pset); 984 self.croots = jas.application.PolyUtilApp.realAlgebraicRoots(I); 985 for R in self.croots: 986 R.doDecimalApproximation(); 987 for Ic in self.croots: 988 for Dc in Ic.decimalApproximation(): 989 print str(Dc); 990 print;
991
992 - def primeDecomp(self):
993 '''Compute prime decomposition of this ideal. 994 ''' 995 I = jas.application.Ideal(self.pset); 996 self.prime = I.primeDecomposition(); 997 return self.prime;
998
999 - def primaryDecomp(self):
1000 '''Compute primary decomposition of this ideal. 1001 ''' 1002 I = jas.application.Ideal(self.pset); 1003 ## if self.prime == None: 1004 ## self.prime = I.primeDecomposition(); 1005 self.primary = I.primaryDecomposition(); 1006 return self.primary;
1007
1008 - def toInteger(self):
1009 '''Convert rational coefficients to integer coefficients. 1010 ''' 1011 p = self.pset; 1012 l = p.list; 1013 r = p.ring; 1014 ri = GenPolynomialRing( BigInteger(), r.nvar, r.tord, r.vars ); 1015 pi = PolyUtil.integerFromRationalCoefficients(ri,l); 1016 r = Ring("",ri); 1017 return Ideal(r,"",pi);
1018
1019 - def toModular(self,mf):
1020 '''Convert integer coefficients to modular coefficients. 1021 ''' 1022 p = self.pset; 1023 l = p.list; 1024 r = p.ring; 1025 if isinstance(mf,RingElem): 1026 mf = mf.ring; 1027 rm = GenPolynomialRing( mf, r.nvar, r.tord, r.vars ); 1028 pm = PolyUtil.fromIntegerCoefficients(rm,l); 1029 r = Ring("",rm); 1030 return Ideal(r,"",pm);
1031
1032 - def CS(self):
1033 '''Compute a Characteristic Set. 1034 ''' 1035 s = self.pset; 1036 cofac = s.ring.coFac; 1037 F = s.list; 1038 t = System.currentTimeMillis(); 1039 if cofac.isField(): 1040 G = CharacteristicSetWu().characteristicSet(F); 1041 else: 1042 print "CS not implemented for coefficients %s" % cofac.toScriptFactory(); 1043 G = None; 1044 t = System.currentTimeMillis() - t; 1045 print "sequential CS executed in %s ms" % t; 1046 return Ideal(self.ring,"",G);
1047
1048 - def isCS(self):
1049 '''Test for Characteristic Set. 1050 ''' 1051 s = self.pset; 1052 cofac = s.ring.coFac; 1053 F = s.list.clone(); 1054 Collections.reverse(F); # todo 1055 t = System.currentTimeMillis(); 1056 if cofac.isField(): 1057 b = CharacteristicSetWu().isCharacteristicSet(F); 1058 else: 1059 print "isCS not implemented for coefficients %s" % cofac.toScriptFactory(); 1060 b = False; 1061 t = System.currentTimeMillis() - t; 1062 return b;
1063
1064 - def csReduction(self,p):
1065 '''Compute a normal form of p with respect to this characteristic set. 1066 ''' 1067 s = self.pset; 1068 F = s.list.clone(); 1069 Collections.reverse(F); # todo 1070 if isinstance(p,RingElem): 1071 p = p.elem; 1072 t = System.currentTimeMillis(); 1073 n = CharacteristicSetWu().characteristicSetReduction(F,p); 1074 t = System.currentTimeMillis() - t; 1075 #print "sequential char set reduction executed in %s ms" % t; 1076 return RingElem(n);
1077
1078 - def syzygy(self):
1079 '''Syzygy of generating polynomials. 1080 ''' 1081 p = self.pset; 1082 l = p.list; 1083 t = System.currentTimeMillis(); 1084 s = SyzygySeq(p.ring.coFac).zeroRelations( l ); 1085 t = System.currentTimeMillis() - t; 1086 print "executed syzygy in %s ms" % t; 1087 m = Module("",p.ring); #cols=s[0].size() 1088 return SubModule(m,"",s);
1089
1090 - def isSyzygy(self,m):
1091 '''Test if this is a syzygy of the module in m. 1092 ''' 1093 p = self.pset; 1094 g = p.list; 1095 l = m.list; 1096 t = System.currentTimeMillis(); 1097 z = SyzygySeq(p.ring.coFac).isZeroRelation( l, g ); 1098 t = System.currentTimeMillis() - t; 1099 print "executed isSyzygy in %s ms" % t; 1100 return z;
1101 1102
1103 -class ParamIdeal:
1104 '''Represents a JAS polynomial ideal with polynomial coefficients. 1105 1106 Methods to compute comprehensive Groebner bases. 1107 ''' 1108
1109 - def __init__(self,ring,polystr="",list=None,gbsys=None):
1110 '''Parametric ideal constructor. 1111 ''' 1112 self.ring = ring; 1113 if list == None and polystr != None: 1114 sr = StringReader( polystr ); 1115 tok = GenPolynomialTokenizer(ring.ring,sr); 1116 self.list = tok.nextPolynomialList(); 1117 else: 1118 self.list = pylist2arraylist(list,rec=1); 1119 self.gbsys = gbsys; 1120 self.pset = OrderedPolynomialList(ring.ring,self.list);
1121
1122 - def __str__(self):
1123 '''Create a string representation. 1124 ''' 1125 if self.gbsys == None: 1126 return self.pset.toScript(); 1127 else: 1128 # return self.gbsys.toString(); # toScript() not available 1129 return self.pset.toScript() + "\n" + self.gbsys.toScript();
1130
1131 - def optimizeCoeff(self):
1132 '''Optimize the term order on the variables of the coefficients. 1133 ''' 1134 p = self.pset; 1135 o = TermOrderOptimization.optimizeTermOrderOnCoefficients(p); 1136 r = Ring("",o.ring); 1137 return ParamIdeal(r,"",o.list);
1138
1139 - def optimizeCoeffQuot(self):
1140 '''Optimize the term order on the variables of the quotient coefficients. 1141 ''' 1142 p = self.pset; 1143 l = p.list; 1144 r = p.ring; 1145 q = r.coFac; 1146 c = q.ring; 1147 rc = GenPolynomialRing( c, r.nvar, r.tord, r.vars ); 1148 #print "rc = ", rc; 1149 lp = PolyUfdUtil.integralFromQuotientCoefficients(rc,l); 1150 #print "lp = ", lp; 1151 pp = PolynomialList(rc,lp); 1152 #print "pp = ", pp; 1153 oq = TermOrderOptimization.optimizeTermOrderOnCoefficients(pp); 1154 oor = oq.ring; 1155 qo = oor.coFac; 1156 cq = QuotientRing( qo ); 1157 rq = GenPolynomialRing( cq, r.nvar, r.tord, r.vars ); 1158 #print "rq = ", rq; 1159 o = PolyUfdUtil.quotientFromIntegralCoefficients(rq,oq.list); 1160 r = Ring("",rq); 1161 return ParamIdeal(r,"",o);
1162
1163 - def toIntegralCoeff(self):
1164 '''Convert rational function coefficients to integral function coefficients. 1165 ''' 1166 p = self.pset; 1167 l = p.list; 1168 r = p.ring; 1169 q = r.coFac; 1170 c = q.ring; 1171 rc = GenPolynomialRing( c, r.nvar, r.tord, r.vars ); 1172 #print "rc = ", rc; 1173 lp = PolyUfdUtil.integralFromQuotientCoefficients(rc,l); 1174 #print "lp = ", lp; 1175 r = Ring("",rc); 1176 return ParamIdeal(r,"",lp);
1177
1178 - def toModularCoeff(self,mf):
1179 '''Convert integral function coefficients to modular function coefficients. 1180 ''' 1181 p = self.pset; 1182 l = p.list; 1183 r = p.ring; 1184 c = r.coFac; 1185 #print "c = ", c; 1186 if isinstance(mf,RingElem): 1187 mf = mf.ring; 1188 cm = GenPolynomialRing( mf, c.nvar, c.tord, c.vars ); 1189 #print "cm = ", cm; 1190 rm = GenPolynomialRing( cm, r.nvar, r.tord, r.vars ); 1191 #print "rm = ", rm; 1192 pm = PolyUfdUtil.fromIntegerCoefficients(rm,l); 1193 r = Ring("",rm); 1194 return ParamIdeal(r,"",pm);
1195
1196 - def toQuotientCoeff(self):
1197 '''Convert integral function coefficients to rational function coefficients. 1198 ''' 1199 p = self.pset; 1200 l = p.list; 1201 r = p.ring; 1202 c = r.coFac; 1203 #print "c = ", c; 1204 q = QuotientRing(c); 1205 #print "q = ", q; 1206 qm = GenPolynomialRing( q, r.nvar, r.tord, r.vars ); 1207 #print "qm = ", qm; 1208 pm = PolyUfdUtil.quotientFromIntegralCoefficients(qm,l); 1209 r = Ring("",qm); 1210 return ParamIdeal(r,"",pm);
1211
1212 - def GB(self):
1213 '''Compute a Groebner base. 1214 ''' 1215 I = Ideal(self.ring,"",self.pset.list); 1216 g = I.GB(); 1217 return ParamIdeal(g.ring,"",g.pset.list);
1218
1219 - def isGB(self):
1220 '''Test if this is a Groebner base. 1221 ''' 1222 I = Ideal(self.ring,"",self.pset.list); 1223 return I.isGB();
1224
1225 - def CGB(self):
1226 '''Compute a comprehensive Groebner base. 1227 ''' 1228 s = self.pset; 1229 F = s.list; 1230 t = System.currentTimeMillis(); 1231 if self.gbsys == None: 1232 self.gbsys = ComprehensiveGroebnerBaseSeq(self.ring.ring.coFac).GBsys(F); 1233 G = self.gbsys.getCGB(); 1234 t = System.currentTimeMillis() - t; 1235 print "sequential comprehensive executed in %s ms" % t; 1236 return ParamIdeal(self.ring,"",G,self.gbsys);
1237
1238 - def CGBsystem(self):
1239 '''Compute a comprehensive Groebner system. 1240 ''' 1241 s = self.pset; 1242 F = s.list; 1243 t = System.currentTimeMillis(); 1244 S = ComprehensiveGroebnerBaseSeq(self.ring.ring.coFac).GBsys(F); 1245 t = System.currentTimeMillis() - t; 1246 print "sequential comprehensive system executed in %s ms" % t; 1247 return ParamIdeal(self.ring,None,F,S);
1248
1249 - def isCGB(self):
1250 '''Test if this is a comprehensive Groebner base. 1251 ''' 1252 s = self.pset; 1253 F = s.list; 1254 t = System.currentTimeMillis(); 1255 b = ComprehensiveGroebnerBaseSeq(self.ring.ring.coFac).isGB(F); 1256 t = System.currentTimeMillis() - t; 1257 print "isCGB executed in %s ms" % t; 1258 return b;
1259
1260 - def isCGBsystem(self):
1261 '''Test if this is a comprehensive Groebner system. 1262 ''' 1263 s = self.pset; 1264 S = self.gbsys; 1265 t = System.currentTimeMillis(); 1266 b = ComprehensiveGroebnerBaseSeq(self.ring.ring.coFac).isGBsys(S); 1267 t = System.currentTimeMillis() - t; 1268 print "isCGBsystem executed in %s ms" % t; 1269 return b;
1270
1271 - def regularRepresentation(self):
1272 '''Convert Groebner system to a representation with regular ring coefficents. 1273 ''' 1274 if self.gbsys == None: 1275 return None; 1276 G = PolyUtilApp.toProductRes(self.gbsys.list); 1277 ring = Ring(None,G[0].ring); 1278 return ParamIdeal(ring,None,G);
1279
1280 - def regularRepresentationBC(self):
1281 '''Convert Groebner system to a boolean closed representation with regular ring coefficents. 1282 ''' 1283 if self.gbsys == None: 1284 return None; 1285 G = PolyUtilApp.toProductRes(self.gbsys.list); 1286 ring = Ring(None,G[0].ring); 1287 res = RReductionSeq(); 1288 G = res.booleanClosure(G); 1289 return ParamIdeal(ring,None,G);
1290
1291 - def regularGB(self):
1292 '''Compute a Groebner base over a regular ring. 1293 ''' 1294 s = self.pset; 1295 F = s.list; 1296 t = System.currentTimeMillis(); 1297 G = RGroebnerBasePseudoSeq(self.ring.ring.coFac).GB(F); 1298 t = System.currentTimeMillis() - t; 1299 print "sequential regular GB executed in %s ms" % t; 1300 return ParamIdeal(self.ring,None,G);
1301
1302 - def isRegularGB(self):
1303 '''Test if this is Groebner base over a regular ring. 1304 ''' 1305 s = self.pset; 1306 F = s.list; 1307 t = System.currentTimeMillis(); 1308 b = RGroebnerBasePseudoSeq(self.ring.ring.coFac).isGB(F); 1309 t = System.currentTimeMillis() - t; 1310 print "isRegularGB executed in %s ms" % t; 1311 return b;
1312
1313 - def stringSlice(self):
1314 '''Get each component (slice) of regular ring coefficients separate. 1315 ''' 1316 s = self.pset; 1317 b = PolyUtilApp.productToString(s); 1318 return b;
1319 1320
1321 -class SolvableRing(Ring):
1322 '''Represents a JAS solvable polynomial ring: GenSolvablePolynomialRing. 1323 1324 Has a method to create solvable ideals. 1325 ''' 1326
1327 - def __init__(self,ringstr="",ring=None):
1328 '''Solvable polynomial ring constructor. 1329 ''' 1330 if ring == None: 1331 sr = StringReader( ringstr ); 1332 tok = RingFactoryTokenizer(sr); 1333 pfac = tok.nextSolvablePolynomialRing(); 1334 #tok = GenPolynomialTokenizer(pfac,sr); 1335 #plist = tok.nextSolvablePolynomialList(); 1336 #self.pset = PolynomialList(pfac,plist); 1337 self.ring = pfac; 1338 else: 1339 if isinstance(ring,Ring): 1340 self.ring = ring.ring; 1341 else: 1342 self.ring = ring; 1343 if not self.ring.isAssociative(): 1344 print "warning: ring is not associative"; 1345 else: 1346 print "ring is associative"; 1347 Ring.__init__(self,ring=self.ring)
1348
1349 - def __str__(self):
1350 '''Create a string representation. 1351 ''' 1352 return str(self.ring.toScript());
1353
1354 - def ideal(self,ringstr="",list=None):
1355 '''Create a solvable ideal. 1356 ''' 1357 return SolvableIdeal(self,ringstr,list);
1358
1359 - def one(self):
1360 '''Get the one of the solvable polynomial ring. 1361 ''' 1362 return RingElem( self.ring.getONE() );
1363
1364 - def zero(self):
1365 '''Get the zero of the solvable polynomial ring. 1366 ''' 1367 return RingElem( self.ring.getZERO() );
1368
1369 - def element(self,poly):
1370 '''Create an element from a string or object. 1371 ''' 1372 if not isinstance(poly,str): 1373 try: 1374 if self.ring == poly.ring: 1375 return RingElem(poly); 1376 except Exception, e: 1377 pass 1378 poly = str(poly); 1379 I = SolvableIdeal(self, "( " + poly + " )"); 1380 list = I.pset.list; 1381 if len(list) > 0: 1382 return RingElem( list[0] );
1383 1384
1385 -class SolvableIdeal:
1386 '''Represents a JAS solvable polynomial ideal. 1387 1388 Methods for left, right two-sided Groebner basees and others. 1389 ''' 1390
1391 - def __init__(self,ring,ringstr="",list=None):
1392 '''Constructor for an ideal in a solvable polynomial ring. 1393 ''' 1394 self.ring = ring; 1395 if list == None: 1396 sr = StringReader( ringstr ); 1397 tok = GenPolynomialTokenizer(ring.ring,sr); 1398 self.list = tok.nextSolvablePolynomialList(); 1399 else: 1400 self.list = pylist2arraylist(list,rec=1); 1401 self.pset = OrderedPolynomialList(ring.ring,self.list);
1402 #self.pset = PolynomialList(ring.ring,self.list); 1403
1404 - def __str__(self):
1405 '''Create a string representation. 1406 ''' 1407 return str(self.pset.toScript());
1408
1409 - def __cmp__(self,other):
1410 '''Compare two ideals. 1411 ''' 1412 t = False; 1413 if not isinstance(other,SolvableIdeal): 1414 return t; 1415 t = self.pset.compareTo(other.pset); 1416 return t;
1417
1418 - def __eq__(self,other):
1419 '''Test if two ideals are equal. 1420 ''' 1421 if not isinstance(other, SolvableIdeal): 1422 return False; 1423 s = self.pset; 1424 t = other.pset; 1425 return s.equals(t)
1426
1427 - def leftGB(self):
1428 '''Compute a left Groebner base. 1429 ''' 1430 cofac = self.ring.ring.coFac; 1431 F = self.pset.list; 1432 kind = ""; 1433 t = System.currentTimeMillis(); 1434 if isinstance(cofac,GenPolynomialRing): #and cofac.isCommutative(): 1435 G = SolvableGroebnerBasePseudoRecSeq(cofac).leftGB(F); 1436 kind = "pseudorec" 1437 else: 1438 if cofac.isField() or not cofac.isCommutative(): 1439 G = SolvableGroebnerBaseSeq().leftGB(F); 1440 kind = "field|nocom" 1441 else: 1442 G = SolvableGroebnerBasePseudoSeq(cofac).leftGB(F); 1443 kind = "pseudo" 1444 t = System.currentTimeMillis() - t; 1445 print "sequential(%s) left GB executed in %s ms" % (kind, t); 1446 return SolvableIdeal(self.ring,"",G);
1447
1448 - def isLeftGB(self):
1449 '''Test if this is a left Groebner base. 1450 ''' 1451 cofac = self.ring.ring.coFac; 1452 F = self.pset.list; 1453 kind = ""; 1454 t = System.currentTimeMillis(); 1455 if isinstance(cofac,GenPolynomialRing): #and cofac.isCommutative(): 1456 b = SolvableGroebnerBasePseudoRecSeq(cofac).isLeftGB(F); 1457 kind = "pseudorec" 1458 else: 1459 if cofac.isField() or not cofac.isCommutative(): 1460 b = SolvableGroebnerBaseSeq().isLeftGB(F); 1461 kind = "field|nocom" 1462 else: 1463 b = SolvableGroebnerBasePseudoSeq(cofac).isLeftGB(F); 1464 kind = "pseudo" 1465 t = System.currentTimeMillis() - t; 1466 print "sequential(%s) isLeftGB executed in %s ms" % (kind, t); 1467 return b;
1468
1469 - def twosidedGB(self):
1470 '''Compute a two-sided Groebner base. 1471 ''' 1472 cofac = self.ring.ring.coFac; 1473 F = self.pset.list; 1474 kind = ""; 1475 t = System.currentTimeMillis(); 1476 if isinstance(cofac,GenPolynomialRing): # and cofac.isCommutative(): 1477 G = SolvableGroebnerBasePseudoRecSeq(cofac).twosidedGB(F); 1478 kind = "pseudorec" 1479 else: 1480 if cofac.isField() or not cofac.isCommutative(): 1481 G = SolvableGroebnerBaseSeq().twosidedGB(F); 1482 kind = "field|nocom" 1483 else: 1484 G = SolvableGroebnerBasePseudoSeq(cofac).twosidedGB(F); 1485 kind = "pseudo" 1486 t = System.currentTimeMillis() - t; 1487 print "sequential(%s) twosided GB executed in %s ms" % (kind, t); 1488 return SolvableIdeal(self.ring,"",G);
1489
1490 - def isTwosidedGB(self):
1491 '''Test if this is a two-sided Groebner base. 1492 ''' 1493 cofac = self.ring.ring.coFac; 1494 F = self.pset.list; 1495 kind = ""; 1496 t = System.currentTimeMillis(); 1497 if isinstance(cofac,GenPolynomialRing): # and cofac.isCommutative(): 1498 b = SolvableGroebnerBasePseudoRecSeq(cofac).isTwosidedGB(F); 1499 kind = "pseudorec" 1500 else: 1501 if cofac.isField() or not cofac.isCommutative(): 1502 b = SolvableGroebnerBaseSeq().isTwosidedGB(F); 1503 kind = "field|nocom" 1504 else: 1505 b = SolvableGroebnerBasePseudoSeq(cofac).isTwosidedGB(F); 1506 kind = "pseudo" 1507 t = System.currentTimeMillis() - t; 1508 print "sequential(%s) isTwosidedGB executed in %s ms" % (kind, t); 1509 return b;
1510
1511 - def rightGB(self):
1512 '''Compute a right Groebner base. 1513 ''' 1514 cofac = self.ring.ring.coFac; 1515 F = self.pset.list; 1516 kind = ""; 1517 t = System.currentTimeMillis(); 1518 if isinstance(cofac,GenPolynomialRing): # and cofac.isCommutative(): 1519 G = SolvableGroebnerBasePseudoRecSeq(cofac).rightGB(F); 1520 kind = "pseudorec" 1521 else: 1522 if cofac.isField() or not cofac.isCommutative(): 1523 G = SolvableGroebnerBaseSeq().rightGB(F); 1524 kind = "field|nocom" 1525 else: 1526 G = SolvableGroebnerBasePseudoSeq(cofac).rightGB(F); 1527 kind = "pseudo" 1528 t = System.currentTimeMillis() - t; 1529 print "sequential(%s) right GB executed in %s ms" % (kind, t); 1530 return SolvableIdeal(self.ring,"",G);
1531
1532 - def isRightGB(self):
1533 '''Test if this is a right Groebner base. 1534 ''' 1535 cofac = self.ring.ring.coFac; 1536 F = self.pset.list; 1537 kind = ""; 1538 t = System.currentTimeMillis(); 1539 if isinstance(cofac,GenPolynomialRing): # and cofac.isCommutative(): 1540 b = SolvableGroebnerBasePseudoRecSeq(cofac).isRightGB(F); 1541 kind = "pseudorec" 1542 else: 1543 if cofac.isField() or not cofac.isCommutative(): 1544 b = SolvableGroebnerBaseSeq().isRightGB(F); 1545 kind = "field|nocom" 1546 else: 1547 b = SolvableGroebnerBasePseudoSeq(cofac).isRightGB(F); 1548 kind = "pseudo" 1549 t = System.currentTimeMillis() - t; 1550 print "sequential(%s) isRightGB executed in %s ms" % (kind, t); 1551 return b;
1552
1553 - def intersectRing(self,ring):
1554 '''Compute the intersection of this and the polynomial ring. 1555 ''' 1556 s = jas.application.SolvableIdeal(self.pset); 1557 N = s.intersect(ring.ring); 1558 return SolvableIdeal(self.ring,"",N.getList());
1559
1560 - def intersect(self,other):
1561 '''Compute the intersection of this and the other ideal. 1562 ''' 1563 s = jas.application.SolvableIdeal(self.pset); 1564 t = jas.application.SolvableIdeal(other.pset); 1565 N = s.intersect( t ); 1566 return SolvableIdeal(self.ring,"",N.getList());
1567
1568 - def sum(self,other):
1569 '''Compute the sum of this and the other ideal. 1570 ''' 1571 s = jas.application.SolvableIdeal(self.pset); 1572 t = jas.application.SolvableIdeal(other.pset); 1573 N = s.sum( t ); 1574 return SolvableIdeal(self.ring,"",N.getList());
1575
1576 - def univariates(self):
1577 '''Compute the univariate polynomials in each variable of this twosided ideal. 1578 ''' 1579 s = jas.application.SolvableIdeal(self.pset); 1580 L = s.constructUnivariate(); 1581 N = [ RingElem(e) for e in L ]; 1582 return N;
1583
1584 - def toQuotientCoefficients(self):
1585 '''Convert to polynomials with SolvableQuotient coefficients. 1586 ''' 1587 if isinstance(self.pset.ring.coFac,SolvableResidueRing): 1588 cf = self.pset.ring.coFac.ring; 1589 else: 1590 if isinstance(self.pset.ring.coFac,GenSolvablePolynomialRing): 1591 cf = self.pset.ring.coFac; 1592 #else: if @pset.ring.coFac.getClass().getSimpleName() == "GenPolynomialRing" 1593 # cf = @pset.ring.coFac; 1594 # puts "cf = " + cf.toScript(); 1595 else: 1596 return self; 1597 rrel = self.pset.ring.table.relationList(); 1598 rrel.addAll(self.pset.ring.polCoeff.coeffTable.relationList()); 1599 #print "rrel = " + str(rrel); 1600 qf = SolvableQuotientRing(cf); 1601 qr = QuotSolvablePolynomialRing(qf,self.pset.ring); 1602 #print "qr = " + str(qr); 1603 qrel = [ RingElem(qr.fromPolyCoefficients(r)) for r in rrel ]; 1604 qring = SolvPolyRing(qf,self.ring.ring.getVars(),self.ring.ring.tord,qrel); 1605 #print "qring = " + str(qring); 1606 qlist = [ qr.fromPolyCoefficients(self.ring.ring.toPolyCoefficients(r)) for r in self.list ]; 1607 qlist = [ RingElem(r) for r in qlist ]; 1608 return SolvableIdeal(qring,"",qlist);
1609
1610 - def inverse(self,p):
1611 '''Compute the inverse polynomial modulo this ideal, if it exists. 1612 ''' 1613 s = jas.application.SolvableIdeal(self.pset); 1614 if isinstance(p,RingElem): 1615 p = p.elem; 1616 i = s.inverse(p); 1617 return RingElem(i);
1618
1619 - def leftReduction(self,p):
1620 '''Compute a left normal form of p with respect to this ideal. 1621 ''' 1622 s = self.pset; 1623 G = s.list; 1624 if isinstance(p,RingElem): 1625 p = p.elem; 1626 n = SolvableReductionSeq().leftNormalform(G,p); 1627 return RingElem(n);
1628
1629 - def rightReduction(self,p):
1630 '''Compute a right normal form of p with respect to this ideal. 1631 ''' 1632 s = self.pset; 1633 G = s.list; 1634 if isinstance(p,RingElem): 1635 p = p.elem; 1636 n = SolvableReductionSeq().rightNormalform(G,p); 1637 return RingElem(n);
1638
1639 - def parLeftGB(self,th):
1640 '''Compute a left Groebner base in parallel. 1641 ''' 1642 s = self.pset; 1643 F = s.list; 1644 bbpar = SolvableGroebnerBaseParallel(th); 1645 t = System.currentTimeMillis(); 1646 G = bbpar.leftGB(F); 1647 t = System.currentTimeMillis() - t; 1648 bbpar.terminate(); 1649 print "parallel %s leftGB executed in %s ms" % (th, t); 1650 return SolvableIdeal(self.ring,"",G);
1651
1652 - def parTwosidedGB(self,th):
1653 '''Compute a two-sided Groebner base in parallel. 1654 ''' 1655 s = self.pset; 1656 F = s.list; 1657 bbpar = SolvableGroebnerBaseParallel(th); 1658 t = System.currentTimeMillis(); 1659 G = bbpar.twosidedGB(F); 1660 t = System.currentTimeMillis() - t; 1661 bbpar.terminate(); 1662 print "parallel %s twosidedGB executed in %s ms" % (th, t); 1663 return SolvableIdeal(self.ring,"",G);
1664
1665 - def leftSyzygy(self):
1666 '''left Syzygy of generating polynomials. 1667 ''' 1668 p = self.pset; 1669 l = p.list; 1670 t = System.currentTimeMillis(); 1671 s = SolvableSyzygySeq(p.ring.coFac).leftZeroRelationsArbitrary( l ); 1672 t = System.currentTimeMillis() - t; 1673 print "executed left syzygy in %s ms" % t; 1674 m = SolvableModule("",p.ring); 1675 return SolvableSubModule(m,"",s);
1676
1677 - def isLeftSyzygy(self,m):
1678 '''Test if this is a left syzygy of the module in m. 1679 ''' 1680 p = self.pset; 1681 g = p.list; 1682 l = m.list; 1683 t = System.currentTimeMillis(); 1684 z = SolvableSyzygySeq(p.ring.coFac).isLeftZeroRelation( l, g ); 1685 t = System.currentTimeMillis() - t; 1686 print "executed isLeftSyzygy in %s ms" % t; 1687 return z;
1688
1689 - def rightSyzygy(self):
1690 '''right Syzygy of generating polynomials. 1691 ''' 1692 p = self.pset; 1693 l = p.list; 1694 t = System.currentTimeMillis(); 1695 s = SolvableSyzygySeq(p.ring.coFac).rightZeroRelationsArbitrary( l ); 1696 t = System.currentTimeMillis() - t; 1697 print "executed right syzygy in %s ms" % t; 1698 m = SolvableModule("",p.ring); 1699 return SolvableSubModule(m,"",s);
1700
1701 - def isRightSyzygy(self,m):
1702 '''Test if this is a right syzygy of the module in m. 1703 ''' 1704 p = self.pset; 1705 g = p.list; 1706 l = m.list; 1707 t = System.currentTimeMillis(); 1708 z = SolvableSyzygySeq(p.ring.coFac).isRightZeroRelation( l, g ); 1709 t = System.currentTimeMillis() - t; 1710 print "executed isRightSyzygy in %s ms" % t; 1711 return z;
1712 1713
1714 -class Module:
1715 '''Represents a JAS module over a polynomial ring. 1716 1717 Method to create sub-modules. 1718 ''' 1719
1720 - def __init__(self,modstr="",ring=None,cols=0):
1721 '''Module constructor. 1722 ''' 1723 if ring == None: 1724 sr = StringReader( modstr ); 1725 tok = RingFactoryTokenizer(sr); 1726 pfac = tok.nextPolynomialRing(); 1727 #tok = GenPolynomialTokenizer(pfac,sr); 1728 #mlist = tok.nextSubModuleList(); 1729 #self.mset = ModuleList(pfac,mlist); 1730 #if self.mset.cols >= 0: 1731 # self.cols = self.mset.cols; 1732 #else: 1733 self.ring = pfac 1734 else: 1735 if isinstance(ring,Ring): 1736 self.ring = ring.ring; 1737 else: 1738 self.ring = ring; 1739 self.mset = ModuleList(self.ring,None); # because of toScript 1740 if cols < 0: 1741 cols = 0; 1742 self.cols = cols;
1743
1744 - def __str__(self):
1745 '''Create a string representation. 1746 ''' 1747 return str(self.mset.toScript());
1748
1749 - def submodul(self,modstr="",list=None):
1750 '''Create a sub-module. 1751 ''' 1752 return SubModule(self,modstr,list);
1753
1754 - def element(self,poly):
1755 '''Create an element from a string or object. 1756 ''' 1757 if not isinstance(poly,str): 1758 try: 1759 if self.ring == poly.ring: 1760 return RingElem(poly); 1761 except Exception, e: 1762 pass 1763 poly = str(poly); 1764 I = SubModule(self, "( " + poly + " )"); 1765 list = I.mset.list; 1766 if len(list) > 0: 1767 return RingElem( list[0] );
1768
1769 - def gens(self):
1770 '''Get the generators of this module. 1771 ''' 1772 gm = GenVectorModul(self.ring,self.cols); 1773 L = gm.generators(); 1774 #for g in L: 1775 # print "g = ", str(g); 1776 N = [ RingElem(e) for e in L ]; # want use val here, but can not 1777 return N;
1778
1779 - def inject_variables(self):
1780 '''Inject generators as variables into the main global namespace 1781 ''' 1782 inject_generators(self.gens());
1783 1784
1785 -class SubModule:
1786 '''Represents a JAS sub-module over a polynomial ring. 1787 1788 Methods to compute Groebner bases. 1789 ''' 1790
1791 - def __init__(self,module,modstr="",list=None):
1792 '''Constructor for a sub-module. 1793 ''' 1794 self.module = module; 1795 if list == None: 1796 sr = StringReader( modstr ); 1797 tok = GenPolynomialTokenizer(module.ring,sr); 1798 self.list = tok.nextSubModuleList(); 1799 else: 1800 if isinstance(list,PyList) or isinstance(list,PyTuple): 1801 if len(list) != 0: 1802 if isinstance(list[0],RingElem): 1803 list = [ re.elem for re in list ]; 1804 self.list = pylist2arraylist(list,self.module.ring,rec=2); 1805 else: 1806 self.list = list; 1807 #print "list = ", str(list); 1808 #e = self.list[0]; 1809 #print "e = ", e; 1810 self.mset = OrderedModuleList(module.ring,self.list); 1811 self.cols = self.mset.cols; 1812 self.rows = self.mset.rows; 1813 #print "list = %s" % self.list; 1814 #print "cols = %s" % self.cols; 1815 #print "mset = %s" % self.mset.toString(); 1816 #print "mset = %s" % self.mset.toScript(); 1817 self.pset = self.mset.getPolynomialList();
1818
1819 - def __str__(self):
1820 '''Create a string representation. 1821 ''' 1822 return str(self.mset.toScript()); # + "\n\n" + str(self.pset);
1823
1824 - def GB(self):
1825 '''Compute a Groebner base. 1826 ''' 1827 t = System.currentTimeMillis(); 1828 #G = ModGroebnerBaseSeq(self.module.ring.coFac).GB(self.mset); 1829 G = GroebnerBaseSeq().GB(self.mset); 1830 t = System.currentTimeMillis() - t; 1831 print "executed module GB in %s ms" % t; 1832 return SubModule(self.module,"",G.list);
1833
1834 - def isGB(self):
1835 '''Test if this is a Groebner base. 1836 ''' 1837 t = System.currentTimeMillis(); 1838 #b = ModGroebnerBaseSeq(self.module.ring.coFac).isGB(self.mset); 1839 b = GroebnerBaseSeq().isGB(self.mset); 1840 t = System.currentTimeMillis() - t; 1841 print "module isGB executed in %s ms" % t; 1842 return b;
1843
1844 - def isSyzygy(self,g):
1845 '''Test if this is a syzygy of the vectors in g. 1846 ''' 1847 l = self.list; 1848 if isinstance(g,Ideal): 1849 s = g.pset.list; 1850 else: 1851 if isinstance(g,SubModule): 1852 s = g.mset; 1853 l = self.mset; 1854 else: 1855 raise ValueError, "unknown type %s" % g.getClass().getName(); 1856 #print "l = %s" % l; 1857 #print "s = %s" % s; 1858 t = System.currentTimeMillis(); 1859 z = SyzygySeq(self.module.ring.coFac).isZeroRelation( l, s ); 1860 t = System.currentTimeMillis() - t; 1861 print "executed isSyzygy in %s ms" % t; 1862 return z;
1863
1864 - def syzygy(self):
1865 '''Compute syzygys of this module. 1866 ''' 1867 l = self.mset; 1868 t = System.currentTimeMillis(); 1869 p = SyzygySeq(self.module.ring.coFac).zeroRelations( l ); 1870 t = System.currentTimeMillis() - t; 1871 print "executed module syzygy in %s ms" % t; 1872 #print "p = " + str(p.ring.toScript()); 1873 m = Module("",p.ring,p.cols); 1874 return SubModule(m,"",p.list);
1875 1876
1877 -class SolvableModule(Module):
1878 '''Represents a JAS module over a solvable polynomial ring. 1879 1880 Method to create solvable sub-modules. 1881 ''' 1882
1883 - def __init__(self,modstr="",ring=None,cols=0):
1884 '''Solvable module constructor. 1885 ''' 1886 if ring == None: 1887 sr = StringReader( modstr ); 1888 tok = RingFactoryTokenizer(sr); 1889 pfac = tok.nextSolvablePolynomialRing(); 1890 #tok = GenPolynomialTokenizer(pfac,sr); 1891 #mlist = tok.nextSolvableSubModuleList(); 1892 #self.mset = PolynomialList(pfac,mlist); 1893 #if self.mset.cols >= 0: 1894 # self.cols = self.mset.cols; 1895 self.ring = pfac; 1896 else: 1897 if isinstance(ring,Ring): 1898 self.ring = ring.ring; 1899 else: 1900 self.ring = ring; 1901 self.mset = ModuleList(self.ring,None); 1902 if cols < 0: 1903 cols = 0; 1904 self.cols = cols;
1905
1906 - def __str__(self):
1907 '''Create a string representation. 1908 ''' 1909 return str(self.mset.toScript());
1910
1911 - def submodul(self,modstr="",list=None):
1912 '''Create a solvable sub-module. 1913 ''' 1914 return SolvableSubModule(self,modstr,list);
1915
1916 - def element(self,poly):
1917 '''Create an element from a string or object. 1918 ''' 1919 if not isinstance(poly,str): 1920 try: 1921 if self.ring == poly.ring: 1922 return RingElem(poly); 1923 except Exception, e: 1924 pass 1925 poly = str(poly); 1926 I = SolvableSubModule(self, "( " + poly + " )"); 1927 list = I.mset.list; 1928 if len(list) > 0: 1929 return RingElem( list[0] );
1930 1931
1932 -class SolvableSubModule:
1933 '''Represents a JAS sub-module over a solvable polynomial ring. 1934 1935 Methods to compute left, right and two-sided Groebner bases. 1936 ''' 1937
1938 - def __init__(self,module,modstr="",list=None):
1939 '''Constructor for sub-module over a solvable polynomial ring. 1940 ''' 1941 self.module = module; 1942 if list == None: 1943 sr = StringReader( modstr ); 1944 tok = GenPolynomialTokenizer(module.ring,sr); 1945 self.list = tok.nextSolvableSubModuleList(); 1946 else: 1947 if isinstance(list,PyList) or isinstance(list,PyTuple): 1948 self.list = pylist2arraylist(list,self.module.ring,rec=2); 1949 else: 1950 self.list = list; 1951 self.mset = OrderedModuleList(module.ring,self.list); 1952 self.cols = self.mset.cols; 1953 self.rows = self.mset.rows;
1954
1955 - def __str__(self):
1956 '''Create a string representation. 1957 ''' 1958 return str(self.mset.toScript()); # + "\n\n" + str(self.pset);
1959
1960 - def leftGB(self):
1961 '''Compute a left Groebner base. 1962 ''' 1963 t = System.currentTimeMillis(); 1964 #G = SolvableGroebnerBaseSeq(self.module.ring.coFac).leftGB(self.mset); 1965 G = SolvableGroebnerBaseSeq().leftGB(self.mset); 1966 t = System.currentTimeMillis() - t; 1967 print "executed left module GB in %s ms" % t; 1968 return SolvableSubModule(self.module,"",G.list);
1969
1970 - def isLeftGB(self):
1971 '''Test if this is a left Groebner base. 1972 ''' 1973 t = System.currentTimeMillis(); 1974 #b = SolvableGroebnerBaseSeq(self.module.ring.coFac).isLeftGB(self.mset); 1975 b = SolvableGroebnerBaseSeq().isLeftGB(self.mset); 1976 t = System.currentTimeMillis() - t; 1977 print "module isLeftGB executed in %s ms" % t; 1978 return b;
1979
1980 - def twosidedGB(self):
1981 '''Compute a two-sided Groebner base. 1982 ''' 1983 t = System.currentTimeMillis(); 1984 #G = SolvableGroebnerBaseSeq(self.module.ring.coFac).twosidedGB(self.mset); 1985 G = SolvableGroebnerBaseSeq().twosidedGB(self.mset); 1986 t = System.currentTimeMillis() - t; 1987 print "executed twosided module GB in %s ms" % t; 1988 return SolvableSubModule(self.module,"",G.list);
1989
1990 - def isTwosidedGB(self):
1991 '''Test if this is a two-sided Groebner base. 1992 ''' 1993 t = System.currentTimeMillis(); 1994 #b = SolvableGroebnerBaseSeq(self.module.ring.coFac).isTwosidedGB(self.mset); 1995 b = SolvableGroebnerBaseSeq().isTwosidedGB(self.mset); 1996 t = System.currentTimeMillis() - t; 1997 print "module isTwosidedGB executed in %s ms" % t; 1998 return b;
1999
2000 - def rightGB(self):
2001 '''Compute a right Groebner base. 2002 ''' 2003 t = System.currentTimeMillis(); 2004 #G = SolvableGroebnerBaseSeq(self.module.ring.coFac).rightGB(self.mset); 2005 G = SolvableGroebnerBaseSeq().rightGB(self.mset); 2006 t = System.currentTimeMillis() - t; 2007 print "executed right module GB in %s ms" % t; 2008 return SolvableSubModule(self.module,"",G.list);
2009
2010 - def isRightGB(self):
2011 '''Test if this is a right Groebner base. 2012 ''' 2013 t = System.currentTimeMillis(); 2014 #b = SolvableGroebnerBaseSeq(self.module.ring.coFac).isRightGB(self.mset); 2015 b = SolvableGroebnerBaseSeq().isRightGB(self.mset); 2016 t = System.currentTimeMillis() - t; 2017 print "module isRightGB executed in %s ms" % t; 2018 return b;
2019
2020 - def isLeftSyzygy(self,g):
2021 '''Test if this is a syzygy of the vectors in g. 2022 ''' 2023 l = self.list; 2024 if isinstance(g,SolvableIdeal): 2025 s = g.pset.list; 2026 else: 2027 if isinstance(g,SolvableSubModule): 2028 s = g.mset; 2029 l = self.mset; 2030 else: 2031 raise ValueError, "unknown type %s" % g.getClass().getName(); 2032 #print "l = %s" % l; 2033 #print "g = %s" % g; 2034 t = System.currentTimeMillis(); 2035 z = SolvableSyzygySeq(self.module.ring.coFac).isLeftZeroRelation( l, s ); 2036 t = System.currentTimeMillis() - t; 2037 print "executed isLeftSyzygy in %s ms" % t; 2038 return z;
2039
2040 - def leftSyzygy(self):
2041 '''Compute left syzygys of this module. 2042 ''' 2043 l = self.mset; 2044 t = System.currentTimeMillis(); 2045 p = SolvableSyzygySeq(self.module.ring.coFac).leftZeroRelationsArbitrary( l ); 2046 t = System.currentTimeMillis() - t; 2047 print "executed left module syzygy in %s ms" % t; 2048 #print "p = " + str(p.ring.toScript()); 2049 m = SolvableModule("",p.ring,p.cols); 2050 return SolvableSubModule(m,"",p.list);
2051
2052 - def isRightSyzygy(self,g):
2053 '''Test if this is a syzygy of the vectors in g. 2054 ''' 2055 l = self.list; 2056 if isinstance(g,SolvableIdeal): 2057 s = g.pset.list; 2058 else: 2059 if isinstance(g,SolvableSubModule): 2060 s = g.mset; 2061 l = self.mset; 2062 else: 2063 raise ValueError, "unknown type %s" % g.getClass().getName(); 2064 #print "l = %s" % l; 2065 #print "g = %s" % g; 2066 t = System.currentTimeMillis(); 2067 z = SolvableSyzygySeq(self.module.ring.coFac).isRightZeroRelation( l, s ); 2068 t = System.currentTimeMillis() - t; 2069 print "executed isRightSyzygy in %s ms" % t; 2070 return z;
2071
2072 - def rightSyzygy(self):
2073 '''Compute right syzygys of this module. 2074 ''' 2075 l = self.mset; 2076 t = System.currentTimeMillis(); 2077 # no: p = SolvableSyzygySeq(self.module.ring.coFac).rightZeroRelations( l ); 2078 p = SolvableSyzygySeq(self.module.ring.coFac).rightZeroRelationsArbitrary( l ); 2079 t = System.currentTimeMillis() - t; 2080 print "executed right module syzygy in %s ms" % t; 2081 #print "p = " + str(p.ring.toScript()); 2082 m = SolvableModule("",p.ring,p.cols); 2083 return SolvableSubModule(m,"",p.list);
2084 2085
2086 -class SeriesRing:
2087 '''Represents a JAS power series ring: UnivPowerSeriesRing. 2088 2089 Methods for univariate power series arithmetic. 2090 ''' 2091
2092 - def __init__(self,ringstr="",truncate=None,ring=None,cofac=None,name="z"):
2093 '''Ring constructor. 2094 ''' 2095 if ring == None: 2096 if len(ringstr) > 0: 2097 sr = StringReader( ringstr ); 2098 tok = RingFactoryTokenizer(sr); 2099 pfac = tok.nextPolynomialRing(); 2100 #tok = GenPolynomialTokenizer(pfac,sr); 2101 #plist = tok.nextPolynomialList(); 2102 #pset = PolynomialList(pfac,plist); 2103 ring = pfac; 2104 vname = ring.vars; 2105 name = vname[0]; 2106 cofac = ring.coFac; 2107 if isinstance(cofac,RingElem): 2108 cofac = cofac.elem; 2109 if truncate == None: 2110 self.ring = UnivPowerSeriesRing(cofac,name); 2111 else: 2112 self.ring = UnivPowerSeriesRing(cofac,truncate,name); 2113 else: 2114 self.ring = ring;
2115
2116 - def __str__(self):
2117 '''Create a string representation. 2118 ''' 2119 return str(self.ring.toScript());
2120
2121 - def gens(self):
2122 '''Get the generators of the power series ring. 2123 ''' 2124 L = self.ring.generators(); 2125 N = [ RingElem(e) for e in L ]; 2126 return N;
2127
2128 - def inject_variables(self):
2129 '''Inject generators as variables into the main global namespace 2130 ''' 2131 inject_generators(self.gens());
2132
2133 - def one(self):
2134 '''Get the one of the power series ring. 2135 ''' 2136 return RingElem( self.ring.getONE() );
2137
2138 - def zero(self):
2139 '''Get the zero of the power series ring. 2140 ''' 2141 return RingElem( self.ring.getZERO() );
2142
2143 - def random(self,n):
2144 '''Get a random power series. 2145 ''' 2146 return RingElem( self.ring.random(n) );
2147
2148 - def exp(self):
2149 '''Get the exponential power series. 2150 ''' 2151 return RingElem( self.ring.getEXP() );
2152
2153 - def sin(self):
2154 '''Get the sinus power series. 2155 ''' 2156 return RingElem( self.ring.getSIN() );
2157
2158 - def cos(self):
2159 '''Get the cosinus power series. 2160 ''' 2161 return RingElem( self.ring.getCOS() );
2162
2163 - def tan(self):
2164 '''Get the tangens power series. 2165 ''' 2166 return RingElem( self.ring.getTAN() );
2167
2168 - def create(self,ifunc=None,jfunc=None,clazz=None):
2169 '''Create a power series with given generating function. 2170 2171 ifunc(int i) must return a value which is used in RingFactory.fromInteger(). 2172 jfunc(int i) must return a value of type ring.coFac. 2173 clazz must implement the Coefficients abstract class. 2174 ''' 2175 class coeff( Coefficients ): 2176 def __init__(self,cofac): 2177 self.coFac = cofac;
2178 def generate(self,i): 2179 if jfunc == None: 2180 return self.coFac.fromInteger( ifunc(i) ); 2181 else: 2182 return jfunc(i);
2183 if clazz == None: 2184 ps = UnivPowerSeries( self.ring, coeff(self.ring.coFac) ); 2185 else: 2186 ps = UnivPowerSeries( self.ring, clazz ); 2187 return RingElem( ps ); 2188
2189 - def fixPoint(self,psmap):
2190 '''Create a power series as fixed point of the given mapping. 2191 2192 psmap must implement the UnivPowerSeriesMap interface. 2193 ''' 2194 ps = self.ring.fixPoint( psmap ); 2195 return RingElem( ps );
2196
2197 - def gcd(self,a,b):
2198 '''Compute the greatest common divisor of a and b. 2199 ''' 2200 if isinstance(a,RingElem): 2201 a = a.elem; 2202 if isinstance(b,RingElem): 2203 b = b.elem; 2204 return RingElem( a.gcd(b) );
2205
2206 - def fromPoly(self,a):
2207 '''Convert a GenPolynomial to a power series. 2208 ''' 2209 if isinstance(a,RingElem): 2210 a = a.elem; 2211 return RingElem( self.ring.fromPolynomial(a) );
2212 2213
2214 -class MultiSeriesRing:
2215 '''Represents a JAS power series ring: MultiVarPowerSeriesRing. 2216 2217 Methods for multivariate power series arithmetic. 2218 ''' 2219
2220 - def __init__(self,ringstr="",truncate=None,ring=None,cofac=None,names=None):
2221 '''Ring constructor. 2222 ''' 2223 if ring == None: 2224 if len(ringstr) > 0: 2225 sr = StringReader( ringstr ); 2226 tok = RingFactoryTokenizer(sr); 2227 pfac = tok.nextPolynomialRing(); 2228 #tok = GenPolynomialTokenizer(pfac,sr); 2229 #plist = tok.nextPolynomialList(); 2230 #pset = PolynomialList(pfac,plist); 2231 ring = pfac; 2232 names = ring.vars; 2233 cofac = ring.coFac; 2234 if isinstance(cofac,RingElem): 2235 cofac = cofac.elem; 2236 if truncate == None: 2237 self.ring = MultiVarPowerSeriesRing(cofac,names); 2238 else: 2239 self.ring = MultiVarPowerSeriesRing(cofac,len(names),truncate,names); 2240 else: 2241 self.ring = ring;
2242
2243 - def __str__(self):
2244 '''Create a string representation. 2245 ''' 2246 return str(self.ring.toScript());
2247
2248 - def gens(self):
2249 '''Get the generators of the power series ring. 2250 ''' 2251 L = self.ring.generators(); 2252 N = [ RingElem(e) for e in L ]; 2253 return N;
2254
2255 - def inject_variables(self):
2256 '''Inject generators as variables into the main global namespace 2257 ''' 2258 inject_generators(self.gens());
2259
2260 - def one(self):
2261 '''Get the one of the power series ring. 2262 ''' 2263 return RingElem( self.ring.getONE() );
2264
2265 - def zero(self):
2266 '''Get the zero of the power series ring. 2267 ''' 2268 return RingElem( self.ring.getZERO() );
2269
2270 - def random(self,n):
2271 '''Get a random power series. 2272 ''' 2273 return RingElem( self.ring.random(n) );
2274
2275 - def exp(self,r):
2276 '''Get the exponential power series, var r. 2277 ''' 2278 return RingElem( self.ring.getEXP(r) );
2279
2280 - def sin(self,r):
2281 '''Get the sinus power series, var r. 2282 ''' 2283 return RingElem( self.ring.getSIN(r) );
2284
2285 - def cos(self,r):
2286 '''Get the cosinus power series, var r. 2287 ''' 2288 return RingElem( self.ring.getCOS(r) );
2289
2290 - def tan(self,r):
2291 '''Get the tangens power series, var r. 2292 ''' 2293 return RingElem( self.ring.getTAN(r) );
2294
2295 - def create(self,ifunc=None,jfunc=None,clazz=None):
2296 '''Create a power series with given generating function. 2297 2298 ifunc(int i) must return a value which is used in RingFactory.fromInteger(). 2299 jfunc(int i) must return a value of type ring.coFac. 2300 clazz must implement the Coefficients abstract class. 2301 ''' 2302 class coeff( MultiVarCoefficients ): 2303 def __init__(self,r): 2304 MultiVarCoefficients.__init__(self,r); 2305 self.coFac = r.coFac;
2306 def generate(self,i): 2307 if jfunc == None: 2308 return self.coFac.fromInteger( ifunc(i) ); 2309 else: 2310 return jfunc(i);
2311 #print "ifunc" 2312 if clazz == None: 2313 ps = MultiVarPowerSeries( self.ring, coeff(self.ring) ); 2314 else: 2315 ps = MultiVarPowerSeries( self.ring, clazz ); 2316 #print "ps ", ps.toScript(); 2317 return RingElem( ps ); 2318
2319 - def fixPoint(self,psmap):
2320 '''Create a power series as fixed point of the given mapping. 2321 2322 psmap must implement the UnivPowerSeriesMap interface. 2323 ''' 2324 ps = self.ring.fixPoint( psmap ); 2325 return RingElem( ps );
2326
2327 - def gcd(self,a,b):
2328 '''Compute the greatest common divisor of a and b. 2329 ''' 2330 if isinstance(a,RingElem): 2331 a = a.elem; 2332 if isinstance(b,RingElem): 2333 b = b.elem; 2334 return RingElem( a.gcd(b) );
2335
2336 - def fromPoly(self,a):
2337 '''Convert a GenPolynomial to a power series. 2338 ''' 2339 if isinstance(a,RingElem): 2340 a = a.elem; 2341 return RingElem( self.ring.fromPolynomial(a) );
2342 2343
2344 -class PSIdeal:
2345 '''Represents a JAS power series ideal. 2346 2347 Method for Standard bases. 2348 ''' 2349
2350 - def __init__(self,ring,polylist,ideal=None,list=None):
2351 '''PSIdeal constructor. 2352 ''' 2353 if isinstance(ring,Ring) or isinstance(ring,PolyRing): 2354 ring = MultiVarPowerSeriesRing(ring.ring); 2355 if isinstance(ring,MultiSeriesRing): 2356 ring = ring.ring; 2357 self.ring = ring; 2358 #print "ring = ", ring.toScript(); 2359 if ideal != None: 2360 polylist = ideal.pset.list; 2361 if list == None: 2362 self.polylist = pylist2arraylist( [ a.elem for a in polylist ] ); 2363 #print "polylist = ", self.polylist; 2364 self.list = self.ring.fromPolynomial(self.polylist); 2365 else: 2366 self.polylist = None; 2367 self.list = pylist2arraylist( [ a.elem for a in list ] );
2368
2369 - def __str__(self):
2370 '''Create a string representation. 2371 ''' 2372 ll = [ e.toScript() for e in self.list ] 2373 return "( " + ", ".join(ll) + " )";
2374
2375 - def STD(self,trunc=None):
2376 '''Compute a standard base. 2377 ''' 2378 pr = self.ring; 2379 if trunc != None: 2380 pr.setTruncate(trunc); 2381 #print "pr = ", pr.toScript(); 2382 F = self.list; 2383 #print "F = ", F; 2384 tm = StandardBaseSeq(); 2385 t = System.currentTimeMillis(); 2386 S = tm.STD(F); 2387 t = System.currentTimeMillis() - t; 2388 print "sequential standard base executed in %s ms" % t; 2389 #Sp = [ RingElem(a.asPolynomial()) for a in S ]; 2390 Sp = [ RingElem(a) for a in S ]; 2391 #return Sp; 2392 return PSIdeal(self.ring,None,list=Sp);
2393 2394
2395 -def pylist2arraylist(list,fac=None,rec=1):
2396 '''Convert a Python list to a Java ArrayList. 2397 2398 If list is a Python list, it is converted, else list is left unchanged. 2399 ''' 2400 #print "list type(%s) = %s" % (list,type(list)); 2401 if isinstance(list,PyList) or isinstance(list,PyTuple): 2402 L = ArrayList(); 2403 for e in list: 2404 t = True; 2405 if isinstance(e,RingElem): 2406 t = False; 2407 e = e.elem; 2408 if isinstance(e,PyList) or isinstance(e,PyTuple): 2409 if rec <= 1: 2410 e = makeJasArith(e); 2411 else: 2412 t = False; 2413 e = pylist2arraylist(e,fac,rec-1); 2414 try: 2415 #n = e.getClass().getSimpleName(); 2416 if isinstance(e,ArrayList) or isinstance(e,LinkedList): 2417 t = False; 2418 except: 2419 pass; 2420 if t and fac != None: 2421 #print "e.p(%s) = %s" % (e,e.getClass().getName()); 2422 e = fac.parse( str(e) ); #or makeJasArith(e) ? 2423 L.add(e); 2424 list = L; 2425 #print "list type(%s) = %s" % (list,type(list)); 2426 return list
2427 2428
2429 -def arraylist2pylist(list,rec=1):
2430 '''Convert a Java ArrayList to a Python list. 2431 2432 If list is a Java ArrayList list, it is converted, else list is left unchanged. 2433 ''' 2434 #print "list type(%s) = %s" % (list,type(list)); 2435 if isinstance(list,List): 2436 L = []; 2437 for e in list: 2438 if not isinstance(e,RingElem): 2439 e = RingElem(e); 2440 L.append(e); 2441 list = L; 2442 #print "list type(%s) = %s" % (list,type(list)); 2443 return list
2444 2445
2446 -def makeJasArith(item):
2447 '''Construct a jas.arith object. 2448 If item is a python tuple or list then a BigRational, BigComplex is constructed. 2449 If item is a python float then a BigDecimal is constructed. 2450 ''' 2451 #print "item type(%s) = %s" % (item,type(item)); 2452 if isinstance(item,PyInteger) or isinstance(item,PyLong): 2453 return BigInteger( item ); 2454 if isinstance(item,PyFloat): # ?? what to do ?? 2455 return BigDecimal( str(item) ); 2456 if isinstance(item,PyTuple) or isinstance(item,PyList): 2457 if len(item) > 2: 2458 print "len(item) > 2, remaining items ignored"; 2459 #print "item[0] type(%s) = %s" % (item[0],type(item[0])); 2460 isc = isinstance(item[0],PyTuple) or isinstance(item[0],PyList) 2461 if len(item) > 1: 2462 isc = isc or isinstance(item[1],PyTuple) or isinstance(item[1],PyList); 2463 if isc: 2464 if len(item) > 1: 2465 re = makeJasArith( item[0] ); 2466 if not re.isField(): 2467 re = BigRational( re.val ); 2468 im = makeJasArith( item[1] ); 2469 if not im.isField(): 2470 im = BigRational( im.val ); 2471 jasArith = BigComplex( re, im ); 2472 else: 2473 re = makeJasArith( item[0] ); 2474 jasArith = BigComplex( re ); 2475 else: 2476 if len(item) > 1: 2477 jasArith = BigRational( item[0] ).divide( BigRational( item[1] ) ); 2478 else: 2479 jasArith = BigRational( item[0] ); 2480 return jasArith; 2481 print "makeJasArith: unknown item type(%s) = %s" % (item,type(item)); 2482 return item;
2483 2484
2485 -def ZZ(z=0):
2486 '''Create JAS BigInteger as ring element. 2487 ''' 2488 if isinstance(z,RingElem): 2489 z = z.elem; 2490 r = BigInteger(z); 2491 return RingElem(r);
2492
2493 -def ZM(m,z=0,field=False):
2494 '''Create JAS ModInteger as ring element. 2495 ''' 2496 if isinstance(m,RingElem): 2497 m = m.elem; 2498 if isinstance(z,RingElem): 2499 z = z.elem; 2500 if z != 0 and ( z == False or z == True ): # never true 2501 field = z; 2502 z = 0; 2503 if m < ModLongRing.MAX_LONG: 2504 if m < ModIntRing.MAX_INT: 2505 if field: 2506 mf = ModIntRing(m,field); 2507 else: 2508 mf = ModIntRing(m); 2509 r = ModInt(mf,z); 2510 else: 2511 if field: 2512 mf = ModLongRing(m,field); 2513 else: 2514 mf = ModLongRing(m); 2515 r = ModLong(mf,z); 2516 else: 2517 if field: 2518 mf = ModIntegerRing(m,field); 2519 else: 2520 mf = ModIntegerRing(m); 2521 r = ModInteger(mf,z); 2522 return RingElem(r);
2523 2524
2525 -def ZML(m,z=0,field=False):
2526 '''Create JAS ModLong as ring element. 2527 ''' 2528 return ZM(m,z,field);
2529 2530
2531 -def ZMI(m,z=0,field=False):
2532 '''Create JAS ModInt as ring element. 2533 ''' 2534 return ZM(m,z,field);
2535 2536
2537 -def GF(m,z=0):
2538 '''Create JAS ModInteger as field element. 2539 ''' 2540 #print "m = %s" % m 2541 return ZM(m,z,True);
2542 2543
2544 -def GFL(m,z=0):
2545 '''Create JAS ModLong as field element. 2546 ''' 2547 #print "m = %s" % m 2548 return ZM(m,z,True);
2549 2550
2551 -def GFI(m,z=0):
2552 '''Create JAS ModInt as field element. 2553 ''' 2554 return ZM(m,z,True);
2555 2556
2557 -def QQ(d=0,n=1):
2558 '''Create JAS BigRational as ring element. 2559 ''' 2560 if isinstance(d,PyTuple) or isinstance(d,PyList): 2561 if n != 1: 2562 print "%s ignored" % n; 2563 if len(d) > 1: 2564 n = d[1]; 2565 d = d[0]; 2566 if isinstance(d,RingElem): 2567 d = d.elem; 2568 if isinstance(n,RingElem): 2569 n = n.elem; 2570 if n == 1: 2571 if d == 0: 2572 r = BigRational(); 2573 else: 2574 r = BigRational(d); 2575 else: 2576 d = BigRational(d); 2577 n = BigRational(n); 2578 r = d.divide(n); # BigRational(d,n); only for short integers 2579 return RingElem(r);
2580 2581
2582 -def CC(re=BigRational(),im=BigRational()):
2583 '''Create JAS BigComplex as ring element. 2584 ''' 2585 if re == 0: 2586 re = BigRational(); 2587 if im == 0: 2588 im = BigRational(); 2589 if isinstance(re,PyTuple) or isinstance(re,PyList): 2590 if isinstance(re[0],PyTuple) or isinstance(re[0],PyList): 2591 if len(re) > 1: 2592 im = QQ( re[1] ); 2593 re = QQ( re[0] ); 2594 else: 2595 re = QQ(re); 2596 # re = makeJasArith( re ); 2597 if isinstance(im,PyTuple) or isinstance(im,PyList): 2598 im = QQ( im ); 2599 # im = makeJasArith( im ); 2600 if isinstance(re,RingElem): 2601 re = re.elem; 2602 if isinstance(im,RingElem): 2603 im = im.elem; 2604 if im.isZERO(): 2605 if re.isZERO(): 2606 c = BigComplex(); 2607 else: 2608 c = BigComplex(re); 2609 else: 2610 c = BigComplex(re,im); 2611 return RingElem(c);
2612 2613
2614 -def CR(re=BigRational(),im=BigRational(),ring=None):
2615 '''Create JAS generic Complex as ring element. 2616 ''' 2617 if re == 0: 2618 re = BigRational(); 2619 if im == 0: 2620 im = BigRational(); 2621 if isinstance(re,PyTuple) or isinstance(re,PyList): 2622 if isinstance(re[0],PyTuple) or isinstance(re[0],PyList): 2623 if len(re) > 1: 2624 im = QQ( re[1] ); 2625 re = QQ( re[0] ); 2626 else: 2627 re = QQ(re); 2628 # re = makeJasArith( re ); 2629 if isinstance(im,PyTuple) or isinstance(im,PyList): 2630 im = QQ( im ); 2631 # im = makeJasArith( im ); 2632 if isinstance(re,RingElem): 2633 re = re.elem; 2634 if isinstance(im,RingElem): 2635 im = im.elem; 2636 if ring == None: 2637 ring = re.factory(); 2638 r = ComplexRing(ring); 2639 #print "d type(%s) = %s" % (r,type(r)); 2640 if im.isZERO(): 2641 if re.isZERO(): 2642 c = Complex(r); 2643 else: 2644 c = Complex(r,re); 2645 else: 2646 c = Complex(r,re,im); 2647 #print "d type(%s) = %s" % (c,type(c)); 2648 return RingElem(c);
2649 2650
2651 -def DD(d=0):
2652 '''Create JAS BigDecimal as ring element. 2653 ''' 2654 if isinstance(d,RingElem): 2655 d = d.elem; 2656 if isinstance(d,PyFloat): 2657 d = str(d); 2658 #print "d type(%s) = %s" % (d,type(d)); 2659 if d == 0: 2660 r = BigDecimal(); 2661 else: 2662 r = BigDecimal(d); 2663 return RingElem(r);
2664 2665
2666 -def Quat(re=BigRational(),im=BigRational(),jm=BigRational(),km=BigRational()):
2667 '''Create JAS BigQuaternion as ring element. 2668 ''' 2669 if re == 0: 2670 re = BigRational(); 2671 if im == 0: 2672 im = BigRational(); 2673 if jm == 0: 2674 jm = BigRational(); 2675 if km == 0: 2676 km = BigRational(); 2677 if isinstance(re,PyTuple) or isinstance(re,PyList): 2678 if isinstance(re[0],PyTuple) or isinstance(re[0],PyList): 2679 if len(re) > 1: 2680 im = QQ( re[1] ); 2681 re = QQ( re[0] ); 2682 else: 2683 re = QQ(re); 2684 # re = makeJasArith( re ); 2685 if isinstance(im,PyTuple) or isinstance(im,PyList): 2686 im = QQ( im ); 2687 if isinstance(jm,PyTuple) or isinstance(jm,PyList): 2688 jm = QQ( jm ); 2689 if isinstance(km,PyTuple) or isinstance(km,PyList): 2690 kim = QQ( km ); 2691 # im = makeJasArith( im ); 2692 if isinstance(re,RingElem): 2693 re = re.elem; 2694 if isinstance(im,RingElem): 2695 im = im.elem; 2696 if isinstance(jm,RingElem): 2697 jm = jm.elem; 2698 if isinstance(km,RingElem): 2699 km = km.elem; 2700 cf = BigQuaternionRing(); 2701 c = BigQuaternion(cf, re,im,jm,km); 2702 return RingElem(c);
2703 2704
2705 -def Oct(ro=0,io=0):
2706 '''Create JAS BigOctonion as ring element. 2707 ''' 2708 cf = BigQuaternionRing(); 2709 if ro == 0: 2710 ro = BigQuaternion(cf); 2711 if io == 0: 2712 io = BigQuaternion(cf); 2713 if isinstance(ro,PyTuple) or isinstance(ro,PyList): 2714 if isinstance(ro[0],PyTuple) or isinstance(ro[0],PyList): 2715 if len(ro) > 1: 2716 io = QQ( ro[1] ); 2717 ro = QQ( ro[0] ); 2718 else: 2719 ro = QQ(ro); 2720 # re = makeJasArith( re ); 2721 if isinstance(io,PyTuple) or isinstance(io,PyList): 2722 io = QQ( io ); 2723 # im = makeJasArith( im ); 2724 if isinstance(ro,RingElem): 2725 ro = ro.elem; 2726 if isinstance(io,RingElem): 2727 io = io.elem; 2728 c = BigOctonion(ro,io); 2729 return RingElem(c);
2730 2731
2732 -def AN(m,z=0,field=False,pr=None):
2733 '''Create JAS AlgebraicNumber as ring element. 2734 ''' 2735 if isinstance(m,RingElem): 2736 m = m.elem; 2737 if isinstance(z,RingElem): 2738 z = z.elem; 2739 # if (z == True or z == False): # not working 2740 # field = z; 2741 # z = 0; 2742 #print "m.getClass() = " + str(m.getClass().getName()); 2743 #print "field = " + str(field); 2744 if isinstance(m,AlgebraicNumber): 2745 mf = AlgebraicNumberRing(m.factory().modul,m.factory().isField()); 2746 else: 2747 if field: 2748 mf = AlgebraicNumberRing(m,field); 2749 else: 2750 mf = AlgebraicNumberRing(m); 2751 #print "mf = " + mf.toString(); 2752 if z == 0: 2753 r = AlgebraicNumber(mf); 2754 else: 2755 r = AlgebraicNumber(mf,z); 2756 return RingElem(r);
2757 2758 2759 _finiteFields = {}; '''List of already constructed FiniteFields.''' 2760 2761
2762 -def FF(p,n,z=0):
2763 '''Create JAS Field element as ring element. 2764 FF has p<sup>n</sup> elements. 2765 ''' 2766 if isinstance(p,RingElem): 2767 p = p.elem; 2768 if isinstance(n,RingElem): 2769 n = n.elem; 2770 if isinstance(z,RingElem): 2771 z = z.elem; 2772 if (p == 0): 2773 raise "p =="; 2774 if (n == 0): 2775 raise "n =="; 2776 field = True; 2777 if not PrimeInteger.isPrime(p): 2778 field = False; 2779 raise ValueError, str(p) + " not prime."; 2780 mf = _finiteFields.get( (p,n) ); 2781 if mf == None: 2782 cf = GF(p).ring; 2783 mf = PolyUfdUtil.algebraicNumberField(cf,n); 2784 _finiteFields[ (p,n) ] = mf; 2785 #print "mf = " + mf.toScript(); 2786 if z == 0: 2787 r = AlgebraicNumber(mf); 2788 else: 2789 r = AlgebraicNumber(mf,z); 2790 return RingElem(r);
2791 2792
2793 -def RealN(m,i,r=0):
2794 '''Create JAS RealAlgebraicNumber as ring element. 2795 ''' 2796 if isinstance(m,RingElem): 2797 m = m.elem; 2798 if isinstance(r,RingElem): 2799 r = r.elem; 2800 if isinstance(i,PyTuple) or isinstance(i,PyList): 2801 il = BigRational(i[0]); 2802 ir = BigRational(i[1]); 2803 i = Interval(il,ir); 2804 #print "m.getClass() = " + str(m.getClass().getName()); 2805 if isinstance(m,RealAlgebraicNumber): 2806 mf = RealAlgebraicRing(m.factory().algebraic.modul,i); 2807 else: 2808 mf = RealAlgebraicRing(m,i); 2809 if r == 0: 2810 rr = RealAlgebraicNumber(mf); 2811 else: 2812 rr = RealAlgebraicNumber(mf,r); 2813 return RingElem(rr);
2814 2815
2816 -def RF(pr,d=0,n=1):
2817 '''Create JAS rational function Quotient as ring element. 2818 ''' 2819 if isinstance(d,PyTuple) or isinstance(d,PyList): 2820 if n != 1: 2821 print "%s ignored" % n; 2822 if len(d) > 1: 2823 n = d[1]; 2824 d = d[0]; 2825 if isinstance(d,RingElem): 2826 d = d.elem; 2827 if isinstance(n,RingElem): 2828 n = n.elem; 2829 if isinstance(pr,RingElem): 2830 pr = pr.elem; 2831 if isinstance(pr,Ring): 2832 pr = pr.ring; 2833 qr = QuotientRing(pr); 2834 if d == 0: 2835 r = Quotient(qr); 2836 else: 2837 if n == 1: 2838 r = Quotient(qr,d); 2839 else: 2840 r = Quotient(qr,d,n); 2841 return RingElem(r);
2842 2843
2844 -def RC(ideal,r=0):
2845 '''Create JAS polynomial Residue as ring element. 2846 ''' 2847 if ideal == None: 2848 raise ValueError, "No ideal given." 2849 if isinstance(ideal,Ideal): 2850 ideal = jas.application.Ideal(ideal.pset); 2851 #ideal.doGB(); 2852 #print "ideal.getList().get(0).ring.ideal = %s" % ideal.getList().get(0).ring.ideal; 2853 if isinstance(ideal.getList().get(0).ring,ResidueRing): 2854 rc = ResidueRing( ideal.getList().get(0).ring.ideal ); 2855 else: 2856 rc = ResidueRing(ideal); 2857 if isinstance(r,RingElem): 2858 r = r.elem; 2859 if r == 0: 2860 r = Residue(rc); 2861 else: 2862 r = Residue(rc,r); 2863 return RingElem(r);
2864 2865
2866 -def LC(ideal,d=0,n=1):
2867 '''Create JAS polynomial Local as ring element. 2868 ''' 2869 if ideal == None: 2870 raise ValueError, "No ideal given." 2871 if isinstance(ideal,Ideal): 2872 ideal = jas.application.Ideal(ideal.pset); 2873 #ideal.doGB(); 2874 #print "ideal.getList().get(0).ring.ideal = %s" % ideal.getList().get(0).ring.ideal; 2875 if isinstance(ideal.getList().get(0).ring,LocalRing): 2876 lc = LocalRing( ideal.getList().get(0).ring.ideal ); 2877 else: 2878 lc = LocalRing(ideal); 2879 if isinstance(d,PyTuple) or isinstance(d,PyList): 2880 if n != 1: 2881 print "%s ignored" % n; 2882 if len(d) > 1: 2883 n = d[1]; 2884 d = d[0]; 2885 if isinstance(d,RingElem): 2886 d = d.elem; 2887 if isinstance(n,RingElem): 2888 n = n.elem; 2889 if d == 0: 2890 r = Local(lc); 2891 else: 2892 if n == 1: 2893 r = Local(lc,d); 2894 else: 2895 r = Local(lc,d,n); 2896 return RingElem(r);
2897 2898
2899 -def SRF(pr,d=0,n=1):
2900 '''Create JAS rational function SolvableQuotient as ring element. 2901 ''' 2902 if isinstance(d,PyTuple) or isinstance(d,PyList): 2903 if n != 1: 2904 print "%s ignored" % n; 2905 if len(d) > 1: 2906 n = d[1]; 2907 d = d[0]; 2908 if isinstance(d,RingElem): 2909 d = d.elem; 2910 if isinstance(n,RingElem): 2911 n = n.elem; 2912 if isinstance(pr,RingElem): 2913 pr = pr.elem; 2914 if isinstance(pr,Ring): 2915 pr = pr.ring; 2916 qr = SolvableQuotientRing(pr); 2917 if d == 0: 2918 r = SolvableQuotient(qr); 2919 else: 2920 if n == 1: 2921 r = SolvableQuotient(qr,d); 2922 else: 2923 r = SolvableQuotient(qr,d,n); 2924 return RingElem(r);
2925 2926
2927 -def SRC(ideal,r=0):
2928 '''Create JAS polynomial SolvableResidue as ring element. 2929 ''' 2930 #print "ideal = " + str(ideal); 2931 if ideal == None: # does not work 2932 print "ideal = " + str(ideal); 2933 if False: 2934 raise ValueError, "No ideal given." 2935 if isinstance(ideal,SolvableIdeal): 2936 ideal = jas.application.SolvableIdeal(ideal.pset); 2937 #ideal.doGB(); 2938 #print "ideal.getList().get(0).ring.ideal = %s" % ideal.getList().get(0).ring.ideal; 2939 if isinstance(ideal.getList().get(0).ring,SolvableResidueRing): 2940 rc = SolvableResidueRing( ideal.getList().get(0).ring.ideal ); 2941 else: 2942 rc = SolvableResidueRing(ideal); 2943 if isinstance(r,RingElem): 2944 r = r.elem; 2945 if r == 0: 2946 r = SolvableResidue(rc); 2947 else: 2948 r = SolvableResidue(rc,r); 2949 return RingElem(r);
2950 2951
2952 -def SLC(ideal,d=0,n=1):
2953 '''Create JAS polynomial SolvableLocal as ring element. 2954 ''' 2955 if ideal == None: 2956 #print "ideal = " + str(ideal); 2957 if False: 2958 raise ValueError, "No ideal given." 2959 if isinstance(ideal,SolvableIdeal): 2960 ideal = jas.application.SolvableIdeal(ideal.pset); 2961 #ideal.doGB(); 2962 #print "ideal.getList().get(0).ring.ideal = %s" % ideal.getList().get(0).ring.ideal; 2963 if isinstance(ideal.getList().get(0).ring,SolvableLocalRing): 2964 lc = SolvableLocalRing( ideal.getList().get(0).ring.ideal ); 2965 else: 2966 lc = SolvableLocalRing(ideal); 2967 if isinstance(d,PyTuple) or isinstance(d,PyList): 2968 if n != 1: 2969 print "%s ignored" % n; 2970 if len(d) > 1: 2971 n = d[1]; 2972 d = d[0]; 2973 if isinstance(d,RingElem): 2974 d = d.elem; 2975 if isinstance(n,RingElem): 2976 n = n.elem; 2977 if d == 0: 2978 r = SolvableLocal(lc); 2979 else: 2980 if n == 1: 2981 r = SolvableLocal(lc,d); 2982 else: 2983 r = SolvableLocal(lc,d,n); 2984 return RingElem(r);
2985 2986
2987 -def SLR(ideal,d=0,n=1):
2988 '''Create JAS polynomial SolvableLocalResidue as ring element. 2989 ''' 2990 if ideal == None: 2991 #print "ideal = " + str(ideal); 2992 if False: 2993 raise ValueError, "No ideal given." 2994 if isinstance(ideal,SolvableIdeal): 2995 ideal = jas.application.SolvableIdeal(ideal.pset); 2996 #ideal.doGB(); 2997 #print "ideal.getList().get(0).ring.ideal = %s" % ideal.getList().get(0).ring.ideal; 2998 cfr = ideal.getList().get(0).ring; 2999 if isinstance(cfr,SolvableLocalResidueRing): 3000 lc = SolvableLocalResidueRing( cfr.ideal ); 3001 else: 3002 lc = SolvableLocalResidueRing(ideal); 3003 if isinstance(d,PyTuple) or isinstance(d,PyList): 3004 if n != 1: 3005 print "%s ignored" % n; 3006 if len(d) > 1: 3007 n = d[1]; 3008 d = d[0]; 3009 if isinstance(d,RingElem): 3010 d = d.elem; 3011 if isinstance(n,RingElem): 3012 n = n.elem; 3013 if d == 0: 3014 r = SolvableLocalResidue(lc); 3015 else: 3016 if n == 1: 3017 r = SolvableLocalResidue(lc,d); 3018 else: 3019 r = SolvableLocalResidue(lc,d,n); 3020 return RingElem(r);
3021 3022 3023
3024 -def RR(flist,n=1,r=0):
3025 '''Create JAS regular ring Product as ring element. 3026 ''' 3027 if not isinstance(n,PyInteger): 3028 r = n; 3029 n = 1; 3030 if flist == None: 3031 raise ValueError, "No list given." 3032 if isinstance(flist,PyList) or isinstance(flist,PyTuple): 3033 flist = pylist2arraylist( [ x.factory() for x in flist ], rec=1); 3034 ncop = 0; 3035 else: 3036 ncop = n; 3037 if isinstance(flist,RingElem): 3038 flist = flist.elem; 3039 flist = flist.factory(); 3040 ncop = n; 3041 #print "flist = " + str(flist); 3042 #print "ncop = " + str(ncop); 3043 if ncop == 0: 3044 pr = ProductRing(flist); 3045 else: 3046 pr = ProductRing(flist,ncop); 3047 #print "r type(%s) = %s" % (r,type(r)); 3048 if isinstance(r,RingElem): 3049 r = r.elem; 3050 try: 3051 #print "r.class() = %s" % r.getClass().getSimpleName(); 3052 if isinstance(r,Product): 3053 #print "r.val = %s" % r.val; 3054 r = r.val; 3055 except: 3056 pass; 3057 #print "r = " + str(r); 3058 if r == 0: 3059 r = Product(pr); 3060 else: 3061 r = Product(pr,r); 3062 return RingElem(r);
3063 3064
3065 -def PS(cofac,name,f=None,truncate=None):
3066 '''Create JAS UnivPowerSeries as ring element. 3067 ''' 3068 cf = cofac; 3069 if isinstance(cofac,RingElem): 3070 cf = cofac.elem.factory(); 3071 if isinstance(cofac,Ring): 3072 cf = cofac.ring; 3073 if isinstance(truncate,RingElem): 3074 truncate = truncate.elem; 3075 if truncate == None: 3076 ps = UnivPowerSeriesRing(cf,name); 3077 else: 3078 ps = UnivPowerSeriesRing(cf,truncate,name); 3079 if f == None: 3080 r = ps.getZERO(); 3081 else: 3082 class Coeff( Coefficients ): 3083 def __init__(self,cofac): 3084 self.coFac = cofac;
3085 def generate(self,i): 3086 a = f(i); 3087 if isinstance(a,RingElem): 3088 a = a.elem; 3089 #print "a = " + str(a); 3090 return a; 3091 r = UnivPowerSeries(ps,Coeff(cf)); 3092 return RingElem(r); 3093 3094
3095 -def MPS(cofac,names,f=None,truncate=None):
3096 '''Create JAS MultiVarPowerSeries as ring element. 3097 ''' 3098 cf = cofac; 3099 if isinstance(cofac,RingElem): 3100 cf = cofac.elem.factory(); 3101 if isinstance(cofac,Ring): 3102 cf = cofac.ring; 3103 vars = names; 3104 if isinstance(vars,PyString): 3105 vars = GenPolynomialTokenizer.variableList(vars); 3106 nv = len(vars); 3107 if isinstance(truncate,RingElem): 3108 truncate = truncate.elem; 3109 if truncate == None: 3110 ps = MultiVarPowerSeriesRing(cf,nv,vars); 3111 else: 3112 ps = MultiVarPowerSeriesRing(cf,nv,vars,truncate); 3113 if f == None: 3114 r = ps.getZERO(); 3115 else: 3116 class MCoeff( MultiVarCoefficients ): 3117 def __init__(self,r): 3118 MultiVarCoefficients.__init__(self,r); 3119 self.coFac = r.coFac;
3120 def generate(self,i): 3121 a = f(i); 3122 if isinstance(a,RingElem): 3123 a = a.elem; 3124 return a; 3125 r = MultiVarPowerSeries(ps,MCoeff(ps)); 3126 #print "r = " + str(r); 3127 return RingElem(r); 3128 3129
3130 -def Vec(cofac,n,v=None):
3131 '''Create JAS GenVector ring element. 3132 ''' 3133 cf = cofac; 3134 if isinstance(cofac,RingElem): 3135 cf = cofac.elem.factory(); 3136 if isinstance(cofac,Ring): 3137 cf = cofac.ring; 3138 if isinstance(n,RingElem): 3139 n = n.elem; 3140 if isinstance(v,RingElem): 3141 v = v.elem; 3142 vr = GenVectorModul(cf,n); 3143 if v == None: 3144 r = GenVector(vr); 3145 else: 3146 r = GenVector(vr,v); 3147 return RingElem(r);
3148 3149
3150 -def Mat(cofac,n,m,v=None):
3151 '''Create JAS GenMatrix ring element. 3152 ''' 3153 cf = cofac; 3154 if isinstance(cofac,RingElem): 3155 cf = cofac.elem.factory(); 3156 if isinstance(cofac,Ring): 3157 cf = cofac.ring; 3158 if isinstance(n,RingElem): 3159 n = n.elem; 3160 if isinstance(m,RingElem): 3161 m = m.elem; 3162 if isinstance(v,RingElem): 3163 v = v.elem; 3164 #print "cf type(%s) = %s" % (cf,type(cf)); 3165 mr = GenMatrixRing(cf,n,m); 3166 if v == None: 3167 r = GenMatrix(mr); 3168 else: 3169 r = GenMatrix(mr,v); 3170 return RingElem(r);
3171 3172
3173 -def coercePair(a,b):
3174 '''Coerce type a to type b or type b to type a. 3175 ''' 3176 #print "a type(%s) = %s" % (a,type(a)); 3177 #print "b type(%s) = %s" % (b,type(b)); 3178 try: 3179 if not a.isPolynomial() and b.isPolynomial(): 3180 s = b.coerce(a); 3181 o = b; 3182 else: 3183 s = a; 3184 o = a.coerce(b); 3185 except: 3186 s = a; 3187 o = a.coerce(b); 3188 return (s,o);
3189 3190
3191 -def isJavaInstance(a):
3192 '''Test if a is a Java instance. 3193 ''' 3194 #print "a type(%s) = %s" % (a,type(a)); 3195 try: 3196 c = a.getClass(); 3197 except: 3198 return False; 3199 return True;
3200 3201
3202 -class RingElem:
3203 '''Proxy for JAS ring elements. 3204 3205 Methods to be used as + - * ** / %. 3206 ''' 3207
3208 - def __init__(self,elem):
3209 '''Constructor for ring element. 3210 ''' 3211 if isinstance(elem,RingElem): 3212 self.elem = elem.elem; 3213 else: 3214 self.elem = elem; 3215 try: 3216 self.ring = self.elem.factory(); 3217 except: 3218 self.ring = self.elem;
3219
3220 - def __str__(self):
3221 '''Create a string representation. 3222 ''' 3223 try: 3224 return str(self.elem.toScript()); 3225 except: 3226 return str(self.elem);
3227
3228 - def zero(self):
3229 '''Zero element of this ring. 3230 ''' 3231 return RingElem( self.ring.getZERO() );
3232
3233 - def isZERO(self):
3234 '''Test if this is the zero element of the ring. 3235 ''' 3236 return self.elem.isZERO();
3237
3238 - def one(self):
3239 '''One element of this ring. 3240 ''' 3241 return RingElem( self.ring.getONE() );
3242
3243 - def isONE(self):
3244 '''Test if this is the one element of the ring. 3245 ''' 3246 return self.elem.isONE();
3247
3248 - def signum(self):
3249 '''Get the sign of this element. 3250 ''' 3251 return self.elem.signum();
3252
3253 - def __abs__(self):
3254 '''Absolute value. 3255 ''' 3256 return RingElem( self.elem.abs() );
3257
3258 - def __neg__(self):
3259 '''Negative value. 3260 ''' 3261 return RingElem( self.elem.negate() );
3262
3263 - def __pos__(self):
3264 '''Positive value. 3265 ''' 3266 return self;
3267
3268 - def coerce(self,other):
3269 '''Coerce other to self. 3270 ''' 3271 #print "self type(%s) = %s" % (self,type(self)); 3272 #print "other type(%s) = %s" % (other,type(other)); 3273 #print "self.elem class(%s) = %s" % (self.elem,self.elem.getClass()); 3274 if isinstance(self.elem,GenVector): 3275 #print "self, other = %s, %s " % (self,other); 3276 if isinstance(other,PyTuple) or isinstance(other,PyList): 3277 o = pylist2arraylist(other,self.elem.factory().coFac,rec=1); 3278 o = GenVector(self.elem.factory(),o); 3279 return RingElem( o ); 3280 if isinstance(self.elem,GenMatrix): 3281 #print "self, other = %s, %s " % (type(self),type(other)); 3282 #print "o type(%s) = %s, str = %s" % (o,type(o),str(o)); 3283 if isinstance(other,PyTuple) or isinstance(other,PyList): 3284 o = pylist2arraylist(other,self.elem.factory().coFac,rec=2); 3285 o = GenMatrix(self.elem.factory(),o); 3286 return RingElem( o ); 3287 if isinstance(self.elem,GenPolynomial): 3288 #print "self, other = %s, %s " % (type(self),type(other)); 3289 #print "o type(%s) = %s, str = %s" % (o,type(o),str(o)); 3290 if isinstance(other,PyInteger) or isinstance(other,PyLong): 3291 o = self.ring.fromInteger(other); 3292 return RingElem( o ); 3293 if isinstance(other,RingElem): 3294 o = other.elem; 3295 else: 3296 o = other; 3297 if o == None: 3298 return RingElem( GenPolynomial(self.ring) ) 3299 if isJavaInstance(o): 3300 #print "self.elem, o = %s, %s " % (type(self.ring.coFac),type(o)); 3301 if isinstance(o,ExpVector): # want startsWith or substring(0,8) == "ExpVector": 3302 o = GenPolynomial(self.ring,o); 3303 return RingElem( o ); 3304 if self.ring.coFac.getClass().getSimpleName() == o.getClass().getSimpleName(): 3305 o = GenPolynomial(self.ring,o); 3306 return RingElem( o ); 3307 if isinstance(other,RingElem): 3308 if self.isPolynomial() and not other.isPolynomial(): 3309 #print "self.ring = %s" % (self.ring); 3310 o = self.ring.parse( other.elem.toString() ); # not toScript() 3311 #print "o type(%s) = %s, str = %s" % (o,type(o),str(o)); 3312 return RingElem( o ); 3313 return other; 3314 #print "--1"; 3315 if isinstance(other,PyTuple) or isinstance(other,PyList): 3316 # assume BigRational or BigComplex 3317 # assume self will be compatible with them. todo: check this 3318 o = makeJasArith(other); 3319 #print "other class(%s) = %s" % (o,o.getClass()); 3320 if self.isPolynomial(): 3321 #print "other type(%s) = %s" % (o,type(o)); 3322 o = self.ring.parse( o.toString() ); # not toScript(); 3323 #o = o.elem; 3324 if isinstance(self.elem,BigComplex): 3325 #print "other type(%s) = %s" % (o,type(o)); 3326 o = CC( o ); 3327 o = o.elem; 3328 if isinstance(self.elem,BigQuaternion): 3329 #print "other type(%s) = %s" % (o,type(o)); 3330 o = Quat( o ); 3331 o = o.elem; 3332 if isinstance(self.elem,BigOctonion): 3333 #print "other type(%s) = %s" % (o,type(o)); 3334 o = Oct( Quat(o) ); 3335 o = o.elem; 3336 if isinstance(self.elem,Product): 3337 #print "other type(%s) = %s" % (o,type(o)); 3338 o = RR(self.ring, self.elem.multiply(o) ); # valueOf 3339 #print "o = %s" % o; 3340 o = o.elem; 3341 return RingElem(o); 3342 #print "--2"; 3343 # test if self.elem is a factory itself 3344 if self.isFactory(): 3345 if isinstance(other,PyInteger) or isinstance(other,PyLong): 3346 o = self.elem.fromInteger(other); 3347 else: 3348 if isinstance(other,PyFloat): # ?? what to do ?? 3349 o = self.elem.fromInteger( int(other) ); 3350 else: 3351 print "coerce_1: unknown other type(%s) = %s" % (other,type(other)); 3352 o = self.elem.parse( str(other) ); 3353 return RingElem(o); 3354 #print "--3"; 3355 #print "other type(%s) = %s" % (other,type(other)); 3356 # self.elem has a ring factory 3357 if isinstance(other,PyInteger) or isinstance(other,PyLong): 3358 o = self.elem.factory().fromInteger(other); 3359 else: 3360 if isinstance(other,PyFloat): # ?? what to do ?? 3361 #print "other type(%s) = %s" % (other,type(other)); 3362 #print "self type(%s) = %s" % (self.elem,self.elem.getClass().getName()); 3363 o = BigDecimal(other); 3364 if isinstance(self.elem,Product): 3365 o = RR(self.ring, self.elem.idempotent().multiply(o) ); # valueOf 3366 o = o.elem; 3367 else: 3368 o = self.elem.factory().getZERO().sum( o ); 3369 else: 3370 print "coerce_2: unknown other type(%s) = %s" % (other,type(other)); 3371 print "coerce_2: self type(%s) = %s" % (self,type(self)); 3372 o = self.elem.factory().parse( str(other) ); 3373 #print "--4"; 3374 return RingElem(o);
3375
3376 - def isFactory(self):
3377 '''Test if this is itself a ring factory. 3378 ''' 3379 f = self.elem.factory(); 3380 if self.elem == f: 3381 return True; 3382 else: 3383 return False;
3384
3385 - def isPolynomial(self):
3386 '''Test if this is a polynomial. 3387 ''' 3388 try: 3389 nv = self.elem.ring.nvar; 3390 except: 3391 return False; 3392 return True;
3393
3394 - def __cmp__(self,other):
3395 '''Compare two ring elements. 3396 ''' 3397 [s,o] = coercePair(self,other); 3398 return s.elem.compareTo( o.elem );
3399
3400 - def __hash__(self):
3401 '''Hash value. 3402 ''' 3403 return self.elem.hashCode();
3404
3405 - def __len__(self):
3406 '''Length of the element. 3407 ''' 3408 return self.elem.length();
3409
3410 - def __mul__(self,other):
3411 '''Multiply two ring elements. 3412 ''' 3413 [s,o] = coercePair(self,other); 3414 #print "self type(%s) = %s" % (s,type(s)); 3415 #print "other type(%s) = %s" % (o,type(o)); 3416 return RingElem( s.elem.multiply( o.elem ) );
3417
3418 - def __rmul__(self,other):
3419 '''Reverse multiply two ring elements. 3420 ''' 3421 [s,o] = coercePair(self,other); 3422 return o.__mul__(s);
3423
3424 - def __add__(self,other):
3425 '''Add two ring elements. 3426 ''' 3427 [s,o] = coercePair(self,other); 3428 return RingElem( s.elem.sum( o.elem ) );
3429
3430 - def __radd__(self,other):
3431 '''Reverse add two ring elements. 3432 ''' 3433 [s,o] = coercePair(self,other); 3434 return o.__add__(s);
3435
3436 - def __sub__(self,other):
3437 '''Subtract two ring elements. 3438 ''' 3439 [s,o] = coercePair(self,other); 3440 return RingElem( s.elem.subtract( o.elem ) );
3441
3442 - def __rsub__(self,other):
3443 '''Reverse subtract two ring elements. 3444 ''' 3445 [s,o] = coercePair(self,other); 3446 return o.__sub__(self);
3447
3448 - def __div__(self,other):
3449 '''Divide two ring elements. 3450 ''' 3451 [s,o] = coercePair(self,other); 3452 return RingElem( s.elem.divide( o.elem ) );
3453
3454 - def __rdiv__(self,other):
3455 '''Reverse divide two ring elements. 3456 ''' 3457 [s,o] = coercePair(self,other); 3458 return o.__div__(s);
3459
3460 - def __mod__(self,other):
3461 '''Modular remainder of two ring elements. 3462 ''' 3463 [s,o] = coercePair(self,other); 3464 return RingElem( s.elem.remainder( o.elem ) );
3465
3466 - def __xor__(self,other):
3467 '''Can not be used as power. 3468 ''' 3469 return None;
3470
3471 - def __pow__(self,other,n=None):
3472 '''Power of this to other. 3473 ''' 3474 #print "self type(%s) = %s" % (self,type(self)); 3475 #print "pow other type(%s) = %s" % (other,type(other)); 3476 if isinstance(other,PyInteger) or isinstance(other,PyLong): 3477 n = other; 3478 else: 3479 if isinstance(other,RingElem): 3480 n = other.elem; 3481 #if isinstance(n,BigRational): # does not work 3482 if isinstance(n,BigRational): 3483 n = n.numerator().intValue() / n.denominator().intValue(); 3484 #if isinstance(n,BigInteger): # does not work 3485 if isinstance(n,BigInteger) or isinstance(n,Long) or isinstance(n,Integer): 3486 n = n.intValue(); 3487 if n == None: 3488 n = other; 3489 if self.isFactory(): 3490 p = Power(self.elem).power( self.elem, n ); 3491 else: 3492 p = Power(self.ring).power( self.elem, n ); 3493 return RingElem( p );
3494
3495 - def __eq__(self,other):
3496 '''Test if two ring elements are equal. 3497 ''' 3498 if other == None: 3499 return False; 3500 [s,o] = coercePair(self,other); 3501 return s.elem.equals(o.elem)
3502
3503 - def __ne__(self,other):
3504 '''Test if two ring elements are not equal. 3505 ''' 3506 if other == None: 3507 return False; 3508 [s,o] = coercePair(self,other); 3509 return not self.elem.equals(o.elem)
3510
3511 - def __float__(self):
3512 '''Convert to Python float. 3513 ''' 3514 #print "self type(%s) = %s" % (self,type(self)); 3515 e = self.elem; 3516 if isinstance(e,BigInteger): 3517 e = BigRational(e); 3518 if isinstance(e,BigRational): 3519 e = BigDecimal(e); 3520 if isinstance(e,BigDecimal): 3521 e = e.toString(); 3522 e = float(e); 3523 return e;
3524
3525 - def factory(self):
3526 '''Get the factory of this element. 3527 ''' 3528 fac = self.elem.factory(); 3529 try: 3530 nv = fac.nvar; 3531 except: 3532 return RingElem(fac); 3533 #return PolyRing(fac.coFac,fac.getVars(),fac.tord); 3534 return RingElem(fac);
3535
3536 - def gens(self):
3537 '''Get the generators for the factory of this element. 3538 ''' 3539 L = self.elem.factory().generators(); 3540 #print "L = %s" % L; 3541 N = [ RingElem(e) for e in L ]; 3542 #print "N = %s" % N; 3543 return N;
3544
3545 - def inject_variables(self):
3546 '''Inject generators as variables into the main global namespace 3547 ''' 3548 inject_generators(self.gens());
3549
3550 - def monic(self):
3551 '''Monic polynomial. 3552 ''' 3553 return RingElem( self.elem.monic() );
3554
3555 - def homogenize(self,var='h'):
3556 '''homogenize polynomial. 3557 3558 INPUT: 3559 - "var" - variable name to use for homogenization 3560 ''' 3561 if not self.isPolynomial(): 3562 return self 3563 if var in self.ring.vars: 3564 r = self.ring.extend(1); 3565 print "WARN: case for variable %s not implemented, new name %s" % (var,r.vars[-1]) 3566 else: 3567 r = self.ring.extend([var]); 3568 h = self.elem; 3569 h = h.homogenize(r); 3570 return RingElem(h);
3571
3572 - def evaluate(self,a):
3573 '''Evaluate at a for power series or polynomial. 3574 ''' 3575 #print "self type(%s) = %s" % (self,type(self)); 3576 #print "a type(%s) = %s" % (a,type(a)); 3577 x = None; 3578 if isinstance(a,RingElem): 3579 x = a.elem; 3580 if isinstance(a,PyTuple) or isinstance(a,PyList): 3581 # assume BigRational or BigComplex 3582 # assume self will be compatible with them. todo: check this 3583 #x = makeJasArith(a); 3584 x = pylist2arraylist(a); 3585 else: 3586 x = pylist2arraylist([a]); 3587 try: 3588 if isinstance(self.elem,UnivPowerSeries): 3589 e = self.elem.evaluate(x[0]); 3590 else: 3591 if isinstance(self.elem,MultiVarPowerSeries): 3592 e = self.elem.evaluate(x); 3593 else: 3594 x = [ p.leadingBaseCoefficient() for p in x ]; 3595 #puts "x = " + x[0].getClass().getSimpleName().to_s; 3596 e = PolyUtil.evaluateAll(self.ring.coFac, self.elem, x); 3597 except: 3598 e = 0; 3599 return RingElem( e );
3600
3601 - def integrate(self,a=0,r=None):
3602 '''Integrate a power series or rational function with constant a. 3603 3604 a is the integration constant, r is for partial integration in variable r. 3605 ''' 3606 #print "self type(%s) = %s" % (self,type(self)); 3607 #print "a type(%s) = %s" % (a,type(a)); 3608 x = None; 3609 if isinstance(a,RingElem): 3610 x = a.elem; 3611 if isinstance(a,PyTuple) or isinstance(a,PyList): 3612 # assume BigRational or BigComplex 3613 # assume self will be compatible with them. todo: check this 3614 x = makeJasArith(a); 3615 # power series 3616 try: 3617 if r != None: 3618 e = self.elem.integrate(x,r); 3619 else: 3620 e = self.elem.integrate(x); 3621 return RingElem( e ); 3622 except: 3623 pass; 3624 cf = self.elem.ring; 3625 try: 3626 cf = cf.ring; 3627 except: 3628 pass; 3629 # rational function 3630 integrator = ElementaryIntegration(cf.coFac); 3631 ei = integrator.integrate(self.elem); 3632 return ei;
3633
3634 - def differentiate(self,r=None):
3635 '''Differentiate a power series. 3636 3637 r is for partial differentiation in variable r. 3638 ''' 3639 try: 3640 if r != None: 3641 e = self.elem.differentiate(r); 3642 else: 3643 e = self.elem.differentiate(); 3644 except: 3645 e = self.elem.factory().getZERO(); 3646 return RingElem( e );
3647
3648 - def random(self,n=3):
3649 '''Random element. 3650 3651 n size for random element will be less than 2**n. 3652 ''' 3653 if isinstance(n,RingElem): 3654 n = n.elem; 3655 return RingElem( self.elem.factory().random(n) );
3656
3657 - def gcd(self,b):
3658 '''Compute the greatest common divisor of this/self and b. 3659 3660 ''' 3661 a = self.elem; 3662 if isinstance(b,RingElem): 3663 b = b.elem; 3664 else: 3665 b = element( b ); 3666 b = b.elem; 3667 if self.isPolynomial(): 3668 engine = Ring.getEngineGcd(self.ring); 3669 return RingElem( engine.gcd(a,b) ); 3670 else: 3671 return RingElem( a.gcd(b) );
3672
3673 - def squarefreeFactors(self):
3674 '''Compute squarefree factors of polynomial. 3675 3676 ''' 3677 a = self.elem; 3678 if self.isPolynomial(): 3679 sqf = Ring.getEngineSqf(self.ring); 3680 if sqf == None: 3681 raise ValueError, "squarefreeFactors not implemented for " + self.ring.to_s; 3682 cf = self.ring.coFac; 3683 if isinstance(cf,GenPolynomialRing): 3684 e = sqf.recursiveSquarefreeFactors( a ); 3685 else: 3686 e = sqf.squarefreeFactors( a ); 3687 L = {}; 3688 for a in e.keySet(): 3689 i = e.get(a); 3690 L[ RingElem( a ) ] = i; 3691 return L; 3692 else: 3693 raise ValueError, "squarefreeFactors not implemented for " + a.to_s;
3694
3695 - def factors(self):
3696 '''Compute irreducible factorization for modular, integer, 3697 rational number and algebriac number coefficients. 3698 3699 ''' 3700 a = self.elem; 3701 if self.isPolynomial(): 3702 factor = Ring.getEngineFactor(self.ring); 3703 if factor == None: 3704 raise ValueError, "factors not implemented for " + self.ring.to_s; 3705 cf = self.ring.coFac; 3706 if isinstance(cf,GenPolynomialRing): 3707 e = factor.recursiveFactors( a ); 3708 else: 3709 e = factor.factors( a ); 3710 L = {}; 3711 for a in e.keySet(): 3712 i = e.get(a); 3713 L[ RingElem( a ) ] = i; 3714 return L; 3715 else: 3716 raise ValueError, "factors not implemented for " + a.to_s;
3717
3718 - def factorsAbsolute(self):
3719 '''Compute absolute irreducible factorization for (modular,) 3720 rational number coefficients. 3721 ''' 3722 a = self.elem; 3723 if self.isPolynomial(): 3724 factor = Ring.getEngineFactor(self.ring); 3725 if factor == None: 3726 raise ValueError, "factors not implemented for " + self.ring.to_s; 3727 try: 3728 L = factor.factorsAbsolute( a ); 3729 ## L = {}; 3730 ## for a in e.keySet(): 3731 ## i = e.get(a); 3732 ## L[ RingElem( a ) ] = i; 3733 return L; 3734 except Exception, e: 3735 raise ValueError, "error in factorsAbsolute " + str(e) 3736 else: 3737 raise ValueError, "factors not implemented for " + a.to_s;
3738
3739 - def realRoots(self,eps=None):
3740 '''Compute real roots of univariate polynomial. 3741 ''' 3742 a = self.elem; 3743 if isinstance(eps,RingElem): 3744 eps = eps.elem; 3745 try: 3746 if eps == None: 3747 #R = RealRootsSturm().realRoots( a ); 3748 R = RootFactory.realAlgebraicNumbers( a ); 3749 else: 3750 R = RootFactory.realAlgebraicNumbers( a, eps ); 3751 R = [ RingElem(r) for r in R ]; 3752 #R = [ RingElem(BigDecimal(r.getRational())) for r in R ]; 3753 return R; 3754 except Exception, e: 3755 print "error " + str(e) 3756 return None
3757
3758 - def complexRoots(self,eps=None):
3759 '''Compute complex roots of univariate polynomial. 3760 ''' 3761 a = self.elem; 3762 if isinstance(eps,RingElem): 3763 eps = eps.elem; 3764 cmplx = False; 3765 try: 3766 x = a.ring.coFac.getONE().getRe(); 3767 cmplx = True; 3768 except Exception, e: 3769 pass; 3770 try: 3771 if eps == None: 3772 if cmplx: 3773 R = RootFactory.complexAlgebraicNumbersComplex(a); 3774 else: 3775 R = RootFactory.complexAlgebraicNumbers(a); 3776 # R = ComplexRootsSturm(a.ring.coFac).complexRoots( a ); 3777 # R = [ r.centerApprox() for r in R ]; 3778 # R = [ r.ring.getRoot() for r in R ]; 3779 R = [ RingElem(r) for r in R ]; 3780 else: 3781 if cmplx: 3782 R = RootFactory.complexAlgebraicNumbersComplex(a,eps); 3783 else: 3784 R = RootFactory.complexAlgebraicNumbers(a,eps); 3785 R = [ RingElem(r) for r in R ]; 3786 # R = [ r.decimalMagnitude() for r in R ]; 3787 # R = ComplexRootsSturm(a.ring.coFac).complexRoots( a, eps ); 3788 # R = ComplexRootsSturm(a.ring.coFac).approximateRoots( a, eps ); 3789 return R; 3790 except Exception, e: 3791 print "error " + str(e) 3792 return None
3793
3794 - def algebraicRoots(self,eps=None):
3795 '''Compute algebraic roots, i.e. the real and complex roots of univariate polynomial. 3796 ''' 3797 a = self.elem; 3798 if isinstance(eps,RingElem): 3799 eps = eps.elem; 3800 try: 3801 if eps == None: 3802 R = RootFactory.algebraicRoots(a); 3803 else: 3804 R = RootFactory.algebraicRoots(a, eps); 3805 #R = [ RingElem(r) for r in R ]; 3806 return RingElem(R); 3807 except Exception, e: 3808 print "error " + str(e) 3809 return None
3810
3811 - def rootRefine(self,eps=None):
3812 '''Compute algebraic roots refinement. 3813 ''' 3814 a = self.elem; 3815 if isinstance(eps,RingElem): 3816 eps = eps.elem; 3817 try: 3818 RootFactory.rootRefine(a, eps); 3819 #R = [ RingElem(r) for r in R ]; 3820 return RingElem(a); 3821 except Exception, e: 3822 print "error " + str(e) 3823 return None
3824
3825 - def decimalRoots(self,eps=None):
3826 '''Compute decimal approximation of real and complex roots of univariate polynomial. 3827 ''' 3828 a = self.elem; 3829 if isinstance(eps,RingElem): 3830 eps = eps.elem; 3831 try: 3832 R = RootFactory.decimalRoots(a, eps); 3833 #R = [ RingElem(r) for r in R ]; 3834 return RingElem(R); 3835 except Exception, e: 3836 print "error " + str(e) 3837 return None
3838
3839 - def rootsOfUnity(self):
3840 '''Roots of unity of real and complex algebraic numbers. 3841 ''' 3842 a = self.elem; 3843 try: 3844 if isinstance(a,AlgebraicRootsPrimElem): 3845 R = RootFactoryApp.rootsOfUnity(a); 3846 else: 3847 R = RootFactory.rootsOfUnity(a); 3848 #R = [ RingElem(r) for r in R ]; 3849 return RingElem(R); 3850 except Exception, e: 3851 print "error " + str(e) 3852 return None
3853
3854 - def rootReduce(self, other):
3855 '''Root reduce of real and complex algebraic numbers. 3856 Compute an extension field with a primitive element. 3857 ''' 3858 a = self.elem; 3859 b = other; 3860 if isinstance(b,RingElem): 3861 b = b.elem; 3862 try: 3863 R = RootFactoryApp.rootReduce(a, b); 3864 #R = [ RingElem(r) for r in R ]; 3865 return RingElem(R); 3866 except Exception, e: 3867 print "error " + str(e) 3868 return None
3869
3870 - def coefficients(self):
3871 '''Get the coefficients of a polynomial. 3872 ''' 3873 a = self.elem; 3874 #L = [ c.toScriptFactory() for c in a.coefficientIterator() ]; 3875 L = [ RingElem(c) for c in a.coefficientIterator() ]; 3876 return L
3877 3878 #---------------- 3879 # Compatibility methods for Sage/Singular: 3880 # Note: the meaning of lt and lm is swapped compared to JAS. 3881 #---------------- 3882
3883 - def parent(self):
3884 '''Parent in Sage is factory in JAS. 3885 3886 Compatibility method for Sage/Singular. 3887 ''' 3888 return self.factory();
3889
3890 - def __call__(self,num):
3891 '''Apply this to num. 3892 ''' 3893 if num == 0: 3894 return self.zero(); 3895 if num == 1: 3896 return self.one(); 3897 return RingElem( self.ring.fromInteger(num) );
3898
3899 - def lm(self):
3900 '''Leading monomial of a polynomial. 3901 3902 Compatibility method for Sage/Singular. 3903 Note: the meaning of lt and lm is swapped compared to JAS. 3904 ''' 3905 ev = self.elem.leadingExpVector(); 3906 return ev;
3907
3908 - def lc(self):
3909 '''Leading coefficient of a polynomial. 3910 3911 Compatibility method for Sage/Singular. 3912 ''' 3913 c = self.elem.leadingBaseCoefficient(); 3914 return RingElem(c);
3915
3916 - def lt(self):
3917 '''Leading term of a polynomial. 3918 3919 Compatibility method for Sage/Singular. 3920 Note: the meaning of lt and lm is swapped compared to JAS. 3921 ''' 3922 ev = self.elem.leadingMonomial(); 3923 return Monomial(ev);
3924
3925 - def degree(self):
3926 '''Degree of a polynomial. 3927 ''' 3928 try: 3929 ev = self.elem.degree(); 3930 #ev = self.elem.totalDegree(); 3931 except: 3932 return None; 3933 return ev;
3934
3935 - def base_ring(self):
3936 '''Coefficient ring of a polynomial. 3937 ''' 3938 try: 3939 ev = self.elem.ring.coFac; 3940 except: 3941 return None; 3942 return RingElem(ev);
3943
3944 - def is_field(self):
3945 '''Test if this RingElem is field. 3946 ''' 3947 return self.elem.isField();
3948
3949 - def monomials(self):
3950 '''All monomials of a polynomial. 3951 3952 Compatibility method for Sage/Singular. 3953 ''' 3954 ev = self.elem.getMap().keySet(); 3955 return ev;
3956
3957 - def divides(self,other):
3958 '''Test if self divides other. 3959 3960 Compatibility method for Sage/Singular. 3961 ''' 3962 [s,o] = coercePair(self,other); 3963 return o.elem.remainder( s.elem ).isZERO();
3964
3965 - def ideal(self,list):
3966 '''Create an ideal. 3967 3968 Compatibility method for Sage/Singular. 3969 ''' 3970 r = Ring("",ring=self.ring,fast=True); 3971 return r.ideal("",list=list);
3972
3973 - def monomial_quotient(self,a,b,coeff=False):
3974 '''Quotient of ExpVectors. 3975 3976 Compatibility method for Sage/Singular. 3977 ''' 3978 if isinstance(a,RingElem): 3979 a = a.elem; 3980 if isinstance(b,RingElem): 3981 b = b.elem; 3982 if coeff == False: 3983 if isinstance(a,GenPolynomial): 3984 return RingElem( a.divide(b) ); 3985 else: 3986 return RingElem( GenPolynomial(self.ring, a.subtract(b)) ); 3987 else: 3988 # assume JAS Monomial 3989 c = a.coefficient().divide(b.coefficient()); 3990 e = a.exponent().subtract(b.exponent()) 3991 return RingElem( GenPolynomial(self.ring, c, e) );
3992
3993 - def monomial_divides(self,a,b):
3994 '''Test divide of ExpVectors. 3995 3996 Compatibility method for Sage/Singular. 3997 ''' 3998 #print "JAS a = " + str(a) + ", b = " + str(b); 3999 if isinstance(a,RingElem): 4000 a = a.elem; 4001 if isinstance(a,GenPolynomial): 4002 a = a.leadingExpVector(); 4003 if not isinstance(a,ExpVector): 4004 raise ValueError, "No ExpVector a given " + str(a) + ", " + str(b) 4005 if b == None: 4006 return False; 4007 if isinstance(b,RingElem): 4008 b = b.elem; 4009 if isinstance(b,GenPolynomial): 4010 b = b.leadingExpVector(); 4011 if not isinstance(b,ExpVector): 4012 raise ValueError, "No ExpVector b given " + str(a) + ", " + str(b) 4013 return a.divides(b);
4014
4015 - def monomial_pairwise_prime(self,e,f):
4016 '''Test if ExpVectors are pairwise prime. 4017 4018 Compatibility method for Sage/Singular. 4019 ''' 4020 if isinstance(e,RingElem): 4021 e = e.elem; 4022 if isinstance(f,RingElem): 4023 f = f.elem; 4024 # assume JAS ExpVector 4025 c = e.gcd(f); 4026 return c.isZERO();
4027
4028 - def monomial_lcm(self,e,f):
4029 '''Lcm of ExpVectors. 4030 4031 Compatibility method for Sage/Singular. 4032 ''' 4033 if isinstance(e,RingElem): 4034 e = e.elem; 4035 if isinstance(f,RingElem): 4036 f = f.elem; 4037 # assume JAS ExpVector 4038 c = e.lcm(f); 4039 return c;
4040
4041 - def reduce(self,F):
4042 '''Compute a normal form of self with respect to F. 4043 4044 Compatibility method for Sage/Singular. 4045 ''' 4046 s = self.elem; 4047 Fe = [ e.elem for e in F ]; 4048 if self.ring.coFac.isField(): 4049 n = ReductionSeq().normalform(Fe,s); 4050 else: 4051 n = PseudoReductionSeq().normalform(Fe,s); 4052 return RingElem(n);
4053 4054 #---------------- 4055 # End of compatibility methods 4056 #---------------- 4057 4058
4059 -class Order(TermOrderByName):
4060 '''Collection of JAS and other CAS term order names. 4061 4062 Defines names for TermOrders. 4063 See U{TermOrderByName<http://krum.rz.uni-mannheim.de/jas/doc/api/edu/jas/poly/TermOrderByName.html>}. 4064 '''
4065 # empty 4066 4067
4068 -class PolyRing(Ring):
4069 '''Represents a JAS polynomial ring: GenPolynomialRing. 4070 4071 Provides more convenient constructor. 4072 Then returns a Ring. 4073 4074 Example of the construction a polynomial ring over the 4075 rational numbers QQ() in the variables 'x' and 'y', together 4076 with the input of a polynomial (x+y)**3. 4077 >>> from jas import PolyRing, QQ 4078 >>> r = PolyRing(QQ(),"x,y") 4079 globally defined variables: one, x, y 4080 4081 The example works with p = (x+y)**3, but in doctests the 4082 full notation r.x and r.y must be used for x respectively y. 4083 >>> p = (r.x+r.y)**3 4084 >>> print p 4085 ( y**3 + 3 * x * y**2 + 3 * x**2 * y + x**3 ) 4086 4087 ''' 4088
4089 - def __init__(self,coeff,vars,order=Order.IGRLEX):
4090 '''Ring constructor. 4091 4092 coeff = factory for coefficients, 4093 vars = string with variable names, 4094 order = term order or weight matrix. 4095 ''' 4096 if coeff == None: 4097 raise ValueError, "No coefficient given." 4098 cf = coeff; 4099 if isinstance(coeff,RingElem): 4100 cf = coeff.elem.factory(); 4101 if isinstance(coeff,Ring): 4102 cf = coeff.ring; 4103 if vars == None: 4104 raise ValueError, "No variable names given." 4105 names = vars; 4106 if isinstance(vars,PyString): 4107 names = GenPolynomialTokenizer.variableList(vars); 4108 nv = len(names); 4109 to = Order.IGRLEX; 4110 if isinstance(order,TermOrder): 4111 to = order; 4112 if isinstance(order,PyList) or isinstance(order,PyTuple): 4113 #print "order = " + str(order); 4114 to = TermOrder.reverseWeight(order); 4115 tring = GenPolynomialRing(cf,nv,to,names); 4116 self.ring = tring; 4117 Ring.__init__(self,ring=tring)
4118
4119 - def __str__(self):
4120 '''Create a string representation. 4121 ''' 4122 return self.ring.toScript();
4123 4124 lex = Order.INVLEX 4125 '''Abreviation for INVLEX. 4126 ''' 4127 4128 grad = Order.IGRLEX 4129 '''Abreviation for IGRLEX. 4130 '''
4131 4132
4133 -class SolvPolyRing(SolvableRing):
4134 '''Represents a JAS solvable polynomial ring: GenSolvablePolynomialRing. 4135 4136 Provides more convenient constructor. 4137 Then returns a Ring. 4138 ''' 4139
4140 - def __init__(self,coeff,vars,order=Order.IGRLEX,rel=[]):
4141 '''Ring constructor. 4142 4143 coeff = factory for coefficients, 4144 vars = string with variable names, 4145 order = term order, 4146 rel = triple list of relations. (e,f,p,...) with e * f = p as relation 4147 and e, f and p are commutative polynomials. 4148 ''' 4149 if coeff == None: 4150 raise ValueError, "No coefficient given." 4151 cf = coeff; 4152 if isinstance(coeff,RingElem): 4153 cf = coeff.elem.factory(); 4154 if isinstance(coeff,Ring): 4155 cf = coeff.ring; 4156 if vars == None: 4157 raise ValueError, "No variable names given." 4158 names = vars; 4159 if isinstance(vars,PyString): 4160 names = GenPolynomialTokenizer.variableList(vars); 4161 nv = len(names); 4162 #to = PolyRing.lex; 4163 to = Order.IGRLEX; 4164 if isinstance(order,TermOrder): 4165 to = order; 4166 L = []; 4167 for x in rel: 4168 if isinstance(x,RingElem): 4169 x = x.elem; 4170 L.append(x); 4171 constSolv = False; 4172 for i in range(0,len(L),3): 4173 #print "L[i+1] = " + str(L[i+1]); 4174 if L[i+1].isConstant(): 4175 constSolv = True; 4176 cfs = cf.toScript(); 4177 if cfs[0] == "0": 4178 cfs = cf.toScriptFactory(); 4179 recSolv = isinstance(cf,GenPolynomialRing); 4180 recSolvWord = isinstance(cf,GenWordPolynomialRing); 4181 resWord = isinstance(cf,WordResidueRing); 4182 quotSolv = isinstance(cf,SolvableQuotientRing); 4183 resSolv = isinstance(cf,SolvableResidueRing); 4184 locSolv = isinstance(cf,SolvableLocalRing); 4185 locresSolv = isinstance(cf,SolvableLocalResidueRing); 4186 if recSolv and not constSolv: 4187 recSolv = False; 4188 #print "cf = " + str(cf.getClass().getSimpleName()) + ", quotSolv = " + str(quotSolv) + ", recSolv = " + str(recSolv); 4189 if recSolv: 4190 ring = RecSolvablePolynomialRing(cf,nv,to,names); 4191 table = ring.table; 4192 coeffTable = ring.coeffTable; 4193 else: 4194 if resSolv: 4195 #ring = ResidueSolvablePolynomialRing(cf,nv,to,names); 4196 ring = QLRSolvablePolynomialRing(cf,nv,to,names); 4197 table = ring.table; 4198 coeffTable = ring.polCoeff.coeffTable; 4199 else: 4200 if recSolvWord: 4201 print "RecSolvableWordPolynomialRing: " + cfs; 4202 ring = RecSolvableWordPolynomialRing(cf,nv,to,names); 4203 table = ring.table; 4204 coeffTable = ring.coeffTable; 4205 else: 4206 if resWord: 4207 print "ResWordSolvablePolynomialRing: " + cfs; 4208 ring = GenSolvablePolynomialRing.new(cf,nv,to,names); 4209 #ring = RecSolvableWordPolynomialRing.new(cf,nv,to,names); 4210 #ring = QLRSolvablePolynomialRing.new(cf,nv,to,names); 4211 print "ring = " + str(ring.toScript()); 4212 table = ring.table; 4213 #coeffTable = ring.polCoeff.coeffTable; 4214 #coeffTable = ring.coeffTable; 4215 else: 4216 if quotSolv: 4217 #ring = QuotSolvablePolynomialRing(cf,nv,to,names); 4218 ring = QLRSolvablePolynomialRing(cf,nv,to,names); 4219 table = ring.table; 4220 coeffTable = ring.polCoeff.coeffTable; 4221 else: 4222 if locSolv: 4223 #ring = LocalSolvablePolynomialRing(cf,nv,to,names); 4224 ring = QLRSolvablePolynomialRing(cf,nv,to,names); 4225 table = ring.table; 4226 coeffTable = ring.polCoeff.coeffTable; 4227 else: 4228 if locresSolv: 4229 ring = QLRSolvablePolynomialRing(cf,nv,to,names); 4230 table = ring.table; 4231 coeffTable = ring.polCoeff.coeffTable; 4232 else: 4233 ring = GenSolvablePolynomialRing(cf,nv,to,names); 4234 table = ring.table; 4235 coeffTable = table; 4236 #print "rel = " + str(L); 4237 for i in range(0,len(L),3): 4238 print "adding relation: " + str(L[i]) + " * " + str(L[i+1]) + " = " + str(L[i+2]); 4239 if L[i+1].isConstant(): 4240 if recSolv: 4241 coeffTable.update( L[i], L[i+1], L[i+2] ); 4242 else: 4243 if resSolv: 4244 coeffTable.update(ring.toPolyCoefficients(L[i]), 4245 ring.toPolyCoefficients(L[i+1]), 4246 ring.toPolyCoefficients(L[i+2]) ); 4247 else: 4248 if recSolvWord: 4249 coeffTable.update(L[i],L[i+1],L[i+2]); 4250 else: 4251 if resWord: 4252 print "cf = " + cfs; 4253 #coeffTable.update(L[i],L[i+1],L[i+2]); 4254 else: 4255 if quotSolv: 4256 coeffTable.update(ring.toPolyCoefficients(L[i]), 4257 ring.toPolyCoefficients(L[i+1]), 4258 ring.toPolyCoefficients(L[i+2]) ); 4259 else: 4260 if locSolv: 4261 coeffTable.update(ring.toPolyCoefficients(L[i]), 4262 ring.toPolyCoefficients(L[i+1]), 4263 ring.toPolyCoefficients(L[i+2]) ); 4264 else: 4265 if locresSolv: 4266 coeffTable.update(ring.toPolyCoefficients(L[i]), 4267 ring.toPolyCoefficients(L[i+1]), 4268 ring.toPolyCoefficients(L[i+2]) ); 4269 else: 4270 #print "L[i], L[i+1], L[i+2]: " + str(L[i]) + ", " + str(L[i+1]) + ", " + str(L[i+2]); 4271 table.update( L[i], L[i+1], L[i+2] ); 4272 if locresSolv or locSolv or quotSolv or resSolv or resWord: 4273 #print "ring.polCoeff.table " + str(ring.polCoeff.table.toScript()); 4274 ring.polCoeff.table.update( ring.toPolyCoefficients(L[i]), 4275 ring.toPolyCoefficients(L[i+1]), 4276 ring.toPolyCoefficients(L[i+2]) ); 4277 4278 self.ring = ring; 4279 SolvableRing.__init__(self,ring=self.ring)
4280
4281 - def __str__(self):
4282 '''Create a string representation. 4283 ''' 4284 return self.ring.toScript();
4285 4286
4287 -class EF:
4288 '''Extension field builder. 4289 4290 Construction of extension field towers according to the builder pattern. 4291 ''' 4292
4293 - def __init__(self,base):
4294 '''Constructor to set base field. 4295 ''' 4296 if isinstance(base,RingElem): 4297 #factory = base.elem; 4298 factory = base.ring; 4299 else: 4300 factory = base; 4301 try: 4302 factory = self.factory.factory(); 4303 except: 4304 pass 4305 print "extension field factory: " + factory.toScript(); # + " :: " + factory.toString(); 4306 #print "d type(%s) = %s" % (factory,type(factory)); 4307 if isinstance(factory,ExtensionFieldBuilder): 4308 self.builder = factory; 4309 else: 4310 self.builder = ExtensionFieldBuilder(factory);
4311
4312 - def __str__(self):
4313 '''Create a string representation. 4314 ''' 4315 return str(self.builder.toScript());
4316
4317 - def extend(self,vars,algebraic=None):
4318 '''Create an extension field. 4319 4320 If algebraic is given as string expression, then an algebraic 4321 extension field is constructed, else a transcendental 4322 extension field is constructed. 4323 ''' 4324 if algebraic == None: 4325 ef = self.builder.transcendentExtension(vars); 4326 else: 4327 ef = self.builder.algebraicExtension(vars,algebraic); 4328 return EF(ef.build());
4329
4330 - def realExtend(self,vars,algebraic,interval):
4331 '''Create a real extension field. 4332 4333 Construct a real algebraic extension field with an isolating interval for a real root. 4334 ''' 4335 ef = self.builder.realAlgebraicExtension(vars,algebraic,interval); 4336 return EF(ef.build());
4337
4338 - def complexExtend(self,vars,algebraic,rectangle):
4339 '''Create a complex extension field. 4340 4341 Construct a complex algebraic extension field with an isolating rectangle for a complex root. 4342 ''' 4343 ef = self.builder.complexAlgebraicExtension(vars,algebraic,rectangle); 4344 return EF(ef.build());
4345
4346 - def polynomial(self,vars):
4347 '''Create an polynomial ring extension. 4348 ''' 4349 ef = self.builder.polynomialExtension(vars); 4350 return EF(ef.build());
4351
4352 - def build(self):
4353 '''Get extension field tower. 4354 4355 ''' 4356 rf = self.builder.build(); 4357 if isinstance(rf,GenPolynomialRing): 4358 return PolyRing(rf.coFac,rf.getVars(),rf.tord); 4359 else: 4360 return RingElem(rf.getZERO());
4361 4362
4363 -class WordRing(Ring):
4364 '''Represents a JAS free non-commutative polynomial ring: GenWordPolynomialRing. 4365 4366 Has a method to create word ideals. 4367 <b>Note:</b> watch your step: check that jython does not reorder multiplication. 4368 ''' 4369
4370 - def __init__(self,ringstr="",ring=None):
4371 '''Word polynomial ring constructor. 4372 ''' 4373 if ring == None: 4374 #raise ValueError, "parse of word polynomials not implemented" 4375 sr = StringReader( ringstr ); 4376 tok = RingFactoryTokenizer(sr); 4377 pfac = tok.nextPolynomialRing(); 4378 wfac = GenWordPolynomialRing(pfac); 4379 #list = tok.nextWordPolynomialList(wfac); 4380 self.ring = wfac; 4381 else: 4382 if isinstance(ring,Ring): 4383 self.ring = ring.ring; 4384 else: 4385 self.ring = ring;
4386
4387 - def __str__(self):
4388 '''Create a string representation. 4389 ''' 4390 return str(self.ring.toScript());
4391
4392 - def ideal(self,ringstr="",list=None):
4393 '''Create a word ideal. 4394 ''' 4395 return WordPolyIdeal(self,ringstr,list);
4396
4397 - def one(self):
4398 '''Get the one of the word polynomial ring. 4399 ''' 4400 return RingElem( self.ring.getONE() );
4401
4402 - def zero(self):
4403 '''Get the zero of the word polynomial ring. 4404 ''' 4405 return RingElem( self.ring.getZERO() );
4406
4407 - def random(self,n):
4408 '''Get a random word polynomial. 4409 ''' 4410 return RingElem( self.ring.random(n) );
4411
4412 - def random(self,k,l,d):
4413 '''Get a random word polynomial. 4414 ''' 4415 return RingElem( self.ring.random(k,l,d) );
4416
4417 - def element(self,poly):
4418 '''Create an element from a string or object. 4419 ''' 4420 if not isinstance(poly,str): 4421 try: 4422 if self.ring == poly.ring: 4423 return RingElem(poly); 4424 except Exception, e: 4425 pass 4426 poly = str(poly); 4427 I = WordPolyIdeal(self, "( " + poly + " )"); # should work 4428 list = I.list; 4429 if len(list) > 0: 4430 return RingElem( list[0] );
4431 4432
4433 -class WordPolyRing(WordRing):
4434 '''Represents a JAS free non-commutative polynomial ring: GenWordPolynomialRing. 4435 4436 Provides more convenient constructor. 4437 Then returns a Ring. 4438 <b>Note:</b> watch your step: check that jython does not reorder multiplication. 4439 ''' 4440
4441 - def __init__(self,coeff,vars):
4442 '''Ring constructor. 4443 4444 coeff = factory for coefficients, 4445 vars = string with variable names. 4446 ''' 4447 if coeff == None: 4448 raise ValueError, "No coefficient given." 4449 cf = coeff; 4450 if isinstance(coeff,RingElem): 4451 cf = coeff.elem.factory(); 4452 if isinstance(coeff,Ring): 4453 cf = coeff.ring; 4454 if vars == None: 4455 raise ValueError, "No variable names given." 4456 names = vars; 4457 if isinstance(vars,PyString): 4458 names = GenPolynomialTokenizer.variableList(vars); 4459 wf = WordFactory(names); 4460 ring = GenWordPolynomialRing(cf,wf); 4461 self.ring = ring;
4462
4463 - def __str__(self):
4464 '''Create a string representation. 4465 ''' 4466 return self.ring.toScript();
4467 4468
4469 -class WordPolyIdeal:
4470 '''Represents a JAS word polynomial ideal. 4471 4472 Methods for two-sided Groebner basees and others. 4473 <b>Note:</b> watch your step: check that jython does not reorder multiplication. 4474 ''' 4475
4476 - def __init__(self,ring,ringstr="",list=None):
4477 '''Constructor for an ideal in a word polynomial ring. 4478 ''' 4479 self.ring = ring; 4480 if list == None: 4481 #raise ValueError, "parse of word polynomials not implemented" 4482 sr = StringReader( ringstr ); 4483 tok = GenPolynomialTokenizer(sr); 4484 self.list = tok.nextWordPolynomialList(ring.ring); 4485 else: 4486 if isinstance(list,WordPolyIdeal): 4487 self.list = list.list; 4488 self.ideal = list; 4489 else: 4490 self.list = pylist2arraylist(list,rec=1); 4491 self.ideal = jas.application.WordIdeal(ring.ring, self.list);
4492
4493 - def __str__(self):
4494 '''Create a string representation. 4495 ''' 4496 #ll = [ e.toScript() for e in self.list ] 4497 #return "( " + ", ".join(ll) + " )"; 4498 return self.ideal.toScript();
4499
4500 - def GB(self):
4501 '''Compute a two-sided Groebner base. 4502 ''' 4503 return self.twosidedGB();
4504
4505 - def twosidedGB(self):
4506 '''Compute a two-sided Groebner base. 4507 ''' 4508 cofac = self.ring.ring.coFac; 4509 F = self.ideal.list; 4510 kind = ""; 4511 t = System.currentTimeMillis(); 4512 if cofac.isField() or not cofac.isCommutative(): 4513 G = self.ideal.GB(); 4514 kind = "field|nocom" 4515 else: 4516 if isinstance(cofac,GenPolynomialRing): # and cofac.isCommutative(): 4517 G = WordGroebnerBasePseudoRecSeq(cofac).GB(F); 4518 self.ideal = WordIdeal(self.ring.ring, G); 4519 kind = "pseudorec" 4520 else: 4521 G = WordGroebnerBasePseudoSeq(cofac).GB(F); 4522 self.ideal = WordIdeal(self.ring.ring, G); 4523 kind = "pseudo" 4524 t = System.currentTimeMillis() - t; 4525 print "sequential(%s) twosidedGB executed in %s ms" % (kind, t); 4526 return self;
4527
4528 - def isGB(self):
4529 '''Test if this is a two-sided Groebner base. 4530 ''' 4531 return self.isTwosidedGB();
4532
4533 - def isTwosidedGB(self):
4534 '''Test if this is a two-sided Groebner base. 4535 ''' 4536 cofac = self.ring.ring.coFac; 4537 F = self.ideal.list; 4538 kind = ""; 4539 t = System.currentTimeMillis(); 4540 if cofac.isField() or not cofac.isCommutative(): 4541 b = self.ideal.isGB(); 4542 kind = "field|nocom" 4543 else: 4544 if isinstance(cofac,GenPolynomialRing): 4545 b = WordGroebnerBasePseudoRecSeq(cofac).isGB(F); 4546 kind = "pseudorec" 4547 else: 4548 b = WordGroebnerBasePseudoSeq(cofac).isGB(F); 4549 kind = "pseudo" 4550 t = System.currentTimeMillis() - t; 4551 print "sequential(%s) isTwosidedGB executed in %s ms" % (kind, t); 4552 return b;
4553
4554 - def __cmp__(self, other):
4555 '''Compare two ideals. 4556 ''' 4557 if not isinstance(other, WordPolyIdeal): 4558 return False; 4559 s = self.ideal; 4560 t = other.ideal; 4561 return s.compareTo(t);
4562
4563 - def __eq__(self,other):
4564 '''Test if two ideals are equal. 4565 ''' 4566 if not isinstance(other, WordPolyIdeal): 4567 return False; 4568 s = self.ideal; 4569 t = other.ideal; 4570 return s.equals(t)
4571
4572 - def sum(self,other):
4573 '''Compute the sum of this and the other ideal. 4574 ''' 4575 s = self.ideal; 4576 t = other.ideal; 4577 N = s.sum(t); 4578 return WordIdeal(self.ring, "", N);
4579 4580
4581 -def WRC(ideal,r=0):
4582 '''Create JAS polynomial WordResidue as ring element. 4583 ''' 4584 #print "ideal = " + str(ideal); 4585 if ideal == None: # does not work 4586 print "ideal = " + str(ideal); 4587 if False: 4588 raise ValueError, "No ideal given." 4589 if isinstance(ideal,WordPolyIdeal): 4590 ideal = ideal.ideal 4591 #ideal.doGB(); 4592 if not isinstance(ideal,WordIdeal): 4593 raise ValueError, "No ideal given." 4594 #print "ideal.getList().get(0).ring.ideal = %s" % ideal.getList().get(0).ring.ideal; 4595 if isinstance(ideal.getList().get(0).ring,WordResidueRing): 4596 rc = WordResidueRing( ideal.getList().get(0).ring.ideal ); 4597 else: 4598 rc = WordResidueRing(ideal); 4599 if isinstance(r,RingElem): 4600 r = r.elem; 4601 if r == 0: 4602 r = WordResidue(rc); 4603 else: 4604 r = WordResidue(rc,r); 4605 return RingElem(r);
4606 4607 4608 # doctest: 4609 if __name__ == '__main__': 4610 import doctest, sys 4611 doctest.testmod(sys.modules[__name__]) 4612