Beispiel #1
0
 def _start(self):
     try:
         Expect._start(self)
     except RuntimeError:
         raise RuntimeError, "You must install the optional Kash package to use Kash from Sage."
     # Turn off the annoying timer.
     self.eval('Time(false);')
Beispiel #2
0
    def _start(self):
        """
        Starts the Maxima interpreter.

        EXAMPLES::

            sage: m = Maxima()
            sage: m.is_running()
            False
            sage: m._start()
            sage: m.is_running()
            True

        Test that we can use more than 256MB RAM (see :trac:`6772`)::

            sage: a = maxima(10)^(10^5)
            sage: b = a^600              # long time -- about 10-15 seconds

        """
        Expect._start(self)
        self._sendline(r":lisp (defun tex-derivative (x l r) (tex (if $derivabbrev (tex-dabbrev x) (tex-d x '\\partial)) l r lop rop ))")

        # Don't use ! for factorials (#11539)
        self._sendline(":lisp (remprop 'mfactorial 'grind)")

        # Remove limit on the max heapsize (since otherwise it defaults
        # to 256MB with ECL).
        self._sendline(":lisp (ext:set-limit 'ext:heap-size 0)")
        self._eval_line('0;')

        # set random seed
        self.set_seed(self._seed)
Beispiel #3
0
    def __init__(self, maxread=100, script_subdirectory=None,
                 logfile=None, server=None,server_tmpdir=None,
                 seed=None):
        """
        Initializes the Scilab class.

        EXAMPLES::

            sage: from sage.interfaces.scilab import Scilab
            sage: sci_obj = Scilab()
            sage: del sci_obj
        """
        Expect.__init__(self,
                        name = 'scilab',
                        prompt = '-->',
                        command = "scilab -nw",
                        maxread = maxread,
                        server = server,
                        server_tmpdir = server_tmpdir,
                        script_subdirectory = script_subdirectory,
                        restart_on_ctrlc = False,
                        verbose_start = False,
                        logfile = logfile,
                        eval_using_file_cutoff=100)
        self._seed = seed
Beispiel #4
0
    def __init__(self, maxread=None, script_subdirectory=None, server=None,
            server_tmpdir=None, logfile=None, ulimit=None):
        """
        Create an instance of the Maple interpreter.

        EXAMPLES::

            sage: maple == loads(dumps(maple))
            True
        """
        __maple_iface_opts = [
            'screenwidth=infinity',
            'errorcursor=false',]
        __maple_command = 'maple -t -c "interface({})"'.format(
            ','.join(__maple_iface_opts))
        #errorcursor=false avoids maple command line interface to dump
        #into the editor when an error occurs. Thus pexpect interface
        #is not messed up if a maple error occurs.
        #screenwidth=infinity prevents maple command interface from cutting 
        #your input lines. By doing this, file interface also works in the
        #event that  sage_user_home + sage_tmp_file_stuff exceeds the 
        #length of 79 characters.
        Expect.__init__(self,
                        name = 'maple',
                        prompt = '#-->',
                        command = __maple_command,
                        server = server,
                        server_tmpdir = server_tmpdir,
                        ulimit = ulimit,
                        script_subdirectory = script_subdirectory,
                        restart_on_ctrlc = False,
                        verbose_start = False,
                        logfile = logfile,
                        eval_using_file_cutoff=2048)  # 2048 is
Beispiel #5
0
 def _start(self):
     """
     EXAMPLES::
     
         sage: g = Gap()
         sage: g.is_running()
         False
         sage: g._start()
         sage: g.is_running()
         True
         sage: g.quit()
     """
     if self.__use_workspace_cache and not os.path.exists(WORKSPACE):
         gap_reset_workspace()
     global first_try
     n = self._session_number
     try:
         Expect._start(self, "Failed to start GAP.")
     except Exception, msg:
         if self.__use_workspace_cache and first_try:
             print "A workspace appears to have been corrupted... automatically rebuilding (this is harmless)."
             first_try = False
             self._expect = None
             expect.failed_to_start.remove(self.name())
             gap_reset_workspace(verbose=False)
             Expect._start(self, "Failed to start GAP.")
             self._session_number = n 
             return
         raise RuntimeError, msg
Beispiel #6
0
 def __init__(self, name='axiom', command='axiom -nox -noclef',
              script_subdirectory=None, logfile=None,
              server=None, server_tmpdir=None,
              init_code=[')lisp (si::readline-off)']):
     """
     Create an instance of the Axiom interpreter.
     
     TESTS::
     
         sage: axiom == loads(dumps(axiom))
         True
     """
     eval_using_file_cutoff = 200
     self.__eval_using_file_cutoff = eval_using_file_cutoff
     self._COMMANDS_CACHE = '%s/%s_commandlist_cache.sobj'%(DOT_SAGE, name)
     Expect.__init__(self,
                     name = name,
                     prompt = '\([0-9]+\) -> ',
                     command = command,
                     maxread = 10, 
                     script_subdirectory = script_subdirectory,
                     server=server,
                     server_tmpdir=server_tmpdir,
                     restart_on_ctrlc = False,
                     verbose_start = False,
                     init_code = init_code,
                     logfile = logfile,
                     eval_using_file_cutoff=eval_using_file_cutoff)
     self._prompt_wait = self._prompt
Beispiel #7
0
 def __init__(self, stacksize=10000000,   # 10MB
              maxread=100000, script_subdirectory=None,
              logfile=None,
              server=None,
              server_tmpdir=None,
              init_list_length=1024):
     """
     EXAMPLES::
     
         sage: gp == loads(dumps(gp))
         True
     """
     Expect.__init__(self,
                     name = 'pari',
                     prompt = '\\? ',
                     command = "gp --emacs --fast --quiet --stacksize %s"%stacksize,
                     maxread = maxread,
                     server=server,
                     server_tmpdir=server_tmpdir,
                     script_subdirectory = script_subdirectory,
                     restart_on_ctrlc = False,
                     verbose_start = False,
                     logfile=logfile,
                     eval_using_file_cutoff=50)
     self.__seq = 0
     self.__var_store_len = 0
     self.__init_list_length = init_list_length
