def load_model(model_filename): r""" Read an input ODE system. INPUT: - ``model_filename`` -- string with the model filename OUTPUT: - ``f`` -- list of multivariate polynomials which describes the system of ODEs, each component in the polynomial ring `\mathbb{Q}[x_1,\ldots,x_n]` - ``n`` -- integer, dimension of f - ``k`` -- integer, degree of f """ from sage.structure.sage_object import load # should define n and f load(model_filename) k = max([fi.degree() for fi in f]) return [f, n, k]
def zeta_zeros(): r""" List of the imaginary parts of the first 2,001,052 zeros of the Riemann zeta function, accurate to within 4e-9. In order to use ``zeta_zeros()``, you will need to install the optional Odlyzko database package:: sage -i database_odlyzko_zeta You can see a list of all available optional packages with ``sage --optional``. REFERENCES: - http://www.dtc.umn.edu/~odlyzko/zeta_tables/index.html EXAMPLES: The following example prints the imaginary part of the 13th nontrivial zero of the Riemann zeta function:: sage: zz = zeta_zeros() # optional - database_odlyzko_zeta sage: zz[12] # optional - database_odlyzko_zeta 59.347044003 sage: len(zz) # optional - database_odlyzko_zeta 2001052 """ sobj = os.path.join(SAGE_SHARE, 'odlyzko', 'zeros.sobj') verbose("Loading Odlyzko database from " + sobj) return load(sobj)
def db(name): r""" Load object with given name from the Sage database. Use x.db(name) or db_save(x, name) to save objects to the database. The database directory is ``$HOME/.sage/db``. """ return load('%s/%s'%(SAGE_DB,name))
def _sage_(self): """ Return local copy of self. EXAMPLE:: sage: sr = mq.SR(allow_zero_inversions=True) sage: F,s = sr.polynomial_system() sage: F == sage0(F)._sage_() True """ P = self.parent() if P.is_remote(): P.eval('save(%s, "%s")' % (self.name(), P._remote_tmpfile())) P._get_tmpfile_from_server(self) return load(P._local_tmp_file()) else: P.eval('save(%s, "%s")' % (self.name(), P._local_tmpfile())) return load(P._local_tmpfile())
def _sage_(self): """ Return local copy of self. EXAMPLE:: sage: sr = mq.SR(allow_zero_inversions=True) sage: F,s = sr.polynomial_system() sage: F == sage0(F)._sage_() True """ P = self.parent() if P.is_remote(): P.eval('save(%s, "%s")'%(self.name(), P._remote_tmpfile())) P._get_tmpfile_from_server(self) return load(P._local_tmp_file()) else: P.eval('save(%s, "%s")'%(self.name(), P._local_tmpfile())) return load(P._local_tmpfile())
def cunningham_prime_factors(): """ List of all the prime numbers occuring in the so called Cunningham table. They occur in the factorization of numbers of type $b^n+1$ or $b^n-1$ with $b \in \{2,3,5,6,7,10,11,12\}$. Data from http://cage.ugent.be/~jdemeyer/cunningham/ """ file = os.path.join(SAGE_SHARE,'cunningham_tables','cunningham_prime_factors.sobj') if os.path.exists(file): return map(Integer,load(file)) else: from warnings import warn warn("You might consider installing the optional package for factoring Cunningham numbers with the following command: ``sage -i cunningham_tables``") return []
def __init__(self): """ Initialize the database. TESTS:: sage: c = ConwayPolynomials() sage: c Frank Luebeck's database of Conway polynomials """ global _conwaydict if _conwaydict is None: if not os.path.exists(_CONWAYDATA): raise RuntimeError('In order to initialize the database, ' + '%s must exist.'%_CONWAYDATA) from sage.structure.sage_object import load _conwaydict = load(_CONWAYDATA) self._store = _conwaydict
def get(self, S, var='a'): """ Return all fields in the database ramified exactly at the primes in S. INPUT: - ``S`` - list or set of primes, or a single prime - ``var`` - the name used for the generator of the number fields (default 'a'). EXAMPLES:: sage: J = JonesDatabase() # optional - database_jones_numfield sage: J.get(163, var='z') # optional - database_jones_numfield [Number Field in z with defining polynomial x^2 + 163, Number Field in z with defining polynomial x^3 - x^2 - 54*x + 169, Number Field in z with defining polynomial x^4 - x^3 - 7*x^2 + 2*x + 9] sage: J.get([3, 4]) # optional - database_jones_numfield Traceback (most recent call last): ... ValueError: S must be a list of primes """ if self.root is None: if os.path.exists(JONESDATA + "/jones.sobj"): self.root = load(JONESDATA + "/jones.sobj") else: raise RuntimeError( "You must install the Jones database optional package.") try: S = list(S) except TypeError: S = [S] if not all([p.is_prime() for p in S]): raise ValueError("S must be a list of primes") S.sort() s = tuple(S) if s not in self.root: return [] return [NumberField(f, var, check=False) for f in self.root[s]]
def get(self, S, var='a'): """ Return all fields in the database ramified exactly at the primes in S. INPUT: - ``S`` - list or set of primes, or a single prime - ``var`` - the name used for the generator of the number fields (default 'a'). EXAMPLES:: sage: J = JonesDatabase() # optional - database_jones_numfield sage: J.get(163, var='z') # optional - database_jones_numfield [Number Field in z with defining polynomial x^2 + 163, Number Field in z with defining polynomial x^3 - x^2 - 54*x + 169, Number Field in z with defining polynomial x^4 - x^3 - 7*x^2 + 2*x + 9] sage: J.get([3, 4]) # optional - database_jones_numfield Traceback (most recent call last): ... ValueError: S must be a list of primes """ if self.root is None: if os.path.exists(JONESDATA+ "/jones.sobj"): self.root = load(JONESDATA+ "/jones.sobj") else: raise RuntimeError, "You must install the Jones database optional package." try: S = list(S) except TypeError: S = [S] if not all([p.is_prime() for p in S]): raise ValueError, "S must be a list of primes" S.sort() s = tuple(S) if not self.root.has_key(s): return [] return [NumberField(f, var, check=False) for f in self.root[s]]
from superpartition import Superpartitions from sym_superfunct import SymSuperfunctionsAlgebra from sage.rings.rational_field import QQ from sage.structure.sage_object import load load('superspace.py') def super_init(): """Inject the basis and the coeff ring.""" global QQqta global Sym global Sparts QQqta = QQ['q', 't', 'alpha'].fraction_field() print("Defining QQqta as " + str(QQqta)) Sym = SymSuperfunctionsAlgebra(QQqta) print("Defining Sym as " + str(Sym)) global p, m, e, h p = Sym.Powersum() m = Sym.Monomial() e = Sym.Elementary() h = Sym.Homogeneous() print("Defining m, p, e, h as monomial, powersum, elementary and" "homogensous bases") Sparts = Superpartitions() print("Defining Sparts as " + str(Sparts))
def __call__(self, f, inputs): """ Parallel iterator using ``fork()``. INPUT: - ``f`` -- a Python function that need not be pickleable or anything else! - ``inputs`` -- a list of pickleable pairs ``(args, kwds)``, where ``args`` is a tuple and ``kwds`` is a dictionary. OUTPUT: EXAMPLES:: sage: F = sage.parallel.use_fork.p_iter_fork(2,3) sage: sorted(list( F( (lambda x: x^2), [([10],{}), ([20],{})]))) [(([10], {}), 100), (([20], {}), 400)] sage: sorted(list( F( (lambda x, y: x^2+y), [([10],{'y':1}), ([20],{'y':2})]))) [(([10], {'y': 1}), 101), (([20], {'y': 2}), 402)] """ n = self.ncpus v = list(inputs) import os, sys, signal from sage.structure.sage_object import load from sage.misc.misc import tmp_dir, walltime dir = tmp_dir() timeout = self.timeout # Subprocesses shouldn't inherit unflushed buffers (cf. #11778): sys.stdout.flush() sys.stderr.flush() workers = {} try: while len(v) > 0 or len(workers) > 0: # Spawn up to n subprocesses while len(v) > 0 and len(workers) < n: pid = os.fork() # The way fork works is that pid returns the # nonzero pid of the subprocess for the master # process and returns 0 for the subprocess. if pid: # This is the parent master process. workers[pid] = [v[0], walltime(), ''] del v[0] else: # This is the subprocess. self._subprocess(f, dir, v[0]) if len(workers) > 0: # Now wait for one subprocess to finish and report the result. # However, wait at most the time since the oldest process started. if timeout: def mysig(a, b): raise RuntimeError, "SIGALRM" oldest = min([X[1] for X in workers.values()]) signal.signal(signal.SIGALRM, mysig) signal.alarm( max(int(timeout - (walltime() - oldest)), 1)) try: pid = os.wait()[0] signal.signal(signal.SIGALRM, signal.SIG_IGN) except RuntimeError: signal.signal(signal.SIGALRM, signal.SIG_IGN) # Kill workers that are too old for pid, X in workers.iteritems(): if walltime() - X[1] > timeout: if self.verbose: print( "Killing subprocess %s with input %s which took too long" % (pid, X[0])) sys.stdout.flush() os.kill(pid, 9) X[-1] = ' (timed out)' else: # If the computation was interrupted the pid # might not be in the workers list, in which # case we skip this. if pid in workers: # collect data from process that successfully terminated sobj = os.path.join(dir, '%s.sobj' % pid) if not os.path.exists(sobj): X = "NO DATA" + workers[pid][ -1] # the message field else: X = load(sobj, compress=False) os.unlink(sobj) out = os.path.join(dir, '%s.out' % pid) if not os.path.exists(out): output = "NO OUTPUT" else: output = open(out).read() os.unlink(out) if output.strip(): print output, sys.stdout.flush() yield (workers[pid][0], X) del workers[pid] except Exception, msg: print msg sys.stdout.flush()
def __call__(self, f, inputs): """ Parallel iterator using ``fork()``. INPUT: - ``f`` -- a Python function that need not be pickleable or anything else! - ``inputs`` -- a list of pickleable pairs ``(args, kwds)``, where ``args`` is a tuple and ``kwds`` is a dictionary. OUTPUT: EXAMPLES:: sage: F = sage.parallel.use_fork.p_iter_fork(2,3) sage: sorted(list( F( (lambda x: x^2), [([10],{}), ([20],{})]))) [(([10], {}), 100), (([20], {}), 400)] sage: sorted(list( F( (lambda x, y: x^2+y), [([10],{'y':1}), ([20],{'y':2})]))) [(([10], {'y': 1}), 101), (([20], {'y': 2}), 402)] """ n = self.ncpus v = list(inputs) import os, sys, signal from sage.structure.sage_object import load from sage.misc.misc import tmp_dir, walltime dir = tmp_dir() timeout = self.timeout # Subprocesses shouldn't inherit unflushed buffers (cf. #11778): sys.stdout.flush() sys.stderr.flush() workers = {} try: while len(v) > 0 or len(workers) > 0: # Spawn up to n subprocesses while len(v) > 0 and len(workers) < n: pid = os.fork() # The way fork works is that pid returns the # nonzero pid of the subprocess for the master # process and returns 0 for the subprocess. if pid: # This is the parent master process. workers[pid] = [v[0], walltime(), ''] del v[0] else: # This is the subprocess. self._subprocess(f, dir, v[0]) if len(workers) > 0: # Now wait for one subprocess to finish and report the result. # However, wait at most the time since the oldest process started. if timeout: def mysig(a,b): raise RuntimeError, "SIGALRM" oldest = min([X[1] for X in workers.values()]) signal.signal(signal.SIGALRM, mysig) signal.alarm(max(int(timeout - (walltime()-oldest)), 1)) try: pid = os.wait()[0] signal.signal(signal.SIGALRM, signal.SIG_IGN) except RuntimeError: signal.signal(signal.SIGALRM, signal.SIG_IGN) # Kill workers that are too old for pid, X in workers.iteritems(): if walltime() - X[1] > timeout: if self.verbose: print( "Killing subprocess %s with input %s which took too long" % (pid, X[0]) ) sys.stdout.flush() os.kill(pid,9) X[-1] = ' (timed out)' else: # If the computation was interrupted the pid # might not be in the workers list, in which # case we skip this. if pid in workers: # collect data from process that successfully terminated sobj = os.path.join(dir, '%s.sobj'%pid) if not os.path.exists(sobj): X = "NO DATA" + workers[pid][-1] # the message field else: X = load(sobj, compress=False) os.unlink(sobj) out = os.path.join(dir, '%s.out'%pid) if not os.path.exists(out): output = "NO OUTPUT" else: output = open(out).read() os.unlink(out) if output.strip(): print output, sys.stdout.flush() yield (workers[pid][0], X) del workers[pid] except Exception, msg: print msg sys.stdout.flush()
def __call__(self, f, inputs): """ Parallel iterator using ``fork()``. INPUT: - ``f`` -- a Python function that need not be pickleable or anything else! - ``inputs`` -- a list of pickleable pairs ``(args, kwds)``, where ``args`` is a tuple and ``kwds`` is a dictionary. OUTPUT: EXAMPLES:: sage: F = sage.parallel.use_fork.p_iter_fork(2,3) sage: sorted(list( F( (lambda x: x^2), [([10],{}), ([20],{})]))) [(([10], {}), 100), (([20], {}), 400)] sage: sorted(list( F( (lambda x, y: x^2+y), [([10],{'y':1}), ([20],{'y':2})]))) [(([10], {'y': 1}), 101), (([20], {'y': 2}), 402)] TESTS: The output of functions decorated with :func:parallel is read as a pickle by the parent process. We intentionally break the unpickling and demonstrate that this failure is handled gracefully (an exception is displayed and an empty list is returned):: sage: Polygen = parallel(polygen) sage: list(Polygen([QQ])) [(((Rational Field,), {}), x)] sage: from sage.structure.sage_object import unpickle_override, register_unpickle_override sage: register_unpickle_override('sage.rings.polynomial.polynomial_rational_flint', 'Polynomial_rational_flint', Integer) sage: L = list(Polygen([QQ])) ('__init__() takes at most 2 positional arguments (4 given)', <type 'sage.rings.integer.Integer'>, (Univariate Polynomial Ring in x over Rational Field, [0, 1], False, True)) sage: L [] Fix the unpickling:: sage: del unpickle_override[('sage.rings.polynomial.polynomial_rational_flint', 'Polynomial_rational_flint')] sage: list(Polygen([QQ,QQ])) [(((Rational Field,), {}), x), (((Rational Field,), {}), x)] """ n = self.ncpus v = list(inputs) import os, sys, signal from sage.structure.sage_object import load from sage.misc.all import tmp_dir, walltime dir = tmp_dir() timeout = self.timeout workers = {} try: while len(v) > 0 or len(workers) > 0: # Spawn up to n subprocesses while len(v) > 0 and len(workers) < n: # Subprocesses shouldn't inherit unflushed buffers (cf. #11778): sys.stdout.flush() sys.stderr.flush() pid = os.fork() # The way fork works is that pid returns the # nonzero pid of the subprocess for the master # process and returns 0 for the subprocess. if pid: # This is the parent master process. workers[pid] = [v[0], walltime(), ''] del v[0] else: # This is the subprocess. self._subprocess(f, dir, v[0]) if len(workers) > 0: # Now wait for one subprocess to finish and report the result. # However, wait at most the time since the oldest process started. if timeout: oldest = min([X[1] for X in workers.values()]) alarm(max(timeout - (walltime() - oldest), 0.1)) try: pid = os.wait()[0] cancel_alarm() w = workers.pop(pid) except AlarmInterrupt: cancel_alarm() # Kill workers that are too old for pid, X in workers.iteritems(): if walltime() - X[1] > timeout: if self.verbose: print( "Killing subprocess %s with input %s which took too long" % (pid, X[0])) os.kill(pid, signal.SIGKILL) X[-1] = ' (timed out)' except KeyError: # Some other process exited, not our problem... pass else: # collect data from process that successfully terminated sobj = os.path.join(dir, '%s.sobj' % pid) if not os.path.exists(sobj): X = "NO DATA" + w[-1] # the message field else: X = load(sobj, compress=False) os.unlink(sobj) out = os.path.join(dir, '%s.out' % pid) if not os.path.exists(out): output = "NO OUTPUT" else: output = open(out).read() os.unlink(out) if output.strip(): print output, yield (w[0], X) except Exception as msg: print msg finally: # Clean up all temporary files. try: for X in os.listdir(dir): os.unlink(os.path.join(dir, X)) os.rmdir(dir) except OSError as msg: if self.verbose: print msg # Send "kill -9" signal to workers that are left. if len(workers) > 0: if self.verbose: print "Killing any remaining workers..." sys.stdout.flush() for pid in workers.keys(): try: os.kill(pid, signal.SIGKILL) os.waitpid(pid, 0) except OSError as msg: if self.verbose: print msg
def __call__(self, f, inputs): """ Parallel iterator using ``fork()``. INPUT: - ``f`` -- a Python function that need not be pickleable or anything else! - ``inputs`` -- a list of pickleable pairs ``(args, kwds)``, where ``args`` is a tuple and ``kwds`` is a dictionary. OUTPUT: EXAMPLES:: sage: F = sage.parallel.use_fork.p_iter_fork(2,3) sage: sorted(list( F( (lambda x: x^2), [([10],{}), ([20],{})]))) [(([10], {}), 100), (([20], {}), 400)] sage: sorted(list( F( (lambda x, y: x^2+y), [([10],{'y':1}), ([20],{'y':2})]))) [(([10], {'y': 1}), 101), (([20], {'y': 2}), 402)] TESTS: The output of functions decorated with :func:parallel is read as a pickle by the parent process. We intentionally break the unpickling and demonstrate that this failure is handled gracefully (an exception is displayed and an empty list is returned):: sage: Polygen = parallel(polygen) sage: list(Polygen([QQ])) [(((Rational Field,), {}), x)] sage: from sage.structure.sage_object import unpickle_override, register_unpickle_override sage: register_unpickle_override('sage.rings.polynomial.polynomial_rational_flint', 'Polynomial_rational_flint', Integer) sage: L = list(Polygen([QQ])) ('__init__() takes at most 2 positional arguments (4 given)', <type 'sage.rings.integer.Integer'>, (Univariate Polynomial Ring in x over Rational Field, [0, 1], False, True)) sage: L [] Fix the unpickling:: sage: del unpickle_override[('sage.rings.polynomial.polynomial_rational_flint', 'Polynomial_rational_flint')] sage: list(Polygen([QQ,QQ])) [(((Rational Field,), {}), x), (((Rational Field,), {}), x)] """ n = self.ncpus v = list(inputs) import os, sys, signal from sage.structure.sage_object import load from sage.misc.all import tmp_dir, walltime dir = tmp_dir() timeout = self.timeout workers = {} try: while len(v) > 0 or len(workers) > 0: # Spawn up to n subprocesses while len(v) > 0 and len(workers) < n: # Subprocesses shouldn't inherit unflushed buffers (cf. #11778): sys.stdout.flush() sys.stderr.flush() pid = os.fork() # The way fork works is that pid returns the # nonzero pid of the subprocess for the master # process and returns 0 for the subprocess. if pid: # This is the parent master process. workers[pid] = [v[0], walltime(), ''] del v[0] else: # This is the subprocess. self._subprocess(f, dir, v[0]) if len(workers) > 0: # Now wait for one subprocess to finish and report the result. # However, wait at most the time since the oldest process started. if timeout: oldest = min([X[1] for X in workers.values()]) alarm(max(timeout - (walltime()-oldest), 0.1)) try: pid = os.wait()[0] cancel_alarm() w = workers.pop(pid) except AlarmInterrupt: cancel_alarm() # Kill workers that are too old for pid, X in workers.iteritems(): if walltime() - X[1] > timeout: if self.verbose: print( "Killing subprocess %s with input %s which took too long" % (pid, X[0]) ) os.kill(pid, signal.SIGKILL) X[-1] = ' (timed out)' except KeyError: # Some other process exited, not our problem... pass else: # collect data from process that successfully terminated sobj = os.path.join(dir, '%s.sobj'%pid) if not os.path.exists(sobj): X = "NO DATA" + w[-1] # the message field else: X = load(sobj, compress=False) os.unlink(sobj) out = os.path.join(dir, '%s.out'%pid) if not os.path.exists(out): output = "NO OUTPUT" else: output = open(out).read() os.unlink(out) if output.strip(): print output, yield (w[0], X) except Exception as msg: print msg finally: # Clean up all temporary files. try: for X in os.listdir(dir): os.unlink(os.path.join(dir, X)) os.rmdir(dir) except OSError as msg: if self.verbose: print msg # Send "kill -9" signal to workers that are left. if len(workers) > 0: if self.verbose: print "Killing any remaining workers..." sys.stdout.flush() for pid in workers.keys(): try: os.kill(pid, signal.SIGKILL) os.waitpid(pid, 0) except OSError as msg: if self.verbose: print msg
from os import path from __init__ import * directory = "/".join(path.abspath(__file__).split("/")[:-1]) + "/" from sage.all import * from sage.structure.sage_object import load files = ["theta_trans.sage"] for f in files: load(directory + f)