def test_if_rctemplate_is_up_to_date(): # This tests if the matplotlibrc.template file contains all valid rcParams. deprecated = {*mpl._all_deprecated, *mpl._deprecated_remain_as_none} path_to_rc = os.path.join(mpl.get_data_path(), 'matplotlibrc') with open(path_to_rc, "r") as f: rclines = f.readlines() missing = {} for k, v in mpl.defaultParams.items(): if k[0] == "_": continue if k in deprecated: continue if k.startswith( ("verbose.", "examples.directory", "text.latex.unicode")): continue found = False for line in rclines: if k in line: found = True if not found: missing.update({k: v}) if missing: raise ValueError("The following params are missing in the " "matplotlibrc.template file: {}" .format(missing.items()))
def test_if_rctemplate_is_up_to_date(): # This tests if the matplotlibrc.template file # contains all valid rcParams. dep1 = mpl._all_deprecated dep2 = mpl._deprecated_set deprecated = list(dep1.union(dep2)) path_to_rc = os.path.join(mpl.get_data_path(), 'matplotlibrc') with open(path_to_rc, "r") as f: rclines = f.readlines() missing = {} for k, v in mpl.defaultParams.items(): if k[0] == "_": continue if k in deprecated: continue if "verbose" in k: continue found = False for line in rclines: if k in line: found = True if not found: missing.update({k: v}) if missing: raise ValueError("The following params are missing " + "in the matplotlibrc.template file: {}" .format(missing.items()))
def __init__(self, lines): import gtk.glade datadir = matplotlib.get_data_path() gladefile = os.path.join(datadir, 'lineprops.glade') if not os.path.exists(gladefile): raise IOError('Could not find gladefile lineprops.glade in %s'%datadir) self._inited = False self._updateson = True # suppress updates when setting widgets manually self.wtree = gtk.glade.XML(gladefile, 'dialog_lineprops') self.wtree.signal_autoconnect(dict([(s, getattr(self, s)) for s in self.signals])) self.dlg = self.wtree.get_widget('dialog_lineprops') self.lines = lines cbox = self.wtree.get_widget('combobox_lineprops') cbox.set_active(0) self.cbox_lineprops = cbox cbox = self.wtree.get_widget('combobox_linestyles') for ls in self.linestyles: cbox.append_text(ls) cbox.set_active(0) self.cbox_linestyles = cbox cbox = self.wtree.get_widget('combobox_markers') for m in self.markers: cbox.append_text(m) cbox.set_active(0) self.cbox_markers = cbox self._lastcnt = 0 self._inited = True
def test_if_rctemplate_would_be_valid(tmpdir): # This tests if the matplotlibrc.template file would result in a valid # rc file if all lines are uncommented. path_to_rc = os.path.join(mpl.get_data_path(), 'matplotlibrc') with open(path_to_rc, "r") as f: rclines = f.readlines() newlines = [] for line in rclines: if line[0] == "#": newline = line[1:] else: newline = line if "$TEMPLATE_BACKEND" in newline: newline = "backend : Agg" if "datapath" in newline: newline = "" newlines.append(newline) d = tmpdir.mkdir('test1') fname = str(d.join('testrcvalid.temp')) with open(fname, "w") as f: f.writelines(newlines) with pytest.warns(None) as record: mpl.rc_params_from_file(fname, fail_on_error=True, use_default_template=False) assert len(record) == 0
def recipe_matplotlib(mf): m = mf.findNode('matplotlib') if not isRealModule(m): return import matplotlib if 0: # do not copy matplotlibdata. assume matplotlib is installed as egg dp = matplotlib.get_data_path() assert dp mf.copyTree(dp, "matplotlibdata", m) # mf.import_hook("matplotlib.numerix.random_array", m) backend_name = 'backend_' + matplotlib.get_backend().lower() print "recipe_matplotlib: using the %s matplotlib backend" % (backend_name, ) mf.import_hook('matplotlib.backends.' + backend_name, m) return True
def default(self, o): if isinstance(o, FontManager): return dict(o.__dict__, __class__='FontManager') elif isinstance(o, FontEntry): d = dict(o.__dict__, __class__='FontEntry') try: # Cache paths of fonts shipped with mpl relative to the mpl # data path, which helps in the presence of venvs. d["fname"] = str( Path(d["fname"]).relative_to(mpl.get_data_path())) except ValueError: pass return d else: return super().default(o)
def _json_decode(o): cls = o.pop('__class__', None) if cls is None: return o elif cls == 'FontManager': r = FontManager.__new__(FontManager) r.__dict__.update(o) return r elif cls == 'FontEntry': r = FontEntry.__new__(FontEntry) r.__dict__.update(o) if not os.path.isabs(r.fname): r.fname = os.path.join(mpl.get_data_path(), r.fname) return r else: raise ValueError("don't know how to deserialize __class__=%s" % cls)
def recipe_matplotlib(mf): m = mf.findNode('matplotlib') if not isRealModule(m): return import matplotlib if 0: # do not copy matplotlibdata. assume matplotlib is installed as egg dp = matplotlib.get_data_path() assert dp mf.copyTree(dp, "matplotlibdata", m) mf.import_hook("matplotlib.numerix.random_array", m) # the import hook expects a string (matplotlib in later versions has # all rcParams, including the backend as unicode) backend_name = 'backend_' + str(matplotlib.get_backend().lower()) print "recipe_matplotlib: using the %s matplotlib backend" % (backend_name, ) mf.import_hook('matplotlib.backends.' + backend_name, m) return True
def __init__(self, data_source, figure_size, fontsize): self.data_source = data_source if iterable(figure_size): self.figure_size = float(figure_size[0]), float(figure_size[1]) else: self.figure_size = float(figure_size) self.plots = PlotDictionary(data_source) self._callbacks = [] self._field_transform = {} self._colormaps = defaultdict(lambda: 'algae') font_path = matplotlib.get_data_path() + '/fonts/ttf/STIXGeneral.ttf' self._font_properties = FontProperties(size=fontsize, fname=font_path) self._font_color = None self._xlabel = None self._ylabel = None self._minorticks = {} self._cbar_minorticks = {} self._colorbar_label = PlotDictionary( self.data_source, lambda: None)
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') configdir = mpl.get_configdir() texcache = os.path.join(configdir, 'tex.cache') if os.path.exists(oldcache): print("""\ WARNING: found a TeX cache dir in the deprecated location "%s". Moving it to the new default location "%s"."""%(oldcache, texcache), file=sys.stderr) shutil.move(oldcache, texcache) 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', r'\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', r'\usepackage{mathptmx}'), 'palatino': ('ppl', r'\usepackage{mathpazo}'), 'zapf chancery': ('pzc', r'\usepackage{chancery}'), 'cursive': ('pzc', r'\usepackage{chancery}'), 'charter': ('pch', r'\usepackage{charter}'), 'serif': ('cmr', ''), 'sans-serif': ('cmss', ''), 'helvetica': ('phv', r'\usepackage{helvet}'), 'avant garde': ('pag', r'\usepackage{avant}'), 'courier': ('pcr', r'\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): 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: found_font = self.font_info[font.lower()] 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}']) 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 = str(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 = r"""\usepackage{ucs} \usepackage[utf8x]{inputenc}""" else: unicode_preamble = '' s = r"""\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 = r"""\usepackage{ucs} \usepackage[utf8x]{inputenc}""" else: unicode_preamble = '' # newbox, setbox, immediate, etc. are used to find the box # extent of the rendered text. s = r"""\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)) + 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
def __init__(self, size=12.0, weight='normal'): self.__default_size = size self.__default_weight = weight paths = [rcParams['datapath']] # Create list of font paths for pathname in ['TTFPATH', 'AFMPATH']: if os.environ.has_key(pathname): ttfpath = os.environ[pathname] if ttfpath.find(';') >= 0: #win32 style paths.extend(ttfpath.split(';')) elif ttfpath.find(':') >= 0: # unix style paths.extend(ttfpath.split(':')) else: paths.append(ttfpath) # Load TrueType fonts and create font dictionary. self.ttffiles = findSystemFonts(paths) + findSystemFonts() for fname in self.ttffiles: if fname.lower().find('vera.ttf') >= 0: self.defaultFont = fname break else: # use anything self.defaultFont = self.ttffiles[0] cache_message = \ """Saving TTF font cache for non-PS backends to %s. Delete this file to have matplotlib rebuild the cache.""" ttfpath = get_home() if ttfpath is None: ttfpath = get_data_path() ttfcache = os.path.join(ttfpath, '.ttffont.cache') try: import cPickle as pickle except ImportError: import pickle def rebuild(): self.ttfdict = createFontDict(self.ttffiles) pickle.dump(self.ttfdict, file(ttfcache, 'w')) print cache_message % ttfcache try: self.ttfdict = pickle.load(file(ttfcache)) except: rebuild() else: # verify all the cached fnames still exist; if not rebuild for fname in ttfdict_to_fnames(self.ttfdict): if not os.path.exists(fname): rebuild() break #self.ttfdict = createFontDict(self.ttffiles) # Load AFM fonts for PostScript # Only load file names at this stage, the font dictionary will be # created when needed. self.afmfiles = findSystemFonts(paths, fontext='afm') + \ findSystemFonts(fontext='afm') self.afmdict = {}
"include_files": [(str(scipy_path), "scipy"), #for scipy (matplotlib.get_data_path(), "mpl-data"),], "includes":['PyQt4.QtCore','PyQt4.QtGui','mayavi','PyQt4'], 'excludes':'Tkinter', "namespace_packages": ['mayavi'] } """ build_exe_options = { "packages": [ "pyface.ui.qt4", "tvtk.vtk_module", "tvtk.pyface.ui.wx", "matplotlib.backends.backend_qt4", 'pygments.lexers', 'tvtk.pyface.ui.qt4', 'pyface.qt', 'pyface.qt.QtGui', 'pyface.qt.QtCore', 'numpy', 'matplotlib', 'mayavi' ], "include_files": [(matplotlib.get_data_path(), "mpl-data")], "includes": ['PyQt5.QtCore', 'PyQt5.QtGui', 'mayavi', 'PyQt5'], 'excludes': 'Tkinter', "namespace_packages": ['mayavi'] } executables = [ Executable( 'main.py', targetName="main.exe", base='Win32GUI', ) ] setup(
# Include packages not detected by cx_Freeze includes = ['matplotlib.backends.backend_qt4agg', 'scipy.special._ufuncs_cxx', 'scipy.sparse.csgraph._validation', #'scipy.sparse.linalg.dsolve.umfpack', 'scipy.integrate.vode', 'scipy.integrate.lsoda' ] # includes += ['skimage.io._plugins.'+modname # for __, modname, __ in # pkgutil.iter_modules(skimage.io._plugins.__path__) ] # Include data/package files not accounted for by cx_Freeze import matplotlib include_files = [(matplotlib.get_data_path(), 'mpl-data'), ('matplotlibrc', '')] #A simple util to get the egg dir name def get_egg_dir(name): base_name = pkg_resources.get_distribution(name).egg_name() for posible_extention in ['.egg-info','.dist-info']: full_path = os.path.join(SITE_PACKAGE_DIR , base_name + posible_extention) print full_path if os.path.exists(full_path): return base_name+posible_extention def get_pth_dir(name): return pkg_resources.get_distribution(name).egg_name()+'-nspkg.pth'
def __init__(self, size=12.0, weight='normal'): self.__default_size = size self.__default_weight = weight paths = [rcParams['datapath']] # Create list of font paths for pathname in ['TTFPATH', 'AFMPATH']: if os.environ.has_key(pathname): ttfpath = os.environ[pathname] if ttfpath.find(';') >= 0: #win32 style paths.extend(ttfpath.split(';')) elif ttfpath.find(':') >= 0: # unix style paths.extend(ttfpath.split(':')) else: paths.append(ttfpath) # Load TrueType fonts and create font dictionary. self.ttffiles = findSystemFonts(paths) + findSystemFonts() for fname in self.ttffiles: if fname.lower().find('vera.ttf')>=0: self.defaultFont = fname break else: # use anything self.defaultFont = self.ttffiles[0] cache_message = \ """Saving TTF font cache for non-PS backends to %s. Delete this file to have matplotlib rebuild the cache.""" ttfpath = get_home() if ttfpath is None: ttfpath = get_data_path() ttfcache = os.path.join(ttfpath, '.ttffont.cache') try: import cPickle as pickle except ImportError: import pickle def rebuild(): self.ttfdict = createFontDict(self.ttffiles) pickle.dump(self.ttfdict, file(ttfcache, 'w')) print cache_message % ttfcache try: self.ttfdict = pickle.load(file(ttfcache)) except: rebuild() else: # verify all the cached fnames still exist; if not rebuild for fname in ttfdict_to_fnames(self.ttfdict): if not os.path.exists(fname): rebuild() break #self.ttfdict = createFontDict(self.ttffiles) # Load AFM fonts for PostScript # Only load file names at this stage, the font dictionary will be # created when needed. self.afmfiles = findSystemFonts(paths, fontext='afm') + \ findSystemFonts(fontext='afm') self.afmdict = {}
from matplotlib.ft2font import FT2Font from matplotlib.font_manager import FontProperties from pylab import figure, table, show, axis, title import six from six import unichr # the font table grid labelc = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F"] labelr = ["00", "10", "20", "30", "40", "50", "60", "70", "80", "90", "A0", "B0", "C0", "D0", "E0", "F0"] if len(sys.argv) > 1: fontname = sys.argv[1] else: fontname = os.path.join(matplotlib.get_data_path(), "fonts", "ttf", "Vera.ttf") font = FT2Font(fontname) codes = list(font.get_charmap().items()) codes.sort() # a 16,16 array of character strings chars = [["" for c in range(16)] for r in range(16)] colors = [[(0.95, 0.95, 0.95) for c in range(16)] for r in range(16)] figure(figsize=(8, 4), dpi=120) for ccode, glyphind in codes: if ccode >= 256: continue r, c = divmod(ccode, 16) s = unichr(ccode)
'libwebkitgtk-3.0-0.dll', 'libwebp-5.dll', 'libwinpthread-1.dll', 'libxslt-1.dll', 'libzzz.dll', ] include_files = [] for dll in missing_dlls: include_files.append((os.path.join(include_dll_path, dll), dll)) gtk_libs = ['etc', 'lib', 'share'] for lib in gtk_libs: include_files.append((os.path.join(include_dll_path, lib), lib)) include_files.append((matplotlib.get_data_path(), 'mpl-data')) include_files.append((basemap.basemap_datadir, 'mpl-basemap-data')) include_files.append(('data/client/king_phisher', 'king_phisher')) exe_base = 'Win32GUI' if is_debugging_build: exe_base = 'Console' executables = [ Executable( 'KingPhisher', base=exe_base, icon='data/client/king_phisher/king-phisher-icon.ico', shortcutName='KingPhisher', shortcutDir='ProgramMenuFolder' )
class FigureCanvasPS(FigureCanvasBase): basepath = get_data_path() def draw(self): pass def print_figure(self, outfile, dpi=72, facecolor='w', edgecolor='w', orientation='portrait'): """ Render the figure to hardcopy. Set the figure patch face and edge colors. This is useful because some of the GUIs have a gray figure face color background and you'll probably want to override this on hardcopy If outfile is a string, it is interpreted as a file name. If the extension matches .ep* write encapsulated postscript, otherwise write a stand-alone PostScript file. If outfile is a file object, a stand-alone PostScript file is written into this file object. If text.usetex is True in rc, a temporary pair of tex/eps files are created to allow tex to handle the text. The final output is a simple ps or eps file. """ if isinstance(outfile, file): # assume plain PostScript and write to fileobject isEPSF = False fh = outfile needsClose = False title = None else: basename, ext = os.path.splitext(outfile) if not ext: if rcParams['text.usetex']: ext = '.eps' outfile += ext else: ext = '.ps' outfile += ext if rcParams['text.usetex']: # need to make some temporary files so latex can run without # writing over something important. m = md5.md5(outfile) tmpname = m.hexdigest() epsfile = tmpname + '.eps' psfile = tmpname + '.ps' texfile = tmpname + '.tex' dvifile = tmpname + '.dvi' latexh = file(texfile, 'w') fh = file(epsfile, 'w') else: fh = file(outfile, 'w') isEPSF = ext.lower().startswith('.ep') or rcParams['text.usetex'] needsClose = True title = outfile # center the figure on the paper self.figure.dpi.set(72) # ignore the passsed dpi setting for PS width, height = self.figure.get_size_inches() if orientation == 'landscape': isLandscape = True paperHeight, paperWidth = defaultPaperSize else: isLandscape = False paperWidth, paperHeight = defaultPaperSize xo = 72 * 0.5 * (paperWidth - width) yo = 72 * 0.5 * (paperHeight - height) l, b, w, h = self.figure.bbox.get_bounds() llx = xo lly = yo urx = llx + w ury = lly + h if isLandscape: xo, yo = 72 * paperHeight - yo, xo llx, lly, urx, ury = lly, llx, ury, urx rotation = 90 else: rotation = 0 # generate PostScript code for the figure and store it in a string origfacecolor = self.figure.get_facecolor() origedgecolor = self.figure.get_edgecolor() self.figure.set_facecolor(facecolor) self.figure.set_edgecolor(edgecolor) self._pswriter = StringIO() renderer = RendererPS(width, height, self._pswriter) self.figure.draw(renderer) self.figure.set_facecolor(origfacecolor) self.figure.set_edgecolor(origedgecolor) # write the PostScript headers if isEPSF: print >> fh, "%!PS-Adobe-3.0 EPSF-3.0" else: print >> fh, "%!PS-Adobe-3.0" if title: print >> fh, "%%Title: " + title print >> fh, ("%%Creator: matplotlib version " + __version__ + ", http://matplotlib.sourceforge.net/") print >> fh, "%%CreationDate: " + time.ctime(time.time()) if not isEPSF: if paperWidth > paperHeight: ostr = "Landscape" else: ostr = "Portrait" print >> fh, "%%Orientation: " + ostr print >> fh, "%%DocumentPaperSizes: " + defaultPaperType print >> fh, "%%%%BoundingBox: %d %d %d %d" % (llx, lly, urx, ury) if not isEPSF: print >> fh, "%%Pages: 1" print >> fh, "%%EndComments" Ndict = len(psDefs) print >> fh, "%%BeginProlog" if not rcParams['text.usetex']: type42 = _type42 + [os.path.join(self.basepath, name) + '.ttf' \ for name in bakoma_fonts] if not rcParams['ps.useafm']: Ndict += len(type42) print >> fh, "/mpldict %d dict def" % Ndict print >> fh, "mpldict begin" for d in psDefs: d = d.strip() for l in d.split('\n'): print >> fh, l.strip() if not rcParams['text.usetex']: if not rcParams['ps.useafm']: for font in type42: print >> fh, "%%BeginFont: " + FT2Font( str(font)).postscript_name print >> fh, encodeTTFasPS(font) print >> fh, "%%EndFont" print >> fh, "%%EndProlog" if not isEPSF: print >> fh, "%%Page: 1 1" print >> fh, "mpldict begin" #print >>fh, "gsave" print >> fh, "%s translate" % _nums_to_str(xo, yo) if rotation: print >> fh, "%d rotate" % rotation print >> fh, "%s clipbox" % _nums_to_str(width * 72, height * 72, 0, 0) # write the figure print >> fh, self._pswriter.getvalue() # write the trailer #print >>fh, "grestore" print >> fh, "end" print >> fh, "showpage" if not isEPSF: print >> fh, "%%EOF" if needsClose: fh.close() if rcParams['text.usetex']: if rcParams['text.tex.engine'] == 'latex': fontpackage = rcParams['font.latex.package'] else: fontpackage = 'type1cm' pw, ph = defaultPaperSize if width > pw - 2 or height > ph - 2: pw, ph = _get_papersize(width, height) print >> latexh, r"""\documentclass{scrartcl} \usepackage{%s} \usepackage{psfrag} \usepackage[dvips]{graphicx} \usepackage{color} \pagestyle{empty} \setlength{\paperheight}{%fin} \setlength{\paperwidth}{%fin} \setlength{\textwidth}{%fin} \setlength{\textheight}{%fin} \special{papersize=%fin,%fin} \begin{document} \begin{figure}[th!] \begin{center} %s \includegraphics{%s} \end{center} \end{figure} \end{document} """ % (fontpackage, pw, ph, pw - 2, ph - 2, pw, ph, '\n'.join( renderer.psfrag), epsfile) latexh.close() command = 'latex -interaction=nonstopmode "%s"' % texfile verbose.report(command, 'debug-annoying') stdin, stdout, stderr = os.popen3(command) verbose.report(stdout.read(), 'debug-annoying') verbose.report(stderr.read(), 'helpful') command = 'dvips -R -T %fin,%fin -o "%s" "%s"' % (pw, ph, psfile, dvifile) verbose.report(command, 'debug-annoying') stdin, stdout, stderr = os.popen3(command) verbose.report(stdout.read(), 'debug-annoying') verbose.report(stderr.read(), 'helpful') os.remove(epsfile) if ext.startswith('.ep'): dpi = rcParams['ps.distiller.res'] if sys.platform == 'win32': command = 'gswin32c -dBATCH -dNOPAUSE -dSAFER -r%d \ -sDEVICE=epswrite -dLanguageLevel=2 -dEPSFitPage \ -sOutputFile="%s" "%s"' % (dpi, epsfile, psfile) else: command = 'gs -dBATCH -dNOPAUSE -dSAFER -r%d \ -sDEVICE=epswrite -dLanguageLevel=2 -dEPSFitPage \ -sOutputFile="%s" "%s"' % (dpi, epsfile, psfile) verbose.report(command, 'debug-annoying') stdin, stdout, stderr = os.popen3(command) verbose.report(stdout.read(), 'debug-annoying') verbose.report(stderr.read(), 'helpful') shutil.move(epsfile, outfile) else: shutil.move(psfile, outfile) for fname in glob.glob(tmpname + '.*'): os.remove(fname) if rcParams['ps.usedistiller']: dpi = rcParams['ps.distiller.res'] m = md5.md5(outfile) tmpfile = m.hexdigest() if ext.startswith('ep'): command = 'eps2eps -dSAFER -r%d "%s" "%s"' % (dpi, outfile, tmpfile) else: command = 'ps2ps -dSAFER -r%d "%s" "%s"' % (dpi, outfile, tmpfile) verbose.report(command, 'debug-annoying') stdin, stdout, stderr = os.popen3(command) verbose.report(stdout.read(), 'debug-annoying') verbose.report(stderr.read(), 'helpful') shutil.move(tmpfile, outfile)
def findfont(self, prop, fontext="ttf"): """Search the font dictionary for a font that exactly or closely matches the specified font properties. See the FontProperties class for a description. The properties are searched in the following order: name, style, variant, weight, stretch, and size. The font weight always matches returning the closest weight, and the font size always matches for scalable fonts. An oblique style font will be used inplace of a missing italic style font if present. See the W3C Cascading Style Sheet, Level 1 (CSS1; http://www.w3.org/TR/1998/REC-CSS2-19980512/) documentation for a description of the font finding algorithm. """ cache_message = """Saving AFM font cache for PS backend to %s. Delete this file to have matplotlib rebuild the cache.""" debug = False if prop.fname is not None: fname = prop.fname verbose.report("findfont returning %s" % fname, "debug") return fname if fontext == "ttf": fontdict = self.ttfdict elif fontext == "afm": if len(self.afmdict) == 0: afmpath = os.environ.get("HOME", get_data_path()) afmcache = os.path.join(afmpath, ".afmfont.cache") try: import cPickle as pickle except ImportError: import pickle try: self.afmdict = pickle.load(file(afmcache)) except: self.afmdict = createFontDict(self.afmfiles, fontext="afm") pickle.dump(self.afmdict, file(afmcache, "w")) verbose.report(cache_message % afmcache) fontdict = self.afmdict name = prop.get_family()[0] style = prop.get_style() variant = prop.get_variant() weight = weight_as_number(prop.get_weight()) stretch = prop.get_stretch() size = str(prop.get_size_in_points()) try: fname = fontdict[name][style][variant][weight][stretch][size] verbose.report( "\tfindfont cached %(name)s, %(style)s, %(variant)s, %(weight)s, %(stretch)s, %(size)s" % locals(), "debug", ) verbose.report("findfont returning %s" % fname, "debug") return fname except KeyError: pass for name in prop.get_family(): font = fontdict if font.has_key(name): font = font[name] else: verbose.report("\tfindfont failed %(name)s" % locals(), "debug") continue if font.has_key(style): font = font[style] elif style == "italics" and font.has_key("oblique"): font = font["oblique"] else: verbose.report("\tfindfont failed %(name)s, %(style)s" % locals(), "debug") continue if font.has_key(variant): font = font[variant] else: verbose.report("\tfindfont failed %(name)s, %(style)s, %(variant)s" % locals(), "debug") continue if not font.has_key(weight): setWeights(font) font = font[weight] # !!!! need improvement if font.has_key(stretch): font = font[stretch] else: verbose.report( "\tfindfont failed %(name)s, %(style)s, %(variant)s %(weight)s, %(stretch)s" % locals(), "debug" ) continue if font.has_key("scalable"): fname = font["scalable"] elif font.has_key(size): fname = font[size] else: verbose.report( "\tfindfont failed %(name)s, %(style)s, %(variant)s %(weight)s, %(stretch)s, %(size)s" % locals(), "debug", ) continue fontkey = FontKey(name, style, variant, weight, stretch, size) add_filename(fontdict, fontkey, fname) verbose.report( "\tfindfont found %(name)s, %(style)s, %(variant)s %(weight)s, %(stretch)s, %(size)s" % locals(), "debug", ) verbose.report("findfont returning %s" % fname, "debug") return fname fontkey = FontKey(name, style, variant, weight, stretch, size) add_filename(fontdict, fontkey, self.defaultFont) verbose.report_error("Could not match %s, %s, %s. Returning %s" % (name, style, variant, self.defaultFont)) return self.defaultFont
def __init__(self, size=12.0, weight="normal"): self.__default_size = size self.__default_weight = weight paths = [rcParams["datapath"]] # Create list of font paths for pathname in ["TTFPATH", "AFMPATH"]: if os.environ.has_key(pathname): ttfpath = os.environ[pathname] if ttfpath.find(";") >= 0: # win32 style paths.extend(ttfpath.split(";")) elif ttfpath.find(":") >= 0: # unix style paths.extend(ttfpath.split(":")) else: paths.append(ttfpath) verbose.report("font search path %s" % (str(paths))) # Load TrueType fonts and create font dictionary. self.ttffiles = findSystemFonts(paths) + findSystemFonts() for fname in self.ttffiles: if fname.lower().find("vera.ttf") >= 0: self.defaultFont = fname break else: # use anything self.defaultFont = self.ttffiles[0] cache_message = """Saving TTF font cache for non-PS backends to %s. Delete this file to have matplotlib rebuild the cache.""" ttfpath = get_home() if ttfpath is None: ttfpath = get_data_path() ttfcache = os.path.join(ttfpath, ".ttffont.cache") try: import cPickle as pickle except ImportError: import pickle def rebuild(): self.ttfdict = createFontDict(self.ttffiles) pickle.dump(self.ttfdict, file(ttfcache, "w")) verbose.report(cache_message % ttfcache) try: self.ttfdict = pickle.load(file(ttfcache)) except: rebuild() else: # verify all the cached fnames still exist; if not rebuild for fname in ttfdict_to_fnames(self.ttfdict): if not os.path.exists(fname): rebuild() break verbose.report("loaded ttfcache file %s" % ttfcache) # self.ttfdict = createFontDict(self.ttffiles) # Load AFM fonts for PostScript # Only load file names at this stage, the font dictionary will be # created when needed. self.afmfiles = findSystemFonts(paths, fontext="afm") + findSystemFonts(fontext="afm") self.afmdict = {}
self.name = "SasView" data_files = [] if tinycc: data_files += tinycc.data_files() # Include data for supporting packages import periodictable data_files += periodictable.data_files() # # Adapted from http://www.py2exe.org/index.cgi/MatPlotLib # to use the MatPlotLib. # mpl_dir = matplotlib.get_data_path() for dirpath, dirnames, filenames in os.walk(mpl_dir): target_dir = os.path.join("mpl-data", os.path.relpath(dirpath, mpl_dir)) source_files = [os.path.join(dirpath, f) for f in filenames] data_files.append((target_dir, source_files)) import sasmodels data_files += sasmodels.data_files() # precompile sas models into the sasview build path; doesn't matter too much # where it is so long as it is a place that will get cleaned up afterwards. import sasmodels.core dll_path = os.path.join(build_path, 'compiled_models') compiled_dlls = sasmodels.core.precompile_dlls(dll_path, dtype='double') # include the compiled models as data; coordinate the target path for the
# Polices GetDossiers("Static/Polices"), # Fichiers à importer : ('', ['noethys/Versions.txt', 'noethys/Licence.txt', 'noethys/Icone.ico']), ] # Autres data_files if "py2exe" in sys.argv : # Ajoute les fichiers de Matplotlib import matplotlib as mp matplotlib_font_afm = glob.glob(os.sep.join([mp.get_data_path(), 'fonts\\afm\\*'])) matplotlib_font_pdfcorefonts = glob.glob(os.sep.join([mp.get_data_path(), 'fonts\\pdfcorefonts\\*'])) matplotlib_font_ttf = glob.glob(os.sep.join([mp.get_data_path(), 'fonts\\ttf\\*'])) matplotlib_images = glob.glob(os.sep.join([mp.get_data_path(), 'images\\*'])) data_files += mp.get_py2exe_datafiles() # Ajoute les fichiers Windows data_files.append(('', ['noethys/msvcm90.dll', 'noethys/msvcp90.dll', 'noethys/msvcr90.dll', 'noethys/Microsoft.VC90.CRT.manifest', 'noethys/gdiplus.dll', ])) setup( name = "Noethys", version = VERSION_APPLICATION, author = "Ivan LUCAS", description = u"Noethys, le logiciel libre et gratuit de gestion multi-activités", long_description = open("README.md").read().decode("iso-8859-15"),
=============== This example lists the attributes of an `.FT2Font` object, which describe global font properties. For individual character metrics, use the `.Glyph` object, as returned by `.load_char`. """ import os import matplotlib import matplotlib.ft2font as ft font = ft.FT2Font( # Use a font shipped with Matplotlib. os.path.join(matplotlib.get_data_path(), 'fonts/ttf/DejaVuSans-Oblique.ttf')) print('Num faces: ', font.num_faces) # number of faces in file print('Num glyphs: ', font.num_glyphs) # number of glyphs in the face print('Family name:', font.family_name) # face family name print('Style name: ', font.style_name) # face style name print('PS name: ', font.postscript_name) # the postscript name print('Num fixed: ', font.num_fixed_sizes) # number of embedded bitmaps # the following are only available if face.scalable if font.scalable: # the face global bounding box (xmin, ymin, xmax, ymax) print('Bbox: ', font.bbox) # number of font units covered by the EM print('EM: ', font.units_per_EM)
class TexManager(object): """ 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) # 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: _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, 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: _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 = 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}']) 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.fromkeys(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 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: _log.info("You are using unicode and latex, but " "have not enabled the matplotlib " "'text.latex.unicode' rcParam.") 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 determine 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: _log.info("You are using unicode and latex, but " "have not enabled the matplotlib " "'text.latex.unicode' rcParam.") 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) command = [ str("latex"), "-interaction=nonstopmode", os.path.basename(texfile) ] _log.debug(command) with Locked(self.texcache): try: report = subprocess.check_output(command, cwd=self.texcache, stderr=subprocess.STDOUT) except subprocess.CalledProcessError as exc: raise RuntimeError( ('LaTeX was not able to process the following ' 'string:\n%s\n\n' 'Here is the full report generated by LaTeX:\n%s ' '\n\n' % (repr(tex.encode('unicode_escape')), exc.output.decode("utf-8")))) _log.debug(report) 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) command = [ str("latex"), "-interaction=nonstopmode", os.path.basename(texfile) ] _log.debug(command) try: report = subprocess.check_output(command, cwd=self.texcache, stderr=subprocess.STDOUT) except subprocess.CalledProcessError as exc: raise RuntimeError( ('LaTeX was not able to process the following ' 'string:\n%s\n\n' 'Here is the full report generated by LaTeX:\n%s ' '\n\n' % (repr(tex.encode('unicode_escape')), exc.output.decode("utf-8")))) _log.debug(report) # find the box extent information in the latex output # file and store them in ".baseline" file m = TexManager._re_vbox.search(report.decode("utf-8")) 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) command = [ str("dvipng"), "-bg", "Transparent", "-D", str(dpi), "-T", "tight", "-o", os.path.basename(pngfile), os.path.basename(dvifile) ] _log.debug(command) try: report = subprocess.check_output(command, cwd=self.texcache, stderr=subprocess.STDOUT) except subprocess.CalledProcessError as exc: raise RuntimeError( ('dvipng was not able to process the following ' 'string:\n%s\n\n' 'Here is the full report generated by dvipng:\n%s ' '\n\n' % (repr(tex.encode('unicode_escape')), exc.output.decode("utf-8")))) _log.debug(report) 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) command = [ str("dvips"), "-q", "-E", "-o", os.path.basename(psfile), os.path.basename(dvifile) ] _log.debug(command) try: report = subprocess.check_output(command, cwd=self.texcache, stderr=subprocess.STDOUT) except subprocess.CalledProcessError as exc: raise RuntimeError( ('dvips was not able to process the following ' 'string:\n%s\n\n' 'Here is the full report generated by dvips:\n%s ' '\n\n' % (repr(tex.encode('unicode_escape')), exc.output.decode("utf-8")))) _log.debug(report) 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)) self.grey_arrayd[key] = alpha = X[:, :, -1] 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), 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) with dviread.Dvi(dvifile, 72 * dpi_fraction) as dvi: page = next(iter(dvi)) # A total height (including the descent) needs to be returned. return page.width, page.height + page.descent, page.descent
class BakomaPSFonts(Fonts): """ Use the Bakoma postscript fonts for rendering to backend_ps """ fnames = ('cmmi10', 'cmsy10', 'cmex10', 'cmtt10', 'cmr10') # allocate a new set of fonts basepath = get_data_path() fontmap = { 'cal': 'cmsy10', 'rm': 'cmr10', 'tt': 'cmtt10', 'it': 'cmmi10', None: 'cmmi10', } def __init__(self): self.glyphd = {} self.fonts = dict([ (name, FT2Font(os.path.join(self.basepath, name) + '.ttf')) for name in self.fnames ]) for font in self.fonts.values(): font.clear() def _get_info(self, font, sym, fontsize, dpi): 'load the cmfont, metrics and glyph with caching' key = font, sym, fontsize, dpi tup = self.glyphd.get(key) if tup is not None: return tup basename = self.fontmap[font] if latex_to_bakoma.has_key(sym): basename, num = latex_to_bakoma[sym] sym = self.fonts[basename].get_glyph_name(num) num = self.fonts[basename].get_charmap()[num] elif len(sym) == 1: num = ord(sym) else: num = 0 sym = '.notdef' verbose.report_error('unrecognized symbol "%s, %d"' % (sym, num)) if basename not in bakoma_fonts: bakoma_fonts.append(basename) cmfont = self.fonts[basename] cmfont.set_size(fontsize, dpi) head = cmfont.get_sfnt_table('head') glyph = cmfont.load_char(num) xmin, ymin, xmax, ymax = [val / 64.0 for val in glyph.bbox] if basename == 'cmex10': offset = -(head['yMin'] + 512) / head['unitsPerEm'] * 10. else: offset = 0. metrics = Bunch(advance=glyph.horiAdvance / 64.0, height=glyph.height / 64.0, width=glyph.width / 64.0, xmin=xmin, xmax=xmax, ymin=ymin + offset, ymax=ymax + offset) self.glyphd[key] = basename, metrics, sym, offset return basename, metrics, '/' + sym, offset def set_canvas_size(self, w, h, pswriter): 'Dimension the drawing canvas; may be a noop' self.width = w self.height = h self.pswriter = pswriter def get_metrics(self, font, sym, fontsize, dpi): basename, metrics, sym, offset = \ self._get_info(font, sym, fontsize, dpi) return metrics def render(self, ox, oy, font, sym, fontsize, dpi): fontname, metrics, glyphname, offset = \ self._get_info(font, sym, fontsize, dpi) fontname = fontname.capitalize() if fontname == 'Cmex10': oy += offset - 512 / 2048. * 10. ps = """/%(fontname)s findfont %(fontsize)s scalefont setfont %(ox)f %(oy)f moveto /%(glyphname)s glyphshow """ % locals() self.pswriter.write(ps)
def find_matplotlib_font(**kw): prop = FontProperties(**kw) path = findfont(prop, directory=mpl.get_data_path()) return FontProperties(fname=path)
mpi2 = find_files('/usr/lib/openmpi/lib','libmpi') vtk_files2 = ['/usr/lib/x86_64-linux-gnu/libmysqlclient.so','/usr/lib/x86_64-linux-gnu/libmysqlclient.so.20','/usr/lib/x86_64-linux-gnu/libmysqlclient.so.20.3.8', '/usr/lib/x86_64-linux-gnu/libnetcdf.so','/usr/lib/x86_64-linux-gnu/libnetcdf.so.11','/usr/lib/x86_64-linux-gnu/libnetcdf.so.11.0.0', '/usr/lib/x86_64-linux-gnu/libnetcdf_c++.so','/usr/lib/x86_64-linux-gnu/libnetcdf_c++.so.4','/usr/lib/x86_64-linux-gnu/libnetcdf_c++.so.4.2.0', '/usr/lib/libLSDyna.so.5.10','/usr/lib/libLSDyna.so.5.10.1','/usr/lib/x86_64-linux-gnu/libhdf5_serial_hl.so.10', '/usr/lib/x86_64-linux-gnu/libhdf5_serial_hl.so.10.0.2','/usr/lib/x86_64-linux-gnu/libsz.so','/usr/lib/x86_64-linux-gnu/libsz.so.2', '/usr/lib/x86_64-linux-gnu/libsz.so.2.0.1','/usr/lib/x86_64-linux-gnu/libaec.so','/usr/lib/x86_64-linux-gnu/libaec.so.0','/usr/lib/x86_64-linux-gnu/libaec.so.0.0.3', '/usr/lib/libgl2ps.so','/usr/lib/libgl2ps.so.0','/usr/lib/libgl2ps.so.0.0.0','/usr/lib/libVPIC.so.5.10','/usr/lib/libVPIC.so.5.10.1', '/usr/lib/libCosmo.so.5.10','/usr/lib/libCosmo.so.5.10.1','/usr/lib/libibverbs.so','/usr/lib/libibverbs.so.1','/usr/lib/libibverbs.so.1.0.0', '/usr/lib/libopen-rte.so.12','/usr/lib/openmpi/lib/libopen-pal.so.13.0.2','/usr/lib/openmpi/lib/libopen-pal.so','/usr/lib/libopen-pal.so.13', '/usr/lib/x86_64-linux-gnu/libhwloc.so.5','/usr/lib/x86_64-linux-gnu/libhwloc.so.5.6.8'] build_exe_options = {"packages": ["pyface.ui.qt4", "tvtk.vtk_module", "tvtk.pyface.ui.wx", "matplotlib.backends.backend_qt4",'pkg_resources._vendor','pkg_resources.extern','pygments.lexers', 'tvtk.pyface.ui.qt4','pyface.qt','PySide','pyface.qt.QtGui','pyface.qt.QtCore','Shiboken','numpy','matplotlib'], "include_files": [(str(scipy_path), "scipy"), #for scipy (matplotlib.get_data_path(), "mpl-data"),'/home/jannick/python_programs/OpenDFT/data', '/usr/lib/x86_64-linux-gnu/libpyside-python2.7.so.1.2','/usr/lib/x86_64-linux-gnu/libpyside-python2.7.so.1.2.2', '/usr/lib/x86_64-linux-gnu/libshiboken-python2.7.so.1.2','/usr/lib/x86_64-linux-gnu/libshiboken-python2.7.so.1.2.2' ,'/usr/lib/x86_64-linux-gnu/libpq.so','/usr/lib/x86_64-linux-gnu/libpq.so.5','/usr/lib/x86_64-linux-gnu/libpq.so.5.8', ], "includes":['PyQt4.QtCore','PyQt4.QtGui','pymatgen','pymatgen.symmetry.bandstructure'], 'excludes':'Tkinter', "namespace_packages": ["ruamel.yaml",'numpy'] } # build_exe_options['include_files'].extend(vtk_files) # build_exe_options['include_files'].extend(hdf_files) # build_exe_options['include_files'].extend(mpi1) # build_exe_options['include_files'].extend(mpi2) # build_exe_options['include_files'].extend(vtk_files2)
import os, os.path import matplotlib def adddir(path,localtarget=None): if localtarget==None: localtarget = path for f in findall(path): localname = os.path.join(localtarget, f[len(path)+1:]) if 'CVS' in localname: continue own_data_files.append((os.path.dirname(localname),[f])) own_data_files = [] own_data_files.append(('',['logo.png'])) own_data_files.append(('',['C:\Program Files\Python24\MSVCP71.dll'])) adddir(matplotlib.get_data_path(),'matplotlibdata') adddir('defaultscenarios') adddir('reporttemplates') adddir('schemas') setup( console=['gotm.py'], options={'py2exe': { 'packages' : ['matplotlib', 'pytz'], 'includes' : ['sip'], 'excludes' : ['_gtkagg', '_tkagg', '_wxagg','Tkconstants','Tkinter','tcl','wx'], 'dll_excludes': ['libgdk-win32-2.0-0.dll', 'libgobject-2.0-0.dll', 'libgdk_pixbuf-2.0-0.dll','wxmsw26uh_vc.dll','tcl84.dll','tk84.dll'], }}, data_files=own_data_files )
#!/usr/bin/env python """ This is a demo script to show you how to use all the properties of an FT2Font object. These describe global font properties. For individual character metrices, use the Glyp object, as returned by load_char """ import matplotlib from matplotlib.ft2font import FT2Font #fname = '/usr/local/share/matplotlib/VeraIt.ttf' fname = matplotlib.get_data_path() + '/fonts/ttf/VeraIt.ttf' #fname = '/usr/local/share/matplotlib/cmr10.ttf' font = FT2Font(fname) # these constants are used to access the style_flags and face_flags FT_FACE_FLAG_SCALABLE = 1 << 0 FT_FACE_FLAG_FIXED_SIZES = 1 << 1 FT_FACE_FLAG_FIXED_WIDTH = 1 << 2 FT_FACE_FLAG_SFNT = 1 << 3 FT_FACE_FLAG_HORIZONTAL = 1 << 4 FT_FACE_FLAG_VERTICAL = 1 << 5 FT_FACE_FLAG_KERNING = 1 << 6 FT_FACE_FLAG_FAST_GLYPHS = 1 << 7 FT_FACE_FLAG_MULTIPLE_MASTERS = 1 << 8 FT_FACE_FLAG_GLYPH_NAMES = 1 << 9 FT_FACE_FLAG_EXTERNAL_STREAM = 1 << 10 FT_STYLE_FLAG_ITALIC = 1 << 0 FT_STYLE_FLAG_BOLD = 1 << 1
class Target: def __init__(self, **kw): self.__dict__.update(kw) # for the versioninfo resources self.version = local_config.__version__ self.company_name = "SasView.org" self.copyright = "copyright 2009 - 2016" self.name = "SasView" # # Adapted from http://www.py2exe.org/index.cgi/MatPlotLib # to use the MatPlotLib. # path = os.getcwd() matplotlibdatadir = matplotlib.get_data_path() matplotlibdata = findall(matplotlibdatadir) DATA_FILES = [] if tinycc: DATA_FILES += tinycc.data_files() # Copying SLD data import periodictable DATA_FILES += periodictable.data_files() from sas.sasgui.perspectives import fitting DATA_FILES += fitting.data_files() from sas.sasgui.perspectives import calculator
import os import matplotlib import matplotlib.font_manager import shutil import pkg_resources fonts_dir = os.path.join(matplotlib.get_data_path(), 'fonts/ttf') helvetica_filename = 'Helvetica_33244fbeea10f093ae87de7a994c3697.ttf' helvetica_dest_filename = os.path.join(fonts_dir, helvetica_filename) helvetica_src_filename = pkg_resources.resource_filename( 'vetica', 'data/' + helvetica_filename) if not os.path.exists(helvetica_dest_filename): shutil.copyfile(helvetica_src_filename, helvetica_dest_filename) matplotlib.font_manager._rebuild() prop = matplotlib.font_manager.FontProperties(fname=helvetica_dest_filename) matplotlib.rcParams['font.family'] = 'sans-serif' matplotlib.rcParams['font.sans-serif'] = 'Helvetica'
version=version, description=description, long_description=long_description, license=license, author=author, url=url, author_email=author_email, include_package_data=True, options={ 'build_exe': { 'packages': ['openroast'], 'includes': ['matplotlib', 'serial', 'matplotlib.backends.backend_qt5agg'], 'include_files': [ 'static', 'openroast/views', 'openroast/controllers', 'LICENSE', (matplotlib.get_data_path(), 'mpl-data'), (distutils_path, 'distutils') ], 'excludes': ['distutils'], 'icon': 'static/icons/openroast-windows.ico', 'include_msvcr': True }, 'bdist_msi': { 'data': { 'Shortcut': [( 'DesktopShortcut', # Shortcut 'DesktopFolder', # Directory_ 'Openroast', # Name 'TARGETDIR', # Component_
#os.environ['TK_LIBRARY'] = r'D:\Anaconda\envs\py34\tcl\tk8.6' executable = [ cx_Freeze.Executable("Dynamic Plotting Animate.py", base=base, icon="Icons8-Halloween-Cat.ico") ] build_exe_options = { "includes": [ "numpy.core._methods", "numpy.lib.format", "matplotlib.backends.backend_tkagg" ], "packages": ["tkinter"], "include_files": [(matplotlib.get_data_path(), "mpl-data"), ("D:\\Anaconda\\envs\\py34\\tcl\\tcl8.6", "tcl8.6"), ("D:\\Anaconda\\envs\\py34\\tcl\\tk8.6", "tk8.6"), ("D:\\Anaconda\\envs\\py34\\lib\\site-packages\\numpy", "numpy"), ("D:\\Anaconda\\envs\\py34\\lib\\site-packages\\matplotlib", "matplotlib"), ("D:\\Anaconda\\envs\\py34\\Lib\\site-packages\\mkl\\__init__.py", "__init__.py"), ("D:\\Anaconda\\envs\\py34\\Lib\\site-packages\\mkl\\__pycache__\\__init__.cpython-34.pyc", "_init__.cpython-34.pyc"), ("D:\\Anaconda\\envs\\py34\\Lib\\site-packages\\mkl\\__pycache__\\test.cpython-34.pyc", "test.cpython-34.pyc"), ("D:\\Anaconda\\envs\\py34\\Lib\\site-packages\\mkl\\service.pyd", "service.pyd"), ("D:\\Anaconda\\envs\\py34\\Lib\\site-packages\\mkl\\test.py", "test.py"), ("D:/Anaconda/envs/py34/Library/bin/cilkrts20.dll", "cilkrts20.dll"),
class FigureCanvasPS(FigureCanvasBase): basepath = get_data_path() def draw(self): pass def print_figure(self, outfile, dpi=72, facecolor='w', edgecolor='w', orientation='portrait'): """ Render the figure to hardcopy. Set the figure patch face and edge colors. This is useful because some of the GUIs have a gray figure face color background and you'll probably want to override this on hardcopy If outfile is a string, it is interpreted as a file name. If the extension matches .ep* write encapsulated postscript, otherwise write a stand-alone PostScript file. If outfile is a file object, a stand-alone PostScript file is written into this file object. """ if isinstance(outfile, file): # assume plain PostScript and write to fileobject isEPSF = False fh = outfile needsClose = False title = None else: basename, ext = os.path.splitext(outfile) if not ext: outfile += '.ps' isEPSF = ext.lower().startswith('.ep') fh = file(outfile, 'w') needsClose = True title = outfile # center the figure on the paper self.figure.dpi.set(72) # ignore the passsed dpi setting for PS width, height = self.figure.get_size_inches() if orientation=='landscape': isLandscape = True paperHeight, paperWidth = defaultPaperSize else: isLandscape = False paperWidth, paperHeight = defaultPaperSize xo = 72*0.5*(paperWidth - width) yo = 72*0.5*(paperHeight - height) l, b, w, h = self.figure.bbox.get_bounds() llx = xo lly = yo urx = llx + w ury = lly + h if isLandscape: xo, yo = 72*paperHeight - yo, xo llx, lly, urx, ury = lly, llx, ury, urx rotation = 90 else: rotation = 0 # generate PostScript code for the figure and store it in a string origfacecolor = self.figure.get_facecolor() origedgecolor = self.figure.get_edgecolor() self.figure.set_facecolor(facecolor) self.figure.set_edgecolor(edgecolor) self._pswriter = StringIO() renderer = RendererPS(width, height, self._pswriter) self.figure.draw(renderer) self.figure.set_facecolor(origfacecolor) self.figure.set_edgecolor(origedgecolor) # write the PostScript headers if isEPSF: print >>fh, "%!PS-Adobe-3.0 EPSF-3.0" else: print >>fh, "%!PS-Adobe-3.0" if title: print >>fh, "%%Title: "+title print >>fh, ("%%Creator: matplotlib version " +__version__+", http://matplotlib.sourceforge.net/") print >>fh, "%%CreationDate: "+time.ctime(time.time()) if not isEPSF: if paperWidth > paperHeight: ostr="Landscape" else: ostr="Portrait" print >>fh, "%%Orientation: "+ostr print >>fh, "%%%%BoundingBox: %d %d %d %d" % (llx, lly, urx, ury) if not isEPSF: print >>fh, "%%Pages: 1" print >>fh, "%%EndComments" type42 = _type42 + [os.path.join(self.basepath, name) + '.ttf' \ for name in bakoma_fonts] print >>fh, "%%BeginProlog" Ndict = len(_psDefs) if not rcParams['ps.useafm']: Ndict += len(type42) print >>fh, "/mpldict %d dict def"%Ndict print >>fh, "mpldict begin" for d in _psDefs: d=d.strip() for l in d.split('\n'): print >>fh, l.strip() if not rcParams['ps.useafm']: for font in type42: print >>fh, "%%BeginFont: "+FT2Font(str(font)).postscript_name print >>fh, encodeTTFasPS(font) print >>fh, "%%EndFont" print >>fh, "%%EndProlog" if not isEPSF: print >>fh, "%%Page: 1 1" print >>fh, "mpldict begin" print >>fh, "gsave" print >>fh, "%s translate"%_nums_to_str(xo, yo) if rotation: print >>fh, "%d rotate"%rotation print >>fh, "%s clipbox"%_nums_to_str(width*72, height*72, 0, 0) # write the figure print >>fh, self._pswriter.getvalue() # write the trailer print >>fh, "grestore" print >>fh, "end" print >>fh, "showpage" if not isEPSF: print >>fh, "%%EOF" if needsClose: fh.close()
#!/usr/bin/env python from __future__ import print_function """ This is a demo script to show you how to use all the properties of an FT2Font object. These describe global font properties. For individual character metrices, use the Glyp object, as returned by load_char """ import matplotlib import matplotlib.ft2font as ft #fname = '/usr/local/share/matplotlib/VeraIt.ttf' fname = matplotlib.get_data_path() + '/fonts/ttf/VeraIt.ttf' #fname = '/usr/local/share/matplotlib/cmr10.ttf' font = ft.FT2Font(fname) print('Num faces :', font.num_faces) # number of faces in file print('Num glyphs :', font.num_glyphs) # number of glyphs in the face print('Family name :', font.family_name) # face family name print('Syle name :', font.style_name) # face syle name print('PS name :', font.postscript_name) # the postscript name print('Num fixed :', font.num_fixed_sizes) # number of embedded bitmap in face # the following are only available if face.scalable if font.scalable: # the face global bounding box (xmin, ymin, xmax, ymax) print('Bbox :', font.bbox) # number of font units covered by the EM
# the font table grid labelc = [ '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' ] labelr = [ '00', '10', '20', '30', '40', '50', '60', '70', '80', '90', 'A0', 'B0', 'C0', 'D0', 'E0', 'F0' ] if len(sys.argv) > 1: fontname = sys.argv[1] else: fontname = os.path.join(matplotlib.get_data_path(), 'fonts', 'ttf', 'DejaVuSans.ttf') font = FT2Font(fontname) codes = list(font.get_charmap().items()) codes.sort() # a 16,16 array of character strings chars = [['' for c in range(16)] for r in range(16)] colors = [[(0.95, 0.95, 0.95) for c in range(16)] for r in range(16)] plt.figure(figsize=(8, 4), dpi=120) for ccode, glyphind in codes: if ccode >= 256: continue r, c = divmod(ccode, 16)
def findfont(self, prop, fontext='ttf'): """Search the font dictionary for a font that exactly or closely matches the specified font properties. See the FontProperties class for a description. The properties are searched in the following order: name, style, variant, weight, stretch, and size. The font weight always matches returning the closest weight, and the font size always matches for scalable fonts. An oblique style font will be used inplace of a missing italic style font if present. See the W3C Cascading Style Sheet, Level 1 (CSS1; http://www.w3.org/TR/1998/REC-CSS2-19980512/) documentation for a description of the font finding algorithm. """ cache_message = \ """Saving AFM font cache for PS backend to %s. Delete this file to have matplotlib rebuild the cache.""" debug = False if fontext == 'ttf': fontdict = self.ttfdict elif fontext == 'afm': if len(self.afmdict) == 0: afmpath = os.environ.get('HOME', get_data_path()) afmcache = os.path.join(afmpath, '.afmfont.cache') try: import cPickle as pickle except ImportError: import pickle try: self.afmdict = pickle.load(file(afmcache)) except: self.afmdict = createFontDict(self.afmfiles, fontext='afm') pickle.dump(self.afmdict, file(afmcache, 'w')) print cache_message % afmcache fontdict = self.afmdict name = prop.get_family()[0] style = prop.get_style() variant = prop.get_variant() weight = weight_as_number(prop.get_weight()) stretch = prop.get_stretch() size = str(prop.get_size_in_points()) try: fname = fontdict[name][style][variant][weight][stretch][size] if debug: print 'Cache:', name, style, variant, weight, stretch, size return fname except KeyError: pass for name in prop.get_family(): font = fontdict if font.has_key(name): font = font[name] else: if debug: print name continue if font.has_key(style): font = font[style] elif style == 'italics' and font.has_key('oblique'): font = font['oblique'] else: if debug: print name, style continue if font.has_key(variant): font = font[variant] else: if debug: print name, style, variant continue if not font.has_key(weight): setWeights(font) font = font[weight] # !!!! need improvement if font.has_key(stretch): font = font[stretch] else: if debug: print name, style, variant, weight, stretch continue if font.has_key('scalable'): fname = font['scalable'] elif font.has_key(size): fname = font[size] else: if debug: print name, style, variant, weight, stretch, size continue fontkey = FontKey(name, style, variant, weight, stretch, size) add_filename(fontdict, fontkey, fname) if debug: print 'Found:', name, style, variant, weight, stretch, size return fname if debug: print name, style, variant, weight, stretch, size fontkey = FontKey(name, style, variant, weight, stretch, size) add_filename(fontdict, fontkey, self.defaultFont) print >> sys.stderr, 'Could not match %s, %s, %s. Returning %s' % ( name, style, variant, self.defaultFont) return self.defaultFont
def load_matplotlib(finder, module): """the matplotlib module requires data to be found in mpl-data in the same directory as the frozen executable so oblige it""" import matplotlib dataPath = matplotlib.get_data_path() finder.IncludeFiles(dataPath, "mpl-data", copyDependentFiles=False)
class BakomaTrueTypeFonts(Fonts): """ Use the Bakoma true type fonts for rendering """ fnames = ('cmmi10', 'cmsy10', 'cmex10', 'cmtt10', 'cmr10') # allocate a new set of fonts basepath = get_data_path() fontmap = { 'cal': 'cmsy10', 'rm': 'cmr10', 'tt': 'cmtt10', 'it': 'cmmi10', None: 'cmmi10', } def __init__(self, useSVG=False): self.glyphd = {} self.fonts = dict([ (name, FT2Font(os.path.join(self.basepath, name) + '.ttf')) for name in self.fnames ]) for font in self.fonts.values(): font.clear() if useSVG: self.svg_glyphs = [ ] # a list of "glyphs" we need to render this thing in SVG else: pass self.usingSVG = useSVG def get_metrics(self, font, sym, fontsize, dpi): cmfont, metrics, glyph, offset = \ self._get_info(font, sym, fontsize, dpi) return metrics def _get_info(self, font, sym, fontsize, dpi): 'load the cmfont, metrics and glyph with caching' key = font, sym, fontsize, dpi tup = self.glyphd.get(key) if tup is not None: return tup basename = self.fontmap[font] if latex_to_bakoma.has_key(sym): basename, num = latex_to_bakoma[sym] num = self.fonts[basename].get_charmap()[num] elif len(sym) == 1: num = ord(sym) else: num = 0 verbose.report_error('unrecognized symbol "%s"' % sym) cmfont = self.fonts[basename] cmfont.set_size(fontsize, dpi) head = cmfont.get_sfnt_table('head') glyph = cmfont.load_char(num) xmin, ymin, xmax, ymax = [val / 64.0 for val in glyph.bbox] if basename == 'cmex10': offset = glyph.height / 64.0 / 2 + 256.0 / 64.0 * dpi / 72.0 #offset = -(head['yMin']+512)/head['unitsPerEm']*10. else: offset = 0. metrics = Bunch( advance=glyph.horiAdvance / 64.0, height=glyph.height / 64.0, width=glyph.width / 64.0, xmin=xmin, xmax=xmax, ymin=ymin + offset, ymax=ymax + offset, ) self.glyphd[key] = cmfont, metrics, glyph, offset return self.glyphd[key] def set_canvas_size(self, w, h): 'Dimension the drawing canvas; may be a noop' self.width = int(w) self.height = int(h) for font in self.fonts.values(): font.set_bitmap_size(int(w), int(h)) def render(self, ox, oy, font, sym, fontsize, dpi): cmfont, metrics, glyph, offset = \ self._get_info(font, sym, fontsize, dpi) if not self.usingSVG: cmfont.draw_glyph_to_bitmap(int(ox), int(self.height - oy - metrics.ymax), glyph) else: oy += offset - 512 / 2048. * 10. basename = self.fontmap[font] if latex_to_bakoma.has_key(sym): basename, num = latex_to_bakoma[sym] num = self.fonts[basename].get_charmap()[num] elif len(sym) == 1: num = ord(sym) else: num = 0 print >> sys.stderr, 'unrecognized symbol "%s"' % sym self.svg_glyphs.append((basename, fontsize, num, ox, oy, metrics))
def GoBackToNormal(self): file = mpl.get_data_path() + '/matplotlibrc' mpl.rcParams.update(mpl.rc_params_from_file(file)) self.f.canvas.draw()
# cx_freeze script to generate a executable # to run it, type in a command-line interface # python setup.py build import sys import matplotlib from cx_Freeze import setup, Executable # replace base by None if a debug console is required if sys.platform == "win32": base = "Win32GUI" build_exe_options = {"includes":["matplotlib.backends.backend_qt4agg","scipy.special._ufuncs_cxx", "scipy.integrate","scipy.integrate.vode", "scipy.integrate.lsoda","scipy.sparse.csgraph._validation"], "include_files":[(matplotlib.get_data_path(), "mpl-data"), ('application_edit.ico','application_edit.ico'), ('trad.txt','trad.txt'), ('settings.ini','settings.ini')], "excludes":[]} setup( name = "TopoPyGUI", options = {"build_exe": build_exe_options}, version = "8.1", description = "Draw topographic maps", executables = [Executable("TopoPyGUI.py", base = base)], )
GetDossiers("Static/Lang"), # Polices GetDossiers("Static/Polices"), # Fichiers à importer : ('', ['noethys/Versions.txt', 'noethys/Licence.txt', 'noethys/Icone.ico']), ] # Autres data_files if "py2exe" in sys.argv: # Ajoute les fichiers de Matplotlib import matplotlib as mp matplotlib_font_afm = glob.glob( os.sep.join([mp.get_data_path(), 'fonts\\afm\\*'])) matplotlib_font_pdfcorefonts = glob.glob( os.sep.join([mp.get_data_path(), 'fonts\\pdfcorefonts\\*'])) matplotlib_font_ttf = glob.glob( os.sep.join([mp.get_data_path(), 'fonts\\ttf\\*'])) matplotlib_images = glob.glob( os.sep.join([mp.get_data_path(), 'images\\*'])) data_files += mp.get_py2exe_datafiles() # Ajoute les fichiers Windows data_files.append(('', [ 'noethys/msvcm90.dll', 'noethys/msvcp90.dll', 'noethys/msvcr90.dll', 'noethys/Microsoft.VC90.CRT.manifest', 'noethys/gdiplus.dll',
x,y = tup[1:] path.line_to(x,y) elif code == CURVE3: xctl, yctl, xto, yto= tup[1:] path.curve3(xctl, yctl, xto, yto) elif code == CURVE4: xctl1, yctl1, xctl2, yctl2, xto, yto= tup[1:] path.curve4(xctl1, yct1, xctl2, yctl2, xto, yto) elif code == ENDPOLY: path.end_poly() return path width, height = 300,300 fname = os.path.join(matplotlib.get_data_path(), 'fonts/ttf/Vera.ttf') font = FT2Font(fname) glyph = font.load_char(ord('y')) path = glyph_to_agg_path(glyph) curve = agg.conv_curve_path(path) scaling = agg.trans_affine_scaling(20,20) translation = agg.trans_affine_translation(4,4) rotation = agg.trans_affine_rotation(3.1415926) mtrans = translation*scaling # cannot use this as a temporary tpath = agg.conv_transform_path(path, mtrans) curve = agg.conv_curve_trans(tpath)
class BakomaTrueTypeFonts(Fonts): """ Use the Bakoma true type fonts for rendering """ fnames = ('cmmi10', 'cmsy10', 'cmex10', 'cmtt10', 'cmr10') # allocate a new set of fonts basepath = get_data_path() fontmap = { 'cal': 'cmsy10', 'rm': 'cmr10', 'tt': 'cmtt10', 'it': 'cmmi10', None: 'cmmi10', } def __init__(self, useSVG=False): self.glyphd = {} self.fonts = dict([ (name, FT2Font(os.path.join(self.basepath, name) + '.ttf')) for name in self.fnames ]) self.charmaps = dict([(name, self.fonts[name].get_charmap()) for name in self.fnames]) # glyphmaps is a dict names to a dict of charcode -> glyphindex self.glyphmaps = {} for name in self.fnames: cmap = self.charmaps[name] self.glyphmaps[name] = dict([(ccode, glyphind) for glyphind, ccode in cmap.items()]) for font in self.fonts.values(): font.clear() if useSVG: self.svg_glyphs = [ ] # a list of "glyphs" we need to render this thing in SVG else: pass self.usingSVG = useSVG def get_metrics(self, font, sym, fontsize, dpi): cmfont, metrics, glyph, offset = \ self._get_info(font, sym, fontsize, dpi) return metrics def _get_info(self, font, sym, fontsize, dpi): 'load the cmfont, metrics and glyph with caching' key = font, sym, fontsize, dpi tup = self.glyphd.get(key) if tup is not None: return tup basename = self.fontmap[font] if latex_to_bakoma.has_key(sym): basename, num = latex_to_bakoma[sym] num = self.charmaps[basename][num] elif len(sym) == 1: num = ord(sym) else: num = 0 raise ValueError('unrecognized symbol "%s"' % sym) #print sym, basename, num cmfont = self.fonts[basename] cmfont.set_size(fontsize, dpi) head = cmfont.get_sfnt_table('head') glyph = cmfont.load_char(num) xmin, ymin, xmax, ymax = [val / 64.0 for val in glyph.bbox] if basename == 'cmex10': offset = glyph.height / 64.0 / 2 + 256.0 / 64.0 * dpi / 72.0 #offset = -(head['yMin']+512)/head['unitsPerEm']*10. else: offset = 0. metrics = Bunch( advance=glyph.linearHoriAdvance / 65536.0, height=glyph.height / 64.0, width=glyph.width / 64.0, xmin=xmin, xmax=xmax, ymin=ymin + offset, ymax=ymax + offset, ) self.glyphd[key] = cmfont, metrics, glyph, offset return self.glyphd[key] def set_canvas_size(self, w, h): 'Dimension the drawing canvas; may be a noop' self.width = int(w) self.height = int(h) for font in self.fonts.values(): font.set_bitmap_size(int(w), int(h)) def render(self, ox, oy, font, sym, fontsize, dpi): cmfont, metrics, glyph, offset = \ self._get_info(font, sym, fontsize, dpi) if not self.usingSVG: cmfont.draw_glyph_to_bitmap(int(ox), int(self.height - oy - metrics.ymax), glyph) else: oy += offset - 512 / 2048. * 10. basename = self.fontmap[font] if latex_to_bakoma.has_key(sym): basename, num = latex_to_bakoma[sym] num = self.charmaps[basename][num] elif len(sym) == 1: num = ord(sym) else: num = 0 print >> sys.stderr, 'unrecognized symbol "%s"' % sym self.svg_glyphs.append((basename, fontsize, num, ox, oy, metrics)) def get_kern(self, font, symleft, symright, fontsize, dpi): """ Get the kerning distance for font between symleft and symright. font is one of tt, it, rm, cal or None sym is a single symbol(alphanum, punct) or a special symbol like \sigma. """ basename = self.fontmap[font] cmfont = self.fonts[basename] cmfont.set_size(fontsize, dpi) kernd = cmkern[basename] key = symleft, symright kern = kernd.get(key, 0) #print basename, symleft, symright, key, kern return kern def _get_num(self, font, sym): 'get charcode for sym' basename = self.fontmap[font] if latex_to_bakoma.has_key(sym): basename, num = latex_to_bakoma[sym] num = self.charmaps[basename][num] elif len(sym) == 1: num = ord(sym) else: num = 0 return num
except: print >>sys.stderr, 'The CococaAgg backend required PyObjC to be installed!' print >>sys.stderr, ' (currently testing v1.3.7)' sys.exit() from Foundation import * from AppKit import * from PyObjCTools import NibClassBuilder, AppHelper import matplotlib from matplotlib.figure import Figure from matplotlib.backend_bases import FigureManagerBase from backend_agg import FigureCanvasAgg from matplotlib._pylab_helpers import Gcf mplBundle = NSBundle.bundleWithPath_(matplotlib.get_data_path()) def new_figure_manager(num, *args, **kwargs): thisFig = Figure( *args, **kwargs ) canvas = FigureCanvasCocoaAgg(thisFig) return FigureManagerCocoaAgg(canvas, num) def show(): for manager in Gcf.get_all_fig_managers(): manager.show() def draw_if_interactive(): if matplotlib.is_interactive(): figManager = Gcf.get_active() if figManager is not None: figManager.show()
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') configdir = mpl.get_configdir() texcache = os.path.join(configdir, 'tex.cache') if os.path.exists(oldcache): print >> sys.stderr, """\ WARNING: found a TeX cache dir in the deprecated location "%s". Moving it to the new default location "%s".""" % (oldcache, texcache) shutil.move(oldcache, texcache) if not os.path.exists(texcache): os.mkdir(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', r'\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', r'\usepackage{mathptmx}'), 'palatino': ('ppl', r'\usepackage{mathpazo}'), 'zapf chancery': ('pzc', r'\usepackage{chancery}'), 'cursive': ('pzc', r'\usepackage{chancery}'), 'charter': ('pch', r'\usepackage{charter}'), 'serif': ('cmr', ''), 'sans-serif': ('cmss', ''), 'helvetica': ('phv', r'\usepackage{helvet}'), 'avant garde': ('pag', r'\usepackage{avant}'), 'courier': ('pcr', r'\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 not os.path.isdir(self.texcache): os.mkdir(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: found_font = self.font_info[font.lower()] 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}']) 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 = unicode(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 fh = file(texfile, 'w') 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 = r"""\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) if rcParams['text.latex.unicode']: fh.write(s.encode('utf8')) else: try: fh.write(s) except UnicodeEncodeError, err: mpl.verbose.report( "You are using unicode and latex, but have " "not enabled the matplotlib 'text.latex.unicode' " "rcParam.", 'helpful') raise fh.close() return texfile
def write_setup(name, version, description="", author="", modules=[NUMPY], includes=[], include_files=[], icon=None, gui_only="True"): """['appfuncs','gui_test']""" """["graphics/", "imageformats/", ]""" """"includes":["sip"],""" imports = [] base = "" excludes = ['PyQt4.uic.port_v3', 'Tkconstants', 'tcl', 'tk', 'doctest', '_gtkagg', '_tkagg', 'bsddb', 'curses', 'pywin.debugger', 'pywin.debugger.dbgcon', 'pywin.dialogs', 'Tkinter', 'tables', 'zmq', 'win32', 'Pythonwin', 'Cython', 'statmodels', 'cvxopt', '_sqlite3', '_ssl', '_testcapi', 'markupsafe', 'numexpr', '_elementtree', '_hashlib', '_testcapi', 'simplejson', 'pyexpat', "lxml", MATPLOTLIB, GUIDATA, PYQT4, PYSIDE, SCIPY, NUMPY, MULTIPROCESSING, DOCX, OPENGL, PIL, HDF5] def add(module): try: excludes.remove(module) except: pass #'pandas', '_socket', 'sip', if MATPLOTLIB in modules: mpl_path = matplotlib.get_data_path() include_files.append(('mpl-data', mpl_path)) imports.append("import matplotlib") if GUIDATA in modules: include_files.append("guidata/images/") if PYQT4 in modules: #include_files.append("imageformats/") includes.append("sip") includes.append("PyQt4.QtWebKit") includes.append("PyQt4.QtNetwork") includes.append("PyQt4.Qsci") # includes.append("PyQt4.uic") # includes.append("PyQt4.uic.port_v3") base = "base='Win32GUI', " if SCIPY in modules: imports.append("import scipy.sparse.csgraph") includes.extend(["scipy.sparse.csgraph._validation", "scipy.sparse.linalg.dsolve.umfpack", "scipy.integrate.vode", "scipy.integrate._ode", "scipy.integrate.lsoda"]) includes.append("scipy.special._ufuncs_cxx") #py3_64 from scipy.sparse.sparsetools import csr, csc, coo, dia, bsr, csgraph for f in [csr._csr.__file__, csc._csc.__file__, coo._coo.__file__, dia._dia.__file__, bsr._bsr.__file__, csgraph._csgraph.__file__]: shutil.copy(f, os.path.basename(f)) include_files.append("%s" % os.path.basename(f)) if DOCX in modules: include_files.append("functions/docx_document/docx-template_clean/") #include_files.append("functions/docx_document/inkscape/") includes.append("lxml._elementpath") excludes.remove("lxml") excludes.remove(PIL) if OPENGL in modules: includes.append("OpenGL") includes.append("OpenGL.platform.win32") includes.append("OpenGL.arrays.numpymodule") includes.append("OpenGL.arrays.arraydatatype") includes.append("OpenGL.converters") includes.append("OpenGL.arrays.numbers") includes.append("OpenGL.arrays.strings") if HDF5 in modules: includes.append("h5py") includes.append('h5py.h5ac') if PANDAS in modules: #add('email') includes.append("Pandas") for m in modules: try: excludes.remove(m) except ValueError: pass imports = "\n".join(imports) if include_files: #while any([os.path.isdir(f) for f in include_files if isinstance(f, str)]): # for folder in [f for f in include_files if isinstance(f, str) and os.path.isdir(f)]: # include_files.remove(folder) # include_files.extend(os.listdir(folder)) include_files = "[" + ",".join([("'%s'" % str(f), str(f))[isinstance(f, tuple)] for f in include_files]) + "]" include_files = include_files.replace("""'(matplotlib.get_data_path(),"mpl-data")'""", """(matplotlib.get_data_path(), "mpl-data")""") if includes: includes = "['" + "','".join(includes) + "']" if icon is not None: icon = "icon='%s', " % icon else: icon = "" with open('setup.py', 'w') as fid: fid.writelines("""from distutils.core import setup from esky import bdist_esky from esky.bdist_esky import Executable %s build_exe_options = { "includes": %s, 'excludes' : %s, 'freezer_module': "cxfreeze", } executable = Executable("%s.py", %s gui_only=%s) setup( name = "%s", version="%s", description="%s", author = "%s", scripts = [executable], data_files = %s, script_args = ("bdist_esky",), options = { "bdist_esky": build_exe_options}) """ % (imports, includes, excludes, name, icon, gui_only, name, version, description, author, include_files))
'libwebp-5.dll', 'libwinpthread-1.dll', 'libxmlxpat.dll', 'libxslt-1.dll', 'libzzz.dll', ] include_files = [] for dll in missing_dlls: include_files.append((os.path.join(include_dll_path, dll), dll)) gtk_libs = ['etc', 'lib', 'share'] for lib in gtk_libs: include_files.append((os.path.join(include_dll_path, lib), lib)) include_files.append((matplotlib.get_data_path(), 'mpl-data')) include_files.append((basemap.basemap_datadir, 'mpl-basemap-data')) include_files.append(('data/client/king_phisher', 'king_phisher')) exe_base = 'Win32GUI' if is_debugging_build: exe_base = 'Console' executables = [ Executable('KingPhisher', base=exe_base, icon='data/client/king_phisher/king-phisher-icon.ico', shortcutName='KingPhisher', shortcutDir='ProgramMenuFolder') ]
#!/usr/bin/env python """ This is a demo script to show you how to use all the properties of an FT2Font object. These describe global font properties. For individual character metrices, use the Glyp object, as returned by load_char """ import matplotlib from matplotlib.ft2font import FT2Font #fname = '/usr/local/share/matplotlib/VeraIt.ttf' fname = matplotlib.get_data_path() + '/VeraIt.ttf' #fname = '/usr/local/share/matplotlib/cmr10.ttf' font = FT2Font(fname) # these constants are used to access the style_flags and face_flags FT_FACE_FLAG_SCALABLE = 1 << 0 FT_FACE_FLAG_FIXED_SIZES = 1 << 1 FT_FACE_FLAG_FIXED_WIDTH = 1 << 2 FT_FACE_FLAG_SFNT = 1 << 3 FT_FACE_FLAG_HORIZONTAL = 1 << 4 FT_FACE_FLAG_VERTICAL = 1 << 5 FT_FACE_FLAG_KERNING = 1 << 6 FT_FACE_FLAG_FAST_GLYPHS = 1 << 7 FT_FACE_FLAG_MULTIPLE_MASTERS = 1 << 8 FT_FACE_FLAG_GLYPH_NAMES = 1 << 9 FT_FACE_FLAG_EXTERNAL_STREAM = 1 << 10 FT_STYLE_FLAG_ITALIC = 1 << 0 FT_STYLE_FLAG_BOLD = 1 << 1
x,y = tup[1:] path.line_to(x,y) elif code == CURVE3: xctl, yctl, xto, yto= tup[1:] path.curve3(xctl, yctl, xto, yto) elif code == CURVE4: xctl1, yctl1, xctl2, yctl2, xto, yto= tup[1:] path.curve4(xctl1, yct1, xctl2, yctl2, xto, yto) elif code == ENDPOLY: path.end_poly() return path width, height = 300,300 fname = os.path.join(matplotlib.get_data_path(), 'Vera.ttf') font = FT2Font(fname) glyph = font.load_char(ord('y')) path = glyph_to_agg_path(glyph) curve = agg.conv_curve_path(path) scaling = agg.trans_affine_scaling(20,20) translation = agg.trans_affine_translation(4,4) rotation = agg.trans_affine_rotation(3.1415926) mtrans = translation*scaling # cannot use this as a temporary tpath = agg.conv_transform_path(path, mtrans) curve = agg.conv_curve_trans(tpath)
""" import contextlib import os import re import warnings import matplotlib as mpl from matplotlib import rc_params_from_file, rcParamsDefault from matplotlib.cbook import MatplotlibDeprecationWarning __all__ = ['use', 'context', 'available', 'library', 'reload_library'] BASE_LIBRARY_PATH = os.path.join(mpl.get_data_path(), 'stylelib') # Users may want multiple library paths, so store a list of paths. USER_LIBRARY_PATHS = [os.path.join(mpl.get_configdir(), 'stylelib')] STYLE_EXTENSION = 'mplstyle' STYLE_FILE_PATTERN = re.compile(r'([\S]+).%s$' % STYLE_EXTENSION) # A list of rcParams that should not be applied from styles STYLE_BLACKLIST = { 'interactive', 'backend', 'backend.qt4', 'webagg.port', 'webagg.address', 'webagg.port_retries', 'webagg.open_in_browser', 'backend_fallback', 'toolbar', 'timezone', 'datapath', 'figure.max_open_warning', 'savefig.directory', 'tk.window_focus', 'docstring.hardcopy'} def _remove_blacklisted_style_params(d, warn=True):
List available style sheets. ``library`` A dictionary of style names and matplotlib settings. """ import os import re import contextlib import warnings import matplotlib as mpl from matplotlib import cbook from matplotlib import rc_params_from_file, rcParamsDefault __all__ = ['use', 'context', 'available', 'library', 'reload_library'] BASE_LIBRARY_PATH = os.path.join(mpl.get_data_path(), 'stylelib') # Users may want multiple library paths, so store a list of paths. USER_LIBRARY_PATHS = [os.path.join(mpl._get_configdir(), 'stylelib')] STYLE_EXTENSION = 'mplstyle' STYLE_FILE_PATTERN = re.compile(r'([\S]+).%s$' % STYLE_EXTENSION) # A list of rcParams that should not be applied from styles STYLE_BLACKLIST = { 'interactive', 'backend', 'backend.qt4', 'webagg.port', 'webagg.address', 'webagg.port_retries', 'webagg.open_in_browser', 'backend_fallback', 'toolbar', 'timezone', 'datapath', 'figure.max_open_warning', 'savefig.directory', 'tk.window_focus', 'docstring.hardcopy' } def _remove_blacklisted_style_params(d, warn=True):
def findfont(self, prop, fontext='ttf'): """Search the font dictionary for a font that exactly or closely matches the specified font properties. See the FontProperties class for a description. The properties are searched in the following order: name, style, variant, weight, stretch, and size. The font weight always matches returning the closest weight, and the font size always matches for scalable fonts. An oblique style font will be used inplace of a missing italic style font if present. See the W3C Cascading Style Sheet, Level 1 (CSS1; http://www.w3.org/TR/1998/REC-CSS2-19980512/) documentation for a description of the font finding algorithm. """ cache_message = \ """Saving AFM font cache for PS backend to %s. Delete this file to have matplotlib rebuild the cache.""" debug = False if fontext == 'ttf': fontdict = self.ttfdict elif fontext == 'afm': if len(self.afmdict) == 0: afmpath = os.environ.get('HOME', get_data_path()) afmcache = os.path.join(afmpath, '.afmfont.cache') try: import cPickle as pickle except ImportError: import pickle try: self.afmdict = pickle.load(file(afmcache)) except: self.afmdict = createFontDict(self.afmfiles, fontext='afm') pickle.dump(self.afmdict, file(afmcache, 'w')) print cache_message % afmcache fontdict = self.afmdict name = prop.get_family()[0] style = prop.get_style() variant = prop.get_variant() weight = weight_as_number(prop.get_weight()) stretch = prop.get_stretch() size = str(prop.get_size_in_points()) try: fname = fontdict[name][style][variant][weight][stretch][size] if debug: print 'Cache:', name, style, variant, weight, stretch, size return fname except KeyError: pass for name in prop.get_family(): font = fontdict if font.has_key(name): font = font[name] else: if debug: print name continue if font.has_key(style): font = font[style] elif style == 'italics' and font.has_key('oblique'): font = font['oblique'] else: if debug: print name, style continue if font.has_key(variant): font = font[variant] else: if debug: print name, style, variant continue if not font.has_key(weight): setWeights(font) font = font[weight] # !!!! need improvement if font.has_key(stretch): font = font[stretch] else: if debug: print name, style, variant, weight, stretch continue if font.has_key('scalable'): fname = font['scalable'] elif font.has_key(size): fname = font[size] else: if debug: print name, style, variant, weight, stretch, size continue fontkey = FontKey(name, style, variant, weight, stretch, size) add_filename(fontdict, fontkey, fname) if debug: print 'Found:', name, style, variant, weight, stretch, size return fname if debug: print name, style, variant, weight, stretch, size fontkey = FontKey(name, style, variant, weight, stretch, size) add_filename(fontdict, fontkey, self.defaultFont) print >> sys.stderr, 'Could not match %s, %s, %s. Returning %s' % (name, style, variant, self.defaultFont) return self.defaultFont
# ============================================================================ # ============================================================================ # Imports # ============================================================================ from distutils.core import setup import glob import py2exe # ============================================================================ from distutils.filelist import findall import os import matplotlib matplotlibdatadir = matplotlib.get_data_path() matplotlibdata = findall(matplotlibdatadir) matplotlibdata_files =[("cache",[]), ("alerts",[]), ("data",["data/places.txt","data/yahoo_tickers.txt","data/srd.txt","data/hours.txt","data/closed.txt","data/fr.messages.txt","data/us.messages.txt","data/pt.messages.txt"]), ("images",glob.glob("images\\*.gif")), ("res",glob.glob("res\\*.*")), ("ext",glob.glob("ext\\*.*")), ("symbols",glob.glob("symbols\\*.lst")), ("brokers",glob.glob("brokers\\*.txt")), ("usrdata",["usrdata/usrquotes.txt","usrdata/portfolio.txt","usrdata/default.matrix.txt","usrdata/default.operations.txt","usrdata/default.stops.txt"]), ] for f in matplotlibdata:
import matplotlib.pyplot as plt import six from six import unichr # the font table grid labelc = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'] labelr = ['00', '10', '20', '30', '40', '50', '60', '70', '80', '90', 'A0', 'B0', 'C0', 'D0', 'E0', 'F0'] if len(sys.argv) > 1: fontname = sys.argv[1] else: fontname = os.path.join(matplotlib.get_data_path(), 'fonts', 'ttf', 'DejaVuSans.ttf') font = FT2Font(fontname) codes = sorted(font.get_charmap().items()) # a 16,16 array of character strings chars = [['' for c in range(16)] for r in range(16)] colors = [[(0.95, 0.95, 0.95) for c in range(16)] for r in range(16)] plt.figure(figsize=(8, 4), dpi=120) for ccode, glyphind in codes: if ccode >= 256: continue r, c = divmod(ccode, 16) s = unichr(ccode)
""" ============= Font Indexing ============= A little example that shows how the various indexing into the font tables relate to one another. Mainly for mpl developers.... """ from __future__ import print_function import matplotlib from matplotlib.ft2font import FT2Font, KERNING_DEFAULT, KERNING_UNFITTED, KERNING_UNSCALED fname = matplotlib.get_data_path() + '/fonts/ttf/DejaVuSans.ttf' font = FT2Font(fname) font.set_charmap(0) codes = font.get_charmap().items() #dsu = [(ccode, glyphind) for ccode, glyphind in codes] #dsu.sort() #for ccode, glyphind in dsu: # try: name = font.get_glyph_name(glyphind) # except RuntimeError: pass # else: print('% 4d % 4d %s %s' % (glyphind, ccode, hex(int(ccode)), name)) # make a charname to charcode and glyphind dictionary coded = {} glyphd = {} for ccode, glyphind in codes: name = font.get_glyph_name(glyphind) coded[name] = ccode
Matplotlib. For a more flexible solution, see :doc:`/gallery/text_labels_and_annotations/font_family_rc_sgskip` and :doc:`/gallery/text_labels_and_annotations/fonts_demo`. """ from pathlib import Path import matplotlib as mpl from matplotlib import font_manager as fm import matplotlib.pyplot as plt fig, ax = plt.subplots() fpath = Path(mpl.get_data_path(), "fonts/ttf/cmr10.ttf") prop = fm.FontProperties(fname=fpath) ax.set_title(f'This is a special font: {fpath.name}', fontproperties=prop) ax.set_xlabel('This is the default font') plt.show() ############################################################################# # # ------------ # # References # """""""""" # # The use of the following functions, methods, classes and modules is shown # in this example:
See the License for the specific language governing permissions and limitations under the License. """ import cx_Freeze, os, sys, matplotlib import PyQt5 os.environ['TCL_LIBRARY'] = r'C:\Users\lis12\Anaconda3\envs\python\tcl\tcl8.6' os.environ['TK_LIBRARY'] = r'C:\Users\lis12\Anaconda3\envs\python\tcl\tk8.6' # exe = [ cx_Freeze.Executable("GPA_UI.py", base="Console") ] PYTHON_INSTALL_DIR = os.path.dirname(os.path.dirname(os.__file__)) build_exe_options = { "packages": ["xlrd", "pandas", "numpy", "openpyxl", "matplotlib"], "includes": ["PyQt5.QtCore", "PyQt5.QtGui", "PyQt5.QtWidgets"], # "tkinter.filedialog","numpy"], "include_files": [(matplotlib.get_data_path(), "mpl-data"), "libEGL.dll", "qwindows.dll"], "excludes": [], } base = None if sys.platform == "win32": base = "Win32GUI" DLLS_FOLDER = os.path.join(PYTHON_INSTALL_DIR, 'Library', 'bin') dependencies = [ 'libiomp5md.dll', 'mkl_core.dll', 'mkl_def.dll', 'mkl_intel_thread.dll' ] for dependency in dependencies: build_exe_options['include_files'].append(
""" A little example that shows how the various indexing into the font tables relate to one another. Mainly for mpl developers.... """ from __future__ import print_function import matplotlib from matplotlib.ft2font import FT2Font, KERNING_DEFAULT, KERNING_UNFITTED, KERNING_UNSCALED #fname = '/usr/share/fonts/sfd/FreeSans.ttf' fname = matplotlib.get_data_path() + '/fonts/ttf/DejaVuSans.ttf' font = FT2Font(fname) font.set_charmap(0) codes = font.get_charmap().items() #dsu = [(ccode, glyphind) for ccode, glyphind in codes] #dsu.sort() #for ccode, glyphind in dsu: # try: name = font.get_glyph_name(glyphind) # except RuntimeError: pass # else: print('% 4d % 4d %s %s' % (glyphind, ccode, hex(int(ccode)), name)) # make a charname to charcode and glyphind dictionary coded = {} glyphd = {} for ccode, glyphind in codes: name = font.get_glyph_name(glyphind) coded[name] = ccode glyphd[name] = glyphind
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sat Jan 26 20:45:41 2019 @author: xsxsz """ import matplotlib import matplotlib.pyplot as plt print(matplotlib.get_backend()) print('-------------------') print(matplotlib.get_configdir()) print('-------------------') print(matplotlib.get_cachedir()) print('-------------------') print(matplotlib.get_data_path()) print('-------------------') print(matplotlib.matplotlib_fname()) print('-------------------') print(matplotlib.rc_params()) print('-------------------')