Beispiel #8
0
    def _start(self):
        """
        Starts Scilab and sets some options.

        EXAMPLES:
            sage: scilab._start()                       # optional - scilab
        """
        Expect._start(self)
        self.eval("mode(0)")
Beispiel #9
0
    def _start(self, alt_message=None, block_during_init=True):
        r"""
        Restart the underlying process.

        .. note:: This is handled by the Expect class, except that we
           need to reset the breakloop configuration parameter.
        """
        Expect._start(self, alt_message=alt_message, block_during_init=block_during_init)
        self.set_default('breakloop',0)
Beispiel #10
0
 def __init__(self, server=None, server_tmpdir=None, logfile=None):
     Expect.__init__(self,
                     name = 'genus2reduction',
                     prompt = 'enter',
                     command = 'genus2reduction',
                     server = server,
                     server_tmpdir = server_tmpdir,
                     maxread = 10000,
                     restart_on_ctrlc = True,
                     logfile = logfile,
                     verbose_start = False)
Beispiel #11
0
 def __init__(self, maxread=100, script_subdirectory="", logfile=None, server=None, server_tmpdir=None):
     Expect.__init__(self,
                     name = 'mathematica',
                     prompt = 'In[[0-9]+]:=',
                     command = "math",
                     maxread = maxread,
                     server = server,
                     server_tmpdir = server_tmpdir,
                     script_subdirectory = script_subdirectory,
                     verbose_start = False,
                     logfile=logfile,
                     eval_using_file_cutoff=50)
Beispiel #12
0
 def _start(self, *args, **kwds):
     """
     EXAMPLES:
         sage: l = Lisp()
         sage: l.is_running()
         False
         sage: l._start()
         sage: l.is_running()
         True
     """
     Expect._start(self, *args, **kwds)
     self.__in_seq = 1
Beispiel #13
0
 def __init__(self, maxread=None, script_subdirectory=None,
              logfile=None, server=None,server_tmpdir=None):
     Expect.__init__(self,
                     name = 'matlab',
                     prompt = '>> ',
                     command = "sage-native-execute matlab -nodisplay",
                     server = server,
                     server_tmpdir = server_tmpdir,
                     script_subdirectory = script_subdirectory,
                     restart_on_ctrlc = False,
                     verbose_start = False,
                     logfile = logfile,
                     eval_using_file_cutoff=100)
Beispiel #14
0
 def _start(self, alt_message=None, block_during_init=True):
     Expect._start(self, alt_message, block_during_init)
     # disable timer
     self._eval_line('default(timer,0);')
     # disable the break loop, otherwise gp will seem to hang on errors
     self._eval_line('default(breakloop,0);')
     # list of directories where gp will look for scripts (only current working directory)
     self._eval_line('default(path,".");')
     # location of elldata, seadata, galdata
     self._eval_line('default(datadir, "$SAGE_LOCAL/share/pari");')
     # executable for gp ?? help
     self._eval_line('default(help, "$SAGE_LOCAL/bin/gphelp -detex");')
     # logfile disabled since Expect already logs
     self._eval_line('default(log,0);')
Beispiel #15
0
    def __enter__(self):
        monitor_path = join(self.tempdir, 'monitor')
        if not self.boot:
            serial_path = join(self.tempdir, 'serial')

        qemu_args = [self.qemu_path, self.qcow]
#        if not self.boot:
#
        qemu_args.extend(['-monitor', 'unix:{},server,nowait'.format(monitor_path)])
        if self.boot:
            qemu_args.append('-S')
        else:
            qemu_args.extend(['-serial', 'unix:{},server,nowait'.format(serial_path),
                              '-loadvm', self.snapshot])
        qemu_args.extend(['-display', 'none'])
        qemu_args.extend(self.extra_args)
        if self.rr: qemu_args = ['rr', 'record'] + qemu_args
        if self.perf: qemu_args = ['perf', 'record'] + qemu_args

        progress("Running qemu with args:")
        print subprocess32.list2cmdline(qemu_args)

        self.qemu = subprocess32.Popen(qemu_args) # , stdout=DEVNULL, stderr=DEVNULL)
        while not os.path.exists(monitor_path):
            time.sleep(0.1)
        if not self.boot:
            while not os.path.exists(serial_path):
                time.sleep(0.1)
#        while not all([os.path.exists(p) for p in [monitor_path, serial_path]]):
#            time.sleep(0.1)

        self.monitor_socket = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
        self.monitor_socket.connect(monitor_path)
        self.monitor = Expect(self.monitor_socket)
        if not self.boot:
            self.serial_socket = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
            self.serial_socket.connect(serial_path)
            self.console = Expect(self.serial_socket)

        # Make sure monitor/console are in right state.
        self.monitor.expect("(qemu)")
        print
        if not self.boot:
            self.console.sendline()
            self.console.expect(self.expect_prompt)
        print
        print

        return self
Beispiel #16
0
    def __init__(self, options="", server=None,server_tmpdir=None):
        """
        INPUT:


        -  ``options`` - string; passed when starting mwrank.
           The format is::

           -h       help            prints this info and quits
           -q       quiet           turns OFF banner display and prompt
           -v n     verbosity       sets verbosity to n (default=1)
           -o       PARI/GP output  turns ON extra PARI/GP short output (default is OFF)
           -p n     precision       sets precision to n decimals (default=15)
           -b n     quartic bound   bound on quartic point search (default=10)
           -x n     n aux           number of aux primes used for sieving (default=6)
           -l       list            turns ON listing of points (default ON unless v=0)
           -s       selmer_only     if set, computes Selmer rank only (default: not set)
           -d       skip_2nd_descent        if set, skips the second descent for curves with 2-torsion (default: not set)
           -S n     sat_bd          upper bound on saturation primes (default=100, -1 for automatic)

    .. warning:

       Do not use the option "-q" which turns off the prompt.


        .. note::

           Normally instances of this class would be created by
           calling the global function :meth:`Mwrank`.

        EXAMPLES::

            sage: from sage.interfaces.mwrank import Mwrank_class
            sage: M = Mwrank_class('-v 0 -l')
            sage: M('0 -1 1 0 0')
            'Curve [0,-1,1,0,0] :...Rank = 0...Regulator = 1...'

            sage: from sage.interfaces.mwrank import Mwrank_class
            sage: TestSuite(Mwrank_class).run()
        """
        Expect.__init__(self,
                        name = 'mwrank',
                        prompt = 'Enter curve: ',
                        command = "mwrank %s"%options,
                        server = server,
                        server_tmpdir = server_tmpdir,
                        maxread = 10000,
                        restart_on_ctrlc = True,
                        verbose_start = False)
