コード例 #1
0
ファイル: __init__.py プロジェクト: JamesMakela/matplotlib
def _get_config_or_cache_dir(xdg_base):
    from matplotlib.cbook import mkdirs

    configdir = os.environ.get('MPLCONFIGDIR')
    if configdir is not None:
        if not os.path.exists(configdir):
            from matplotlib.cbook import mkdirs
            mkdirs(configdir)

        if not _is_writable_dir(configdir):
            return _create_tmp_config_dir()
        return configdir

    p = None
    h = get_home()
    if h is not None:
        p = os.path.join(h, '.matplotlib')
        if (sys.platform.startswith('linux') and
            xdg_base is not None):
            p = os.path.join(xdg_base, 'matplotlib')

    if p is not None:
        if os.path.exists(p):
            if _is_writable_dir(p):
                return p
        else:
            try:
                mkdirs(p)
            except OSError:
                pass
            else:
                return p

    return _create_tmp_config_dir()
コード例 #2
0
ファイル: __init__.py プロジェクト: chrishowes/matplotlib
def _get_configdir():
    """
    Return the string representing the configuration directory.

    Default is HOME/.matplotlib.  You can override this with the
    MPLCONFIGDIR environment variable.  If the default is not
    writable, and MPLCONFIGDIR is not set, then
    tempfile.gettempdir() is used to provide a directory in
    which a matplotlib subdirectory is created as the configuration
    directory.
    """

    configdir = os.environ.get('MPLCONFIGDIR')
    if configdir is not None:
        if not os.path.exists(configdir):
            os.makedirs(configdir)
        if not _is_writable_dir(configdir):
            return _create_tmp_config_dir()
        return configdir

    h = get_home()
    p = os.path.join(get_home(), '.matplotlib')

    if os.path.exists(p):
        if not _is_writable_dir(p):
            return _create_tmp_config_dir()
    else:
        if not _is_writable_dir(h):
            return _create_tmp_config_dir()
        from matplotlib.cbook import mkdirs
        mkdirs(p)

    return p
コード例 #3
0
ファイル: __init__.py プロジェクト: EnochManohar/matplotlib
def _get_configdir():
    """
    Return the string representing the configuration dir.

    default is HOME/.matplotlib.  you can override this with the
    MPLCONFIGDIR environment variable
    """

    configdir = os.environ.get('MPLCONFIGDIR')
    if configdir is not None:
        if not os.path.exists(configdir):
            os.makedirs(configdir)
        if not _is_writable_dir(configdir):
            raise RuntimeError('Could not write to MPLCONFIGDIR="%s"'%configdir)
        return configdir

    h = get_home()
    p = os.path.join(get_home(), '.matplotlib')

    if os.path.exists(p):
        if not _is_writable_dir(p):
            raise RuntimeError("'%s' is not a writable dir; you must set %s/.matplotlib to be a writable dir.  You can also set environment variable MPLCONFIGDIR to any writable directory where you want matplotlib data stored "% (h, h))
    else:
        if not _is_writable_dir(h):
            raise RuntimeError("Failed to create %s/.matplotlib; consider setting MPLCONFIGDIR to a writable directory for matplotlib configuration data"%h)
        from matplotlib.cbook import mkdirs
        mkdirs(p)

    return p
コード例 #4
0
ファイル: __init__.py プロジェクト: hitej/meta-core
def _get_config_or_cache_dir(xdg_base):
    from matplotlib.cbook import mkdirs

    configdir = os.environ.get("MPLCONFIGDIR")
    if configdir is not None:
        if not os.path.exists(configdir):
            from matplotlib.cbook import mkdirs

            mkdirs(configdir)

        if not _is_writable_dir(configdir):
            return _create_tmp_config_dir()
        return configdir

    h = get_home()
    p = os.path.join(h, ".matplotlib")
    if sys.platform.startswith("linux") and not os.path.exists(p):
        p = os.path.join(xdg_base, "matplotlib")

    if os.path.exists(p):
        if not _is_writable_dir(p):
            return _create_tmp_config_dir()
    else:
        try:
            mkdirs(p)
        except OSError:
            return _create_tmp_config_dir()

    return p
コード例 #5
0
def fetch_historical_yahoo(ticker, date1, date2, cachename=None,dividends=False):
    """
    Fetch historical data for ticker between date1 and date2.  date1 and
    date2 are date or datetime instances, or (year, month, day) sequences.

    Ex:
    fh = fetch_historical_yahoo('^GSPC', (2000, 1, 1), (2001, 12, 31))

    cachename is the name of the local file cache.  If None, will
    default to the md5 hash or the url (which incorporates the ticker
    and date range)
    
    set dividends=True to return dividends instead of price data.  With
    this option set, parse functions will not work

    a file handle is returned
    """

    ticker = ticker.upper()


    if iterable(date1):
        d1 = (date1[1]-1, date1[2], date1[0])
    else:
        d1 = (date1.month-1, date1.day, date1.year)
    if iterable(date2):
        d2 = (date2[1]-1, date2[2], date2[0])
    else:
        d2 = (date2.month-1, date2.day, date2.year)


    if dividends:
        g='v'
        verbose.report('Retrieving dividends instead of prices')
    else:
        g='d'

    urlFmt = 'http://table.finance.yahoo.com/table.csv?a=%d&b=%d&c=%d&d=%d&e=%d&f=%d&s=%s&y=0&g=%s&ignore=.csv'


    url =  urlFmt % (d1[0], d1[1], d1[2],
                     d2[0], d2[1], d2[2], ticker, g)


    if cachename is None:
        cachename = os.path.join(cachedir, md5(url).hexdigest())
    if os.path.exists(cachename):
        fh = open(cachename)
        verbose.report('Using cachefile %s for %s'%(cachename, ticker))
    else:
        mkdirs(cachedir)
        urlfh = urlopen(url)

        fh = open(cachename, 'wb')
        fh.write(urlfh.read())
        fh.close()
        verbose.report('Saved %s data to cache file %s'%(ticker, cachename))
        fh = open(cachename, 'r')

    return fh
コード例 #6
0
ファイル: texmanager.py プロジェクト: bcongdon/matplotlib
    def __init__(self):

        if self.texcache is None:
            raise RuntimeError(
                ('Cannot create TexManager, as there is no cache directory '
                 'available'))

        mkdirs(self.texcache)
        ff = rcParams['font.family']
        if len(ff) == 1 and ff[0].lower() in self.font_families:
            self.font_family = ff[0].lower()
        elif isinstance(ff, six.string_types) and ff.lower() in self.font_families:
            self.font_family = ff.lower()
        else:
            mpl.verbose.report(
                'font.family must be one of (%s) when text.usetex is True. '
                'serif will be used by default.' %
                   ', '.join(self.font_families),
                'helpful')
            self.font_family = 'serif'

        fontconfig = [self.font_family]
        for font_family, font_family_attr in [(ff, ff.replace('-', '_'))
                                              for ff in self.font_families]:
            for font in rcParams['font.' + font_family]:
                if font.lower() in self.font_info:
                    setattr(self, font_family_attr,
                            self.font_info[font.lower()])
                    if DEBUG:
                        print('family: %s, font: %s, info: %s' %
                              (font_family, font,
                               self.font_info[font.lower()]))
                    break
                else:
                    if DEBUG:
                        print('$s font is not compatible with usetex')
            else:
                mpl.verbose.report('No LaTeX-compatible font found for the '
                                   '%s font family in rcParams. Using '
                                   'default.' % font_family, 'helpful')
                setattr(self, font_family_attr, self.font_info[font_family])
            fontconfig.append(getattr(self, font_family_attr)[0])
        # Add a hash of the latex preamble to self._fontconfig so that the
        # correct png is selected for strings rendered with same font and dpi
        # even if the latex preamble changes within the session
        preamble_bytes = six.text_type(self.get_custom_preamble()).encode('utf-8')
        fontconfig.append(md5(preamble_bytes).hexdigest())
        self._fontconfig = ''.join(fontconfig)

        # The following packages and commands need to be included in the latex
        # file's preamble:
        cmd = [self.serif[1], self.sans_serif[1], self.monospace[1]]
        if self.font_family == 'cursive':
            cmd.append(self.cursive[1])
        while '\\usepackage{type1cm}' in cmd:
            cmd.remove('\\usepackage{type1cm}')
        cmd = '\n'.join(cmd)
        self._font_preamble = '\n'.join(['\\usepackage{type1cm}', cmd,
                                         '\\usepackage{textcomp}'])
コード例 #7
0
def run(arguments, options, state_machine, lineno):
    reference = directives.uri(arguments[0])
    basedir, fname = os.path.split(reference)
    basename, ext = os.path.splitext(fname)
    if ext != '.py':
        basename = fname
    sourcename = fname
    #print 'plotdir', reference, basename, ext

    # get the directory of the rst file
    rstdir, rstfile = os.path.split(state_machine.document.attributes['source'])
    reldir = rstdir[len(setup.confdir)+1:]
    relparts = [p for p in os.path.split(reldir) if p.strip()]
    nparts = len(relparts)
    #print '    rstdir=%s, reldir=%s, relparts=%s, nparts=%d'%(rstdir, reldir, relparts, nparts)
    #print 'RUN', rstdir, reldir
    outdir = os.path.join(setup.confdir, setup.config.plot_output_dir, basedir)
    if not os.path.exists(outdir):
        cbook.mkdirs(outdir)

    linkdir = ('../' * nparts) + setup.config.plot_output_dir.replace(os.path.sep, '/') + '/' + basedir
    #linkdir = os.path.join('..', outdir)
    num_figs = makefig(reference, outdir,
                       is_doctest=('doctest-format' in options))
    #print '    reference="%s", basedir="%s", linkdir="%s", outdir="%s"'%(reference, basedir, linkdir, outdir)

    if options.has_key('include-source'):
        contents = open(reference, 'r').read()
        if 'doctest-format' in options:
            lines = ['']
        else:
            lines = ['.. code-block:: python', '']
        lines += ['    %s'%row.rstrip() for row in contents.split('\n')]
        del options['include-source']
    else:
        lines = []

    if 'doctest-format' in options:
        del options['doctest-format']
    
    if num_figs > 0:
        options = ['      :%s: %s' % (key, val) for key, val in
                   options.items()]
        options = "\n".join(options)

        for i in range(num_figs):
            if num_figs == 1:
                outname = basename
            else:
                outname = "%s_%02d" % (basename, i)
            lines.extend((template % locals()).split('\n'))
    else:
        lines.extend((exception_template % locals()).split('\n'))

    if len(lines):
        state_machine.insert_input(
            lines, state_machine.input_lines.source(0))
    return []
