Esempio n. 1
0
def run_code(code, code_path, ns=None, function_name=None):
    """
    Import a Python module from a path, and run the function given by
    name, if function_name is not None.
    """

    # Change the working directory to the directory of the example, so
    # it can get at its data files, if any.  Add its path to sys.path
    # so it can import any helper modules sitting beside it.
    pwd = os.getcwd()
    if setup.config.plot_working_directory is not None:
        try:
            os.chdir(setup.config.plot_working_directory)
        except OSError as err:
            raise OSError(str(err) + '\n`plot_working_directory` option in'
                          'Sphinx configuration file must be a valid '
                          'directory path')
        except TypeError as err:
            raise TypeError(str(err) + '\n`plot_working_directory` option in '
                            'Sphinx configuration file must be a string or '
                            'None')
    elif code_path is not None:
        dirname = os.path.abspath(os.path.dirname(code_path))
        os.chdir(dirname)

    with cbook._setattr_cm(
            sys, argv=[code_path], path=[os.getcwd(), *sys.path]), \
            contextlib.redirect_stdout(StringIO()):
        try:
            code = unescape_doctest(code)
            if ns is None:
                ns = {}
            if not ns:
                if setup.config.plot_pre_code is None:
                    exec('import numpy as np\n'
                         'from matplotlib import pyplot as plt\n', ns)
                else:
                    exec(str(setup.config.plot_pre_code), ns)
            if "__main__" in code:
                ns['__name__'] = '__main__'

            # Patch out non-interactive show() to avoid triggering a warning.
            with cbook._setattr_cm(FigureManagerBase, show=lambda self: None):
                exec(code, ns)
                if function_name is not None:
                    exec(function_name + "()", ns)

        except (Exception, SystemExit) as err:
            raise PlotError(traceback.format_exc())
        finally:
            os.chdir(pwd)
    return ns
Esempio n. 2
0
    def print_png(self, filename_or_obj, *args, **kwargs):
        """
        Write the figure to a PNG file.

        Parameters
        ----------
        filename_or_obj : str or PathLike or file-like object
            The file to write to.

        metadata : dict, optional
            Metadata in the PNG file as key-value pairs of bytes or latin-1
            encodable strings.
            According to the PNG specification, keys must be shorter than 79
            chars.

            The `PNG specification`_ defines some common keywords that may be
            used as appropriate:

            - Title: Short (one line) title or caption for image.
            - Author: Name of image's creator.
            - Description: Description of image (possibly long).
            - Copyright: Copyright notice.
            - Creation Time: Time of original image creation
              (usually RFC 1123 format).
            - Software: Software used to create the image.
            - Disclaimer: Legal disclaimer.
            - Warning: Warning of nature of content.
            - Source: Device used to create the image.
            - Comment: Miscellaneous comment;
              conversion from other image format.

            Other keywords may be invented for other purposes.

            If 'Software' is not given, an autogenerated value for matplotlib
            will be used.

            For more details see the `PNG specification`_.

            .. _PNG specification: \
                https://www.w3.org/TR/2003/REC-PNG-20031110/#11keywords

        """
        FigureCanvasAgg.draw(self)
        renderer = self.get_renderer()

        version_str = (
            'matplotlib version ' + __version__ + ', http://matplotlib.org/')
        metadata = OrderedDict({'Software': version_str})
        user_metadata = kwargs.pop("metadata", None)
        if user_metadata is not None:
            metadata.update(user_metadata)

        with cbook._setattr_cm(renderer, dpi=self.figure.dpi), \
                cbook.open_file_cm(filename_or_obj, "wb") as fh:
            _png.write_png(renderer._renderer, fh,
                            self.figure.dpi, metadata=metadata)
Esempio n. 3
0
 def draw(self):
     """Render the figure, and queue a request for a Qt draw.
     """
     # The renderer draw is done here; delaying causes problems with code
     # that uses the result of the draw() to update plot elements.
     if self._is_drawing:
         return
     with cbook._setattr_cm(self, _is_drawing=True):
         super().draw()
     self.update()
Esempio n. 4
0
 def draw(self, renderer):
     position3d = np.array((self._x, self._y, self._z))
     proj = proj3d.proj_trans_points(
         [position3d, position3d + self._dir_vec], self.axes.M)
     dx = proj[0][1] - proj[0][0]
     dy = proj[1][1] - proj[1][0]
     angle = math.degrees(math.atan2(dy, dx))
     with cbook._setattr_cm(self,
                            _x=proj[0][0],
                            _y=proj[1][0],
                            _rotation=_norm_text_angle(angle)):
         mtext.Text.draw(self, renderer)
     self.stale = False