Beispiel #17
0
 def quit(self, verbose=False, timeout=0.25):
     """
     EXAMPLES::
     
         sage: a = gp('10'); a
         10
         sage: gp.quit()
         sage: a
         (invalid object -- defined in terms of closed session)
         sage: gp(pi)
         3.1415926535897932384626433832795028842    # 64-bit
         3.141592653589793238462643383              # 32-bit
     """
     self.__var_store_len = 0
     Expect.quit(self, verbose=verbose, timeout=timeout)
Beispiel #18
0
    def _eval_line(self, line, allow_use_file=True, wait_for_prompt=True, restart_if_needed=False):
        """
        EXAMPLES::

            sage: gp._eval_line('2+2')
            '4'

        TESTS:

        We verify that trac 11617 is fixed::

            sage: gp._eval_line('a='+str(range(2*10^5)))[:70]
            '[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19,'
        """
        line = line.strip()
        if len(line) == 0:
            return ''
        a = Expect._eval_line(self, line,
                              allow_use_file=allow_use_file,
                              wait_for_prompt=wait_for_prompt)
        if a.find("the PARI stack overflows") != -1:
            verbose("automatically doubling the PARI stack and re-executing current input line")
            b = self.eval("allocatemem()")
            if b.find("Warning: not enough memory") != -1:
                raise RuntimeError(a)
            return self._eval_line(line, allow_use_file=allow_use_file,
                                   wait_for_prompt=wait_for_prompt)
        else:
            return a
Beispiel #19
0
 def _start(self):
     """
     Starts the Octave process.
     
     EXAMPLES::
     
         sage: o = Octave()    #optional -- requires Octave
         sage: o.is_running()  #optional -- requires Octave
         False
         sage: o._start()      #optional -- requires Octave
         sage: o.is_running()  #optional -- requires Octave
         True
     """
     Expect._start(self)
     self.eval("page_screen_output=0;")
     self.eval("format none;")
Beispiel #20
0
    def _eval_line(self,
                   line,
                   allow_use_file=True,
                   wait_for_prompt=True,
                   restart_if_needed=False):
        """
        EXAMPLES:
            sage: lie._eval_line('2+2') # optional - lie
            '     4'
            sage: lie._eval_line('diagram(2)') # optional - lie
            Traceback (most recent call last):
            ...
            RuntimeError: An error occurred running a LiE command:
            Argument types do not match in call. Types are: diagram(bin).
            Valid argument types are for instance: diagram(grp).

        """
        out = Expect._eval_line(self,
                                line,
                                allow_use_file=allow_use_file,
                                wait_for_prompt=wait_for_prompt)
        #Check to see if an error has occurred
        err = max(out.find("\n(in"), out.find('not defined'),
                  out.find('Argument types'))
        if err != -1:
            raise RuntimeError, "An error occurred running a LiE command:\n%s" % (
                out.replace('\r\n', '\n'))
        return out
Beispiel #21
0
    def _eval_line(self,
                   line,
                   allow_use_file=True,
                   wait_for_prompt=True,
                   restart_if_needed=False):
        """
        EXAMPLES::

            sage: maple._eval_line('2+2')  # optional - maple
            '4'
        """
        line += ';'
        with gc_disabled():
            z = Expect._eval_line(self,
                                  line,
                                  allow_use_file=allow_use_file,
                                  wait_for_prompt=wait_for_prompt).replace(
                                      '\\\n', '').strip()
            if z.lower().find("error") != -1:
                # The following was very tricky to figure out.
                # When an error occurs using Maple, unfortunately,
                # Maple also dumps one into the line where the
                # error occurred with that line copied in.  This
                # totally messes up the pexpect interface.  However,
                # I think the following few lines successfully
                # "clear things out", i.e., delete the text from
                # the edit buffer and get a clean prompt.
                e = self.expect()
                e.sendline('%s__sage__;' % (chr(8) * len(line)))
                e.expect('__sage__;')
                e.expect(self._prompt)
                raise RuntimeError, "An error occurred running a Maple command:\nINPUT:\n%s\nOUTPUT:\n%s" % (
                    line, z)
        return z
Beispiel #22
0
    def _reset_expect(self):
        """
        Reset state of the GP interface.

        EXAMPLES::

            sage: a = gp('10'); a
            10
            sage: gp.quit()  # indirect doctest
            sage: a
            <repr(<sage.interfaces.gp.GpElement at 0x...>) failed: ValueError: The pari session in which this object was defined is no longer running.>
            sage: gp("30!")
            265252859812191058636308480000000
        """
        self.__var_store_len = 0
        Expect._reset_expect(self)
Beispiel #23
0
 def eval(self, x, newlines=False, strip=True, **kwds):
     r"""
     Send the code in the string s to the Kash interpreter and return
     the output as a string.
     
     INPUT:
     
     
     -  ``s`` - string containing Kash code.
     
     -  ``newlines`` - bool (default: True); if False,
        remove all backslash-newlines inserted by the Kash output
        formatter.
     
     -  ``strip`` - ignored
     """
     x = str(x)
     x = x.rstrip()
     if len(x) == 0 or x[len(x) - 1] != ';':
         x += ';'
     s = Expect.eval(self, x, **kwds)
     i = s.find('\r\n')
     if i != -1:
         s = s[i + 2:]
     if newlines:
         return s
     else:
         return s.replace("\\\n", "")