コード例 #8
0
ファイル: decorators.py プロジェクト: dstolts/cityscorewebapp
def _image_directories(func):
    """
    Compute the baseline and result image directories for testing *func*.
    Create the result directory if it doesn't exist.
    """
    module_name = func.__module__
    if module_name == '__main__':
        # FIXME: this won't work for nested packages in matplotlib.tests
        warnings.warn('test module run as script. guessing baseline image locations')
        script_name = sys.argv[0]
        basedir = os.path.abspath(os.path.dirname(script_name))
        subdir = os.path.splitext(os.path.split(script_name)[1])[0]
    else:
        mods = module_name.split('.')
        if len(mods) >= 3:
            mods.pop(0)
            # mods[0] will be the name of the package being tested (in
            # most cases "matplotlib") However if this is a
            # namespace package pip installed and run via the nose
            # multiprocess plugin or as a specific test this may be
            # missing. See https://github.com/matplotlib/matplotlib/issues/3314
        if mods.pop(0) != 'tests':
            warnings.warn(("Module '%s' does not live in a parent module "
                "named 'tests'. This is probably ok, but we may not be able "
                "to guess the correct subdirectory containing the baseline "
                "images. If things go wrong please make sure that there is "
                "a parent directory named 'tests' and that it contains a "
                "__init__.py file (can be empty).") % module_name)
        subdir = os.path.join(*mods)

        import imp
        def find_dotted_module(module_name, path=None):
            """A version of imp which can handle dots in the module name.
               As for imp.find_module(), the return value is a 3-element
               tuple (file, pathname, description)."""
            res = None
            for sub_mod in module_name.split('.'):
                try:
                    res = file, path, _ = imp.find_module(sub_mod, path)
                    path = [path]
                    if file is not None:
                        file.close()
                except ImportError:
                    # assume namespace package
                    path = sys.modules[sub_mod].__path__
                    res = None, path, None
            return res

        mod_file = find_dotted_module(func.__module__)[1]
        basedir = os.path.dirname(mod_file)

    baseline_dir = os.path.join(basedir, 'baseline_images', subdir)
    result_dir = os.path.abspath(os.path.join('result_images', subdir))

    if not os.path.exists(result_dir):
        cbook.mkdirs(result_dir)

    return baseline_dir, result_dir
コード例 #9
0
ファイル: texmanager.py プロジェクト: alephu5/Soundbyte
    def __init__(self):

        if self.texcache is None:
            raise RuntimeError(
                ('Cannot create TexManager, as there is no cache directory '
                 'available'))

        mkdirs(self.texcache)
        ff = rcParams['font.family']
        if len(ff) == 1 and ff[0].lower() in self.font_families:
            self.font_family = ff[0].lower()
        elif isinstance(ff, str) and ff.lower() in self.font_families:
            self.font_family = ff.lower()
        else:
            mpl.verbose.report(
                'font.family must be one of (%s) when text.usetex is True. '
                'serif will be used by default.' %
                   ', '.join(self.font_families),
                'helpful')
            self.font_family = 'serif'

        fontconfig = [self.font_family]
        for font_family, font_family_attr in [(ff, ff.replace('-', '_'))
                                              for ff in self.font_families]:
            for font in rcParams['font.' + font_family]:
                if font.lower() in self.font_info:
                    setattr(self, font_family_attr,
                            self.font_info[font.lower()])
                    if DEBUG:
                        print('family: %s, font: %s, info: %s' %
                              (font_family, font,
                               self.font_info[font.lower()]))
                    break
                else:
                    if DEBUG:
                        print('$s font is not compatible with usetex')
            else:
                mpl.verbose.report('No LaTeX-compatible font found for the '
                                   '%s font family in rcParams. Using '
                                   'default.' % ff, 'helpful')
                setattr(self, font_family_attr, self.font_info[font_family])
            fontconfig.append(getattr(self, font_family_attr)[0])
        self._fontconfig = ''.join(fontconfig)

        # The following packages and commands need to be included in the latex
        # file's preamble:
        cmd = [self.serif[1], self.sans_serif[1], self.monospace[1]]
        if self.font_family == 'cursive':
            cmd.append(self.cursive[1])
        while r'\usepackage{type1cm}' in cmd:
            cmd.remove(r'\usepackage{type1cm}')
        cmd = '\n'.join(cmd)
        self._font_preamble = '\n'.join([r'\usepackage{type1cm}', cmd,
                                         r'\usepackage{textcomp}'])
コード例 #10
0
ファイル: texmanager.py プロジェクト: KevKeating/matplotlib
    def __init__(self):

        if self.texcache is None:
            raise RuntimeError(("Cannot create TexManager, as there is no cache directory " "available"))

        mkdirs(self.texcache)
        ff = rcParams["font.family"]
        if len(ff) == 1 and ff[0].lower() in self.font_families:
            self.font_family = ff[0].lower()
        elif isinstance(ff, six.string_types) and ff.lower() in self.font_families:
            self.font_family = ff.lower()
        else:
            mpl.verbose.report(
                "font.family must be one of (%s) when text.usetex is True. "
                "serif will be used by default." % ", ".join(self.font_families),
                "helpful",
            )
            self.font_family = "serif"

        fontconfig = [self.font_family]
        for font_family, font_family_attr in [(ff, ff.replace("-", "_")) for ff in self.font_families]:
            for font in rcParams["font." + font_family]:
                if font.lower() in self.font_info:
                    setattr(self, font_family_attr, self.font_info[font.lower()])
                    if DEBUG:
                        print("family: %s, font: %s, info: %s" % (font_family, font, self.font_info[font.lower()]))
                    break
                else:
                    if DEBUG:
                        print("$s font is not compatible with usetex")
            else:
                mpl.verbose.report(
                    "No LaTeX-compatible font found for the " "%s font family in rcParams. Using " "default." % ff,
                    "helpful",
                )
                setattr(self, font_family_attr, self.font_info[font_family])
            fontconfig.append(getattr(self, font_family_attr)[0])
        # Add a hash of the latex preamble to self._fontconfig so that the
        # correct png is selected for strings rendered with same font and dpi
        # even if the latex preamble changes within the session
        preamble_bytes = six.text_type(self.get_custom_preamble()).encode("utf-8")
        fontconfig.append(md5(preamble_bytes).hexdigest())
        self._fontconfig = "".join(fontconfig)

        # The following packages and commands need to be included in the latex
        # file's preamble:
        cmd = [self.serif[1], self.sans_serif[1], self.monospace[1]]
        if self.font_family == "cursive":
            cmd.append(self.cursive[1])
        while "\\usepackage{type1cm}" in cmd:
            cmd.remove("\\usepackage{type1cm}")
        cmd = "\n".join(cmd)
        self._font_preamble = "\n".join(["\\usepackage{type1cm}", cmd, "\\usepackage{textcomp}"])
コード例 #11
0
ファイル: compare.py プロジェクト: Creence/matplotlib
def get_cache_dir():
    cachedir = _get_cachedir()
    if cachedir is None:
        raise RuntimeError('Could not find a suitable configuration directory')
    cache_dir = os.path.join(cachedir, 'test_cache')
    if not os.path.exists(cache_dir):
        try:
            cbook.mkdirs(cache_dir)
        except IOError:
            return None
    if not os.access(cache_dir, os.W_OK):
        return None
    return cache_dir
コード例 #12
0
ファイル: test_plotting.py プロジェクト: mzwiessele/topslam
def _image_directories():
    """
    Compute the baseline and result image directories for testing *func*.
    Create the result directory if it doesn't exist.
    """
    # module_name = __init__.__module__
    # mods = module_name.split('.')
    # basedir = os.path.join(*mods)
    result_dir = os.path.join(basedir, "testresult", ".")
    baseline_dir = os.path.join(basedir, "baseline", ".")
    if not os.path.exists(result_dir):
        cbook.mkdirs(result_dir)
    return baseline_dir, result_dir
コード例 #13
0
ファイル: texmanager.py プロジェクト: adnanb59/matplotlib
    def __init__(self):

        if self.texcache is None:
            raise RuntimeError('Cannot create TexManager, as there is no '
                               'cache directory available')

        mkdirs(self.texcache)
        ff = rcParams['font.family']
        if len(ff) == 1 and ff[0].lower() in self.font_families:
            self.font_family = ff[0].lower()
        elif (isinstance(ff, six.string_types)
              and ff.lower() in self.font_families):
            self.font_family = ff.lower()
        else:
            _log.info('font.family must be one of (%s) when text.usetex is '
                      'True. serif will be used by default.',
                      ', '.join(self.font_families))
            self.font_family = 'serif'

        fontconfig = [self.font_family]
        for font_family in self.font_families:
            font_family_attr = font_family.replace('-', '_')
            for font in rcParams['font.' + font_family]:
                if font.lower() in self.font_info:
                    setattr(self, font_family_attr,
                            self.font_info[font.lower()])
                    _log.debug('family: %s, font: %s, info: %s',
                               font_family, font, self.font_info[font.lower()])
                    break
                else:
                    _log.debug('%s font is not compatible with usetex.',
                               font_family)
            else:
                _log.info('No LaTeX-compatible font found for the %s font '
                          'family in rcParams. Using default.', font_family)
                setattr(self, font_family_attr, self.font_info[font_family])
            fontconfig.append(getattr(self, font_family_attr)[0])
        # Add a hash of the latex preamble to self._fontconfig so that the
        # correct png is selected for strings rendered with same font and dpi
        # even if the latex preamble changes within the session
        preamble_bytes = self.get_custom_preamble().encode('utf-8')
        fontconfig.append(md5(preamble_bytes).hexdigest())
        self._fontconfig = ''.join(fontconfig)

        # The following packages and commands need to be included in the latex
        # file's preamble:
        cmd = [self.serif[1], self.sans_serif[1], self.monospace[1]]
        if self.font_family == 'cursive':
            cmd.append(self.cursive[1])
        self._font_preamble = '\n'.join(
            [r'\usepackage{type1cm}'] + cmd + [r'\usepackage{textcomp}'])