Esempio n. 5
0
def run_code(code, code_path, ns=None, function_name=None):
    """
    Import a Python module from a path, and run the function given by
    name, if function_name is not None.
    """

    # Change the working directory to the directory of the example, so
    # it can get at its data files, if any.  Add its path to sys.path
    # so it can import any helper modules sitting beside it.
    pwd = os.getcwd()
    if setup.config.plot_working_directory is not None:
        try:
            os.chdir(setup.config.plot_working_directory)
        except OSError as err:
            raise OSError(
                str(err) + '\n`plot_working_directory` option in'
                'Sphinx configuration file must be a valid '
                'directory path')
        except TypeError as err:
            raise TypeError(
                str(err) + '\n`plot_working_directory` option in '
                'Sphinx configuration file must be a string or '
                'None')
    elif code_path is not None:
        dirname = os.path.abspath(os.path.dirname(code_path))
        os.chdir(dirname)

    with cbook._setattr_cm(
            sys, argv=[code_path], path=[os.getcwd(), *sys.path]), \
            contextlib.redirect_stdout(StringIO()):
        try:
            code = unescape_doctest(code)
            if ns is None:
                ns = {}
            if not ns:
                if setup.config.plot_pre_code is None:
                    exec(
                        'import numpy as np\n'
                        'from matplotlib import pyplot as plt\n', ns)
                else:
                    exec(str(setup.config.plot_pre_code), ns)
            if "__main__" in code:
                ns['__name__'] = '__main__'
            exec(code, ns)
            if function_name is not None:
                exec(function_name + "()", ns)
        except (Exception, SystemExit) as err:
            raise PlotError(traceback.format_exc())
        finally:
            os.chdir(pwd)
    return ns
Esempio n. 6
0
    def print_png(self, filename_or_obj, *args, **kwargs):
        FigureCanvasAgg.draw(self)
        renderer = self.get_renderer()

        version_str = (
            'matplotlib version ' + __version__ + ', http://matplotlib.org/')
        metadata = OrderedDict({'Software': version_str})
        user_metadata = kwargs.pop("metadata", None)
        if user_metadata is not None:
            metadata.update(user_metadata)

        with cbook._setattr_cm(renderer, dpi=self.figure.dpi), \
                cbook.open_file_cm(filename_or_obj, "wb") as fh:
            _png.write_png(renderer._renderer, fh,
                            self.figure.dpi, metadata=metadata)
Esempio n. 7
0
def test_tilde_in_tempfilename(tmpdir):
    # Tilde ~ in the tempdir path (e.g. TMPDIR, TMP or TEMP on windows
    # when the username is very long and windows uses a short name) breaks
    # latex before https://github.com/matplotlib/matplotlib/pull/5928
    base_tempdir = Path(tmpdir, "short-1")
    base_tempdir.mkdir()
    # Change the path for new tempdirs, which is used internally by the ps
    # backend to write a file.
    with cbook._setattr_cm(tempfile, tempdir=str(base_tempdir)):
        # usetex results in the latex call, which does not like the ~
        mpl.rcParams['text.usetex'] = True
        plt.plot([1, 2, 3, 4])
        plt.xlabel(r'\textbf{time} (s)')
        # use the PS backend to write the file...
        plt.savefig(base_tempdir / 'tex_demo.eps', format="ps")
Esempio n. 8
0
def test_tilde_in_tempfilename(tmpdir):
    # Tilde ~ in the tempdir path (e.g. TMPDIR, TMP or TEMP on windows
    # when the username is very long and windows uses a short name) breaks
    # latex before https://github.com/matplotlib/matplotlib/pull/5928
    base_tempdir = Path(tmpdir, "short-1")
    base_tempdir.mkdir()
    # Change the path for new tempdirs, which is used internally by the ps
    # backend to write a file.
    with cbook._setattr_cm(tempfile, tempdir=str(base_tempdir)):
        # usetex results in the latex call, which does not like the ~
        mpl.rcParams['text.usetex'] = True
        plt.plot([1, 2, 3, 4])
        plt.xlabel(r'\textbf{time} (s)')
        # use the PS backend to write the file...
        plt.savefig(base_tempdir / 'tex_demo.eps', format="ps")