Beispiel #24
0
 def _start(self, alt_message=None, block_during_init=True):
     Expect._start(self, alt_message, block_during_init)
     # disable timer
     self._eval_line('default(timer,0);')
     # disable the break loop, otherwise gp will seem to hang on errors
     self._eval_line('default(breakloop,0);')
     # list of directories where gp will look for scripts (only current working directory)
     self._eval_line('default(path,".");')
     # location of elldata, seadata, galdata
     self._eval_line('default(datadir, "$SAGE_LOCAL/share/pari");')
     # executable for gp ?? help
     self._eval_line('default(help, "$SAGE_LOCAL/bin/gphelp -detex");')
     # logfile disabled since Expect already logs
     self._eval_line('default(log,0);')
     # set random seed
     self.set_seed(self._seed)
Beispiel #25
0
 def _eval_line(self, line, allow_use_file=True, wait_for_prompt=True):
     """
     EXAMPLES::
     
         sage: maple._eval_line('2+2')  # optional - maple
         '4'
     """
     line += ';'
     with gc_disabled():
         z = Expect._eval_line(self, line, allow_use_file=allow_use_file,
                 wait_for_prompt=wait_for_prompt).replace('\\\n','').strip()
         if z.lower().find("error") != -1:
             # The following was very tricky to figure out.
             # When an error occurs using Maple, unfortunately,
             # Maple also dumps one into the line where the
             # error occurred with that line copied in.  This
             # totally messes up the pexpect interface.  However,
             # I think the following few lines successfully
             # "clear things out", i.e., delete the text from
             # the edit buffer and get a clean prompt. 
             e = self.expect()
             e.sendline('%s__sage__;'%(chr(8)*len(line)))
             e.expect('__sage__;')
             e.expect(self._prompt)            
             raise RuntimeError, "An error occurred running a Maple command:\nINPUT:\n%s\nOUTPUT:\n%s"%(line, z)
     return z
Beispiel #26
0
    def _reset_expect(self):
        """
        Reset state of the GP interface.

        EXAMPLES::

            sage: a = gp('10'); a
            10
            sage: gp.quit()  # indirect doctest
            sage: a
            <repr(<sage.interfaces.gp.GpElement at 0x...>) failed: ValueError: The pari session in which this object was defined is no longer running.>
            sage: gp("30!")
            265252859812191058636308480000000
        """
        self.__var_store_len = 0
        Expect._reset_expect(self)
Beispiel #27
0
 def eval(self, x, newlines=False, strip=True, **kwds):
     r"""
     Send the code in the string s to the Kash interpreter and return
     the output as a string.
     
     INPUT:
     
     
     -  ``s`` - string containing Kash code.
     
     -  ``newlines`` - bool (default: True); if False,
        remove all backslash-newlines inserted by the Kash output
        formatter.
     
     -  ``strip`` - ignored
     """
     x = str(x)
     x = x.rstrip()
     if len(x) == 0 or x[len(x) - 1] != ';':
         x += ';'
     s = Expect.eval(self, x, **kwds)
     i = s.find('\r\n')
     if i != -1:
         s = s[i+2:]
     if newlines:
         return s
     else:
         return s.replace("\\\n","")
Beispiel #28
0
 def help(self, s, pager=True):
     """
     Print help on a given topic.
     
     EXAMPLES::
     
         sage: print gap.help('SymmetricGroup', pager=False)
         Basic Groups _____________________________________________ Group Libraries
         ...
     """
     tmp_to_use = self._local_tmpfile()
     if self.is_remote():
         tmp_to_use = self._remote_tmpfile()
     else:
         tmp_to_use = self._local_tmpfile()
     self.eval('$SAGE.tempfile := "%s";'%tmp_to_use)
     line = Expect.eval(self, "? %s"%s)
     match = re.search("Page from (\d+)", line)
     if match == None:
         print line
     else:
         (sline,) = match.groups()
         if self.is_remote():
             self._get_tmpfile()
         F = open(self._local_tmpfile(),"r")
         if pager:
             page(F.read(), start = int(sline)-1)
         else:
             return F.read()
Beispiel #29
0
 def __init__(self):
     self.connect = Expect()
     if self.connect.mode == 'ssh':
         self.connect.ssh_login()
     elif self.connect.mode == 'telnet':
         self.connect.telnet_login()
     self._data()
Beispiel #30
0
    def _eval_line(self, line, allow_use_file=True, wait_for_prompt=True, restart_if_needed=False):
        """
        EXAMPLES::

            sage: gp._eval_line('2+2')
            '4'

        TESTS:

        We verify that trac 11617 is fixed::

            sage: gp._eval_line('a='+str(range(2*10^5)))[:70]
            '[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19,'
        """
        line = line.strip()
        if len(line) == 0:
            return ''
        a = Expect._eval_line(self, line,
                              allow_use_file=allow_use_file,
                              wait_for_prompt=wait_for_prompt)
        if a.find("the PARI stack overflows") != -1:
            verbose("automatically doubling the PARI stack and re-executing current input line")
            b = self.eval("allocatemem()")
            if b.find("Warning: not enough memory") != -1:
                raise RuntimeError(a)
            return self._eval_line(line, allow_use_file=allow_use_file,
                                   wait_for_prompt=wait_for_prompt)
        else:
            return a
Beispiel #31
0
 def _start(self):
     """
     Starts the Octave process.
     
     EXAMPLES::
     
         sage: o = Octave()    # optional - octave
         sage: o.is_running()  # optional - octave
         False
         sage: o._start()      # optional - octave
         sage: o.is_running()  # optional - octave
         True
     """
     Expect._start(self)
     self.eval("page_screen_output=0;")
     self.eval("format none;")
