def have_chomp(program='homsimpl'): """ Return True if this computer has ``program`` installed. The first time it is run, this function caches its result in the variable ``_have_chomp`` -- a dictionary indexed by program name -- and any subsequent time, it just checks the value of the variable. This program is used in the routine CHomP.__call__. If this computer doesn't have CHomP installed, you may obtain it from http://chomp.rutgers.edu/. EXAMPLES:: sage: from sage.interfaces.chomp import have_chomp sage: have_chomp() # random -- depends on whether CHomP is installed True sage: 'homsimpl' in sage.interfaces.chomp._have_chomp True sage: sage.interfaces.chomp._have_chomp['homsimpl'] == have_chomp() True """ global _have_chomp if program not in _have_chomp: from sage.misc.sage_ostools import have_program _have_chomp[program] = have_program(program) return _have_chomp[program]
def trac_create_instance(directory='sage_trac', easy_setup=False): """ Create a new Trac project instance if Trac is installed. INPUT: - ``directory`` - a string (default: 'sage_trac'); the name of the project directory - ``easy_setup`` - a bool (default: False); whether to use the project name 'Sage', the default database, enable the webadmin plugin, and enable the source browser for the 'sage' Mercurial repository. .. note:: To access the webadmin panel, first create a user, give that user admin permissions, and log in as that user. Create new accounts using htdigest (part of Apache):: cd <directory>/conf htdigest passwd <server_address> <username> Grant a user administrative privileges with:: trac-admin <directory> add <username> TRAC_ADMIN """ from sage.misc.sage_ostools import have_program if not have_program('trac-admin'): raise RuntimeError("trac is not installed") if easy_setup: cmd = 'trac-admin "%s" initenv "Sage" "sqlite:db/trac.db" "" ""' % directory else: cmd = 'trac-admin "%s" initenv' % directory e = os.system(cmd) if e: raise RuntimeError("Error creating trac environment.") if easy_setup: conf_name = os.path.abspath(os.path.join(directory, 'conf/trac.ini')) __import__('trac.config') Configuration = sys.modules['trac.config'].Configuration conf = Configuration(conf_name) conf.set('trac', 'repository_dir', SAGE_LIB) conf.set('trac', 'repository_type', 'hg') conf.set('components', 'tracext.hg.*', 'enabled') conf.set('components', 'webadmin.*', 'enabled') conf.set('hg', 'node_format', 'short') conf.set('hg', 'show_rev', 'yes') conf.save()
def trac_create_instance(directory = 'sage_trac', easy_setup = False): """ Create a new Trac project instance if Trac is installed. INPUT: - ``directory`` - a string (default: 'sage_trac'); the name of the project directory - ``easy_setup`` - a bool (default: False); whether to use the project name 'Sage', the default database, enable the webadmin plugin, and enable the source browser for the 'sage' Mercurial repository. .. note:: To access the webadmin panel, first create a user, give that user admin permissions, and log in as that user. Create new accounts using htdigest (part of Apache):: cd <directory>/conf htdigest passwd <server_address> <username> Grant a user administrative privileges with:: trac-admin <directory> add <username> TRAC_ADMIN """ from sage.misc.sage_ostools import have_program if not have_program('trac-admin'): raise RuntimeError("trac is not installed") if easy_setup: cmd = 'trac-admin "%s" initenv "Sage" "sqlite:db/trac.db" "" ""' % directory else: cmd = 'trac-admin "%s" initenv' % directory e = os.system(cmd) if e: raise RuntimeError("Error creating trac environment.") if easy_setup: conf_name = os.path.abspath(os.path.join(directory, 'conf/trac.ini')) __import__('trac.config') Configuration = sys.modules['trac.config'].Configuration conf = Configuration(conf_name) conf.set('trac', 'repository_dir', SAGE_LIB) conf.set('trac', 'repository_type', 'hg') conf.set('components', 'tracext.hg.*', 'enabled') conf.set('components', 'webadmin.*', 'enabled') conf.set('hg', 'node_format', 'short') conf.set('hg', 'show_rev', 'yes') conf.save()
def _have_ffmpeg(self): """ Return True if the program 'ffmpeg' is installed. See www.ffmpeg.org to download ffmpeg. EXAMPLES:: sage: a = animate([plot(sin, -1,1)], xmin=0, ymin=0) sage: a._have_ffmpeg() # random: depends on whether ffmpeg is installed False """ from sage.misc.sage_ostools import have_program return have_program('ffmpeg')
def blackbox(self, polys, input_ring, verbose=False): """ Returns as a string the result of running PHC with the given polynomials under blackbox mode (the '-b' option). INPUT: polys -- a list of multivariate polynomials (elements of a multivariate polynomial ring). input_ring: for coercion of the variables into the desired ring. verbose -- print lots of verbose information about what this function does. OUTPUT: a PHC_Object object containing the phcpack output string. EXAMPLES:: sage: from sage.interfaces.phc import * sage: R2.<x,y> = PolynomialRing(QQ,2) sage: start_sys = [x^6-y^2,y^5-1] sage: sol = phc.blackbox(start_sys, R2) # optional -- phc sage: len(sol.solutions()) # optional -- phc 30 """ # Get three temporary file names (these will be in SAGE_HOME/.sage/tmp/pid) input_filename = sage.misc.misc.tmp_filename() output_filename = input_filename + ".phc" log_filename = sage.misc.misc.tmp_filename() # Get the input polynomial text input = self._input_file(polys) if verbose: print "Writing the input file to %s" % input_filename open(input_filename, 'w').write(input) if verbose: print "The following file will be the input polynomial file to phc." print input # Create the phc command line> cmd = 'phc -b %s %s' % (input_filename, output_filename) if verbose: print "The phc command line is:" print cmd # Do it -- make the system call. e = os.system(cmd) # Was there an error? if e: from sage.misc.sage_ostools import have_program if not have_program('phc'): print os.system( 'which phc' ) + ' PHC needs to be installed and in your path' raise RuntimeError # todo -- why? etc. raise RuntimeError( open(log_filename).read() + "\nError running phc.") if not os.path.exists(output_filename): raise RuntimeError( "The output file does not exist; something went wrong running phc." ) # Read the output produced by PHC out = open(output_filename).read() # All done return PHC_Object(out, input_ring)
def gif(self, delay=20, savefile=None, iterations=0, show_path=False, use_ffmpeg=False): r""" Returns an animated gif composed from rendering the graphics objects in self. This method will only work if either (a) the ImageMagick software suite is installed, i.e., you have the ``convert`` command or (b) ``ffmpeg`` is installed. See [IM] for more about ImageMagick, and see [FF] for more about ``ffmpeg``. By default, this produces the gif using ``convert`` if it is present. If this can't find ``convert`` or if ``use_ffmpeg`` is True, then it uses ``ffmpeg`` instead. INPUT: - ``delay`` - (default: 20) delay in hundredths of a second between frames - ``savefile`` - file that the animated gif gets saved to - ``iterations`` - integer (default: 0); number of iterations of animation. If 0, loop forever. - ``show_path`` - boolean (default: False); if True, print the path to the saved file - ``use_ffmpeg`` - boolean (default: False); if True, use 'ffmpeg' by default instead of 'convert'. If ``savefile`` is not specified: in notebook mode, display the animation; otherwise, save it to a default file name. EXAMPLES:: sage: a = animate([sin(x + float(k)) for k in srange(0,2*pi,0.7)], ....: xmin=0, xmax=2*pi, figsize=[2,1]) sage: dir = tmp_dir() sage: a.gif() # not tested sage: a.gif(savefile=dir + 'my_animation.gif', delay=35, iterations=3) # optional -- ImageMagick sage: a.gif(savefile=dir + 'my_animation.gif', show_path=True) # optional -- ImageMagick Animation saved to .../my_animation.gif. sage: a.gif(savefile=dir + 'my_animation_2.gif', show_path=True, use_ffmpeg=True) # optional -- ffmpeg Animation saved to .../my_animation_2.gif. .. note:: If neither ffmpeg nor ImageMagick is installed, you will get an error message like this:: Error: Neither ImageMagick nor ffmpeg appears to be installed. Saving an animation to a GIF file or displaying an animation requires one of these packages, so please install one of them and try again. See www.imagemagick.org and www.ffmpeg.org for more information. """ from sage.misc.sage_ostools import have_program have_convert = have_program('convert') have_ffmpeg = self._have_ffmpeg() if use_ffmpeg or not have_convert: if have_ffmpeg: self.ffmpeg(savefile=savefile, show_path=show_path, output_format='.gif', delay=delay, iterations=iterations) else: if not have_convert: msg = """ Error: Neither ImageMagick nor ffmpeg appears to be installed. Saving an animation to a GIF file or displaying an animation requires one of these packages, so please install one of them and try again. See www.imagemagick.org and www.ffmpeg.org for more information.""" else: msg = """ Error: ffmpeg does not appear to be installed. Download it from www.ffmpeg.org, or use 'convert' to produce gifs instead.""" raise OSError(msg) else: if not savefile: savefile = tmp_filename(ext='.gif') if not savefile.endswith('.gif'): savefile += '.gif' savefile = os.path.abspath(savefile) d = self.png() cmd = ( 'cd "%s"; sage-native-execute convert -dispose Background ' '-delay %s -loop %s *.png "%s"' ) % ( d, int(delay), int(iterations), savefile ) from subprocess import check_call, CalledProcessError try: check_call(cmd, shell=True) if show_path: print "Animation saved to file %s." % savefile except (CalledProcessError, OSError): msg = """ Error: Cannot generate GIF animation. Verify that convert (ImageMagick) or ffmpeg is installed, and that the objects passed to the animate command can be saved in PNG image format. See www.imagemagick.org and www.ffmpeg.org for more information.""" raise OSError(msg)
def default_viewer(viewer=None): """ Set up default programs for opening web pages, PDFs, PNGs, and DVI files. INPUT: - ``viewer``: ``None`` or a string: one of 'browser', 'pdf', 'png', 'dvi' -- return the name of the corresponding program. ``None`` is treated the same as 'browser'. EXAMPLES:: sage: from sage.misc.viewer import default_viewer sage: default_viewer(None) # random -- depends on OS, etc. 'sage-open' sage: default_viewer('pdf') # random -- depends on OS, etc. 'xdg-open' sage: default_viewer('jpg') Traceback (most recent call last): ... ValueError: Unknown type of viewer: jpg. """ import os from sage.misc.sage_ostools import have_program if isinstance(viewer, str): viewer = viewer.lower() if "SAGE_BROWSER" in os.environ: BROWSER = os.environ["SAGE_BROWSER"] DVI_VIEWER = BROWSER PDF_VIEWER = BROWSER PNG_VIEWER = BROWSER elif os.uname()[0] == "Darwin": # Simple on OS X, since there is an open command that opens # anything, using the user's preferences. # sage-open -- a wrapper around OS X open that # turns off any of Sage's special library stuff. BROWSER = "sage-open" DVI_VIEWER = BROWSER PDF_VIEWER = BROWSER PNG_VIEWER = BROWSER elif os.uname()[0][:6] == "CYGWIN": # Windows is also easy, since it has a system for # determining what opens things. # Bobby Moreti provided the following. if not "BROWSER" in os.environ: systemroot = os.environ["SYSTEMROOT"].replace(":", "/").replace("\\", "") systemroot = "/cygdrive/" + systemroot BROWSER = "%s/system32/rundll32.exe url.dll,FileProtocolHandler" % systemroot else: BROWSER = os.environ["BROWSER"] DVI_VIEWER = BROWSER PDF_VIEWER = BROWSER PNG_VIEWER = BROWSER elif have_program("xdg-open"): # On other OS'es try xdg-open if present. # See http://portland.freedesktop.org/xdg-utils-1.0. BROWSER = "xdg-open" DVI_VIEWER = BROWSER PDF_VIEWER = BROWSER PNG_VIEWER = BROWSER else: # If all fails try to get something from the environment. try: BROWSER = os.environ["BROWSER"] except KeyError: BROWSER = "less" # silly default; lets hope it doesn't come to this! for cmd in ["firefox", "konqueror", "mozilla", "mozilla-firefox"]: if have_program(cmd): BROWSER = cmd break DVI_VIEWER = BROWSER PDF_VIEWER = BROWSER PNG_VIEWER = BROWSER # Alternatives, if they are set in the environment or available. try: DVI_VIEWER = os.environ["DVI_VIEWER"] except KeyError: for cmd in ["xdvi", "kdvi"]: if have_program(cmd): DVI_VIEWER = cmd break try: PDF_VIEWER = os.environ["PDF_VIEWER"] except KeyError: for cmd in ["acroread", "xpdf"]: if have_program(cmd): PDF_VIEWER = cmd break if viewer is None or viewer.startswith("browse"): return BROWSER elif viewer.startswith("dvi"): return DVI_VIEWER elif viewer.startswith("png"): return PNG_VIEWER elif viewer.startswith("pdf"): return PDF_VIEWER else: raise ValueError("Unknown type of viewer: {}.".format(viewer))
def viewer(): from sage.misc.sage_ostools import have_program global BROWSER, DVI_VIEWER, PDF_VIEWER, PNG_VIEWER if not (BROWSER is None): return BROWSER if os.environ.has_key('SAGE_BROWSER'): BROWSER = os.environ['SAGE_BROWSER'] DVI_VIEWER = BROWSER PDF_VIEWER = BROWSER PNG_VIEWER = BROWSER return BROWSER if os.uname()[0] == 'Darwin': # Simple on OS X, since there is an open command that opens # anything, using the user's preferences. # sage-open -- a wrapper around OS X open that # turns off any of Sage's special library stuff. BROWSER = 'sage-open' DVI_VIEWER = BROWSER PDF_VIEWER = BROWSER PNG_VIEWER = BROWSER elif os.uname()[0][:6] == 'CYGWIN': # Windows is also easy, since it has a system for # determining what opens things. # Bobby Moreti provided the following. if not os.environ.has_key('BROWSER'): systemroot = os.environ['SYSTEMROOT'].replace(':','/').replace('\\','') systemroot = '/cygdrive/' + systemroot BROWSER = '%s/system32/rundll32.exe url.dll,FileProtocolHandler'%\ systemroot DVI_VIEWER = BROWSER PDF_VIEWER = BROWSER PNG_VIEWER = BROWSER elif have_program('xdg-open'): # On other OS'es try xdg-open if present. # See http://portland.freedesktop.org/xdg-utils-1.0. BROWSER = 'xdg-open' DVI_VIEWER = BROWSER PDF_VIEWER = BROWSER PNG_VIEWER = BROWSER else: # If all fails try to get something from the environment. try: BROWSER = os.environ['BROWSER'] except KeyError: BROWSER = 'less' # silly default; lets hope it doesn't come to this! for cmd in ['firefox', 'konqueror', 'mozilla', 'mozilla-firefox']: if have_program(cmd): BROWSER = cmd break DVI_VIEWER = BROWSER PDF_VIEWER = BROWSER PNG_VIEWER = BROWSER # Alternatives, if they are set in the environment or available. try: DVI_VIEWER = os.environ['DVI_VIEWER'] except KeyError: for cmd in ['xdvi', 'kdvi']: if have_program(cmd): DVI_VIEWER = cmd break try: PDF_VIEWER = os.environ['PDF_VIEWER'] except KeyError: for cmd in ['acroread', 'xpdf']: if have_program(cmd): PDF_VIEWER = cmd break return BROWSER
def save(self, filename, figsize=None, **kwds): r""" Save ``self`` to a file, in various formats. INPUT: - ``filename`` -- (string) the file name; the image format is given by the extension, which can be one of the following: * ``.eps``, * ``.pdf``, * ``.png``, * ``.ps``, * ``.sobj`` (for a Sage object you can load later), * ``.svg``, * empty extension will be treated as ``.sobj``. - ``figsize`` -- (default: ``None``) width or [width, height] in inches of the Matplotlib figure; if none is provided, Matplotlib's default (6.4 x 4.8 inches) is used - ``kwds`` -- keyword arguments, like ``dpi=...``, passed to the plotter, see :meth:`show` EXAMPLES:: sage: F = tmp_filename(ext='.png') sage: L = [plot(sin(k*x), (x,-pi,pi)) for k in [1..3]] sage: G = graphics_array(L) sage: G.save(F, dpi=500, axes=False) TESTS:: sage: graphics_array([]).save(F) sage: graphics_array([[]]).save(F) """ from matplotlib import rcParams ext = os.path.splitext(filename)[1].lower() if ext in ['', '.sobj']: SageObject.save(self, filename) elif ext not in ALLOWED_EXTENSIONS: raise ValueError("allowed file extensions for images are '" + "', '".join(ALLOWED_EXTENSIONS) + "'!") else: rc_backup = (rcParams['ps.useafm'], rcParams['pdf.use14corefonts'], rcParams['text.usetex']) # save the rcParams figure = self.matplotlib(figsize=figsize, **kwds) transparent = kwds.get('transparent', Graphics.SHOW_OPTIONS['transparent']) fig_tight = kwds.get('fig_tight', Graphics.SHOW_OPTIONS['fig_tight']) dpi = kwds.get('dpi', Graphics.SHOW_OPTIONS['dpi']) # One can output in PNG, PS, EPS, PDF, PGF, or SVG format, # depending on the file extension. # PGF is handled by a different backend if ext == '.pgf': from sage.misc.sage_ostools import have_program latex_implementations = [i for i in ["xelatex", "pdflatex", "lualatex"] if have_program(i)] if not latex_implementations: raise ValueError("Matplotlib requires either xelatex, " "lualatex, or pdflatex.") if latex_implementations[0] == "pdflatex": # use pdflatex and set font encoding as per # Matplotlib documentation: # https://matplotlib.org/users/pgf.html#pgf-tutorial pgf_options = {"pgf.texsystem": "pdflatex", "pgf.preamble": [ r"\usepackage[utf8x]{inputenc}", r"\usepackage[T1]{fontenc}" ]} else: pgf_options = {"pgf.texsystem": latex_implementations[0]} rcParams.update(pgf_options) from matplotlib.backends.backend_pgf import FigureCanvasPgf figure.set_canvas(FigureCanvasPgf(figure)) # Matplotlib looks at the file extension to see what the renderer # should be. The default is FigureCanvasAgg for PNG's because this # is by far the most common type of files rendered, like in the # notebook, for example. If the file extension is not '.png', then # Matplotlib will handle it. else: from matplotlib.backends.backend_agg import FigureCanvasAgg figure.set_canvas(FigureCanvasAgg(figure)) if isinstance(self, GraphicsArray): # tight_layout adjusts the *subplot* parameters so ticks aren't # cut off, etc. figure.tight_layout() opts = dict(dpi=dpi, transparent=transparent) if fig_tight is True: opts['bbox_inches'] = 'tight' figure.savefig(filename, **opts) # Restore the rcParams to the original, possibly user-set values (rcParams['ps.useafm'], rcParams['pdf.use14corefonts'], rcParams['text.usetex']) = rc_backup
def install_scripts(directory=None, ignore_existing=False): r""" Running ``install_scripts(directory)`` creates scripts in the given directory that run various software components included with Sage. Each of these scripts essentially just runs ``sage --CMD`` where ``CMD`` is also the name of the script: - 'gap' runs GAP - 'gp' runs the PARI/GP interpreter - 'hg' runs Mercurial - 'ipython' runs IPython - 'maxima' runs Maxima - 'mwrank' runs mwrank - 'R' runs R - 'singular' runs Singular - 'sqlite3' runs SQLite version 3 - 'kash' runs Kash if it is installed (Kash is an optional Sage package) - 'M2' runs Macaulay2 if it is installed (Macaulay2 is an experimental Sage package) This command: - verbosely tells you which scripts it adds, and - will *not* overwrite any scripts you already have in the given directory. INPUT: - ``directory`` - string; the directory into which to put the scripts. This directory must exist and the user must have write and execute permissions. - ``ignore_existing`` - bool (optional, default False): if True, install script even if another version of the program is in your path. OUTPUT: Verbosely prints what it is doing and creates files in ``directory`` that are world executable and readable. .. note:: You may need to run ``sage`` as ``root`` in order to run ``install_scripts`` successfully, since the user running ``sage`` needs write permissions on ``directory``. Note that one good candidate for ``directory`` is ``'/usr/local/bin'``, so from the shell prompt, you could run :: sudo sage -c "install_scripts('/usr/local/bin')" .. note:: Running ``install_scripts(directory)`` will be most helpful if ``directory`` is in your path. AUTHORS: - William Stein: code / design - Arthur Gaer: design - John Palmieri: revision, 2011-07 (trac ticket #11602) EXAMPLES:: sage: install_scripts(str(SAGE_TMP), ignore_existing=True) Checking that Sage has the command 'gap' installed ... """ if directory is None: # We do this since the intended user of install_scripts # will likely be pretty clueless about how to use Sage or # its help system. import sagedoc print sagedoc.format(install_scripts.__doc__) print "USAGE: install_scripts('directory')" return if not os.path.exists(directory): print "Error: '%s' does not exist." % directory return if not os.path.isdir(directory): print "Error: '%s' is not a directory." % directory return if not (os.access(directory, os.W_OK) and os.access(directory, os.X_OK)): print "Error: you do not have write permission for '%s'." % directory return from sage.misc.sage_ostools import have_program from sage.env import SAGE_LOCAL script_created = False SAGE_BIN = os.path.join(SAGE_LOCAL, 'bin') # See if 'directory' is already in PATH, and then remove # SAGE_LOCAL/bin from PATH so that we can later check whether # cmd is available outside of Sage. PATH = os.environ['PATH'].split(os.pathsep) PATH = [d for d in PATH if os.path.exists(d)] dir_in_path = any([os.path.samefile(directory, d) for d in PATH]) PATH = os.pathsep.join([d for d in PATH if not os.path.samefile(d, SAGE_BIN)]) for cmd in ['gap', 'gp', 'hg', 'ipython', 'maxima', 'mwrank', 'R', 'singular', 'sqlite3', 'M2', 'kash']: print "Checking that Sage has the command '%s' installed" % cmd # Check to see if Sage includes cmd. cmd_inside_sage = have_program(cmd, path=SAGE_BIN) cmd_outside_sage = have_program(cmd, path=PATH) if not cmd_inside_sage: print ("The command '%s' is not available as part " %cmd + "of Sage; not creating script.") print continue if cmd_outside_sage: print "The command '%s' is installed outside of Sage;" % cmd, if not ignore_existing: print "not creating script." print continue print "trying to create script anyway..." else: print "Creating script for '%s'..." % cmd # Install shortcut. target = os.path.join(directory, cmd) if os.path.exists(target): print "The file '%s' already exists; not adding script."%(target) else: o = open(target,'w') o.write('#!/bin/sh\n') o.write('exec sage --%s "$@"\n'%cmd) o.close() print "Created script '%s'"%target os.system('chmod a+rx %s'%target) script_created = True print if script_created: print "Finished creating scripts." print print "You need not do this again even if you upgrade or move Sage." print "The only requirement is that your PATH contains both" print "'%s' and the directory containing the command 'sage'." % directory if not dir_in_path: print print "Warning: '%s' is not currently in your PATH." % directory print else: print "No scripts created."
def default_viewer(viewer=None): """ Set up default programs for opening web pages, PDFs, PNGs, and DVI files. INPUT: - ``viewer``: ``None`` or a string: one of 'browser', 'pdf', 'png', 'dvi' -- return the name of the corresponding program. ``None`` is treated the same as 'browser'. EXAMPLES:: sage: from sage.misc.viewer import default_viewer sage: default_viewer(None) # random -- depends on OS, etc. 'sage-open' sage: default_viewer('pdf') # random -- depends on OS, etc. 'xdg-open' sage: default_viewer('jpg') Traceback (most recent call last): ... ValueError: Unknown type of viewer: jpg. """ import os from sage.misc.sage_ostools import have_program if isinstance(viewer, str): viewer = viewer.lower() if 'SAGE_BROWSER' in os.environ: BROWSER = os.environ['SAGE_BROWSER'] DVI_VIEWER = BROWSER PDF_VIEWER = BROWSER PNG_VIEWER = BROWSER elif os.uname()[0] == 'Darwin': # Simple on OS X, since there is an open command that opens # anything, using the user's preferences. # sage-open -- a wrapper around OS X open that # turns off any of Sage's special library stuff. BROWSER = 'sage-open' DVI_VIEWER = BROWSER PDF_VIEWER = BROWSER PNG_VIEWER = BROWSER elif os.uname()[0][:6] == 'CYGWIN': # Windows is also easy, since it has a system for # determining what opens things. # Bobby Moreti provided the following. if not 'BROWSER' in os.environ: systemroot = os.environ['SYSTEMROOT'].replace(':', '/').replace( '\\', '') systemroot = '/cygdrive/' + systemroot BROWSER = '%s/system32/rundll32.exe url.dll,FileProtocolHandler'%\ systemroot else: BROWSER = os.environ['BROWSER'] DVI_VIEWER = BROWSER PDF_VIEWER = BROWSER PNG_VIEWER = BROWSER elif have_program('xdg-open'): # On other OS'es try xdg-open if present. # See http://portland.freedesktop.org/xdg-utils-1.0. BROWSER = 'xdg-open' DVI_VIEWER = BROWSER PDF_VIEWER = BROWSER PNG_VIEWER = BROWSER else: # If all fails try to get something from the environment. try: BROWSER = os.environ['BROWSER'] except KeyError: BROWSER = 'less' # silly default; lets hope it doesn't come to this! for cmd in ['firefox', 'konqueror', 'mozilla', 'mozilla-firefox']: if have_program(cmd): BROWSER = cmd break DVI_VIEWER = BROWSER PDF_VIEWER = BROWSER PNG_VIEWER = BROWSER # Alternatives, if they are set in the environment or available. try: DVI_VIEWER = os.environ['DVI_VIEWER'] except KeyError: for cmd in ['xdvi', 'kdvi']: if have_program(cmd): DVI_VIEWER = cmd break try: PDF_VIEWER = os.environ['PDF_VIEWER'] except KeyError: for cmd in ['acroread', 'xpdf']: if have_program(cmd): PDF_VIEWER = cmd break if viewer is None or viewer.startswith('browse'): return BROWSER elif viewer.startswith('dvi'): return DVI_VIEWER elif viewer.startswith('png'): return PNG_VIEWER elif viewer.startswith('pdf'): return PDF_VIEWER else: raise ValueError('Unknown type of viewer: {}.'.format(viewer))
def gif(self, delay=20, savefile=None, iterations=0, show_path=False, use_ffmpeg=False): r""" Returns an animated gif composed from rendering the graphics objects in self. This method will only work if either (a) the ImageMagick software suite is installed, i.e., you have the ``convert`` command or (b) ``ffmpeg`` is installed. See [IM] for more about ImageMagick, and see [FF] for more about ``ffmpeg``. By default, this produces the gif using ``convert`` if it is present. If this can't find ``convert`` or if ``use_ffmpeg`` is True, then it uses ``ffmpeg`` instead. INPUT: - ``delay`` - (default: 20) delay in hundredths of a second between frames - ``savefile`` - file that the animated gif gets saved to - ``iterations`` - integer (default: 0); number of iterations of animation. If 0, loop forever. - ``show_path`` - boolean (default: False); if True, print the path to the saved file - ``use_ffmpeg`` - boolean (default: False); if True, use 'ffmpeg' by default instead of 'convert'. If ``savefile`` is not specified: in notebook mode, display the animation; otherwise, save it to a default file name. EXAMPLES:: sage: a = animate([sin(x + float(k)) for k in srange(0,2*pi,0.7)], ....: xmin=0, xmax=2*pi, figsize=[2,1]) sage: dir = tmp_dir() sage: a.gif() # not tested sage: a.gif(savefile=dir + 'my_animation.gif', delay=35, iterations=3) # optional -- ImageMagick sage: a.gif(savefile=dir + 'my_animation.gif', show_path=True) # optional -- ImageMagick Animation saved to .../my_animation.gif. sage: a.gif(savefile=dir + 'my_animation_2.gif', show_path=True, use_ffmpeg=True) # optional -- ffmpeg Animation saved to .../my_animation_2.gif. .. note:: If neither ffmpeg nor ImageMagick is installed, you will get an error message like this:: Error: Neither ImageMagick nor ffmpeg appears to be installed. Saving an animation to a GIF file or displaying an animation requires one of these packages, so please install one of them and try again. See www.imagemagick.org and www.ffmpeg.org for more information. """ from sage.misc.sage_ostools import have_program have_convert = have_program('convert') have_ffmpeg = self._have_ffmpeg() if use_ffmpeg or not have_convert: if have_ffmpeg: self.ffmpeg(savefile=savefile, show_path=show_path, output_format='.gif', delay=delay, iterations=iterations) else: if not have_convert: msg = """ Error: Neither ImageMagick nor ffmpeg appears to be installed. Saving an animation to a GIF file or displaying an animation requires one of these packages, so please install one of them and try again. See www.imagemagick.org and www.ffmpeg.org for more information.""" else: msg = """ Error: ffmpeg does not appear to be installed. Download it from www.ffmpeg.org, or use 'convert' to produce gifs instead.""" raise OSError(msg) else: if not savefile: savefile = graphics_filename(ext='gif') if not savefile.endswith('.gif'): savefile += '.gif' savefile = os.path.abspath(savefile) d = self.png() cmd = ( 'cd "%s"; sage-native-execute convert -dispose Background ' '-delay %s -loop %s *.png "%s"' ) % ( d, int(delay), int(iterations), savefile ) from subprocess import check_call, CalledProcessError try: check_call(cmd, shell=True) if show_path: print "Animation saved to file %s." % savefile except (CalledProcessError, OSError): msg = """ Error: Cannot generate GIF animation. Verify that convert (ImageMagick) or ffmpeg is installed, and that the objects passed to the animate command can be saved in PNG image format. See www.imagemagick.org and www.ffmpeg.org for more information.""" raise OSError(msg)
def default_viewer(viewer=None): """ Set up default programs for opening web pages, PDFs, PNGs, and DVI files. INPUT: - ``viewer``: ``None`` or a string: one of 'browser', 'pdf', 'png', 'dvi' -- return the name of the corresponding program. ``None`` is treated the same as 'browser'. EXAMPLES:: sage: from sage.misc.viewer import default_viewer sage: default_viewer(None) # random -- depends on OS, etc. 'sage-open' sage: default_viewer('pdf') # random -- depends on OS, etc. 'xdg-open' sage: default_viewer('jpg') Traceback (most recent call last): ... ValueError: Unknown type of viewer: jpg. """ import os from sage.misc.sage_ostools import have_program if isinstance(viewer, str): viewer = viewer.lower() if 'SAGE_BROWSER' in os.environ: BROWSER = os.environ['SAGE_BROWSER'] DVI_VIEWER = BROWSER PDF_VIEWER = BROWSER PNG_VIEWER = BROWSER elif os.uname()[0] == 'Darwin': # Simple on OS X, since there is an open command that opens # anything, using the user's preferences. # sage-open -- a wrapper around OS X open that # turns off any of Sage's special library stuff. BROWSER = 'sage-open' DVI_VIEWER = BROWSER PDF_VIEWER = BROWSER PNG_VIEWER = BROWSER elif os.uname()[0][:6] == 'CYGWIN': # Windows is also easy, since it has a system for # determining what opens things. # Bobby Moreti provided the following. if not 'BROWSER' in os.environ: systemroot = os.environ['SYSTEMROOT'].replace(':','/').replace('\\','') systemroot = '/cygdrive/' + systemroot BROWSER = '%s/system32/rundll32.exe url.dll,FileProtocolHandler'%\ systemroot else: BROWSER = os.environ['BROWSER'] DVI_VIEWER = BROWSER PDF_VIEWER = BROWSER PNG_VIEWER = BROWSER elif have_program('xdg-open'): # On other OS'es try xdg-open if present. # See http://portland.freedesktop.org/xdg-utils-1.0. BROWSER = 'xdg-open' DVI_VIEWER = BROWSER PDF_VIEWER = BROWSER PNG_VIEWER = BROWSER else: # If all fails try to get something from the environment. try: BROWSER = os.environ['BROWSER'] except KeyError: BROWSER = 'less' # silly default; lets hope it doesn't come to this! for cmd in ['firefox', 'konqueror', 'mozilla', 'mozilla-firefox']: if have_program(cmd): BROWSER = cmd break DVI_VIEWER = BROWSER PDF_VIEWER = BROWSER PNG_VIEWER = BROWSER # Alternatives, if they are set in the environment or available. try: DVI_VIEWER = os.environ['DVI_VIEWER'] except KeyError: for cmd in ['xdvi', 'kdvi']: if have_program(cmd): DVI_VIEWER = cmd break try: PDF_VIEWER = os.environ['PDF_VIEWER'] except KeyError: for cmd in ['acroread', 'xpdf']: if have_program(cmd): PDF_VIEWER = cmd break if viewer is None or viewer.startswith('browse'): return BROWSER elif viewer.startswith('dvi'): return DVI_VIEWER elif viewer.startswith('png'): return PNG_VIEWER elif viewer.startswith('pdf'): return PDF_VIEWER else: raise ValueError, 'Unknown type of viewer: %s.' % viewer
def install_scripts(directory=None, ignore_existing=False): r""" Running ``install_scripts(directory)`` creates scripts in the given directory that run various software components included with Sage. Each of these scripts essentially just runs ``sage --CMD`` where ``CMD`` is also the name of the script: - 'gap' runs GAP - 'gp' runs the PARI/GP interpreter - 'hg' runs Mercurial - 'ipython' runs IPython - 'maxima' runs Maxima - 'mwrank' runs mwrank - 'R' runs R - 'singular' runs Singular - 'sqlite3' runs SQLite version 3 - 'kash' runs Kash if it is installed (Kash is an optional Sage package) - 'M2' runs Macaulay2 if it is installed (Macaulay2 is an experimental Sage package) This command: - verbosely tells you which scripts it adds, and - will *not* overwrite any scripts you already have in the given directory. INPUT: - ``directory`` - string; the directory into which to put the scripts. This directory must exist and the user must have write and execute permissions. - ``ignore_existing`` - bool (optional, default False): if True, install script even if another version of the program is in your path. OUTPUT: Verbosely prints what it is doing and creates files in ``directory`` that are world executable and readable. .. note:: You may need to run ``sage`` as ``root`` in order to run ``install_scripts`` successfully, since the user running ``sage`` needs write permissions on ``directory``. Note that one good candidate for ``directory`` is ``'/usr/local/bin'``, so from the shell prompt, you could run :: sudo sage -c "install_scripts('/usr/local/bin')" .. note:: Running ``install_scripts(directory)`` will be most helpful if ``directory`` is in your path. AUTHORS: - William Stein: code / design - Arthur Gaer: design - John Palmieri: revision, 2011-07 (:trac:`11602`) EXAMPLES:: sage: install_scripts(str(SAGE_TMP), ignore_existing=True) Checking that Sage has the command 'gap' installed ... """ if directory is None: # We do this since the intended user of install_scripts # will likely be pretty clueless about how to use Sage or # its help system. import sagedoc print(sagedoc.format(install_scripts.__doc__)) print("USAGE: install_scripts('directory')") return if not os.path.exists(directory): print("Error: '{}' does not exist.".format(directory)) return if not os.path.isdir(directory): print("Error: '{}' is not a directory.".format(directory)) return if not (os.access(directory, os.W_OK) and os.access(directory, os.X_OK)): print("Error: you do not have write permission for '{}'.".format( directory)) return from sage.misc.sage_ostools import have_program from sage.env import SAGE_LOCAL script_created = False SAGE_BIN = os.path.join(SAGE_LOCAL, 'bin') # See if 'directory' is already in PATH, and then remove # SAGE_LOCAL/bin from PATH so that we can later check whether # cmd is available outside of Sage. PATH = os.environ['PATH'].split(os.pathsep) PATH = [d for d in PATH if os.path.exists(d)] dir_in_path = any([os.path.samefile(directory, d) for d in PATH]) PATH = os.pathsep.join( [d for d in PATH if not os.path.samefile(d, SAGE_BIN)]) for cmd in [ 'gap', 'gp', 'hg', 'ipython', 'maxima', 'mwrank', 'R', 'singular', 'sqlite3', 'M2', 'kash' ]: print("Checking that Sage has the command '{}' installed".format(cmd)) # Check to see if Sage includes cmd. cmd_inside_sage = have_program(cmd, path=SAGE_BIN) cmd_outside_sage = have_program(cmd, path=PATH) if not cmd_inside_sage: print("The command '{}' is not available as part ".format(cmd) + "of Sage; not creating script.") print() continue if cmd_outside_sage: print("The command '{}' is installed outside of Sage;".format(cmd), end=' ') if not ignore_existing: print("not creating script.") print() continue print("trying to create script anyway...") else: print("Creating script for '{}'...".format(cmd)) # Install shortcut. target = os.path.join(directory, cmd) if os.path.exists(target): print("The file '{}' already exists; not adding script.".format( target)) else: o = open(target, 'w') o.write('#!/bin/sh\n') o.write('exec sage --%s "$@"\n' % cmd) o.close() print("Created script '{}'".format(target)) os.system('chmod a+rx {}'.format(target)) script_created = True print() if script_created: print("Finished creating scripts.") print() print("You need not do this again even if you upgrade or move Sage.") print("The only requirement is that your PATH contains both") print("'{}' and the directory containing the command 'sage'.".format( directory)) if not dir_in_path: print() print("Warning: '{}' is not currently in your PATH.".format( directory)) print() else: print("No scripts created.")
def blackbox(self, polys, input_ring, verbose = False): """ Returns as a string the result of running PHC with the given polynomials under blackbox mode (the '-b' option). INPUT: - polys -- a list of multivariate polynomials (elements of a multivariate polynomial ring). - input_ring -- for coercion of the variables into the desired ring. - verbose -- print lots of verbose information about what this function does. OUTPUT: - a PHC_Object object containing the phcpack output string. EXAMPLES:: sage: from sage.interfaces.phc import * sage: R2.<x,y> = PolynomialRing(QQ,2) sage: start_sys = [x^6-y^2,y^5-1] sage: sol = phc.blackbox(start_sys, R2) # optional -- phc sage: len(sol.solutions()) # optional -- phc 30 """ # Get three temporary file names (these will be in SAGE_HOME/.sage/tmp/pid) input_filename = tmp_filename() output_filename = input_filename + ".phc" log_filename = tmp_filename() # Get the input polynomial text input = self._input_file(polys) if verbose: print("Writing the input file to %s" % input_filename) open(input_filename, 'w').write(input) if verbose: print("The following file will be the input polynomial file to phc.") print(input) # Create the phc command line> cmd = 'phc -b %s %s'%(input_filename, output_filename) if verbose: print("The phc command line is:") print(cmd) # Do it -- make the system call. e = os.system(cmd) # Was there an error? if e: from sage.misc.sage_ostools import have_program if not have_program('phc'): print(os.system('which phc') + ' PHC needs to be installed and in your path') raise RuntimeError # todo -- why? etc. raise RuntimeError(open(log_filename).read() + "\nError running phc.") if not os.path.exists(output_filename): raise RuntimeError("The output file does not exist; something went wrong running phc.") # Read the output produced by PHC out = open(output_filename).read() # All done return PHC_Object(out, input_ring)
def viewer(): from sage.misc.sage_ostools import have_program global BROWSER, DVI_VIEWER, PDF_VIEWER, PNG_VIEWER if not (BROWSER is None): return BROWSER if os.environ.has_key('SAGE_BROWSER'): BROWSER = os.environ['SAGE_BROWSER'] DVI_VIEWER = BROWSER PDF_VIEWER = BROWSER PNG_VIEWER = BROWSER return BROWSER if os.uname()[0] == 'Darwin': # Simple on OS X, since there is an open command that opens # anything, using the user's preferences. # sage-open -- a wrapper around OS X open that # turns off any of Sage's special library stuff. BROWSER = 'sage-open' DVI_VIEWER = BROWSER PDF_VIEWER = BROWSER PNG_VIEWER = BROWSER elif os.uname()[0][:6] == 'CYGWIN': # Windows is also easy, since it has a system for # determining what opens things. # Bobby Moreti provided the following. if not os.environ.has_key('BROWSER'): systemroot = os.environ['SYSTEMROOT'].replace(':', '/').replace( '\\', '') systemroot = '/cygdrive/' + systemroot BROWSER = '%s/system32/rundll32.exe url.dll,FileProtocolHandler'%\ systemroot DVI_VIEWER = BROWSER PDF_VIEWER = BROWSER PNG_VIEWER = BROWSER elif have_program('xdg-open'): # On other OS'es try xdg-open if present. # See http://portland.freedesktop.org/xdg-utils-1.0. BROWSER = 'xdg-open' DVI_VIEWER = BROWSER PDF_VIEWER = BROWSER PNG_VIEWER = BROWSER else: # If all fails try to get something from the environment. try: BROWSER = os.environ['BROWSER'] except KeyError: BROWSER = 'less' # silly default; lets hope it doesn't come to this! for cmd in ['firefox', 'konqueror', 'mozilla', 'mozilla-firefox']: if have_program(cmd): BROWSER = cmd break DVI_VIEWER = BROWSER PDF_VIEWER = BROWSER PNG_VIEWER = BROWSER # Alternatives, if they are set in the environment or available. try: DVI_VIEWER = os.environ['DVI_VIEWER'] except KeyError: for cmd in ['xdvi', 'kdvi']: if have_program(cmd): DVI_VIEWER = cmd break try: PDF_VIEWER = os.environ['PDF_VIEWER'] except KeyError: for cmd in ['acroread', 'xpdf']: if have_program(cmd): PDF_VIEWER = cmd break return BROWSER