Exemple #1
0
 def _find_vtx(self, mdl_path: PurePosixPath) -> AnyBinaryIO:
     possible_vtx_vertsion = [70, 80, 90, 11, 12]
     for vtx_version in possible_vtx_vertsion[::-1]:
         path = mdl_path.with_suffix(f".dx{vtx_version}.vtx")
         try:
             return self._open_path(path)
         except FileNotFoundError:
             pass
     raise FileNotFoundError(mdl_path.with_suffix(".dx*.vtx"))
Exemple #2
0
    def write_json(
        self,
        path: PurePosixPath,
        contents: ResultT,
        encode_json: JSONEncoder[ResultT] = default_encode_json,
    ) -> None:
        """Write an object to a JSON file."""
        file_path = Path(path.with_suffix(".json"))

        try:
            encoded_contents = encode_json(contents)
        except Exception as error:
            log.debug(f"Unexpected error encoding for {file_path}",
                      exc_info=error)
            raise FileEncodeError(str(error)) from error

        try:
            self.ensure_dir(path.parent)
            file_path.write_text(encoded_contents)
        except Exception as error:
            # NOTE: this except branch is not covered by tests, but is important
            log.debug(f"Unexpected error writing to {file_path}",
                      exc_info=error)
            raise FileWriteError(str(error)) from error

        return None
Exemple #3
0
def add_doc_target_ext(target: str, docpath: PurePath,
                       project_root: Path) -> Path:
    """Given the target file of a doc role, add the appropriate extension and return full file path"""
    # Add .txt or .rst to end of doc role target path
    target_path = PurePosixPath(target)
    if target.endswith("/"):
        # return directly if target is a folder.
        fileid, resolved_target_path = reroot_path(target_path, docpath,
                                                   project_root)
        return resolved_target_path
    # File already exists, like images
    fileid, resolved_target_path = reroot_path(target_path, docpath,
                                               project_root)
    if os.path.exists(resolved_target_path):
        return resolved_target_path
    # Adding the current suffix first takes into account dotted targets
    for ext in RST_EXTENSIONS:
        new_suffix = target_path.suffix + ext
        temp_path = target_path.with_suffix(new_suffix)

        fileid, resolved_target_path_suffix = reroot_path(
            temp_path, docpath, project_root)
        if os.path.exists(resolved_target_path_suffix):
            return resolved_target_path_suffix
    # If none of the files exists, return the original file path to trigger errors.
    return resolved_target_path
Exemple #4
0
def add_doc_target_ext(target: str, docpath: PurePath,
                       project_root: Path) -> Path:
    """Given the target file of a doc role, add the appropriate extension and return full file path"""
    # Add .txt to end of doc role target path
    target_path = PurePosixPath(target)
    # Adding the current suffix first takes into account dotted targets
    new_suffix = target_path.suffix + ".txt"
    target_path = target_path.with_suffix(new_suffix)

    fileid, resolved_target_path = reroot_path(target_path, docpath,
                                               project_root)
    return resolved_target_path
Exemple #5
0
    def remove(self, path: PurePosixPath) -> None:
        """Delete a JSON file."""
        file_path = Path(path.with_suffix(".json"))

        try:
            file_path.unlink()
        except FileNotFoundError as error:
            raise PathNotFoundError(str(error)) from error
        except Exception as error:
            # NOTE: this except branch is not covered by tests, but is important
            log.debug(f"Unexpected error reading {file_path}", exc_info=error)
            raise FileRemoveError(str(error)) from error

        return None
Exemple #6
0
    def __init__(self, filesystem: FileSystem, file: File):
        """Parse a model from a file."""
        self._file = file
        self._sys = filesystem
        self.version = 49

        self.phys_keyvalues = Property(None, [])
        with self._sys, self._file.open_bin() as f:
            self._load(f)

        path = PurePosixPath(file.path)
        try:
            phy_file = filesystem[str(path.with_suffix('.phy'))]
        except FileNotFoundError:
            pass
        else:
            with filesystem, phy_file.open_bin() as f:
                self._parse_phy(f, phy_file.path)
Exemple #7
0
 def file_exists(self, path: PurePosixPath) -> bool:
     """Return True if `{path}.json` is a file."""
     return Path(path.with_suffix(".json")).is_file()