Beispiel #32
0
    def __init__(
            self,
            stacksize=10000000,  # 10MB
            maxread=None,
            script_subdirectory=None,
            logfile=None,
            server=None,
            server_tmpdir=None,
            init_list_length=1024,
            seed=None):
        """
        Initialization of this PARI gp interpreter.

        INPUT:

        - ``stacksize`` (int, default 10000000) -- the initial PARI
          stacksize in bytes (default 10MB)
        - ``script_subdirectory`` (string, default None) -- name of the subdirectory of SAGE_EXTCODE/pari from which to read scripts
        - ``logfile`` (string, default None) -- log file for the pexpect interface
        - ``server`` -- name of remote server
        - ``server_tmpdir`` -- name of temporary directory on remote server
        - ``init_list_length`` (int, default 1024) -- length of initial list of local variables.
        - ``seed`` (int,default random nonzero 31 bit integer) -- value of random seed

        EXAMPLES::

            sage: gp == loads(dumps(gp))
            True
        """
        Expect.__init__(
            self,
            name='pari',
            prompt='\\? ',
            # --fast so the system gprc isn't read (we configure below)
            command="gp --fast --emacs --quiet --stacksize %s" % stacksize,
            maxread=maxread,
            server=server,
            server_tmpdir=server_tmpdir,
            script_subdirectory=script_subdirectory,
            restart_on_ctrlc=False,
            verbose_start=False,
            logfile=logfile,
            eval_using_file_cutoff=1024)
        self.__seq = 0
        self.__var_store_len = 0
        self.__init_list_length = init_list_length
        self._seed = seed
Beispiel #33
0
    def __init__(self, options="", server=None, server_tmpdir=None):
        """
        INPUT:

        -  ``options`` - string; passed when starting mwrank.
           The format is::

           -h       help            prints this info and quits
           -q       quiet           turns OFF banner display and prompt
           -v n     verbosity       sets verbosity to n (default=1)
           -o       PARI/GP output  turns ON extra PARI/GP short output (default is OFF)
           -p n     precision       sets precision to n decimals (default=15)
           -b n     quartic bound   bound on quartic point search (default=10)
           -x n     n aux           number of aux primes used for sieving (default=6)
           -l       list            turns ON listing of points (default ON unless v=0)
           -s       selmer_only     if set, computes Selmer rank only (default: not set)
           -d       skip_2nd_descent        if set, skips the second descent for curves with 2-torsion (default: not set)
           -S n     sat_bd          upper bound on saturation primes (default=100, -1 for automatic)

    .. warning:

       Do not use the option "-q" which turns off the prompt.

        .. note::

           Normally instances of this class would be created by
           calling the global function :meth:`Mwrank`.

        EXAMPLES::

            sage: from sage.interfaces.mwrank import Mwrank_class
            sage: M = Mwrank_class('-v 0 -l')
            sage: M('0 -1 1 0 0')
            'Curve [0,-1,1,0,0] :   Rank = 0\n\n\nRegulator = 1\n'

            sage: from sage.interfaces.mwrank import Mwrank_class
            sage: TestSuite(Mwrank_class).run()
        """
        Expect.__init__(self,
                        name='mwrank',
                        prompt='Enter curve: ',
                        command="mwrank %s" % options,
                        server=server,
                        server_tmpdir=server_tmpdir,
                        maxread=10000,
                        restart_on_ctrlc=True,
                        verbose_start=False)
Beispiel #34
0
    def __init__(self,
                 maxread=100000,
                 script_subdirectory=None,
                 logfile=None,
                 server=None):
        """
        EXAMPLES::

            sage: lie == loads(dumps(lie))
            True
        """
        Expect.__init__(
            self,

            # The capitalized version of this is used for printing.
            name='LiE',

            # This is regexp of the input prompt.  If you can change
            # it to be very obfuscated that would be better.   Even
            # better is to use sequence numbers.
            prompt='> ',

            # This is the command that starts up your program
            command="bash " + SAGE_LOCAL + "/bin/lie",
            maxread=maxread,
            server=server,
            script_subdirectory=script_subdirectory,

            # If this is true, then whenever the user presses Control-C to
            # interrupt a calculation, the whole interface is restarted.
            restart_on_ctrlc=False,

            # If true, print out a message when starting
            # up the command when you first send a command
            # to this interface.
            verbose_start=False,
            logfile=logfile,

            # If an input is longer than this number of characters, then
            # try to switch to outputting to a file.
            eval_using_file_cutoff=1024)

        self._seq = 0

        self._trait_names_dict = None
        self._trait_names_list = None
        self._help_dict = None
Beispiel #35
0
    def __init__(self,
                 maxread=100000, script_subdirectory=None,
                 logfile=None,
                 server=None):
        """
        EXAMPLES::

            sage: lie == loads(dumps(lie))
            True
        """
        Expect.__init__(self,

                        # The capitalized version of this is used for printing.
                        name = 'LiE',

                        # This is regexp of the input prompt.  If you can change
                        # it to be very obfuscated that would be better.   Even
                        # better is to use sequence numbers.
                        prompt = '> ',

                        # This is the command that starts up your program
                        command = "bash "+ SAGE_LOCAL + "/bin/lie",

                        maxread = maxread,
                        server=server,
                        script_subdirectory = script_subdirectory,

                        # If this is true, then whenever the user presses Control-C to
                        # interrupt a calculation, the whole interface is restarted.
                        restart_on_ctrlc = False,

                        # If true, print out a message when starting
                        # up the command when you first send a command
                        # to this interface.
                        verbose_start = False,

                        logfile=logfile,

                        # If an input is longer than this number of characters, then
                        # try to switch to outputting to a file.
                        eval_using_file_cutoff=1024)

        self._seq = 0

        self._trait_names_dict = None
        self._trait_names_list = None
        self._help_dict = None