コード例 #14
0
ファイル: conftest.py プロジェクト: jwhendy/plotnine
def make_test_image_filenames(name, test_file):
    """
    Create filenames for testing

    Parameters
    ----------
    name : str
        An identifier for the specific test. This will make-up
        part of the filenames.
    test_file : str
        Full path of the test file. This will determine the
        directory structure

    Returns
    -------
    out : Bunch
        Object with 3 attributes to store the generated filenames

            - result
            - baseline
            - expected

        `result`, is the filename for the image generated by the test.
        `baseline`, is the filename for the baseline image to which
        the result will be compared.
        `expected`, is the filename to the copy of the baseline that
        will be stored in the same directory as the result image.
        Creating a copy make comparison easier.
    """
    if '.png' not in name:
        name = name + '.png'

    basedir = os.path.abspath(os.path.dirname(test_file))
    basename = os.path.basename(test_file)
    subdir = os.path.splitext(basename)[0]

    baseline_dir = os.path.join(basedir, 'baseline_images', subdir)
    result_dir = os.path.abspath(os.path.join('result_images', subdir))

    if not os.path.exists(result_dir):
        cbook.mkdirs(result_dir)

    base, ext = os.path.splitext(name)
    expected_name = '{}-{}{}'.format(base, 'expected', ext)

    filenames = cbook.Bunch(
        baseline=os.path.join(baseline_dir, name),
        result=os.path.join(result_dir, name),
        expected=os.path.join(result_dir, expected_name))
    return filenames
コード例 #15
0
def _image_directories(func):
    """
    Compute the baseline and result image directories for testing *func*.
    Create the result directory if it doesn't exist.
    """
    module_name = func.__module__
    if module_name == '__main__':
        # FIXME: this won't work for nested packages in matplotlib.tests
        warnings.warn('test module run as script. guessing baseline image locations')
        script_name = sys.argv[0]
        basedir = os.path.abspath(os.path.dirname(script_name))
        subdir = os.path.splitext(os.path.split(script_name)[1])[0]
    else:
        mods = module_name.split('.')
        if len(mods) >= 3:
            mods.pop(0)
            # mods[0] will be the name of the package being tested (in
            # most cases "matplotlib") However if this is a
            # namespace package pip installed and run via the nose
            # multiprocess plugin or as a specific test this may be
            # missing. See https://github.com/matplotlib/matplotlib/issues/3314
        assert mods.pop(0) == 'tests'
        subdir = os.path.join(*mods)

        import imp
        def find_dotted_module(module_name, path=None):
            """A version of imp which can handle dots in the module name"""
            res = None
            for sub_mod in module_name.split('.'):
                try:
                    res = file, path, _ = imp.find_module(sub_mod, path)
                    path = [path]
                    if file is not None:
                        file.close()
                except ImportError:
                    # assume namespace package
                    path = sys.modules[sub_mod].__path__
                    res = None, path, None
            return res

        mod_file = find_dotted_module(func.__module__)[1]
        basedir = os.path.dirname(mod_file)

    baseline_dir = os.path.join(basedir, 'baseline_images', subdir)
    result_dir = os.path.abspath(os.path.join('result_images', subdir))

    if not os.path.exists(result_dir):
        cbook.mkdirs(result_dir)

    return baseline_dir, result_dir
コード例 #16
0
ファイル: test_plot.py プロジェクト: spxiwh/lalsuite
    def test(*args, **kwargs):
        # Run test function
        fig = testfunc(*args, **kwargs)

        # Create directories if needed
        cbook.mkdirs(baseline_dir)
        cbook.mkdirs(result_dir)

        if os.path.exists(baseline_path):
            fig.savefig(result_path)
            msg = compare_images(baseline_path, result_path, tolerance)
            if msg is not None:
                raise AssertionError(msg)
        else:
            fig.savefig(baseline_path)
            raise unittest.SkipTest(
                "Generated baseline image, {0}".format(baseline_path))
コード例 #17
0
ファイル: decorators.py プロジェクト: robertsd/matplotlib
def _image_directories(func):
    """
    Compute the baseline and result image directories for testing *func*.
    Create the result directory if it doesn't exist.
    """
    module_name = func.__module__
    if module_name == "__main__":
        # FIXME: this won't work for nested packages in matplotlib.tests
        warnings.warn("test module run as script. guessing baseline image locations")
        script_name = sys.argv[0]
        basedir = os.path.abspath(os.path.dirname(script_name))
        subdir = os.path.splitext(os.path.split(script_name)[1])[0]
    else:
        mods = module_name.split(".")
        mods.pop(0)  # <- will be the name of the package being tested (in
        # most cases "matplotlib")
        assert mods.pop(0) == "tests"
        subdir = os.path.join(*mods)

        import imp

        def find_dotted_module(module_name, path=None):
            """A version of imp which can handle dots in the module name"""
            res = None
            for sub_mod in module_name.split("."):
                try:
                    res = file, path, _ = imp.find_module(sub_mod, path)
                    path = [path]
                    if file is not None:
                        file.close()
                except ImportError:
                    # assume namespace package
                    path = sys.modules[sub_mod].__path__
                    res = None, path, None
            return res

        mod_file = find_dotted_module(func.__module__)[1]
        basedir = os.path.dirname(mod_file)

    baseline_dir = os.path.join(basedir, "baseline_images", subdir)
    result_dir = os.path.abspath(os.path.join("result_images", subdir))

    if not os.path.exists(result_dir):
        cbook.mkdirs(result_dir)

    return baseline_dir, result_dir
コード例 #18
0
ファイル: texmanager.py プロジェクト: SunPowered/matplotlib
    def __init__(self):

        mkdirs(self.texcache)
        ff = rcParams['font.family'].lower()
        if ff in self.font_families:
            self.font_family = ff
        else:
            mpl.verbose.report('The %s font family is not compatible with '
                               'LaTeX. serif will be used by default.' % ff,
                               'helpful')
            self.font_family = 'serif'

        fontconfig = [self.font_family]
        for font_family, font_family_attr in [(ff, ff.replace('-', '_'))
                                              for ff in self.font_families]:
            for font in rcParams['font.' + font_family]:
                if font.lower() in self.font_info:
                    setattr(self, font_family_attr,
                            self.font_info[font.lower()])
                    if DEBUG:
                        print('family: %s, font: %s, info: %s' %
                              (font_family, font,
                               self.font_info[font.lower()]))
                    break
                else:
                    if DEBUG:
                        print('$s font is not compatible with usetex')
            else:
                mpl.verbose.report('No LaTeX-compatible font found for the '
                                   '%s font family in rcParams. Using '
                                   'default.' % ff, 'helpful')
                setattr(self, font_family_attr, self.font_info[font_family])
            fontconfig.append(getattr(self, font_family_attr)[0])
        self._fontconfig = ''.join(fontconfig)

        # The following packages and commands need to be included in the latex
        # file's preamble:
        cmd = [self.serif[1], self.sans_serif[1], self.monospace[1]]
        if self.font_family == 'cursive':
            cmd.append(self.cursive[1])
        while r'\usepackage{type1cm}' in cmd:
            cmd.remove(r'\usepackage{type1cm}')
        cmd = '\n'.join(cmd)
        self._font_preamble = '\n'.join([r'\usepackage{type1cm}', cmd,
                                         r'\usepackage{textcomp}'])
コード例 #19
0
ファイル: __init__.py プロジェクト: bwillers/ggplot
def _assert_same_figure_images(fig, name, test_file, tol=17):
    """Asserts that the figure object produces the right image"""
    import os
    import shutil
    from matplotlib import cbook
    from matplotlib.testing.compare import compare_images
    from nose.tools import assert_is_not_none

    if not ".png" in name:
        name = name+".png"

    basedir = os.path.abspath(os.path.dirname(test_file))
    basename = os.path.basename(test_file)
    subdir = os.path.splitext(basename)[0]

    baseline_dir = os.path.join(basedir, 'baseline_images', subdir)
    result_dir = os.path.abspath(os.path.join('result_images', subdir))

    if not os.path.exists(result_dir):
        cbook.mkdirs(result_dir)

    orig_expected_fname = os.path.join(baseline_dir, name)
    actual_fname = os.path.join(result_dir, name)

    def make_test_fn(fname, purpose):
        base, ext = os.path.splitext(fname)
        return '%s-%s%s' % (base, purpose, ext)
    expected_fname = make_test_fn(actual_fname, 'expected')
    # Save the figure before testing whether the original image
    # actually exists. This make creating new tests much easier,
    # as the result image can afterwards just be copied.
    fig.savefig(actual_fname)
    if os.path.exists(orig_expected_fname):
        shutil.copyfile(orig_expected_fname, expected_fname)
    else:
        raise Exception("Baseline image %s is missing" % orig_expected_fname)
    err = compare_images(expected_fname, actual_fname,
                         tol, in_decorator=True)
    if err:
        msg = 'images not close: {actual:s} vs. {expected:s} (RMS {rms:.2f})'.format(**err)
        raise ImagesComparisonFailure(msg)
    return err
コード例 #20
0
ファイル: __init__.py プロジェクト: vMeijin/matplotlib
def _get_configdir():
    """
    Return the string representing the configuration directory.

    The directory is chosen as follows:

    1. If the MPLCONFIGDIR environment variable is supplied, choose that. Else,
       choose the '.matplotlib' subdirectory of the user's home directory (and
       create it if necessary).
    2. If the chosen directory exists and is writable, use that as the
       configuration directory.
    3. If possible, create a temporary directory, and use it as the
       configuration directory.
    4. A writable directory could not be found or created; return None.
    """
    from matplotlib.cbook import mkdirs

    configdir = os.environ.get('MPLCONFIGDIR')
    if configdir is not None:
        if not os.path.exists(configdir):
            from matplotlib.cbook import mkdirs
            mkdirs(configdir)
        if not _is_writable_dir(configdir):
            return _create_tmp_config_dir()
        return configdir

    h = get_home()
    if h is not None:
        p = os.path.join(h, '.matplotlib')

        if os.path.exists(p):
            if not _is_writable_dir(p):
                return _create_tmp_config_dir()
        else:
            if not _is_writable_dir(h):
                return _create_tmp_config_dir()
            mkdirs(p)

        return p

    return _create_tmp_config_dir()
