[BACK]Return to asir.py CVS log [TXT][DIR] Up to [local] / OpenXM / src / sage

Annotation of OpenXM/src/sage/asir.py, Revision 1.1

1.1     ! takayama    1: # $OpenXM$
        !             2: from __future__ import print_function
        !             3: from __future__ import absolute_import
        !             4:
        !             5: import os
        !             6: from .expect import Expect, ExpectElement
        !             7: from sage.misc.misc import verbose
        !             8:
        !             9: class Asir(Expect):
        !            10:     r"""
        !            11:     Interface to the Asir interpreter.
        !            12:
        !            13:     EXAMPLES::
        !            14:
        !            15:         sage: asir.eval("a = [ 1, 1, 2; 3, 5, 8; 13, 21, 33 ]")    # optional - asir
        !            16:         'a =\n\n 1 1 2\n 3 5 8\n 13 21 33\n\n's
        !            17:         sage: asir.eval("b = [ 1; 3; 13]")                         # optional - asir
        !            18:         'b =\n\n 1\n 3\n 13\n\n'
        !            19:         sage: asir.eval("c=a \\ b") # solves linear equation: a*c = b  # optional - asir; random output
        !            20:         'c =\n\n 1\n 7.21645e-16\n -7.21645e-16\n\n'
        !            21:         sage: asir.eval("c")                                 # optional - asir; random output
        !            22:         'c =\n\n 1\n 7.21645e-16\n -7.21645e-16\n\n'
        !            23:     """
        !            24:
        !            25:     def __init__(self, maxread=None, script_subdirectory=None, logfile=None,
        !            26:             server=None, server_tmpdir=None, seed=None, command=None):
        !            27:         """
        !            28:         EXAMPLES::
        !            29:
        !            30:             sage: asir == loads(dumps(asir))
        !            31:             True
        !            32:         """
        !            33:         if command is None:
        !            34:             import os
        !            35:             command = os.getenv('SAGE_ASIR_COMMAND') or 'openxm ox_texmacs --view sage --quiet --noCopyright'
        !            36:         if server is None:
        !            37:             import os
        !            38:             server = os.getenv('SAGE_ASIR_SERVER') or None
        !            39:         Expect.__init__(self,
        !            40:                         name = 'asir',
        !            41:                         # We want the prompt sequence to be unique to avoid confusion with syntax error messages containing >>>
        !            42: #                        prompt = 'asir\:\d+> ',
        !            43:                         prompt = 'asir>',
        !            44: #                        prompt = '',
        !            45:                         # We don't want any pagination of output
        !            46: #                        command = command + " --no-line-editing --silent --eval 'PS2(PS1());more off' --persist",
        !            47:                         command = 'openxm ox_texmacs --view sage --quiet --noCopyright',
        !            48: #                        command = "openxm asir -quiet",
        !            49:                         maxread = maxread,
        !            50:                         server = server,
        !            51:                         server_tmpdir = server_tmpdir,
        !            52:                         script_subdirectory = script_subdirectory,
        !            53:                         restart_on_ctrlc = False,
        !            54:                         verbose_start = False,
        !            55:                         logfile = logfile,
        !            56:                         eval_using_file_cutoff=100)
        !            57:         self._seed = seed
        !            58:
        !            59:     def set_seed(self, seed=None):
        !            60:         """
        !            61:         Sets the seed for the random number generator
        !            62:         for this asir interpreter.
        !            63:
        !            64:         EXAMPLES::
        !            65:
        !            66:             sage: o = Asir() # optional - asir
        !            67:             sage: o.set_seed(1) # optional - asir
        !            68:             1
        !            69:             sage: [o.rand() for i in range(5)] # optional - asir
        !            70:             [ 0.134364,  0.847434,  0.763775,  0.255069,  0.495435]
        !            71:         """
        !            72:         if seed is None:
        !            73:             seed = self.rand_seed()
        !            74:         self.eval("rand('state',%d)" % seed)
        !            75:         self._seed = seed
        !            76:         return seed
        !            77:
        !            78:     def __reduce__(self):
        !            79:         """
        !            80:         EXAMPLES::
        !            81:
        !            82:             sage: asir.__reduce__()
        !            83:             (<function reduce_load_Asir at 0x...>, ())
        !            84:         """
        !            85:         return reduce_load_Asir, tuple([])
        !            86:
        !            87:     def _read_in_file_command(self, filename):
        !            88:         """
        !            89:         EXAMPLES::
        !            90:
        !            91:             sage: filename = tmp_filename()
        !            92:             sage: asir._read_in_file_command(filename)
        !            93:             'source("...");'
        !            94:         """
        !            95:         return 'source("%s");'%filename
        !            96:
        !            97:     def _quit_string(self):
        !            98:         """
        !            99:         EXAMPLES::
        !           100:
        !           101:             sage: asir._quit_string()
        !           102:             'quit;'
        !           103:         """
        !           104:         return '!quit;'
        !           105:
        !           106:     def _install_hints(self):
        !           107:         """
        !           108:         Returns hints on how to install Asir.
        !           109:
        !           110:         EXAMPLES::
        !           111:
        !           112:             sage: print(asir._install_hints())
        !           113:             You must get ...
        !           114:         """
        !           115:         return """
        !           116:         You must get the program "asir" in order to use Asir
        !           117:         from Sage.   You can read all about Asir at
        !           118:                 http://www.gnu.org/software/asir/
        !           119:
        !           120:         LINUX:
        !           121:            Do apt-get install asir as root on your machine (Ubuntu/Debian).
        !           122:            Other Linux systems have asir too.
        !           123:
        !           124:         OS X:
        !           125:            * This website has details on OS X builds of Asir:
        !           126:                     http://wiki.asir.org/Asir_for_MacOS_X
        !           127:            * Darwin ports and fink have Asir as well.
        !           128:         """
        !           129:
        !           130:     def _eval_line(self, line, reformat=True, allow_use_file=False,
        !           131:                    wait_for_prompt=True, restart_if_needed=False):
        !           132:         """
        !           133:         EXAMPLES::
        !           134:
        !           135:             sage: print(asir._eval_line('2+2'))  #optional - asir
        !           136:               ans =  4
        !           137:         """
        !           138:         from pexpect.exceptions import EOF
        !           139:         if not wait_for_prompt:
        !           140:             return Expect._eval_line(self, line)
        !           141:         if line == '':
        !           142:             return ''
        !           143:         if self._expect is None:
        !           144:             self._start()
        !           145:         if allow_use_file and len(line)>3000:
        !           146:             return self._eval_line_using_file(line)
        !           147:         try:
        !           148:             E = self._expect
        !           149:             # debug
        !           150:             # self._synchronize(cmd='1+%s\n')
        !           151:             verbose("in = '%s'"%line,level=3)
        !           152:             E.sendline(line)
        !           153:             E.expect(self._prompt)
        !           154:             out = E.before
        !           155:             # debug
        !           156:             verbose("out = '%s'"%out,level=3)
        !           157:         except EOF:
        !           158:             if self._quit_string() in line:
        !           159:                 return ''
        !           160:         except KeyboardInterrupt:
        !           161:             self._keyboard_interrupt()
        !           162:         try:
        !           163:             if reformat:
        !           164:                 if 'syntax error' in out:
        !           165:                     raise SyntaxError(out)
        !           166:             out = "\n".join(out.splitlines()[1:])
        !           167:             return out
        !           168:         except NameError:
        !           169:             return ''
        !           170:
        !           171:     def _keyboard_interrupt(self):
        !           172:         print("CntrlC: Interrupting %s..."%self)
        !           173:         if self._restart_on_ctrlc:
        !           174:             try:
        !           175:                 self._expect.close(force=1)
        !           176:             except pexpect.ExceptionPexpect as msg:
        !           177:                 raise RuntimeError( "THIS IS A BUG -- PLEASE REPORT. This should never happen.\n" + msg)
        !           178:             self._start()
        !           179:             raise KeyboardInterrupt("Restarting %s (WARNING: all variables defined in previous session are now invalid)"%self)
        !           180:         else:
        !           181:             self._expect.send('\003') # control-c
        !           182:             raise KeyboardInterrupt("Ctrl-c pressed while running %s"%self)
        !           183:
        !           184:     def quit(self, verbose=False):
        !           185:         """
        !           186:         EXAMPLES::
        !           187:
        !           188:             sage: o = Asir()
        !           189:             sage: o._start()    # optional - asir
        !           190:             sage: o.quit(True)  # optional - asir
        !           191:             Exiting spawned Asir process.
        !           192:         """
        !           193:         # Don't bother, since it just hangs in some cases, and it
        !           194:         # isn't necessary, since asir behaves well with respect
        !           195:         # to signals.
        !           196:         if not self._expect is None:
        !           197:             if verbose:
        !           198:                 print("Exiting spawned %s process." % self)
        !           199:         return
        !           200:
        !           201:     def _start(self):
        !           202:         """
        !           203:         Starts the Asir process.
        !           204:
        !           205:         EXAMPLES::
        !           206:
        !           207:             sage: o = Asir()    # optional - asir
        !           208:             sage: o.is_running()  # optional - asir
        !           209:             False
        !           210:             sage: o._start()      # optional - asir
        !           211:             sage: o.is_running()  # optional - asir
        !           212:             True
        !           213:         """
        !           214:         Expect._start(self)
        !           215: #        self.eval("page_screen_output=0;")
        !           216: #        self.eval("format none;")
        !           217:         # set random seed
        !           218: #        self.set_seed(self._seed)
        !           219:
        !           220:     def _equality_symbol(self):
        !           221:         """
        !           222:         EXAMPLES::
        !           223:
        !           224:             sage: asir('0 == 1')  # optional - asir
        !           225:              0
        !           226:             sage: asir('1 == 1')  # optional - asir
        !           227:              1
        !           228:         """
        !           229:         return '=='
        !           230:
        !           231:     def _true_symbol(self):
        !           232:         """
        !           233:         EXAMPLES::
        !           234:
        !           235:             sage: asir('1 == 1')  # optional - asir
        !           236:              1
        !           237:         """
        !           238:         return '1'
        !           239:
        !           240:     def _false_symbol(self):
        !           241:         """
        !           242:         EXAMPLES::
        !           243:
        !           244:             sage: asir('0 == 1')  # optional - asir
        !           245:              0
        !           246:         """
        !           247:         return '0'
        !           248:
        !           249:     def set(self, var, value):
        !           250:         """
        !           251:         Set the variable ``var`` to the given ``value``.
        !           252:
        !           253:         EXAMPLES::
        !           254:
        !           255:             sage: asir.set('x', '2') # optional - asir
        !           256:             sage: asir.get('x') # optional - asir
        !           257:             ' 2'
        !           258:         """
        !           259:         cmd = '%s=%s;'%(var,value)
        !           260:         out = self.eval(cmd)
        !           261:         if out.find("error") != -1 or out.find("Error") != -1:
        !           262:             raise TypeError("Error executing code in Asir\nCODE:\n\t%s\nAsir ERROR:\n\t%s"%(cmd, out))
        !           263:
        !           264:     def get(self, var):
        !           265:         """
        !           266:         Get the value of the variable ``var``.
        !           267:
        !           268:         EXAMPLES::
        !           269:
        !           270:             sage: asir.set('x', '2') # optional - asir
        !           271:             sage: asir.get('x') # optional - asir
        !           272:             ' 2'
        !           273:         """
        !           274:         s = self.eval('%s;'%var)
        !           275:         i = s.find('=')
        !           276:         return s[i+1:]
        !           277:
        !           278:     def clear(self, var):
        !           279:         """
        !           280:         Clear the variable named var.
        !           281:
        !           282:         EXAMPLES::
        !           283:
        !           284:             sage: asir.set('x', '2') # optional - asir
        !           285:             sage: asir.clear('x')    # optional - asir
        !           286:             sage: asir.get('x')      # optional - asir
        !           287:             "error: 'x' undefined near line ... column 1"
        !           288:         """
        !           289:         self.eval('clear %s'%var)
        !           290:
        !           291:     def console(self):
        !           292:         """
        !           293:         Spawn a new Asir command-line session.
        !           294:
        !           295:         This requires that the optional asir program be installed and in
        !           296:         your PATH, but no optional Sage packages need be installed.
        !           297:
        !           298:         EXAMPLES::
        !           299:
        !           300:             sage: asir_console()         # not tested
        !           301:             GNU Asir, version 2.1.73 (i386-apple-darwin8.5.3).
        !           302:             Copyright (C) 2006 John W. Eaton.
        !           303:             ...
        !           304:             asir:1> 2+3
        !           305:             ans = 5
        !           306:             asir:2> [ctl-d]
        !           307:
        !           308:         Pressing ctrl-d exits the asir console and returns you to Sage.
        !           309:         asir, like Sage, remembers its history from one session to
        !           310:         another.
        !           311:         """
        !           312:         asir_console()
        !           313:
        !           314:     def version(self):
        !           315:         """
        !           316:         Return the version of Asir.
        !           317:
        !           318:         OUTPUT: string
        !           319:
        !           320:         EXAMPLES::
        !           321:
        !           322:             sage: v = asir.version()   # optional - asir
        !           323:             sage: v                      # optional - asir; random
        !           324:             '2.13.7'
        !           325:
        !           326:             sage: import re
        !           327:             sage: assert re.match("\d+\.\d+\.\d+", v)  is not None # optional - asir
        !           328:         """
        !           329:         return str(self("version()")).strip()
        !           330:
        !           331:     def solve_linear_system(self, A, b):
        !           332:         r"""
        !           333:         Use asir to compute a solution x to A\*x = b, as a list.
        !           334:
        !           335:         INPUT:
        !           336:
        !           337:         - ``A`` -- mxn matrix A with entries in `\QQ` or `\RR`
        !           338:
        !           339:         - ``b`` -- m-vector b entries in `\QQ` or `\RR` (resp)
        !           340:
        !           341:         OUTPUT: A list x (if it exists) which solves M\*x = b
        !           342:
        !           343:         EXAMPLES::
        !           344:
        !           345:             sage: M33 = MatrixSpace(QQ,3,3)
        !           346:             sage: A   = M33([1,2,3,4,5,6,7,8,0])
        !           347:             sage: V3  = VectorSpace(QQ,3)
        !           348:             sage: b   = V3([1,2,3])
        !           349:             sage: asir.solve_linear_system(A,b)    # optional - asir (and output is slightly random in low order bits)
        !           350:             [-0.33333299999999999, 0.66666700000000001, -3.5236600000000002e-18]
        !           351:
        !           352:         AUTHORS:
        !           353:
        !           354:         - David Joyner and William Stein
        !           355:         """
        !           356:         m = A.nrows()
        !           357:         if m != len(b):
        !           358:             raise ValueError("dimensions of A and b must be compatible")
        !           359:         from sage.matrix.all import MatrixSpace
        !           360:         from sage.rings.all import QQ
        !           361:         MS = MatrixSpace(QQ,m,1)
        !           362:         b  = MS(list(b)) # converted b to a "column vector"
        !           363:         sA = self.sage2asir_matrix_string(A)
        !           364:         sb = self.sage2asir_matrix_string(b)
        !           365:         self.eval("a = " + sA )
        !           366:         self.eval("b = " + sb )
        !           367:         soln = asir.eval("c = a \\ b")
        !           368:         soln = soln.replace("\n\n ","[")
        !           369:         soln = soln.replace("\n\n","]")
        !           370:         soln = soln.replace("\n",",")
        !           371:         sol  = soln[3:]
        !           372:         return eval(sol)
        !           373:
        !           374:
        !           375:     def sage2asir_matrix_string(self, A):
        !           376:         """
        !           377:         Return an asir matrix from a Sage matrix.
        !           378:
        !           379:         INPUT: A Sage matrix with entries in the rationals or reals.
        !           380:
        !           381:         OUTPUT: A string that evaluates to an Asir matrix.
        !           382:
        !           383:         EXAMPLES::
        !           384:
        !           385:             sage: M33 = MatrixSpace(QQ,3,3)
        !           386:             sage: A = M33([1,2,3,4,5,6,7,8,0])
        !           387:             sage: asir.sage2asir_matrix_string(A)   # optional - asir
        !           388:             '[1, 2, 3; 4, 5, 6; 7, 8, 0]'
        !           389:
        !           390:         AUTHORS:
        !           391:
        !           392:         - David Joyner and William Stein
        !           393:         """
        !           394:         return str(A.rows()).replace('), (', '; ').replace('(', '').replace(')','')
        !           395:
        !           396:     def de_system_plot(self, f, ics, trange):
        !           397:         r"""
        !           398:         Plots (using asir's interface to gnuplot) the solution to a
        !           399:         `2\times 2` system of differential equations.
        !           400:
        !           401:         INPUT:
        !           402:
        !           403:
        !           404:         -  ``f`` - a pair of strings representing the
        !           405:            differential equations; The independent variable must be called x
        !           406:            and the dependent variable must be called y.
        !           407:
        !           408:         -  ``ics`` - a pair [x0,y0] such that x(t0) = x0, y(t0)
        !           409:            = y0
        !           410:
        !           411:         -  ``trange`` - a pair [t0,t1]
        !           412:
        !           413:
        !           414:         OUTPUT: a gnuplot window appears
        !           415:
        !           416:         EXAMPLES::
        !           417:
        !           418:             sage: asir.de_system_plot(['x+y','x-y'], [1,-1], [0,2])  # not tested -- does this actually work (on OS X it fails for me -- William Stein, 2007-10)
        !           419:
        !           420:         This should yield the two plots `(t,x(t)), (t,y(t))` on the
        !           421:         same graph (the `t`-axis is the horizontal axis) of the
        !           422:         system of ODEs
        !           423:
        !           424:         .. math::
        !           425:
        !           426:                        x' = x+y, x(0) = 1;\qquad y' = x-y, y(0) = -1,                     \quad\text{for}\quad 0 < t < 2.
        !           427:         """
        !           428:         eqn1 = f[0].replace('x','x(1)').replace('y','x(2)')
        !           429:         eqn2 = f[1].replace('x','x(1)').replace('y','x(2)')
        !           430:         fcn = "function xdot = f(x,t) xdot(1) = %s; xdot(2) = %s; endfunction"%(eqn1, eqn2)
        !           431:         self.eval(fcn)
        !           432:         x0_eqn = "x0 = [%s; %s]"%(ics[0], ics[1])
        !           433:         self.eval(x0_eqn)
        !           434:         t_eqn = "t = linspace(%s, %s, 200)'"%(trange[0], trange[1])
        !           435:         self.eval(t_eqn)
        !           436:         x_eqn = 'x = lsode("f",x0,t);'
        !           437:         self.eval(x_eqn)
        !           438:         self.eval("plot(t,x)")
        !           439:
        !           440:     def _object_class(self):
        !           441:         """
        !           442:         EXAMPLES::
        !           443:
        !           444:             sage: asir._object_class()
        !           445:             <class 'sage.interfaces.asir.AsirElement'>
        !           446:         """
        !           447:         return AsirElement
        !           448:
        !           449:
        !           450: asir_functions = set()
        !           451:
        !           452: def to_complex(asir_string, R):
        !           453:     r"""
        !           454:     Helper function to convert asir complex number
        !           455:
        !           456:     TESTS::
        !           457:
        !           458:         sage: from sage.interfaces.asir import to_complex
        !           459:         sage: to_complex('(0,1)', CDF)
        !           460:         1.0*I
        !           461:         sage: to_complex('(1.3231,-0.2)', CDF)
        !           462:         1.3231 - 0.2*I
        !           463:     """
        !           464:     real, imag = asir_string.strip('() ').split(',')
        !           465:     return R(float(real), float(imag))
        !           466:
        !           467: class AsirElement(ExpectElement):
        !           468:     def _get_sage_ring(self):
        !           469:         r"""
        !           470:         TESTS::
        !           471:
        !           472:             sage: asir('1')._get_sage_ring()  # optional - asir
        !           473:             Real Double Field
        !           474:             sage: asir('I')._get_sage_ring()  # optional - asir
        !           475:             Complex Double Field
        !           476:             sage: asir('[]')._get_sage_ring() # optional - asir
        !           477:             Real Double Field
        !           478:         """
        !           479:         if self.isinteger():
        !           480:             import sage.rings.integer_ring
        !           481:             return sage.rings.integer_ring.ZZ
        !           482:         elif self.isreal():
        !           483:             import sage.rings.real_double
        !           484:             return sage.rings.real_double.RDF
        !           485:         elif self.iscomplex():
        !           486:             import sage.rings.complex_double
        !           487:             return sage.rings.complex_double.CDF
        !           488:         else:
        !           489:             raise TypeError("no Sage ring associated to this element.")
        !           490:
        !           491:     def __nonzero__(self):
        !           492:         r"""
        !           493:         Test whether this element is nonzero.
        !           494:
        !           495:         EXAMPLES::
        !           496:
        !           497:             sage: bool(asir('0'))                 # optional - asir
        !           498:             False
        !           499:             sage: bool(asir('[]'))                # optional - asir
        !           500:             False
        !           501:             sage: bool(asir('[0,0]'))             # optional - asir
        !           502:             False
        !           503:             sage: bool(asir('[0,0,0;0,0,0]'))     # optional - asir
        !           504:             False
        !           505:
        !           506:             sage: bool(asir('0.1'))               # optional - asir
        !           507:             True
        !           508:             sage: bool(asir('[0,1,0]'))           # optional - asir
        !           509:             True
        !           510:             sage: bool(asir('[0,0,-0.1;0,0,0]'))  # optional - asir
        !           511:             True
        !           512:         """
        !           513:         return str(self) != ' [](0x0)' and any(x != '0' for x in str(self).split())
        !           514:
        !           515:     def _matrix_(self, R=None):
        !           516:         r"""
        !           517:         Return Sage matrix from this asir element.
        !           518:
        !           519:         EXAMPLES::
        !           520:
        !           521:             sage: A = asir('[1,2;3,4.5]')     # optional - asir
        !           522:             sage: matrix(A)                     # optional - asir
        !           523:             [1.0 2.0]
        !           524:             [3.0 4.5]
        !           525:             sage: _.base_ring()                 # optional - asir
        !           526:             Real Double Field
        !           527:
        !           528:             sage: A = asir('[I,1;-1,0]')      # optional - asir
        !           529:             sage: matrix(A)                     # optional - asir
        !           530:             [1.0*I   1.0]
        !           531:             [ -1.0   0.0]
        !           532:             sage: _.base_ring()                 # optional - asir
        !           533:             Complex Double Field
        !           534:
        !           535:             sage: A = asir('[1,2;3,4]')       # optional - asir
        !           536:             sage: matrix(ZZ, A)                 # optional - asir
        !           537:             [1 2]
        !           538:             [3 4]
        !           539:             sage: A = asir('[1,2;3,4.5]')     # optional - asir
        !           540:             sage: matrix(RR, A)                 # optional - asir
        !           541:             [1.00000000000000 2.00000000000000]
        !           542:             [3.00000000000000 4.50000000000000]
        !           543:         """
        !           544:         if not self.ismatrix():
        !           545:             raise TypeError('not an asir matrix')
        !           546:         if R is None:
        !           547:             R = self._get_sage_ring()
        !           548:
        !           549:         s = str(self).strip('\n ')
        !           550:         w = [u.strip().split(' ') for u in s.split('\n')]
        !           551:         nrows = len(w)
        !           552:         ncols = len(w[0])
        !           553:
        !           554:         if self.iscomplex():
        !           555:             w = [[to_complex(x,R) for x in row] for row in w]
        !           556:
        !           557:         from sage.matrix.all import MatrixSpace
        !           558:         return MatrixSpace(R, nrows, ncols)(w)
        !           559:
        !           560:     def _vector_(self, R=None):
        !           561:         r"""
        !           562:         Return Sage vector from this asir element.
        !           563:
        !           564:         EXAMPLES::
        !           565:
        !           566:             sage: A = asir('[1,2,3,4]')       # optional - asir
        !           567:             sage: vector(ZZ, A)                 # optional - asir
        !           568:             (1, 2, 3, 4)
        !           569:             sage: A = asir('[1,2.3,4.5]')     # optional - asir
        !           570:             sage: vector(A)                     # optional - asir
        !           571:             (1.0, 2.3, 4.5)
        !           572:             sage: A = asir('[1,I]')           # optional - asir
        !           573:             sage: vector(A)                     # optional - asir
        !           574:             (1.0, 1.0*I)
        !           575:         """
        !           576:         oc = self.parent()
        !           577:         if not self.isvector():
        !           578:             raise TypeError('not an asir vector')
        !           579:         if R is None:
        !           580:             R = self._get_sage_ring()
        !           581:
        !           582:         s = str(self).strip('\n ')
        !           583:         w = s.strip().split(' ')
        !           584:         nrows = len(w)
        !           585:
        !           586:         if self.iscomplex():
        !           587:             w = [to_complex(x, R) for x in w]
        !           588:
        !           589:         from sage.modules.free_module import FreeModule
        !           590:         return FreeModule(R, nrows)(w)
        !           591:
        !           592:     def _scalar_(self):
        !           593:         """
        !           594:         Return Sage scalar from this asir element.
        !           595:
        !           596:         EXAMPLES::
        !           597:
        !           598:             sage: A = asir('2833')      # optional - asir
        !           599:             sage: As = A.sage(); As       # optional - asir
        !           600:             2833.0
        !           601:             sage: As.parent()             # optional - asir
        !           602:             Real Double Field
        !           603:
        !           604:             sage: B = sqrt(A)             # optional - asir
        !           605:             sage: Bs = B.sage(); Bs       # optional - asir
        !           606:             53.2259
        !           607:             sage: Bs.parent()             # optional - asir
        !           608:             Real Double Field
        !           609:
        !           610:             sage: C = sqrt(-A)            # optional - asir
        !           611:             sage: Cs = C.sage(); Cs       # optional - asir
        !           612:             53.2259*I
        !           613:             sage: Cs.parent()             # optional - asir
        !           614:             Complex Double Field
        !           615:         """
        !           616:         if not self.isscalar():
        !           617:             raise TypeError("not an asir scalar")
        !           618:
        !           619:         R = self._get_sage_ring()
        !           620:         if self.iscomplex():
        !           621:             return to_complex(str(self), R)
        !           622:         else:
        !           623:             return R(str(self))
        !           624:
        !           625:     def _sage_(self):
        !           626:         """
        !           627:         Try to parse the asir object and return a sage object.
        !           628:
        !           629:         EXAMPLES::
        !           630:
        !           631:             sage: A = asir('2833')           # optional - asir
        !           632:             sage: A.sage()                     # optional - asir
        !           633:             2833.0
        !           634:             sage: B = sqrt(A)                  # optional - asir
        !           635:             sage: B.sage()                     # optional - asir
        !           636:             53.2259
        !           637:             sage: C = sqrt(-A)                 # optional - asir
        !           638:             sage: C.sage()                     # optional - asir
        !           639:             53.2259*I
        !           640:             sage: A = asir('[1,2,3,4]')      # optional - asir
        !           641:             sage: A.sage()                     # optional - asir
        !           642:             (1.0, 2.0, 3.0, 4.0)
        !           643:             sage: A = asir('[1,2.3,4.5]')    # optional - asir
        !           644:             sage: A.sage()                     # optional - asir
        !           645:             (1.0, 2.3, 4.5)
        !           646:             sage: A = asir('[1,2.3+I,4.5]')  # optional - asir
        !           647:             sage: A.sage()                     # optional - asir
        !           648:             (1.0, 2.3 + 1.0*I, 4.5)
        !           649:         """
        !           650:         if self.isscalar():
        !           651:             return self._scalar_()
        !           652:         elif self.isvector():
        !           653:             return self._vector_()
        !           654:         elif self.ismatrix():
        !           655:             return self._matrix_()
        !           656:         else:
        !           657:             raise NotImplementedError('asir type is not recognized')
        !           658:
        !           659: # An instance
        !           660: asir = Asir()
        !           661:
        !           662: def reduce_load_Asir():
        !           663:     """
        !           664:     EXAMPLES::
        !           665:
        !           666:         sage: from sage.interfaces.asir import reduce_load_Asir
        !           667:         sage: reduce_load_Asir()
        !           668:         Asir
        !           669:     """
        !           670:     return asir
        !           671:
        !           672:
        !           673: def asir_console():
        !           674:     """
        !           675:     Spawn a new Asir command-line session.
        !           676:
        !           677:     This requires that the optional asir program be installed and in
        !           678:     your PATH, but no optional Sage packages need be installed.
        !           679:
        !           680:     EXAMPLES::
        !           681:
        !           682:         sage: asir_console()         # not tested
        !           683:         GNU Asir, version 2.1.73 (i386-apple-darwin8.5.3).
        !           684:         Copyright (C) 2006 John W. Eaton.
        !           685:         ...
        !           686:         asir:1> 2+3
        !           687:         ans = 5
        !           688:         asir:2> [ctl-d]
        !           689:
        !           690:     Pressing ctrl-d exits the asir console and returns you to Sage.
        !           691:     asir, like Sage, remembers its history from one session to
        !           692:     another.
        !           693:     """
        !           694:     from sage.repl.rich_output.display_manager import get_display_manager
        !           695:     if not get_display_manager().is_in_terminal():
        !           696:         raise RuntimeError('Can use the console only in the terminal. Try %%asir magics instead.')
        !           697:     os.system('openxm asir')    # with asir prompt
        !           698: #    os.system('openxm asir -quiet')
        !           699:
        !           700:
        !           701: def asir_version():
        !           702:     """
        !           703:     DEPRECATED: Return the version of Asir installed.
        !           704:
        !           705:     EXAMPLES::
        !           706:
        !           707:         sage: asir_version()    # optional - asir
        !           708:         doctest:...: DeprecationWarning: This has been deprecated. Use
        !           709:         asir.version() instead
        !           710:         See http://trac.sagemath.org/21135 for details.
        !           711:         '...'
        !           712:     """
        !           713:     from sage.misc.superseded import deprecation
        !           714:     deprecation(21135, "This has been deprecated. Use asir.version() instead")
        !           715:     return asir.version()

FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>