Beispiel #36
0
    def __init__(self,
                 maxread=10000,
                 script_subdirectory="",
                 logfile=None,
                 server=None,
                 server_tmpdir=None):
        """
        Initialize a Macaulay2 interface instance.

        We replace the standard input prompt with a strange one, so that
        we do not catch input prompts inside the documentation.

        We replace the standard input continuation prompt, which is
        just a bunch of spaces and cannot be automatically detected in a
        reliable way. This is necessary for allowing commands that occupy
        several strings.

        We also change the starting line number to make all the output
        labels to be of the same length. This allows correct stripping of
        the output of several commands.

        TESTS:
            sage: macaulay2 == loads(dumps(macaulay2))
            True
        """
        init_str = (
            # Prompt changing commands
            """ZZ#{Standard,Core#"private dictionary"#"InputPrompt"} = lineno -> "%s";"""
            % PROMPT +
            """ZZ#{Standard,Core#"private dictionary"#"InputContinuationPrompt"} = lineno -> "%s";"""
            % PROMPT +
            # Also prevent line wrapping in Macaulay2
            "printWidth = 0;" +
            # And make all output labels to be of the same width
            "lineNumber = 10^9;")
        Expect.__init__(
            self,
            name='macaulay2',
            prompt=PROMPT,
            command="M2 --no-debug --no-readline --silent -e '%s'" % init_str,
            maxread=maxread,
            server=server,
            server_tmpdir=server_tmpdir,
            script_subdirectory=script_subdirectory,
            verbose_start=False,
            logfile=logfile,
            eval_using_file_cutoff=500)
Beispiel #37
0
 def __init__(self,
              maxread=None,
              script_subdirectory=None,
              logfile=None,
              server=None,
              server_tmpdir=None):
     Expect.__init__(self,
                     name='matlab',
                     prompt='>> ',
                     command="sage-native-execute matlab -nodisplay",
                     server=server,
                     server_tmpdir=server_tmpdir,
                     script_subdirectory=script_subdirectory,
                     restart_on_ctrlc=False,
                     verbose_start=False,
                     logfile=logfile,
                     eval_using_file_cutoff=100)
Beispiel #38
0
    def quit(self, verbose=False, timeout=0.25):
        """
        Terminate the GP process.

        EXAMPLES::

            sage: a = gp('10'); a
            10
            sage: gp.quit()
            sage: a
            <repr(<sage.interfaces.gp.GpElement at 0x...>) failed: ValueError: The pari session in which this object was defined is no longer running.>
            sage: gp(pi)
            3.1415926535897932384626433832795028842    # 64-bit
            3.141592653589793238462643383              # 32-bit
        """
        self.__var_store_len = 0
        Expect.quit(self, verbose=verbose, timeout=timeout)
Beispiel #39
0
    def __init__(
        self,
        stacksize=10000000,  # 10MB
        maxread=100000,
        script_subdirectory=None,
        logfile=None,
        server=None,
        server_tmpdir=None,
        init_list_length=1024,
    ):
        """
        Initialization of this PARI gp interpreter.

        INPUT:

        - ``stacksize`` (int, default 10000000) -- the initial PARI
          stacksize in bytes (default 10MB)
        - ``maxread`` (int, default 100000) -- ??
        - ``script_subdirectory`` (string, default None) -- name of the subdirectory of SAGE_EXTCODE/pari from which to read scripts
        - ``logfile`` (string, default None) -- log file for the pexpect interface
        - ``server`` -- name of remote server
        - ``server_tmpdir`` -- name of temporary directory on remote server
        - ``init_list_length`` (int, default 1024) -- length of initial list of local variables.

        EXAMPLES::

            sage: gp == loads(dumps(gp))
            True
        """
        Expect.__init__(
            self,
            name="pari",
            prompt="\\? ",
            command="gp --emacs --quiet --stacksize %s" % stacksize,
            maxread=maxread,
            server=server,
            server_tmpdir=server_tmpdir,
            script_subdirectory=script_subdirectory,
            restart_on_ctrlc=False,
            verbose_start=False,
            logfile=logfile,
            eval_using_file_cutoff=1024,
        )
        self.__seq = 0
        self.__var_store_len = 0
        self.__init_list_length = init_list_length
 def __init__(self,
              maxread=100,
              script_subdirectory="",
              logfile=None,
              server=None,
              server_tmpdir=None):
     Expect.__init__(self,
                     name='mathematica',
                     prompt='In[[0-9]+]:=',
                     command="math",
                     maxread=maxread,
                     server=server,
                     server_tmpdir=server_tmpdir,
                     script_subdirectory=script_subdirectory,
                     verbose_start=False,
                     logfile=logfile,
                     eval_using_file_cutoff=50)
Beispiel #41
0
    def __enter__(self):
        self.tempdir_obj = TempDir()
        tempdir = self.tempdir_obj.__enter__()
        logfile = join(tempdir, self.description + "out")
        os.mkfifo(logfile)
        bash_command = "{} 2>&1 | tee -i --output-error=warn {} | tee -i --output-error=warn {}_log.txt".format(
            self.spawn_cmd, pipes.quote(logfile), self.description)

        self.pane = check_output([
            'tmux', 'split-window', '-hdP', '-F', '#{pane_id}', '-t', pane,
            'bash', '-c', bash_command
        ]).strip()

        self.proc = Expect(os.open(logfile, os.O_RDONLY | os.O_NONBLOCK),
                           quiet=True)
        self.proc.expect("(rr) ")
        return self
Beispiel #42
0
    def quit(self, verbose=False, timeout=0.25):
        """
        Terminate the GP process.

        EXAMPLES::

            sage: a = gp('10'); a
            10
            sage: gp.quit()
            sage: a
            <repr(<sage.interfaces.gp.GpElement at 0x...>) failed: ValueError: The pari session in which this object was defined is no longer running.>
            sage: gp(pi)
            3.1415926535897932384626433832795028842    # 64-bit
            3.141592653589793238462643383              # 32-bit
        """
        self.__var_store_len = 0
        Expect.quit(self, verbose=verbose, timeout=timeout)