コード例 #21
0
ファイル: test_images.py プロジェクト: Sathaye/wcsaxes
    def setup_class(cls):
        cls._filedir = os.path.abspath(__file__)
        cls._basedir = os.path.split(cls._filedir)[0]
        cls._baseline_images_dir = os.path.join(cls._basedir, 'baseline_images')
        cls._result_dir = os.path.abspath(os.path.join(cls._basedir, 'test_result_images'))
        cls._data_dir = os.path.abspath(os.path.join(cls._basedir, 'data'))

        if not os.path.exists(cls._result_dir):
            cbook.mkdirs(cls._result_dir)

        if not os.path.exists(cls._baseline_images_dir):
            cbook.mkdirs(cls._baseline_images_dir)

        if not os.path.exists(cls._data_dir):
            cbook.mkdirs(cls._data_dir)

        cls._tolerance = 1

        msx_header = os.path.join(cls._data_dir, 'msx_header')
        cls.msx_header = fits.Header.fromtextfile(msx_header)

        rosat_header = os.path.join(cls._data_dir, 'rosat_header')
        cls.rosat_header = fits.Header.fromtextfile(rosat_header)

        twoMASS_k_header = os.path.join(cls._data_dir, '2MASS_k_header')
        cls.twoMASS_k_header = fits.Header.fromtextfile(twoMASS_k_header)

        cube_header = os.path.join(cls._data_dir, 'cube_header')
        cls.cube_header = fits.Header.fromtextfile(cube_header)
コード例 #22
0
ファイル: mpl_ic.py プロジェクト: bmcfee/mir_eval
def _image_directories(func):
    """
    Compute the baseline and result image directories for testing *func*.
    Create the result directory if it doesn't exist.
    """
    module_name = func.__module__
    # mods = module_name.split('.')
    # mods.pop(0) # <- will be the name of the package being tested (in
    # most cases "matplotlib")
    # assert mods.pop(0) == 'tests'
    # subdir = os.path.join(*mods)
    subdir = module_name

    import imp

    def find_dotted_module(module_name, path=None):
        """A version of imp which can handle dots in the module name"""
        res = None
        for sub_mod in module_name.split('.'):
            try:
                res = file, path, _ = imp.find_module(sub_mod, path)
                path = [path]
                if file is not None:
                    file.close()
            except ImportError:
                # assume namespace package
                path = sys.modules[sub_mod].__path__
                res = None, path, None
        return res

    mod_file = find_dotted_module(func.__module__)[1]
    basedir = os.path.dirname(mod_file)

    baseline_dir = os.path.join(basedir, 'baseline_images', subdir)
    result_dir = os.path.abspath(os.path.join('result_images', subdir))

    if not os.path.exists(result_dir):
        cbook.mkdirs(result_dir)

    return baseline_dir, result_dir
コード例 #23
0
ファイル: __init__.py プロジェクト: BernhardKonrad/ggplot
def _assert_same_figure_images(fig, name, test_file, tol=17):
    """Asserts that the figure object produces the right image"""
    import os
    import shutil
    from matplotlib import cbook
    from matplotlib.testing.compare import compare_images
    from nose.tools import assert_is_not_none

    if not ".png" in name:
        name = name + ".png"

    basedir = os.path.abspath(os.path.dirname(test_file))
    basename = os.path.basename(test_file)
    subdir = os.path.splitext(basename)[0]

    baseline_dir = os.path.join(basedir, "baseline_images", subdir)
    result_dir = os.path.abspath(os.path.join("result_images", subdir))

    if not os.path.exists(result_dir):
        cbook.mkdirs(result_dir)

    orig_expected_fname = os.path.join(baseline_dir, name)
    actual_fname = os.path.join(result_dir, name)

    def make_test_fn(fname, purpose):
        base, ext = os.path.splitext(fname)
        return "%s-%s%s" % (base, purpose, ext)

    expected_fname = make_test_fn(actual_fname, "expected")
    if os.path.exists(orig_expected_fname):
        shutil.copyfile(orig_expected_fname, expected_fname)
    else:
        raise Exception("Baseline image %s is missing" % orig_expected_fname)
    fig.savefig(actual_fname)
    err = compare_images(expected_fname, actual_fname, tol, in_decorator=True)
    if err:
        msg = "images not close: {actual:s} vs. {expected:s} (RMS {rms:.2f})".format(**err)
        raise ImagesComparisonFailure(msg)
    return err
コード例 #24
0
ファイル: decorators.py プロジェクト: JunOu/matplotlib
def _image_directories(func):
    """
    Compute the baseline and result image directories for testing *func*.
    Create the result directory if it doesn't exist.
    """
    module_name = func.__module__
    if module_name == '__main__':
        # FIXME: this won't work for nested packages in matplotlib.tests
        warnings.warn('test module run as script. guessing baseline image locations')
        script_name = sys.argv[0]
        basedir = os.path.abspath(os.path.dirname(script_name))
        subdir = os.path.splitext(os.path.split(script_name)[1])[0]
    else:
        mods = module_name.split('.')
        mods.pop(0) # <- will be the name of the package being tested (in
                    # most cases "matplotlib")
        assert mods.pop(0) == 'tests'
        subdir = os.path.join(*mods)

        import imp
        def find_dotted_module(module_name, path=None):
            """A version of imp which can handle dots in the module name"""
            res = None
            for sub_mod in module_name.split('.'):
                res = _, path, _ = imp.find_module(sub_mod, path)
                path = [path]
            return res

        mod_file = find_dotted_module(func.__module__)[1]
        basedir = os.path.dirname(mod_file)

    baseline_dir = os.path.join(basedir, 'baseline_images', subdir)
    result_dir = os.path.abspath(os.path.join('result_images', subdir))

    if not os.path.exists(result_dir):
        cbook.mkdirs(result_dir)

    return baseline_dir, result_dir
コード例 #25
0
ファイル: __init__.py プロジェクト: jheinen/matplotlib
def _create_tmp_config_dir():
    """
    If the config directory can not be created, create a temporary
    directory.

    Returns None if a writable temporary directory could not be created.
    """
    import getpass
    import tempfile
    from matplotlib.cbook import mkdirs

    try:
        tempdir = tempfile.gettempdir()
    except NotImplementedError:
        # Some restricted platforms (such as Google App Engine) do not provide
        # gettempdir.
        return None
    tempdir = os.path.join(tempdir, 'matplotlib-%s' % getpass.getuser())
    os.environ['MPLCONFIGDIR'] = tempdir

    mkdirs(tempdir)

    return tempdir
コード例 #26
0
def plot_directive(name, arguments, options, content, lineno,
                   content_offset, block_text, state, state_machine):
    """
    Handle the plot directive.
    """
    formats = setup.config.plot_formats
    if type(formats) == str:
        formats = eval(formats)
    if len(arguments) == 1:
        reference = directives.uri(arguments[0])
        basedir, fname = os.path.split(reference)
        basename, ext = os.path.splitext(fname)
        basedir = relpath(basedir, setup.app.builder.srcdir)
        if len(content):
            raise ValueError("plot directive may not specify both a filename and inline content")
        content = None
    else:
        basedir = "inline"
        content = '\n'.join(content)
        reference = basename = md5(content).hexdigest()[-10:]
        fname = None
    rstdir, rstfile = os.path.split(state_machine.document.attributes['source'])
    outdir = os.path.join('plot_directive', basedir)
    reldir = relpath(setup.confdir, rstdir)
    linkdir = os.path.join(reldir, outdir)
    tmpdir = os.path.join('build', outdir)
    if sphinx_version < (0, 6):
        tmpdir = os.path.abspath(tmpdir)
        prefix = ''
    else:
        prefix = '/'
    if not os.path.exists(tmpdir):
        cbook.mkdirs(tmpdir)
    destdir = os.path.abspath(os.path.join(setup.app.builder.outdir, outdir))
    if not os.path.exists(destdir):
        cbook.mkdirs(destdir)
    num_figs = makefig(reference, content, tmpdir)
    if options.has_key('include-source'):
        if content is None:
            content = open(reference, 'r').read()
        lines = ['::', ''] + ['    %s'%row.rstrip() for row in content.split('\n')]
        del options['include-source']
    else:
        lines = []
    if num_figs > 0:
        options = ['      :%s: %s' % (key, val) for key, val in
                   options.items()]
        options = "\n".join(options)
        if fname is not None:
            shutil.copyfile(reference, os.path.join(destdir, fname))
        for i in range(num_figs):
            if num_figs == 1:
                outname = basename
            else:
                outname = "%s_%02d" % (basename, i)
            links = []
            if fname is not None:
                links.append('`source code <%(linkdir)s/%(basename)s.py>`__')
            for format in formats[1:]:
                shutil.copyfile(os.path.join(tmpdir, outname + "." + format),
                                os.path.join(destdir, outname + "." + format))
                links.append('`%s <%s/%s.%s>`__' % (format, linkdir, outname, format))
            links = ', '.join(links) % locals()
            lines.extend((template % locals()).split('\n'))
    else:
        lines.extend((exception_template % locals()).split('\n'))
    if len(lines):
        state_machine.insert_input(
            lines, state_machine.input_lines.source(0))
    return []