Exemple #8
0
def matplotlib_scraper(block, block_vars, gallery_conf, **kwargs):
    """Scrape Matplotlib images.

    Parameters
    ----------
    block : tuple
        A tuple containing the (label, content, line_number) of the block.
    block_vars : dict
        Dict of block variables.
    gallery_conf : dict
        Contains the configuration of Sphinx-Gallery
    **kwargs : dict
        Additional keyword arguments to pass to
        :meth:`~matplotlib.figure.Figure.savefig`, e.g. ``format='svg'``.
        The ``format`` kwarg in particular is used to set the file extension
        of the output file (currently only 'png', 'jpg', and 'svg' are
        supported).

    Returns
    -------
    rst : str
        The ReSTructuredText that will be rendered to HTML containing
        the images. This is often produced by :func:`figure_rst`.
    """
    matplotlib, plt = _import_matplotlib()
    from matplotlib.animation import Animation
    image_path_iterator = block_vars['image_path_iterator']
    image_rsts = []
    # Check for srcset hidpi images
    srcset = gallery_conf.get('image_srcset', [])
    srcset_mult_facs = [1]  # one is always supplied...
    for st in srcset:
        if (len(st) > 0) and (st[-1] == 'x'):
            # "2x" = "2.0"
            srcset_mult_facs += [float(st[:-1])]
        elif st == "":
            pass
        else:
            raise ExtensionError(
                f'Invalid value for image_srcset parameter: "{st}". '
                'Must be a list of strings with the multiplicative '
                'factor followed by an "x".  e.g. ["2.0x", "1.5x"]')

    # Check for animations
    anims = list()
    if gallery_conf.get('matplotlib_animations', False):
        for ani in block_vars['example_globals'].values():
            if isinstance(ani, Animation):
                anims.append(ani)
    # Then standard images
    for fig_num, image_path in zip(plt.get_fignums(), image_path_iterator):
        image_path = PurePosixPath(image_path)
        if 'format' in kwargs:
            image_path = image_path.with_suffix('.' + kwargs['format'])
        # Set the fig_num figure as the current figure as we can't
        # save a figure that's not the current figure.
        fig = plt.figure(fig_num)
        # Deal with animations
        cont = False
        for anim in anims:
            if anim._fig is fig:
                image_rsts.append(
                    _anim_rst(anim, str(image_path), gallery_conf))
                cont = True
                break
        if cont:
            continue
        # get fig titles
        fig_titles = _matplotlib_fig_titles(fig)
        to_rgba = matplotlib.colors.colorConverter.to_rgba
        # shallow copy should be fine here, just want to avoid changing
        # "kwargs" for subsequent figures processed by the loop
        these_kwargs = kwargs.copy()
        for attr in ['facecolor', 'edgecolor']:
            fig_attr = getattr(fig, 'get_' + attr)()
            default_attr = matplotlib.rcParams['figure.' + attr]
            if to_rgba(fig_attr) != to_rgba(default_attr) and \
                    attr not in kwargs:
                these_kwargs[attr] = fig_attr

        # save the figures, and populate the srcsetpaths
        try:
            fig.savefig(image_path, **these_kwargs)
            dpi0 = matplotlib.rcParams['savefig.dpi']
            if dpi0 == 'figure':
                dpi0 = fig.dpi
            dpi0 = these_kwargs.get('dpi', dpi0)
            srcsetpaths = {0: image_path}

            # save other srcset paths, keyed by multiplication factor:
            for mult in srcset_mult_facs:
                if not (mult == 1):
                    multst = f'{mult}'.replace('.', '_')
                    name = f"{image_path.stem}_{multst}x{image_path.suffix}"
                    hipath = image_path.parent / PurePosixPath(name)
                    hikwargs = these_kwargs.copy()
                    hikwargs['dpi'] = mult * dpi0
                    fig.savefig(hipath, **hikwargs)
                    srcsetpaths[mult] = hipath
            srcsetpaths = [srcsetpaths]
        except Exception:
            plt.close('all')
            raise

        if 'images' in gallery_conf['compress_images']:
            optipng(str(image_path), gallery_conf['compress_images_args'])
            for hipath in srcsetpaths[0].items():
                optipng(str(hipath), gallery_conf['compress_images_args'])

        image_rsts.append(
            figure_rst([image_path],
                       gallery_conf['src_dir'],
                       fig_titles,
                       srcsetpaths=srcsetpaths))

    plt.close('all')
    rst = ''
    if len(image_rsts) == 1:
        rst = image_rsts[0]
    elif len(image_rsts) > 1:
        image_rsts = [
            re.sub(r':class: sphx-glr-single-img',
                   ':class: sphx-glr-multi-img', image) for image in image_rsts
        ]
        image_rsts = [
            HLIST_IMAGE_MATPLOTLIB + indent(image, u' ' * 6)
            for image in image_rsts
        ]
        rst = HLIST_HEADER + ''.join(image_rsts)
    return rst
Exemple #9
0
 def as_source_path( self, *, suffix: Optional[str] = None
 ) -> PurePosixPath:
     source_path = PurePosixPath(*self.parts)
     if suffix is not None:
         source_path = source_path.with_suffix(suffix)
     return source_path
Exemple #10
0
def src_dst(p, source, dstsuffix):
    src_path = PurePosixPath(source)
    src_file = p.src_file(source, through_file=src_path.name)
    dst_path = src_path.with_suffix(dstsuffix)
    dst_file = p.dst_file(str(dst_path), through_file=dst_path.name)
    return (src_file, dst_file)