Beispiel #43
0
 def __init__(self, logfile   = None,
                    preparse  = True,
                    python    = False,
                    init_code = None,
                    server    = None,
                    server_tmpdir = None,
                    remote_cleaner = True,
                    **kwds):
     """
     EXAMPLES::
     
         sage: sage0 == loads(dumps(sage0))
         True
     """
     from sage.misc.misc import SAGE_ROOT
     if python:
         if server:
             command = "femhub -python -u"
         else:
             command = SAGE_ROOT + "/femhub -python -u"
         prompt = ">>>"
         if init_code is None:
             init_code = ['from sage.all import *', 'import cPickle']
     else:
         if server:
             command = "femhub"
         else:
             command = SAGE_ROOT + "/femhub"
         prompt = "sage: "
         if init_code is None:
             init_code = ['import cPickle', '%colors NoColor']
     
     Expect.__init__(self,
                     name = 'sage',
                     prompt = prompt,
                     command = command,
                     restart_on_ctrlc = False,
                     logfile = logfile,
                     init_code = init_code,
                     server = server,
                     server_tmpdir = server_tmpdir,
                     remote_cleaner = remote_cleaner,
                     **kwds
                     )
     self._preparse = preparse
Beispiel #44
0
 def __init__(self, options="", server=None, server_tmpdir=None):
     """
     INPUT:
     
     
     -  ``options`` - string; passed when starting mwrank.
        The format is q pprecision vverbosity bhlim_q xnaux chlim_c l t o
        s d]
     """
     Expect.__init__(self,
                     name='mwrank',
                     prompt='Enter curve: ',
                     command="mwrank %s" % options,
                     server=server,
                     server_tmpdir=server_tmpdir,
                     maxread=10000,
                     restart_on_ctrlc=True,
                     verbose_start=False)
Beispiel #45
0
    def _eval_line_using_file(self, line, *args, **kwargs):
        """
        EXAMPLES::

            sage: maple._eval_line_using_file('2+2')  # optional - maple
            '4'
        """
        line += ';'  # Adds the maple ";" thing like in self._eval_line
        return Expect._eval_line_using_file(self, line, *args, **kwargs)
Beispiel #46
0
    def eval(self, code, strip=True, **kwds):
        """
        EXAMPLES:
            sage: mupad.eval('2+2')   # optional - mupad
                                                   4

        """
        s = Expect.eval(self, code, **kwds)
        return AsciiArtString(s)
Beispiel #47
0
    def _start(self):
        """
        Starts the Octave process.

        EXAMPLES::

            sage: o = Octave()    # optional - octave
            sage: o.is_running()  # optional - octave
            False
            sage: o._start()      # optional - octave
            sage: o.is_running()  # optional - octave
            True
        """
        Expect._start(self)
        self.eval("page_screen_output=0;")
        self.eval("format none;")
        # set random seed
        self.set_seed(self._seed)
Beispiel #48
0
 def _eval_line(self,
                line,
                allow_use_file=False,
                wait_for_prompt=True,
                restart_if_needed=False):
     return Expect._eval_line(self,
                              line,
                              allow_use_file=allow_use_file,
                              wait_for_prompt=wait_for_prompt)
Beispiel #49
0
    def _eval_line_using_file(self, line, *args, **kwargs):
        """
        EXAMPLES::

            sage: maple._eval_line_using_file('2+2')  # optional - maple
            '4'
        """
        line += ';'  # Adds the maple ";" thing like in self._eval_line
        return Expect._eval_line_using_file(self, line, *args, **kwargs)
Beispiel #50
0
 def _start(self):
     """
     Start the Axiom interpreter.
     
     EXAMPLES::
     
         sage: a = Axiom()
         sage: a.is_running()
         False
         sage: a._start()     #optional - axiom
         sage: a.is_running() #optional - axiom
         True
         sage: a.quit()       #optional - axiom
     """
     Expect._start(self)
     out = self._eval_line(')set functions compile on', reformat=False)
     out = self._eval_line(')set output length 245', reformat=False)
     out = self._eval_line(')set message autoload off', reformat=False)
Beispiel #51
0
 def _start(self):
     """
     Start the Axiom interpreter.
     
     EXAMPLES::
     
         sage: a = Axiom()
         sage: a.is_running()
         False
         sage: a._start()     #optional - axiom
         sage: a.is_running() #optional - axiom
         True
         sage: a.quit()       #optional - axiom
     """
     Expect._start(self)
     out = self._eval_line(')set functions compile on', reformat=False)
     out = self._eval_line(')set output length 245', reformat=False)
     out = self._eval_line(')set message autoload off', reformat=False)
Beispiel #52
0
 def __init__(self, pgf_path, lang, maxread=100, script_subdirectory="", logfile=None,
              server=None, server_tmpdir=None):
     from os.path import splitext, basename
     module_name = splitext(basename(pgf_path))[0]
     Expect.__init__(self,
                     name = 'gf',
                     prompt = module_name + '>',
                     command = "gf -q %s" % pgf_path,
                     maxread = maxread,
                     server = server,
                     server_tmpdir = server_tmpdir,
                     script_subdirectory = script_subdirectory,
                     restart_on_ctrlc = False,
                     verbose_start = DEBUG,
                     logfile = logfile,
                     eval_using_file_cutoff=1024)
     self.lang = lang
     self.locals = None
     self.pgf_path = pgf_path
Beispiel #53
0
    def quit(self, verbose=False, timeout=0.25):
        """
        Terminate the GP process.

        EXAMPLES::

            sage: a = gp('10'); a
            10
            sage: gp.quit()
            sage: a
            Traceback (most recent call last):
            ...
            ValueError: The pari session in which this object was defined is no longer running.
            sage: gp(pi)
            3.1415926535897932384626433832795028842    # 64-bit
            3.141592653589793238462643383              # 32-bit
        """
        self.__var_store_len = 0
        Expect.quit(self, verbose=verbose, timeout=timeout)
 def _eval_line(self,
                line,
                allow_use_file=True,
                wait_for_prompt=True,
                restart_if_needed=False):
     s = Expect._eval_line(self,
                           line,
                           allow_use_file=allow_use_file,
                           wait_for_prompt=wait_for_prompt)
     return str(s).strip('\n')