コード例 #27
0
def plot_directive(name, arguments, options, content, lineno,
                   content_offset, block_text, state, state_machine):
    """
    Handle the plot directive.
    """
    formats = setup.config.plot_formats
    if type(formats) == str:
        formats = eval(formats)

    # The user may provide a filename *or* Python code content, but not both
    if len(arguments) == 1:
        reference = directives.uri(arguments[0])
        basedir, fname = os.path.split(reference)
        basename, ext = os.path.splitext(fname)
        basedir = relpath(basedir, setup.app.builder.srcdir)
        if len(content):
            raise ValueError("plot directive may not specify both a filename and inline content")
        content = None
    else:
        basedir = "inline"
        content = '\n'.join(content)
        # Since we don't have a filename, use a hash based on the content
        reference = basename = md5(content).hexdigest()[-10:]
        fname = None

    # Get the directory of the rst file, and determine the relative
    # path from the resulting html file to the plot_directive links
    # (linkdir).  This relative path is used for html links *only*,
    # and not the embedded image.  That is given an absolute path to
    # the temporary directory, and then sphinx moves the file to
    # build/html/_images for us later.
    rstdir, rstfile = os.path.split(state_machine.document.attributes['source'])
    outdir = os.path.join('plot_directive', basedir)
    reldir = relpath(setup.confdir, rstdir)
    linkdir = os.path.join(reldir, outdir)

    # tmpdir is where we build all the output files.  This way the
    # plots won't have to be redone when generating latex after html.

    # Prior to Sphinx 0.6, absolute image paths were treated as
    # relative to the root of the filesystem.  0.6 and after, they are
    # treated as relative to the root of the documentation tree.  We need
    # to support both methods here.
    tmpdir = os.path.join('build', outdir)
    tmpdir = os.path.abspath(tmpdir)
    if sphinx_version < (0, 6):
        prefix = ''
    else:
        prefix = '/'
    if not os.path.exists(tmpdir):
        cbook.mkdirs(tmpdir)

    # destdir is the directory within the output to store files
    # that we'll be linking to -- not the embedded images.
    destdir = os.path.abspath(os.path.join(setup.app.builder.outdir, outdir))
    if not os.path.exists(destdir):
        cbook.mkdirs(destdir)

    # Generate the figures, and return the number of them
    num_figs = makefig(reference, content, tmpdir)

    if options.has_key('include-source'):
        if content is None:
            lines = [
                '.. include:: %s' % os.path.join(setup.app.builder.srcdir, reference),
                '    :literal:']
            if options.has_key('encoding'):
                lines.append('    :encoding: %s' % options['encoding'])
                del options['encoding']
        else:
            lines = ['::', ''] + ['    %s'%row.rstrip() for row in content.split('\n')]
        lines.append('')
        del options['include-source']
    else:
        lines = []

    if num_figs > 0:
        options = ['      :%s: %s' % (key, val) for key, val in
                   options.items()]
        options = "\n".join(options)
        if fname is not None:
            shutil.copyfile(reference, os.path.join(destdir, fname))

        for i in range(num_figs):
            if num_figs == 1:
                outname = basename
            else:
                outname = "%s_%02d" % (basename, i)

            # Copy the linked-to files to the destination within the build tree,
            # and add a link for them
            links = []
            if fname is not None:
                links.append('`source code <%(linkdir)s/%(basename)s.py>`__')
            for format in formats[1:]:
                shutil.copyfile(os.path.join(tmpdir, outname + "." + format),
                                os.path.join(destdir, outname + "." + format))
                links.append('`%s <%s/%s.%s>`__' % (format, linkdir, outname, format))
            links = ', '.join(links) % locals()

            # Output the resulting reST
            lines.extend((template % locals()).split('\n'))
    else:
        lines.extend((exception_template % locals()).split('\n'))

    if len(lines):
        state_machine.insert_input(
            lines, state_machine.input_lines.source(0))

    return []
コード例 #28
0
def fetch_historical_yahoo(ticker, date1, date2, cachename=None,
                           dividends=False):
    """
    Fetch historical data for ticker between date1 and date2.  date1 and
    date2 are date or datetime instances, or (year, month, day) sequences.

    Parameters
    ----------
    ticker : str
        ticker

    date1 : sequence of form (year, month, day), `datetime`, or `date`
        start date
    date2 : sequence of form (year, month, day), `datetime`, or `date`
        end date

    cachename : str
        cachename is the name of the local file cache.  If None, will
        default to the md5 hash or the url (which incorporates the ticker
        and date range)

    dividends : bool
        set dividends=True to return dividends instead of price data.  With
        this option set, parse functions will not work

    Returns
    -------
    file_handle : file handle
        a file handle is returned


    Examples
    --------
    >>> fh = fetch_historical_yahoo('^GSPC', (2000, 1, 1), (2001, 12, 31))

    """

    ticker = ticker.upper()

    if iterable(date1):
        d1 = (date1[1] - 1, date1[2], date1[0])
    else:
        d1 = (date1.month - 1, date1.day, date1.year)
    if iterable(date2):
        d2 = (date2[1] - 1, date2[2], date2[0])
    else:
        d2 = (date2.month - 1, date2.day, date2.year)

    if dividends:
        g = 'v'
        verbose.report('Retrieving dividends instead of prices')
    else:
        g = 'd'

    urlFmt = ('http://real-chart.finance.yahoo.com/table.csv?' +
              '&s=%s&d=%d&e=%d&f=%d&g=%s&a=%d&b=%d&c=%d&ignore=.csv')

    url = urlFmt % (ticker, d2[0], d2[1], d2[2], g, d1[0], d1[1], d1[2])
    # Cache the finance data if cachename is supplied, or there is a writable
    # cache directory.
    if cachename is None and cachedir is not None:
        cachename = os.path.join(cachedir, md5(url).hexdigest())
    if cachename is not None:
        if os.path.exists(cachename):
            fh = open(cachename)
            verbose.report('Using cachefile %s for '
                           '%s' % (cachename, ticker))
        else:
            mkdirs(os.path.abspath(os.path.dirname(cachename)))
            with contextlib.closing(urlopen(url)) as urlfh:
                with open(cachename, 'wb') as fh:
                    fh.write(urlfh.read())
            verbose.report('Saved %s data to cache file '
                           '%s' % (ticker, cachename))
            fh = open(cachename, 'r')

        return fh
    else:
        return urlopen(url)
コード例 #29
0
            only_latex=only_latex,
            options=opts,
            images=images,
            source_code=source_code,
            html_show_formats=config.plot_html_show_formats,
            caption=caption)

        total_lines.extend(result.split("\n"))
        total_lines.extend("\n")

    if total_lines:
        state_machine.insert_input(total_lines, source=source_file_name)

    # copy image files to builder's output directory, if necessary
    if not os.path.exists(dest_dir):
        cbook.mkdirs(dest_dir)
    
    for code_piece, images in results:
        for img in images:
            for fn in img.filenames():
                destimg = os.path.join(dest_dir, os.path.basename(fn))
                if fn != destimg:
                    shutil.copyfile(fn, destimg)

    # copy script (if necessary)
    if source_file_name == rst_file:
        target_name = os.path.join(dest_dir, output_base + source_ext)
        f = open(target_name, 'w')
        f.write(unescape_doctest(code))
        f.close()
