def save(self, filename=None, show_path=False, use_ffmpeg=False): """ Save this animation. INPUT: - ``filename`` - (default: None) name of save file - ``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' when creating GIF files. If filename is None, then in notebook mode, display the animation; otherwise, save the animation to a GIF file. If filename ends in '.sobj', save to an sobj file. Otherwise, try to determine the format from the filename extension ('.mpg', '.gif', '.avi', etc.). If the format cannot be determined, default to GIF. For GIF files, either ffmpeg or the ImageMagick suite must be installed. For other movie formats, ffmpeg must be installed. An sobj file can be saved with no extra software installed. 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.save() # not tested sage: a.save(dir + 'wave.gif') # optional -- ImageMagick sage: a.save(dir + 'wave.gif', show_path=True) # optional -- ImageMagick Animation saved to file .../wave.gif. sage: a.save(dir + 'wave.avi', show_path=True) # optional -- ffmpeg Animation saved to file .../wave.avi. sage: a.save(dir + 'wave0.sobj') sage: a.save(dir + 'wave1.sobj', show_path=True) Animation saved to file .../wave1.sobj. """ if filename is None: suffix = '.gif' else: suffix = os.path.splitext(filename)[1] if len(suffix) == 0: suffix = '.gif' if filename is None or suffix == '.gif': self.gif(savefile=filename, show_path=show_path, use_ffmpeg=use_ffmpeg) return elif suffix == '.sobj': SageObject.save(self, filename) if show_path: print "Animation saved to file %s." % filename return else: self.ffmpeg(savefile=filename, show_path=show_path) return
def __init__(self, vert, dop): r""" TESTS:: sage: from ore_algebra import * sage: from ore_algebra.analytic.path import Path sage: Dops, x, Dx = DifferentialOperators() sage: dop = (x^2 + 1)*Dx^2 + 2*x*Dx sage: Path([], Dx) Traceback (most recent call last): ... ValueError: empty path """ SageObject.__init__(self) self.dop = dop if not vert: raise ValueError("empty path") self.vert = [] for v in vert: if isinstance(v, Point): pass elif isinstance(v, list) and len(v) == 1: v = Point(v[0], dop, keep_value=True) else: v = Point(v, dop) self.vert.append(v)
def __init__(self, vert, dop): r""" TESTS:: sage: from ore_algebra import * sage: from ore_algebra.analytic.path import Path sage: Dops, x, Dx = DifferentialOperators() sage: dop = (x^2 + 1)*Dx^2 + 2*x*Dx sage: Path([], Dx) Traceback (most recent call last): ... ValueError: empty path """ SageObject.__init__(self) self.dop = dop if not vert: raise ValueError("empty path") self.vert = [ v if isinstance(v, Point) else Point(v, dop) for v in vert ]
def save(self, filename='sage.wav'): r""" Save this wave file to disk, either as a Sage sobj or as a .wav file. INPUT: filename -- the path of the file to save. If filename ends with 'wav', then save as a wave file, otherwise, save a Sage object. If no input is given, save the file as 'sage.wav'. """ if not filename.endswith('.wav'): SageObject.save(self, filename) return wv = wave.open(filename, 'wb') wv.setnchannels(self._nchannels) wv.setsampwidth(self._width) wv.setframerate(self._framerate) wv.setnframes(self._nframes) wv.writeframes(self._bytes) wv.close()
def _gap_(self, G=None): try: return SageObject._gap_(self, G) except TypeError: raise NotImplementedError, "Matrix group over %s not implemented." % self.__R
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 __init__(self, point, dop=None): """ TESTS:: sage: from ore_algebra import * sage: from ore_algebra.analytic.path import Point sage: Dops, x, Dx = DifferentialOperators() sage: [Point(z, Dx) ....: for z in [1, 1/2, 1+I, QQbar(I), RIF(1/3), CIF(1/3), pi, ....: RDF(1), CDF(I), 0.5r, 0.5jr, 10r, QQbar(1), AA(1/3)]] [1, 1/2, I + 1, I, [0.333333333333333...], [0.333333333333333...], 3.141592653589794?, 1.000000000000000, 1.000000000000000*I, 0.5000000000000000, 0.5000000000000000*I, 10, 1, 1/3] sage: Point(sqrt(2), Dx).iv() [1.414...] """ SageObject.__init__(self) from sage.rings.complex_double import ComplexDoubleField_class from sage.rings.complex_field import ComplexField_class from sage.rings.complex_interval_field import ComplexIntervalField_class from sage.rings.real_double import RealDoubleField_class from sage.rings.real_mpfi import RealIntervalField_class from sage.rings.real_mpfr import RealField_class point = sage.structure.coerce.py_scalar_to_element(point) try: parent = point.parent() except AttributeError: raise TypeError("unexpected value for point: " + repr(point)) if isinstance(point, Point): self.value = point.value elif isinstance( parent, (number_field_base.NumberField, RealBallField, ComplexBallField)): self.value = point elif QQ.has_coerce_map_from(parent): self.value = QQ.coerce(point) # must come before QQbar, due to a bogus coerce map (#14485) elif parent is sage.symbolic.ring.SR: try: return self.__init__(point.pyobject(), dop) except TypeError: pass try: return self.__init__(QQbar(point), dop) except (TypeError, ValueError, NotImplementedError): pass try: self.value = RLF(point) except (TypeError, ValueError): self.value = CLF(point) elif QQbar.has_coerce_map_from(parent): alg = QQbar.coerce(point) NF, val, hom = alg.as_number_field_element() if NF is QQ: self.value = QQ.coerce(val) # parent may be ZZ else: embNF = number_field.NumberField(NF.polynomial(), NF.variable_name(), embedding=hom(NF.gen())) self.value = val.polynomial()(embNF.gen()) elif isinstance( parent, (RealField_class, RealDoubleField_class, RealIntervalField_class)): self.value = RealBallField(point.prec())(point) elif isinstance(parent, (ComplexField_class, ComplexDoubleField_class, ComplexIntervalField_class)): self.value = ComplexBallField(point.prec())(point) else: try: self.value = RLF.coerce(point) except TypeError: self.value = CLF.coerce(point) parent = self.value.parent() assert (isinstance( parent, (number_field_base.NumberField, RealBallField, ComplexBallField)) or parent is RLF or parent is CLF) self.dop = dop or point.dop self.keep_value = False
def _gap_(self, G=None): try: return SageObject._gap_(self, G) except TypeError: raise NotImplementedError, "Matrix group over %s not implemented."%self.__R
def __init__(self, point, dop=None, singular=None, **kwds): """ INPUT: - ``singular``: can be set to True to force this point to be considered a singular point, even if this cannot be checked (e.g. because we only have an enclosure) TESTS:: sage: from ore_algebra import * sage: from ore_algebra.analytic.path import Point sage: Dops, x, Dx = DifferentialOperators() sage: [Point(z, Dx) ....: for z in [1, 1/2, 1+I, QQbar(I), RIF(1/3), CIF(1/3), pi, ....: RDF(1), CDF(I), 0.5r, 0.5jr, 10r, QQbar(1), AA(1/3)]] [1, 1/2, I + 1, I, [0.333333333333333...], [0.333333333333333...], 3.141592653589794?, ~1.0000, ~1.0000*I, ~0.50000, ~0.50000*I, 10, 1, 1/3] sage: Point(sqrt(2), Dx).iv() [1.414...] sage: Point(RBF(0), (x-1)*x*Dx, singular=True).dist_to_sing() 1.000000000000000 """ SageObject.__init__(self) from sage.rings.complex_double import ComplexDoubleField_class from sage.rings.complex_field import ComplexField_class from sage.rings.complex_interval_field import ComplexIntervalField_class from sage.rings.real_double import RealDoubleField_class from sage.rings.real_mpfi import RealIntervalField_class from sage.rings.real_mpfr import RealField_class point = sage.structure.coerce.py_scalar_to_element(point) try: parent = point.parent() except AttributeError: raise TypeError("unexpected value for point: " + repr(point)) if isinstance(point, Point): self.value = point.value elif isinstance(parent, (RealBallField, ComplexBallField)): self.value = point elif isinstance(parent, number_field_base.NumberField): _, hom = good_number_field(point.parent()) self.value = hom(point) elif QQ.has_coerce_map_from(parent): self.value = QQ.coerce(point) elif QQbar.has_coerce_map_from(parent): alg = QQbar.coerce(point) NF, val, hom = alg.as_number_field_element() if NF is QQ: self.value = QQ.coerce(val) # parent may be ZZ else: embNF = number_field.NumberField(NF.polynomial(), NF.variable_name(), embedding=hom(NF.gen())) self.value = val.polynomial()(embNF.gen()) elif isinstance( parent, (RealField_class, RealDoubleField_class, RealIntervalField_class)): self.value = RealBallField(point.prec())(point) elif isinstance(parent, (ComplexField_class, ComplexDoubleField_class, ComplexIntervalField_class)): self.value = ComplexBallField(point.prec())(point) elif parent is sage.symbolic.ring.SR: try: return self.__init__(point.pyobject(), dop) except TypeError: pass try: return self.__init__(QQbar(point), dop) except (TypeError, ValueError, NotImplementedError): pass try: self.value = RLF(point) except (TypeError, ValueError): self.value = CLF(point) else: try: self.value = RLF.coerce(point) except TypeError: self.value = CLF.coerce(point) parent = self.value.parent() assert (isinstance( parent, (number_field_base.NumberField, RealBallField, ComplexBallField)) or parent is RLF or parent is CLF) if dop is None: # TBI if isinstance(point, Point): self.dop = point.dop else: self.dop = DifferentialOperator(dop.numerator()) self._force_singular = bool(singular) self.options = kwds