Esempio n. 9
0
    def print_png(self, filename_or_obj, *args, **kwargs):
        FigureCanvasAgg.draw(self)
        renderer = self.get_renderer()

        version_str = (
            'matplotlib version ' + __version__ + ', http://matplotlib.org/')
        metadata = OrderedDict({'Software': version_str})
        user_metadata = kwargs.pop("metadata", None)
        if user_metadata is not None:
            metadata.update(user_metadata)

        with cbook._setattr_cm(renderer, dpi=self.figure.dpi), \
                cbook.open_file_cm(filename_or_obj, "wb") as fh:
            _png.write_png(renderer._renderer, fh,
                            self.figure.dpi, metadata=metadata)
Esempio n. 10
0
    def create_artists(self, legend, orig_handle,
                       xdescent, ydescent, width, height, fontsize,
                       trans):
        markerline, stemlines, baseline = orig_handle
        # Check to see if the stemcontainer is storing lines as a list or a
        # LineCollection. Eventually using a list will be removed, and this
        # logic can also be removed.
        using_linecoll = isinstance(stemlines, mcoll.LineCollection)

        xdata, xdata_marker = self.get_xdata(legend, xdescent, ydescent,
                                             width, height, fontsize)

        ydata = self.get_ydata(legend, xdescent, ydescent,
                               width, height, fontsize)

        if self._bottom is None:
            bottom = 0.
        else:
            bottom = self._bottom

        leg_markerline = Line2D(xdata_marker, ydata[:len(xdata_marker)])
        self.update_prop(leg_markerline, markerline, legend)

        leg_stemlines = [Line2D([x, x], [bottom, y])
                         for x, y in zip(xdata_marker, ydata)]

        if using_linecoll:
            # change the function used by update_prop() from the default
            # to one that handles LineCollection
            with cbook._setattr_cm(
                    self, _update_prop_func=self._copy_collection_props):
                for line in leg_stemlines:
                    self.update_prop(line, stemlines, legend)

        else:
            for lm, m in zip(leg_stemlines, stemlines):
                self.update_prop(lm, m, legend)

        leg_baseline = Line2D([np.min(xdata), np.max(xdata)],
                              [bottom, bottom])
        self.update_prop(leg_baseline, baseline, legend)

        artists = [*leg_stemlines, leg_baseline, leg_markerline]
        for artist in artists:
            artist.set_transform(trans)
        return artists
Esempio n. 11
0
def mpl_image_comparison_parameters(request, extension):
    # This fixture is applied automatically by the image_comparison decorator.
    #
    # The sole purpose of this fixture is to provide an indirect method of
    # obtaining parameters *without* modifying the decorated function
    # signature. In this way, the function signature can stay the same and
    # pytest won't get confused.
    # We annotate the decorated function with any parameters captured by this
    # fixture so that they can be used by the wrapper in image_comparison.
    baseline_images, = request.node.get_closest_marker('baseline_images').args
    if baseline_images is None:
        # Allow baseline image list to be produced on the fly based on current
        # parametrization.
        baseline_images = request.getfixturevalue('baseline_images')

    func = request.function
    with cbook._setattr_cm(func.__wrapped__,
                           parameters=(baseline_images, extension)):
        yield
Esempio n. 12
0
def mpl_image_comparison_parameters(request, extension):
    # This fixture is applied automatically by the image_comparison decorator.
    #
    # The sole purpose of this fixture is to provide an indirect method of
    # obtaining parameters *without* modifying the decorated function
    # signature. In this way, the function signature can stay the same and
    # pytest won't get confused.
    # We annotate the decorated function with any parameters captured by this
    # fixture so that they can be used by the wrapper in image_comparison.
    baseline_images, = request.node.get_closest_marker('baseline_images').args
    if baseline_images is None:
        # Allow baseline image list to be produced on the fly based on current
        # parametrization.
        baseline_images = request.getfixturevalue('baseline_images')

    func = request.function
    with cbook._setattr_cm(func.__wrapped__,
                           parameters=(baseline_images, extension)):
        yield
Esempio n. 13
0
 def wrapper(self, *args, **kwargs):
     with cbook._setattr_cm(QtWidgets.QWidget,
                            __init__=cooperative_qwidget_init):
         __init__(self, *args, **kwargs)