コード例 #30
0
ファイル: texmanager.py プロジェクト: wdu-wei/matplotlib
class TexManager:
    """
    Convert strings to dvi files using TeX, caching the results to a
    working dir
    """

    oldpath = mpl.get_home()
    if oldpath is None:
        oldpath = mpl.get_data_path()
    oldcache = os.path.join(oldpath, '.tex.cache')

    cachedir = mpl.get_cachedir()
    if cachedir is not None:
        texcache = os.path.join(cachedir, 'tex.cache')
    else:
        # Should only happen in a restricted environment (such as Google App
        # Engine). Deal with this gracefully by not creating a cache directory.
        texcache = None

    if os.path.exists(oldcache):
        if texcache is not None:
            try:
                shutil.move(oldcache, texcache)
            except IOError as e:
                warnings.warn('File could not be renamed: %s' % e)
            else:
                warnings.warn("""\
Found a TeX cache dir in the deprecated location "%s".
    Moving it to the new default location "%s".""" % (oldcache, texcache))
        else:
            warnings.warn("""\
Could not rename old TeX cache dir "%s": a suitable configuration
    directory could not be found.""" % oldcache)

    if texcache is not None:
        mkdirs(texcache)

    _dvipng_hack_alpha = None
    #_dvipng_hack_alpha = dvipng_hack_alpha()
    # mappable cache of
    rgba_arrayd = {}
    grey_arrayd = {}
    postscriptd = {}
    pscnt = 0

    serif = ('cmr', '')
    sans_serif = ('cmss', '')
    monospace = ('cmtt', '')
    cursive = ('pzc', '\\usepackage{chancery}')
    font_family = 'serif'
    font_families = ('serif', 'sans-serif', 'cursive', 'monospace')

    font_info = {
        'new century schoolbook': ('pnc', r'\renewcommand{\rmdefault}{pnc}'),
        'bookman': ('pbk', r'\renewcommand{\rmdefault}{pbk}'),
        'times': ('ptm', '\\usepackage{mathptmx}'),
        'palatino': ('ppl', '\\usepackage{mathpazo}'),
        'zapf chancery': ('pzc', '\\usepackage{chancery}'),
        'cursive': ('pzc', '\\usepackage{chancery}'),
        'charter': ('pch', '\\usepackage{charter}'),
        'serif': ('cmr', ''),
        'sans-serif': ('cmss', ''),
        'helvetica': ('phv', '\\usepackage{helvet}'),
        'avant garde': ('pag', '\\usepackage{avant}'),
        'courier': ('pcr', '\\usepackage{courier}'),
        'monospace': ('cmtt', ''),
        'computer modern roman': ('cmr', ''),
        'computer modern sans serif': ('cmss', ''),
        'computer modern typewriter': ('cmtt', '')
    }

    _rc_cache = None
    _rc_cache_keys = (
        ('text.latex.preamble', ) +
        tuple(['font.' + n for n in ('family', ) + font_families]))

    def __init__(self):

        if self.texcache is None:
            raise RuntimeError(
                ('Cannot create TexManager, as there is no cache directory '
                 'available'))

        mkdirs(self.texcache)
        ff = rcParams['font.family']
        if len(ff) == 1 and ff[0].lower() in self.font_families:
            self.font_family = ff[0].lower()
        elif isinstance(ff,
                        six.string_types) and ff.lower() in self.font_families:
            self.font_family = ff.lower()
        else:
            mpl.verbose.report(
                'font.family must be one of (%s) when text.usetex is True. '
                'serif will be used by default.' %
                ', '.join(self.font_families), 'helpful')
            self.font_family = 'serif'

        fontconfig = [self.font_family]
        for font_family, font_family_attr in [(ff, ff.replace('-', '_'))
                                              for ff in self.font_families]:
            for font in rcParams['font.' + font_family]:
                if font.lower() in self.font_info:
                    setattr(self, font_family_attr,
                            self.font_info[font.lower()])
                    if DEBUG:
                        print(
                            'family: %s, font: %s, info: %s' %
                            (font_family, font, self.font_info[font.lower()]))
                    break
                else:
                    if DEBUG:
                        print('$s font is not compatible with usetex')
            else:
                mpl.verbose.report(
                    'No LaTeX-compatible font found for the '
                    '%s font family in rcParams. Using '
                    'default.' % ff, 'helpful')
                setattr(self, font_family_attr, self.font_info[font_family])
            fontconfig.append(getattr(self, font_family_attr)[0])
        self._fontconfig = ''.join(fontconfig)

        # The following packages and commands need to be included in the latex
        # file's preamble:
        cmd = [self.serif[1], self.sans_serif[1], self.monospace[1]]
        if self.font_family == 'cursive':
            cmd.append(self.cursive[1])
        while '\\usepackage{type1cm}' in cmd:
            cmd.remove('\\usepackage{type1cm}')
        cmd = '\n'.join(cmd)
        self._font_preamble = '\n'.join(
            ['\\usepackage{type1cm}', cmd, '\\usepackage{textcomp}'])

    def get_basefile(self, tex, fontsize, dpi=None):
        """
        returns a filename based on a hash of the string, fontsize, and dpi
        """
        s = ''.join([
            tex,
            self.get_font_config(),
            '%f' % fontsize,
            self.get_custom_preamble(),
            str(dpi or '')
        ])
        # make sure hash is consistent for all strings, regardless of encoding:
        bytes = six.text_type(s).encode('utf-8')
        return os.path.join(self.texcache, md5(bytes).hexdigest())

    def get_font_config(self):
        """Reinitializes self if relevant rcParams on have changed."""
        if self._rc_cache is None:
            self._rc_cache = dict([(k, None) for k in self._rc_cache_keys])
        changed = [
            par for par in self._rc_cache_keys
            if rcParams[par] != self._rc_cache[par]
        ]
        if changed:
            if DEBUG:
                print('DEBUG following keys changed:', changed)
            for k in changed:
                if DEBUG:
                    print('DEBUG %-20s: %-10s -> %-10s' %
                          (k, self._rc_cache[k], rcParams[k]))
                # deepcopy may not be necessary, but feels more future-proof
                self._rc_cache[k] = copy.deepcopy(rcParams[k])
            if DEBUG:
                print('DEBUG RE-INIT\nold fontconfig:', self._fontconfig)
            self.__init__()
        if DEBUG:
            print('DEBUG fontconfig:', self._fontconfig)
        return self._fontconfig

    def get_font_preamble(self):
        """
        returns a string containing font configuration for the tex preamble
        """
        return self._font_preamble

    def get_custom_preamble(self):
        """returns a string containing user additions to the tex preamble"""
        return '\n'.join(rcParams['text.latex.preamble'])

    def _get_shell_cmd(self, *args):
        """
        On windows, changing directories can be complicated by the presence of
        multiple drives. get_shell_cmd deals with this issue.
        """
        if sys.platform == 'win32':
            command = ['%s' % os.path.splitdrive(self.texcache)[0]]
        else:
            command = []
        command.extend(args)
        return ' && '.join(command)

    def make_tex(self, tex, fontsize):
        """
        Generate a tex file to render the tex string at a specific font size

        returns the file name
        """
        basefile = self.get_basefile(tex, fontsize)
        texfile = '%s.tex' % basefile
        custom_preamble = self.get_custom_preamble()
        fontcmd = {
            'sans-serif': r'{\sffamily %s}',
            'monospace': r'{\ttfamily %s}'
        }.get(self.font_family, r'{\rmfamily %s}')
        tex = fontcmd % tex

        if rcParams['text.latex.unicode']:
            unicode_preamble = """\\usepackage{ucs}
\\usepackage[utf8x]{inputenc}"""
        else:
            unicode_preamble = ''

        s = """\\documentclass{article}
%s
%s
%s
\\usepackage[papersize={72in,72in},body={70in,70in},margin={1in,1in}]{geometry}
\\pagestyle{empty}
\\begin{document}
\\fontsize{%f}{%f}%s
\\end{document}
""" % (self._font_preamble, unicode_preamble, custom_preamble, fontsize,
        fontsize * 1.25, tex)
        with open(texfile, 'wb') as fh:
            if rcParams['text.latex.unicode']:
                fh.write(s.encode('utf8'))
            else:
                try:
                    fh.write(s.encode('ascii'))
                except UnicodeEncodeError as err:
                    mpl.verbose.report(
                        "You are using unicode and latex, but "
                        "have not enabled the matplotlib "
                        "'text.latex.unicode' rcParam.", 'helpful')
                    raise

        return texfile

    _re_vbox = re.compile(
        r"MatplotlibBox:\(([\d.]+)pt\+([\d.]+)pt\)x([\d.]+)pt")

    def make_tex_preview(self, tex, fontsize):
        """
        Generate a tex file to render the tex string at a specific
        font size.  It uses the preview.sty to determin the dimension
        (width, height, descent) of the output.

        returns the file name
        """
        basefile = self.get_basefile(tex, fontsize)
        texfile = '%s.tex' % basefile
        custom_preamble = self.get_custom_preamble()
        fontcmd = {
            'sans-serif': r'{\sffamily %s}',
            'monospace': r'{\ttfamily %s}'
        }.get(self.font_family, r'{\rmfamily %s}')
        tex = fontcmd % tex

        if rcParams['text.latex.unicode']:
            unicode_preamble = """\\usepackage{ucs}
\\usepackage[utf8x]{inputenc}"""
        else:
            unicode_preamble = ''

        # newbox, setbox, immediate, etc. are used to find the box
        # extent of the rendered text.

        s = """\\documentclass{article}
%s
%s
%s
\\usepackage[active,showbox,tightpage]{preview}
\\usepackage[papersize={72in,72in},body={70in,70in},margin={1in,1in}]{geometry}

%% we override the default showbox as it is treated as an error and makes
%% the exit status not zero
\\def\\showbox#1{\\immediate\\write16{MatplotlibBox:(\\the\\ht#1+\\the\\dp#1)x\\the\\wd#1}}

\\begin{document}
\\begin{preview}
{\\fontsize{%f}{%f}%s}
\\end{preview}
\\end{document}
""" % (self._font_preamble, unicode_preamble, custom_preamble, fontsize,
        fontsize * 1.25, tex)
        with open(texfile, 'wb') as fh:
            if rcParams['text.latex.unicode']:
                fh.write(s.encode('utf8'))
            else:
                try:
                    fh.write(s.encode('ascii'))
                except UnicodeEncodeError as err:
                    mpl.verbose.report(
                        "You are using unicode and latex, but "
                        "have not enabled the matplotlib "
                        "'text.latex.unicode' rcParam.", 'helpful')
                    raise

        return texfile

    def make_dvi(self, tex, fontsize):
        """
        generates a dvi file containing latex's layout of tex string

        returns the file name
        """

        if rcParams['text.latex.preview']:
            return self.make_dvi_preview(tex, fontsize)

        basefile = self.get_basefile(tex, fontsize)
        dvifile = '%s.dvi' % basefile

        if DEBUG or not os.path.exists(dvifile):
            texfile = self.make_tex(tex, fontsize)
            outfile = basefile + '.output'
            command = self._get_shell_cmd(
                'cd "%s"' % self.texcache,
                'latex -interaction=nonstopmode %s > "%s"' %
                (os.path.split(texfile)[-1], outfile))
            mpl.verbose.report(command, 'debug')
            exit_status = os.system(command)
            try:
                with open(outfile) as fh:
                    report = fh.read()
            except IOError:
                report = 'No latex error report available.'
            try:
                os.stat(dvifile)
                exists = True
            except OSError:
                exists = False
            if exit_status or not exists:
                raise RuntimeError(
                    ('LaTeX was not able to process the following '
                     'string:\n%s\nHere is the full report generated by '
                     'LaTeX: \n\n' % repr(tex.encode('unicode_escape')) +
                     report))
            else:
                mpl.verbose.report(report, 'debug')
            for fname in glob.glob(basefile + '*'):
                if fname.endswith('dvi'):
                    pass
                elif fname.endswith('tex'):
                    pass
                else:
                    try:
                        os.remove(fname)
                    except OSError:
                        pass

        return dvifile

    def make_dvi_preview(self, tex, fontsize):
        """
        generates a dvi file containing latex's layout of tex
        string. It calls make_tex_preview() method and store the size
        information (width, height, descent) in a separte file.

        returns the file name
        """
        basefile = self.get_basefile(tex, fontsize)
        dvifile = '%s.dvi' % basefile
        baselinefile = '%s.baseline' % basefile

        if (DEBUG or not os.path.exists(dvifile)
                or not os.path.exists(baselinefile)):
            texfile = self.make_tex_preview(tex, fontsize)
            outfile = basefile + '.output'
            command = self._get_shell_cmd(
                'cd "%s"' % self.texcache,
                'latex -interaction=nonstopmode %s > "%s"' %
                (os.path.split(texfile)[-1], outfile))
            mpl.verbose.report(command, 'debug')
            exit_status = os.system(command)
            try:
                with open(outfile) as fh:
                    report = fh.read()

            except IOError:
                report = 'No latex error report available.'
            if exit_status:
                raise RuntimeError(
                    ('LaTeX was not able to process the following '
                     'string:\n%s\nHere is the full report generated by '
                     'LaTeX: \n\n' % repr(tex)) + report)
            else:
                mpl.verbose.report(report, 'debug')

            # find the box extent information in the latex output
            # file and store them in ".baseline" file
            m = TexManager._re_vbox.search(report)
            with open(basefile + '.baseline', "w") as fh:
                fh.write(" ".join(m.groups()))

            for fname in glob.glob(basefile + '*'):
                if fname.endswith('dvi'):
                    pass
                elif fname.endswith('tex'):
                    pass
                elif fname.endswith('baseline'):
                    pass
                else:
                    try:
                        os.remove(fname)
                    except OSError:
                        pass

        return dvifile

    def make_png(self, tex, fontsize, dpi):
        """
        generates a png file containing latex's rendering of tex string

        returns the filename
        """
        basefile = self.get_basefile(tex, fontsize, dpi)
        pngfile = '%s.png' % basefile

        # see get_rgba for a discussion of the background
        if DEBUG or not os.path.exists(pngfile):
            dvifile = self.make_dvi(tex, fontsize)
            outfile = basefile + '.output'
            command = self._get_shell_cmd(
                'cd "%s"' % self.texcache,
                'dvipng -bg Transparent -D %s -T tight -o "%s" "%s" > "%s"' %
                (dpi, os.path.split(pngfile)[-1], os.path.split(dvifile)[-1],
                 outfile))
            mpl.verbose.report(command, 'debug')
            exit_status = os.system(command)
            try:
                with open(outfile) as fh:
                    report = fh.read()
            except IOError:
                report = 'No dvipng error report available.'
            if exit_status:
                raise RuntimeError(
                    'dvipng was not able to process the following '
                    'file:\n%s\nHere is the full report generated by '
                    'dvipng: \n\n' % dvifile + report)
            else:
                mpl.verbose.report(report, 'debug')
            try:
                os.remove(outfile)
            except OSError:
                pass

        return pngfile

    def make_ps(self, tex, fontsize):
        """
        generates a postscript file containing latex's rendering of tex string

        returns the file name
        """
        basefile = self.get_basefile(tex, fontsize)
        psfile = '%s.epsf' % basefile

        if DEBUG or not os.path.exists(psfile):
            dvifile = self.make_dvi(tex, fontsize)
            outfile = basefile + '.output'
            command = self._get_shell_cmd(
                'cd "%s"' % self.texcache, 'dvips -q -E -o "%s" "%s" > "%s"' %
                (os.path.split(psfile)[-1], os.path.split(dvifile)[-1],
                 outfile))
            mpl.verbose.report(command, 'debug')
            exit_status = os.system(command)
            with open(outfile) as fh:
                if exit_status:
                    raise RuntimeError(
                        'dvipng was not able to process the flowing '
                        'file:\n%s\nHere is the full report generated by '
                        'dvipng: \n\n' % dvifile + fh.read())
                else:
                    mpl.verbose.report(fh.read(), 'debug')
            os.remove(outfile)

        return psfile

    def get_ps_bbox(self, tex, fontsize):
        """
        returns a list containing the postscript bounding box for latex's
        rendering of the tex string
        """
        psfile = self.make_ps(tex, fontsize)
        with open(psfile) as ps:
            for line in ps:
                if line.startswith('%%BoundingBox:'):
                    return [int(val) for val in line.split()[1:]]
        raise RuntimeError('Could not parse %s' % psfile)

    def get_grey(self, tex, fontsize=None, dpi=None):
        """returns the alpha channel"""
        key = tex, self.get_font_config(), fontsize, dpi
        alpha = self.grey_arrayd.get(key)

        if alpha is None:
            pngfile = self.make_png(tex, fontsize, dpi)
            X = read_png(os.path.join(self.texcache, pngfile))

            if rcParams['text.dvipnghack'] is not None:
                hack = rcParams['text.dvipnghack']
            else:
                if TexManager._dvipng_hack_alpha is None:
                    TexManager._dvipng_hack_alpha = dvipng_hack_alpha()
                hack = TexManager._dvipng_hack_alpha

            if hack:
                # hack the alpha channel
                # dvipng assumed a constant background, whereas we want to
                # overlay these rasters with antialiasing over arbitrary
                # backgrounds that may have other figure elements under them.
                # When you set dvipng -bg Transparent, it actually makes the
                # alpha channel 1 and does the background compositing and
                # antialiasing itself and puts the blended data in the rgb
                # channels.  So what we do is extract the alpha information
                # from the red channel, which is a blend of the default dvipng
                # background (white) and foreground (black).  So the amount of
                # red (or green or blue for that matter since white and black
                # blend to a grayscale) is the alpha intensity.  Once we
                # extract the correct alpha information, we assign it to the
                # alpha channel properly and let the users pick their rgb.  In
                # this way, we can overlay tex strings on arbitrary
                # backgrounds with antialiasing
                #
                # red = alpha*red_foreground + (1-alpha)*red_background
                #
                # Since the foreground is black (0) and the background is
                # white (1) this reduces to red = 1-alpha or alpha = 1-red
                #alpha = npy.sqrt(1-X[:,:,0]) # should this be sqrt here?
                alpha = 1 - X[:, :, 0]
            else:
                alpha = X[:, :, -1]

            self.grey_arrayd[key] = alpha
        return alpha

    def get_rgba(self, tex, fontsize=None, dpi=None, rgb=(0, 0, 0)):
        """
        Returns latex's rendering of the tex string as an rgba array
        """
        if not fontsize:
            fontsize = rcParams['font.size']
        if not dpi:
            dpi = rcParams['savefig.dpi']
        r, g, b = rgb
        key = tex, self.get_font_config(), fontsize, dpi, tuple(rgb)
        Z = self.rgba_arrayd.get(key)

        if Z is None:
            alpha = self.get_grey(tex, fontsize, dpi)

            Z = np.zeros((alpha.shape[0], alpha.shape[1], 4), np.float)

            Z[:, :, 0] = r
            Z[:, :, 1] = g
            Z[:, :, 2] = b
            Z[:, :, 3] = alpha
            self.rgba_arrayd[key] = Z

        return Z

    def get_text_width_height_descent(self, tex, fontsize, renderer=None):
        """
        return width, heigth and descent of the text.
        """
        if tex.strip() == '':
            return 0, 0, 0

        if renderer:
            dpi_fraction = renderer.points_to_pixels(1.)
        else:
            dpi_fraction = 1.

        if rcParams['text.latex.preview']:
            # use preview.sty
            basefile = self.get_basefile(tex, fontsize)
            baselinefile = '%s.baseline' % basefile

            if DEBUG or not os.path.exists(baselinefile):
                dvifile = self.make_dvi_preview(tex, fontsize)

            with open(baselinefile) as fh:
                l = fh.read().split()
            height, depth, width = [float(l1) * dpi_fraction for l1 in l]
            return width, height + depth, depth

        else:
            # use dviread. It sometimes returns a wrong descent.
            dvifile = self.make_dvi(tex, fontsize)
            dvi = dviread.Dvi(dvifile, 72 * dpi_fraction)
            try:
                page = next(iter(dvi))
            finally:
                dvi.close()
            # A total height (including the descent) needs to be returned.
            return page.width, page.height + page.descent, page.descent