Beispiel #55
0
    def __init__(self, maxread=100, script_subdirectory="", logfile=None, server=None, server_tmpdir=None):
        """
        EXAMPLES::

            sage: octave == loads(dumps(octave))
            True
        """
        Expect.__init__(self,
                        name = 'octave',
                        prompt = '>',
                        command = "sage-native-execute octave --no-line-editing --silent",
                        maxread = maxread,
                        server = server,
                        server_tmpdir = server_tmpdir,
                        script_subdirectory = script_subdirectory,
                        restart_on_ctrlc = False,
                        verbose_start = False,
                        logfile = logfile,
                        eval_using_file_cutoff=100)
Beispiel #56
0
 def __init__(self,
              max_workspace_size=None,
              maxread=100000,
              script_subdirectory=None,
              use_workspace_cache=True,
              server=None,
              server_tmpdir=None,
              logfile=None):
     """
     EXAMPLES::
     
         sage: gap == loads(dumps(gap))
         True
     """
     if os.uname()[-1] == 'ia64':
         # workspace cache is buggy on Itanium in GAP-4.4.12 -- see #5455.
         use_workspace_cache = False
     self.__use_workspace_cache = use_workspace_cache
     cmd, self.__make_workspace = gap_command(use_workspace_cache,
                                              server is None)
     cmd += " -b -p -T"
     if max_workspace_size != None:
         cmd += " -o %s" % int(max_workspace_size)
     else:  # unlimited
         if is_64_bit:
             cmd += " -o 9999G"
         else:
             cmd += " -o 3900m"
     cmd += " %s/extcode/gap/sage.g" % DB_HOME
     Expect.__init__(self,
                     name='gap',
                     prompt='gap> ',
                     command=cmd,
                     maxread=maxread,
                     server=server,
                     server_tmpdir=server_tmpdir,
                     script_subdirectory=script_subdirectory,
                     restart_on_ctrlc=True,
                     verbose_start=False,
                     logfile=logfile,
                     eval_using_file_cutoff=100)
     self.__seq = 0
Beispiel #57
0
    def __init__(self, maxread=1000, script_subdirectory="", server=None, server_tmpdir=None, logfile=None):
        """
        Create an instance of the MuPAD interpreter.

        EXAMPLES:
            sage: mupad == loads(dumps(mupad))                      # optional - mupad
            True
        """
        Expect.__init__(self,
                        name = 'MuPAD',
                        prompt = PROMPT,
                        # the -U SAGE=TRUE allows for MuPAD programs to test whether they are run from Sage
                        command = "mupkern -P e -U SAGE=TRUE",
                        maxread = maxread,
                        script_subdirectory = script_subdirectory,
                        server = server,
                        server_tmpdir = server_tmpdir,
                        restart_on_ctrlc = False,
                        verbose_start = False,
                        logfile = None)
Beispiel #58
0
    def __init__(self,
                 logfile=None,
                 preparse=True,
                 python=False,
                 init_code=None,
                 server=None,
                 server_tmpdir=None,
                 remote_cleaner=True,
                 **kwds):
        """
        EXAMPLES::
        
            sage: sage0 == loads(dumps(sage0))
            True
        """
        if python:
            if server:
                command = "sage -python -u"
            else:
                command = "sage -python -u"
            prompt = ">>>"
            if init_code is None:
                init_code = ['from sage.all import *', 'import cPickle']
        else:
            command = "sage"
            prompt = "sage: "
            if init_code is None:
                init_code = ['import cPickle', '%colors NoColor']

        Expect.__init__(self,
                        name='sage',
                        prompt=prompt,
                        command=command,
                        restart_on_ctrlc=False,
                        logfile=logfile,
                        init_code=init_code,
                        server=server,
                        server_tmpdir=server_tmpdir,
                        remote_cleaner=remote_cleaner,
                        **kwds)
        self._preparse = preparse
Beispiel #59
0
    def __init__(self,
                 maxread=100,
                 script_subdirectory=None,
                 server=None,
                 server_tmpdir=None,
                 logfile=None,
                 ulimit=None):
        """
        Create an instance of the Maple interpreter.

        EXAMPLES::

            sage: maple == loads(dumps(maple))
            True
        """
        __maple_iface_opts = [
            'screenwidth=infinity',
            'errorcursor=false',
        ]
        __maple_command = 'maple -t -c "interface({})"'.format(
            ','.join(__maple_iface_opts))
        #errorcursor=false avoids maple command line interface to dump
        #into the editor when an error occurs. Thus pexpect interface
        #is not messed up if a maple error occurs.
        #screenwidth=infinity prevents maple command interface from cutting
        #your input lines. By doing this, file interface also works in the
        #event that  sage_user_home + sage_tmp_file_stuff exceeds the
        #length of 79 characters.
        Expect.__init__(self,
                        name='maple',
                        prompt='#-->',
                        command=__maple_command,
                        server=server,
                        server_tmpdir=server_tmpdir,
                        ulimit=ulimit,
                        maxread=maxread,
                        script_subdirectory=script_subdirectory,
                        restart_on_ctrlc=False,
                        verbose_start=False,
                        logfile=logfile,
                        eval_using_file_cutoff=2048)  # 2048 is
Beispiel #60
0
    def eval(self, command, *args, **kwds):
        """
        Evaluates commands.

        EXAMPLES:
            sage: scilab.eval("5")                      # optional - scilab
            'ans  =\n \n    5.'
            sage: scilab.eval("d=44")                   # optional - scilab
            'd  =\n \n    44.'
        """
        s = Expect.eval(self, command, **kwds).replace("\x1b[?1l\x1b>","").strip()
        return s