Esempio n. 14
0
def test_setattr_cm():
    class A:
        cls_level = object()
        override = object()

        def __init__(self):
            self.aardvark = 'aardvark'
            self.override = 'override'
            self._p = 'p'

        def meth(self):
            ...

        @classmethod
        def classy(cls):
            ...

        @staticmethod
        def static():
            ...

        @property
        def prop(self):
            return self._p

        @prop.setter
        def prop(self, val):
            self._p = val

    class B(A):
        ...

    other = A()

    def verify_pre_post_state(obj):
        # When you access a Python method the function is bound
        # to the object at access time so you get a new instance
        # of MethodType every time.
        #
        # https://docs.python.org/3/howto/descriptor.html#functions-and-methods
        assert obj.meth is not obj.meth
        # normal attribute should give you back the same instance every time
        assert obj.aardvark is obj.aardvark
        assert a.aardvark == 'aardvark'
        # and our property happens to give the same instance every time
        assert obj.prop is obj.prop
        assert obj.cls_level is A.cls_level
        assert obj.override == 'override'
        assert not hasattr(obj, 'extra')
        assert obj.prop == 'p'
        assert obj.monkey == other.meth
        assert obj.cls_level is A.cls_level
        assert 'cls_level' not in obj.__dict__
        assert 'classy' not in obj.__dict__
        assert 'static' not in obj.__dict__

    a = B()

    a.monkey = other.meth
    verify_pre_post_state(a)
    with cbook._setattr_cm(a,
                           prop='squirrel',
                           aardvark='moose',
                           meth=lambda: None,
                           override='boo',
                           extra='extra',
                           monkey=lambda: None,
                           cls_level='bob',
                           classy='classy',
                           static='static'):
        # because we have set a lambda, it is normal attribute access
        # and the same every time
        assert a.meth is a.meth
        assert a.aardvark is a.aardvark
        assert a.aardvark == 'moose'
        assert a.override == 'boo'
        assert a.extra == 'extra'
        assert a.prop == 'squirrel'
        assert a.monkey != other.meth
        assert a.cls_level == 'bob'
        assert a.classy == 'classy'
        assert a.static == 'static'

    verify_pre_post_state(a)
Esempio n. 15
0
 def print_to_buffer(self):
     FigureCanvasAgg.draw(self)
     renderer = self.get_renderer()
     with cbook._setattr_cm(renderer, dpi=self.figure.dpi):
         return (renderer._renderer.buffer_rgba(), (int(renderer.width),
                                                    int(renderer.height)))
Esempio n. 16
0
 def print_raw(self, filename_or_obj, *args, **kwargs):
     FigureCanvasAgg.draw(self)
     renderer = self.get_renderer()
     with cbook._setattr_cm(renderer, dpi=self.figure.dpi), \
             cbook.open_file_cm(filename_or_obj, "wb") as fh:
         fh.write(renderer._renderer.buffer_rgba())
Esempio n. 17
0
    def print_png(self, filename_or_obj, *args,
                  metadata=None, pil_kwargs=None,
                  **kwargs):
        """
        Write the figure to a PNG file.

        Parameters
        ----------
        filename_or_obj : str or PathLike or file-like object
            The file to write to.

        metadata : dict, optional
            Metadata in the PNG file as key-value pairs of bytes or latin-1
            encodable strings.
            According to the PNG specification, keys must be shorter than 79
            chars.

            The `PNG specification`_ defines some common keywords that may be
            used as appropriate:

            - Title: Short (one line) title or caption for image.
            - Author: Name of image's creator.
            - Description: Description of image (possibly long).
            - Copyright: Copyright notice.
            - Creation Time: Time of original image creation
              (usually RFC 1123 format).
            - Software: Software used to create the image.
            - Disclaimer: Legal disclaimer.
            - Warning: Warning of nature of content.
            - Source: Device used to create the image.
            - Comment: Miscellaneous comment;
              conversion from other image format.

            Other keywords may be invented for other purposes.

            If 'Software' is not given, an autogenerated value for matplotlib
            will be used.

            For more details see the `PNG specification`_.

            .. _PNG specification: \
                https://www.w3.org/TR/2003/REC-PNG-20031110/#11keywords

        pil_kwargs : dict, optional
            If set to a non-None value, use Pillow to save the figure instead
            of Matplotlib's builtin PNG support, and pass these keyword
            arguments to `PIL.Image.save`.

            If the 'pnginfo' key is present, it completely overrides
            *metadata*, including the default 'Software' key.
        """
        from matplotlib import _png

        if metadata is None:
            metadata = {}
        metadata = {
            "Software":
                f"matplotlib version{__version__}, http://matplotlib.org/",
            **metadata,
        }

        if pil_kwargs is not None:
            from PIL import Image
            from PIL.PngImagePlugin import PngInfo
            buf, size = self.print_to_buffer()
            # Only use the metadata kwarg if pnginfo is not set, because the
            # semantics of duplicate keys in pnginfo is unclear.
            if "pnginfo" not in pil_kwargs:
                pnginfo = PngInfo()
                for k, v in metadata.items():
                    pnginfo.add_text(k, v)
                pil_kwargs["pnginfo"] = pnginfo
            pil_kwargs.setdefault("dpi", (self.figure.dpi, self.figure.dpi))
            (Image.frombuffer("RGBA", size, buf, "raw", "RGBA", 0, 1)
             .save(filename_or_obj, format="png", **pil_kwargs))

        else:
            FigureCanvasAgg.draw(self)
            renderer = self.get_renderer()
            with cbook._setattr_cm(renderer, dpi=self.figure.dpi), \
                    cbook.open_file_cm(filename_or_obj, "wb") as fh:
                _png.write_png(renderer._renderer, fh,
                               self.figure.dpi, metadata=metadata)