コード例 #31
0
def _plot_directive(plot_path, basedir, package_name, node_name, caption,
                    options, state_machine):
    formats = ['png']

    fname = os.path.basename(plot_path)
    basename, ext = os.path.splitext(fname)

    # Get the directory of the rst file, and determine the relative
    # path from the resulting html file to the plot_directive links
    # (linkdir).  This relative path is used for html links *only*,
    # and not the embedded image.  That is given an absolute path to
    # the temporary directory, and then sphinx moves the file to
    # build/html/_images for us later.
    rstdir, rstfile = os.path.split(state_machine.document.attributes['source'])
    outdir = os.path.join('dataflow_directive', basedir)
    reldir = os.path.relpath(setup.confdir, rstdir)
    linkdir = os.path.join(reldir, outdir)

    # tmpdir is where we build all the output files.  This way the
    # plots won't have to be redone when generating latex after html.

    tmpdir = os.path.join('build', outdir)
    tmpdir = os.path.abspath(tmpdir)
    prefix = '/'
    if not os.path.exists(tmpdir):
        cbook.mkdirs(tmpdir)

    # destdir is the directory within the output to store files
    # that we'll be linking to -- not the embedded images.
    destdir = os.path.abspath(os.path.join(setup.app.builder.outdir, outdir))
    if not os.path.exists(destdir):
        cbook.mkdirs(destdir)

    # Properly indent the caption
    caption = '\n'.join(template_content_indent + line.strip()
                        for line in caption.split('\n'))

    # Generate the figures, and return the number of them
    num_figs = render_figures(plot_path, package_name, node_name, tmpdir, destdir, options)

    # Now start generating the lines of output
    lines = []

    if node_name is None:
        shutil.copyfile(plot_path, os.path.join(destdir, fname))


    if num_figs > 0:
        options = ['%s:%s: %s' % (template_content_indent, key, val)
                   for key, val in options.items()]
        options = "\n".join(options)

        outname = basename
        outname = 'dataflow_'+node_name
        links = []
        if node_name is None:
            links.append('`source code <%(linkdir)s/%(basename)s.py>`__')
        if len(links):
            links = '[%s]' % (', '.join(links) % locals())
        else:
            links = ''

        lines.extend((template % locals()).split('\n'))

    if len(lines):
        state_machine.insert_input(
            lines, state_machine.input_lines.source(0))

    return []
コード例 #32
0
def run(arguments, content, options, state_machine, state, lineno):
    document = state_machine.document
    config = document.settings.env.config
    nofigs = 'nofigs' in options

    formats = get_plot_formats(config)
    default_fmt = formats[0][0]

    options.setdefault('include-source', config.plot_include_source)
    keep_context = 'context' in options
    context_opt = None if not keep_context else options['context']

    rst_file = document.attributes['source']
    rst_dir = os.path.dirname(rst_file)

    if len(arguments):
        if not config.plot_basedir:
            source_file_name = os.path.join(setup.app.builder.srcdir,
                                            directives.uri(arguments[0]))
        else:
            source_file_name = os.path.join(setup.confdir, config.plot_basedir,
                                            directives.uri(arguments[0]))

        # If there is content, it will be passed as a caption.
        caption = '\n'.join(content)

        # If the optional function name is provided, use it
        if len(arguments) == 2:
            function_name = arguments[1]
        else:
            function_name = None

        with io.open(source_file_name, 'r', encoding='utf-8') as fd:
            code = fd.read()
        output_base = os.path.basename(source_file_name)
    else:
        source_file_name = rst_file
        code = textwrap.dedent("\n".join(map(str, content)))
        counter = document.attributes.get('_plot_counter', 0) + 1
        document.attributes['_plot_counter'] = counter
        base, ext = os.path.splitext(os.path.basename(source_file_name))
        output_base = '%s-%d.py' % (base, counter)
        function_name = None
        caption = ''

    base, source_ext = os.path.splitext(output_base)
    if source_ext in ('.py', '.rst', '.txt'):
        output_base = base
    else:
        source_ext = ''

    # ensure that LaTeX includegraphics doesn't choke in foo.bar.pdf filenames
    output_base = output_base.replace('.', '-')

    # is it in doctest format?
    is_doctest = contains_doctest(code)
    if 'format' in options:
        if options['format'] == 'python':
            is_doctest = False
        else:
            is_doctest = True

    # determine output directory name fragment
    source_rel_name = relpath(source_file_name, setup.confdir)
    source_rel_dir = os.path.dirname(source_rel_name)
    while source_rel_dir.startswith(os.path.sep):
        source_rel_dir = source_rel_dir[1:]

    # build_dir: where to place output files (temporarily)
    build_dir = os.path.join(os.path.dirname(setup.app.doctreedir),
                             'plot_directive',
                             source_rel_dir)
    # get rid of .. in paths, also changes pathsep
    # see note in Python docs for warning about symbolic links on Windows.
    # need to compare source and dest paths at end
    build_dir = os.path.normpath(build_dir)

    if not os.path.exists(build_dir):
        os.makedirs(build_dir)

    # output_dir: final location in the builder's directory
    dest_dir = os.path.abspath(os.path.join(setup.app.builder.outdir,
                                            source_rel_dir))
    if not os.path.exists(dest_dir):
        os.makedirs(dest_dir) # no problem here for me, but just use built-ins

    # how to link to files from the RST file
    dest_dir_link = os.path.join(relpath(setup.confdir, rst_dir),
                                 source_rel_dir).replace(os.path.sep, '/')
    try:
        build_dir_link = relpath(build_dir, rst_dir).replace(os.path.sep, '/')
    except ValueError:
        # on Windows, relpath raises ValueError when path and start are on
        # different mounts/drives
        build_dir_link = build_dir
    source_link = dest_dir_link + '/' + output_base + source_ext

    # make figures
    try:
        results = render_figures(code,
                                 source_file_name,
                                 build_dir,
                                 output_base,
                                 keep_context,
                                 function_name,
                                 config,
                                 context_reset=context_opt == 'reset',
                                 close_figs=context_opt == 'close-figs')
        errors = []
    except PlotError as err:
        reporter = state.memo.reporter
        sm = reporter.system_message(
            2, "Exception occurred in plotting %s\n from %s:\n%s" % (output_base,
                                                source_file_name, err),
            line=lineno)
        results = [(code, [])]
        errors = [sm]

    # Properly indent the caption
    caption = '\n'.join('      ' + line.strip()
                        for line in caption.split('\n'))

    # generate output restructuredtext
    total_lines = []
    for j, (code_piece, images) in enumerate(results):
        if options['include-source']:
            if is_doctest:
                lines = ['']
                lines += [row.rstrip() for row in code_piece.split('\n')]
            else:
                lines = ['.. code-block:: python', '']
                lines += ['    %s' % row.rstrip()
                          for row in code_piece.split('\n')]
            source_code = "\n".join(lines)
        else:
            source_code = ""

        if nofigs:
            images = []

        opts = [':%s: %s' % (key, val) for key, val in six.iteritems(options)
                if key in ('alt', 'height', 'width', 'scale', 'align', 'class')]

        only_html = ".. only:: html"
        only_latex = ".. only:: latex"
        only_texinfo = ".. only:: texinfo"

        # Not-None src_link signals the need for a source link in the generated
        # html
        if j == 0 and config.plot_html_show_source_link:
            src_link = source_link
        else:
            src_link = None

        result = format_template(
            config.plot_template or TEMPLATE,
            default_fmt=default_fmt,
            dest_dir=dest_dir_link,
            build_dir=build_dir_link,
            source_link=src_link,
            multi_image=len(images) > 1,
            only_html=only_html,
            only_latex=only_latex,
            only_texinfo=only_texinfo,
            options=opts,
            images=images,
            source_code=source_code,
            html_show_formats=config.plot_html_show_formats and len(images),
            caption=caption)

        total_lines.extend(result.split("\n"))
        total_lines.extend("\n")

    if total_lines:
        state_machine.insert_input(total_lines, source=source_file_name)

    # copy image files to builder's output directory, if necessary
    if not os.path.exists(dest_dir):
        cbook.mkdirs(dest_dir)

    for code_piece, images in results:
        for img in images:
            for fn in img.filenames():
                destimg = os.path.join(dest_dir, os.path.basename(fn))
                if fn != destimg:
                    shutil.copyfile(fn, destimg)

    # copy script (if necessary)
    target_name = os.path.join(dest_dir, output_base + source_ext)
    with io.open(target_name, 'w', encoding="utf-8") as f:
        if source_file_name == rst_file:
            code_escaped = unescape_doctest(code)
        else:
            code_escaped = code
        f.write(code_escaped)

    return errors
コード例 #33
0
            only_latex=only_latex,
            options=opts,
            images=images,
            source_code=source_code,
            html_show_formats=config.plot_html_show_formats,
            caption=caption)

        total_lines.extend(result.split("\n"))
        total_lines.extend("\n")

    if total_lines:
        state_machine.insert_input(total_lines, source=source_file_name)

    # copy image files to builder's output directory, if necessary
    if not os.path.exists(dest_dir):
        cbook.mkdirs(dest_dir)

    for code_piece, images in results:
        for img in images:
            for fn in img.filenames():
                destimg = os.path.join(dest_dir, os.path.basename(fn))
                if fn != destimg:
                    shutil.copyfile(fn, destimg)

    # copy script (if necessary)
    if source_file_name == rst_file:
        target_name = os.path.join(dest_dir, output_base + source_ext)
        f = open(target_name, 'w')
        f.write(unescape_doctest(code))
        f.close()
コード例 #34
0
ファイル: plot_directive.py プロジェクト: xpnguyen/matplotlib
def run(arguments, content, options, state_machine, state, lineno):
    document = state_machine.document
    config = document.settings.env.config
    nofigs = 'nofigs' in options

    formats = get_plot_formats(config)
    default_fmt = formats[0][0]

    options.setdefault('include-source', config.plot_include_source)
    keep_context = 'context' in options
    context_opt = None if not keep_context else options['context']

    rst_file = document.attributes['source']
    rst_dir = os.path.dirname(rst_file)

    if len(arguments):
        if not config.plot_basedir:
            source_file_name = os.path.join(setup.app.builder.srcdir,
                                            directives.uri(arguments[0]))
        else:
            source_file_name = os.path.join(setup.confdir, config.plot_basedir,
                                            directives.uri(arguments[0]))

        # If there is content, it will be passed as a caption.
        caption = '\n'.join(content)

        # If the optional function name is provided, use it
        if len(arguments) == 2:
            function_name = arguments[1]
        else:
            function_name = None

        with io.open(source_file_name, 'r', encoding='utf-8') as fd:
            code = fd.read()
        output_base = os.path.basename(source_file_name)
    else:
        source_file_name = rst_file
        code = textwrap.dedent("\n".join(map(six.text_type, content)))
        counter = document.attributes.get('_plot_counter', 0) + 1
        document.attributes['_plot_counter'] = counter
        base, ext = os.path.splitext(os.path.basename(source_file_name))
        output_base = '%s-%d.py' % (base, counter)
        function_name = None
        caption = ''

    base, source_ext = os.path.splitext(output_base)
    if source_ext in ('.py', '.rst', '.txt'):
        output_base = base
    else:
        source_ext = ''

    # ensure that LaTeX includegraphics doesn't choke in foo.bar.pdf filenames
    output_base = output_base.replace('.', '-')

    # is it in doctest format?
    is_doctest = contains_doctest(code)
    if 'format' in options:
        if options['format'] == 'python':
            is_doctest = False
        else:
            is_doctest = True

    # determine output directory name fragment
    source_rel_name = relpath(source_file_name, setup.confdir)
    source_rel_dir = os.path.dirname(source_rel_name)
    while source_rel_dir.startswith(os.path.sep):
        source_rel_dir = source_rel_dir[1:]

    # build_dir: where to place output files (temporarily)
    build_dir = os.path.join(os.path.dirname(setup.app.doctreedir),
                             'plot_directive', source_rel_dir)
    # get rid of .. in paths, also changes pathsep
    # see note in Python docs for warning about symbolic links on Windows.
    # need to compare source and dest paths at end
    build_dir = os.path.normpath(build_dir)

    if not os.path.exists(build_dir):
        os.makedirs(build_dir)

    # output_dir: final location in the builder's directory
    dest_dir = os.path.abspath(
        os.path.join(setup.app.builder.outdir, source_rel_dir))
    if not os.path.exists(dest_dir):
        os.makedirs(dest_dir)  # no problem here for me, but just use built-ins

    # how to link to files from the RST file
    dest_dir_link = os.path.join(relpath(setup.confdir, rst_dir),
                                 source_rel_dir).replace(os.path.sep, '/')
    try:
        build_dir_link = relpath(build_dir, rst_dir).replace(os.path.sep, '/')
    except ValueError:
        # on Windows, relpath raises ValueError when path and start are on
        # different mounts/drives
        build_dir_link = build_dir
    source_link = dest_dir_link + '/' + output_base + source_ext

    # make figures
    try:
        results = render_figures(code,
                                 source_file_name,
                                 build_dir,
                                 output_base,
                                 keep_context,
                                 function_name,
                                 config,
                                 context_reset=context_opt == 'reset',
                                 close_figs=context_opt == 'close-figs')
        errors = []
    except PlotError as err:
        reporter = state.memo.reporter
        sm = reporter.system_message(
            2,
            "Exception occurred in plotting %s\n from %s:\n%s" %
            (output_base, source_file_name, err),
            line=lineno)
        results = [(code, [])]
        errors = [sm]

    # Properly indent the caption
    caption = '\n'.join('      ' + line.strip()
                        for line in caption.split('\n'))

    # generate output restructuredtext
    total_lines = []
    for j, (code_piece, images) in enumerate(results):
        if options['include-source']:
            if is_doctest:
                lines = ['']
                lines += [row.rstrip() for row in code_piece.split('\n')]
            else:
                lines = ['.. code-block:: python', '']
                lines += [
                    '    %s' % row.rstrip() for row in code_piece.split('\n')
                ]
            source_code = "\n".join(lines)
        else:
            source_code = ""

        if nofigs:
            images = []

        opts = [
            ':%s: %s' % (key, val) for key, val in six.iteritems(options)
            if key in ('alt', 'height', 'width', 'scale', 'align', 'class')
        ]

        only_html = ".. only:: html"
        only_latex = ".. only:: latex"
        only_texinfo = ".. only:: texinfo"

        # Not-None src_link signals the need for a source link in the generated
        # html
        if j == 0 and config.plot_html_show_source_link:
            src_link = source_link
        else:
            src_link = None

        result = format_template(
            config.plot_template or TEMPLATE,
            default_fmt=default_fmt,
            dest_dir=dest_dir_link,
            build_dir=build_dir_link,
            source_link=src_link,
            multi_image=len(images) > 1,
            only_html=only_html,
            only_latex=only_latex,
            only_texinfo=only_texinfo,
            options=opts,
            images=images,
            source_code=source_code,
            html_show_formats=config.plot_html_show_formats and len(images),
            caption=caption)

        total_lines.extend(result.split("\n"))
        total_lines.extend("\n")

    if total_lines:
        state_machine.insert_input(total_lines, source=source_file_name)

    # copy image files to builder's output directory, if necessary
    if not os.path.exists(dest_dir):
        cbook.mkdirs(dest_dir)

    for code_piece, images in results:
        for img in images:
            for fn in img.filenames():
                destimg = os.path.join(dest_dir, os.path.basename(fn))
                if fn != destimg:
                    shutil.copyfile(fn, destimg)

    # copy script (if necessary)
    target_name = os.path.join(dest_dir, output_base + source_ext)
    with io.open(target_name, 'w', encoding="utf-8") as f:
        if source_file_name == rst_file:
            code_escaped = unescape_doctest(code)
        else:
            code_escaped = code
        f.write(code_escaped)

    return errors