Esempio n. 18
0
    def print_png(self,
                  filename_or_obj,
                  *args,
                  metadata=None,
                  pil_kwargs=None,
                  **kwargs):
        """
        Write the figure to a PNG file.

        Parameters
        ----------
        filename_or_obj : str or PathLike or file-like object
            The file to write to.

        metadata : dict, optional
            Metadata in the PNG file as key-value pairs of bytes or latin-1
            encodable strings.
            According to the PNG specification, keys must be shorter than 79
            chars.

            The `PNG specification`_ defines some common keywords that may be
            used as appropriate:

            - Title: Short (one line) title or caption for image.
            - Author: Name of image's creator.
            - Description: Description of image (possibly long).
            - Copyright: Copyright notice.
            - Creation Time: Time of original image creation
              (usually RFC 1123 format).
            - Software: Software used to create the image.
            - Disclaimer: Legal disclaimer.
            - Warning: Warning of nature of content.
            - Source: Device used to create the image.
            - Comment: Miscellaneous comment;
              conversion from other image format.

            Other keywords may be invented for other purposes.

            If 'Software' is not given, an autogenerated value for matplotlib
            will be used.

            For more details see the `PNG specification`_.

            .. _PNG specification: \
                https://www.w3.org/TR/2003/REC-PNG-20031110/#11keywords

        pil_kwargs : dict, optional
            If set to a non-None value, use Pillow to save the figure instead
            of Matplotlib's builtin PNG support, and pass these keyword
            arguments to `PIL.Image.save`.

            If the 'pnginfo' key is present, it completely overrides
            *metadata*, including the default 'Software' key.
        """
        from matplotlib import _png

        if metadata is None:
            metadata = {}
        metadata = {
            "Software":
            f"matplotlib version{__version__}, http://matplotlib.org/",
            **metadata,
        }

        if pil_kwargs is not None:
            from PIL import Image
            from PIL.PngImagePlugin import PngInfo
            buf, size = self.print_to_buffer()
            # Only use the metadata kwarg if pnginfo is not set, because the
            # semantics of duplicate keys in pnginfo is unclear.
            if "pnginfo" not in pil_kwargs:
                pnginfo = PngInfo()
                for k, v in metadata.items():
                    pnginfo.add_text(k, v)
                pil_kwargs["pnginfo"] = pnginfo
            pil_kwargs.setdefault("dpi", (self.figure.dpi, self.figure.dpi))
            (Image.frombuffer("RGBA", size, buf, "raw", "RGBA", 0,
                              1).save(filename_or_obj,
                                      format="png",
                                      **pil_kwargs))

        else:
            FigureCanvasAgg.draw(self)
            renderer = self.get_renderer()
            with cbook._setattr_cm(renderer, dpi=self.figure.dpi), \
                    cbook.open_file_cm(filename_or_obj, "wb") as fh:
                _png.write_png(renderer._renderer,
                               fh,
                               self.figure.dpi,
                               metadata=metadata)
Esempio n. 19
0
 def draw(self, renderer):
     with cbook._setattr_cm(self, _in_draw=True):
         super().draw(renderer)
Esempio n. 20
0
 def print_raw(self, filename_or_obj, *args, **kwargs):
     FigureCanvasAgg.draw(self)
     renderer = self.get_renderer()
     with cbook._setattr_cm(renderer, dpi=self.figure.dpi), \
             cbook.open_file_cm(filename_or_obj, "wb") as fh:
         fh.write(renderer._renderer.buffer_rgba())
Esempio n. 21
0
 def wrapper(self, **kwargs):
     with cbook._setattr_cm(QtWidgets.QWidget,
                            __init__=cooperative_qwidget_init):
         __init__(self, **kwargs)
Esempio n. 22
0
 def print_to_buffer(self):
     FigureCanvasAgg.draw(self)
     renderer = self.get_renderer()
     with cbook._setattr_cm(renderer, dpi=self.figure.dpi):
         return (renderer._renderer.buffer_rgba(),
                 (int(renderer.width), int(renderer.height)))