You can subscribe to this list here.
2007 |
Jan
|
Feb
|
Mar
|
Apr
|
May
|
Jun
|
Jul
(115) |
Aug
(120) |
Sep
(137) |
Oct
(170) |
Nov
(461) |
Dec
(263) |
---|---|---|---|---|---|---|---|---|---|---|---|---|
2008 |
Jan
(120) |
Feb
(74) |
Mar
(35) |
Apr
(74) |
May
(245) |
Jun
(356) |
Jul
(240) |
Aug
(115) |
Sep
(78) |
Oct
(225) |
Nov
(98) |
Dec
(271) |
2009 |
Jan
(132) |
Feb
(84) |
Mar
(74) |
Apr
(56) |
May
(90) |
Jun
(79) |
Jul
(83) |
Aug
(296) |
Sep
(214) |
Oct
(76) |
Nov
(82) |
Dec
(66) |
2010 |
Jan
(46) |
Feb
(58) |
Mar
(51) |
Apr
(77) |
May
(58) |
Jun
(126) |
Jul
(128) |
Aug
(64) |
Sep
(50) |
Oct
(44) |
Nov
(48) |
Dec
(54) |
2011 |
Jan
(68) |
Feb
(52) |
Mar
|
Apr
|
May
|
Jun
|
Jul
|
Aug
|
Sep
|
Oct
|
Nov
|
Dec
(1) |
2018 |
Jan
|
Feb
|
Mar
|
Apr
|
May
(1) |
Jun
|
Jul
|
Aug
|
Sep
|
Oct
|
Nov
|
Dec
|
S | M | T | W | T | F | S |
---|---|---|---|---|---|---|
1
|
2
|
3
|
4
|
5
|
6
|
7
|
8
|
9
|
10
|
11
|
12
|
13
|
14
|
15
(1) |
16
(14) |
17
(9) |
18
(13) |
19
(11) |
20
(20) |
21
(4) |
22
(4) |
23
|
24
(3) |
25
(4) |
26
(8) |
27
(2) |
28
(1) |
29
(2) |
30
(15) |
31
(4) |
|
|
|
|
Revision: 3646 http://matplotlib.svn.sourceforge.net/matplotlib/?rev=3646&view=rev Author: mdboom Date: 2007年07月31日 11:42:39 -0700 (2007年7月31日) Log Message: ----------- Refactor distutils script to display information about the extensions being built. Use pkg-config to find freetype if possible. Modified Paths: -------------- trunk/matplotlib/setup.cfg trunk/matplotlib/setup.py trunk/matplotlib/setupext.py Modified: trunk/matplotlib/setup.cfg =================================================================== --- trunk/matplotlib/setup.cfg 2007年07月31日 14:05:01 UTC (rev 3645) +++ trunk/matplotlib/setup.cfg 2007年07月31日 18:42:39 UTC (rev 3646) @@ -1,2 +1,7 @@ [egg_info] tag_svn_revision = 1 + +[status] +# To suppress display of the dependencies and their versions +# at the top of the build log, uncomment the following line: +# suppress = 1 \ No newline at end of file Modified: trunk/matplotlib/setup.py =================================================================== --- trunk/matplotlib/setup.py 2007年07月31日 14:05:01 UTC (rev 3645) +++ trunk/matplotlib/setup.py 2007年07月31日 18:42:39 UTC (rev 3646) @@ -35,7 +35,7 @@ # build wxPython extension code to efficiently blit agg into wx. Only # needed for wxpython <2.8 if you plan on doing animations -BUILD_WXAGG = 0 +BUILD_WXAGG = 1 # build a small extension to manage the focus on win32 platforms. @@ -71,18 +71,57 @@ setuptools requirement, you must delete the old matplotlib install directory.""") +if major==2 and minor1<3 or major<2: + raise SystemExit("""matplotlib requires Python 2.3 or later.""") + import glob from distutils.core import setup from setupext import build_agg, build_gtkagg, build_tkagg, build_wxagg,\ build_ft2font, build_image, build_windowing, build_transforms, \ build_contour, build_nxutils, build_enthought, build_swigagg, build_gdk, \ - build_subprocess, build_ttconv + build_subprocess, build_ttconv, print_line, print_status, print_message, \ + print_raw, check_for_freetype, check_for_libpng, check_for_gtk, check_for_tk, \ + check_for_wx, check_for_numpy, check_for_qt, check_for_qt4, check_for_cairo #import distutils.sysconfig +# jdh +packages = [ + 'matplotlib', + 'matplotlib.backends', + 'matplotlib.toolkits', + 'matplotlib.numerix', + 'matplotlib.numerix.mlab', + 'matplotlib.numerix.ma', + 'matplotlib.numerix.npyma', + 'matplotlib.numerix.linear_algebra', + 'matplotlib.numerix.random_array', + 'matplotlib.numerix.fft', + 'matplotlib.config' + ] + +ext_modules = [] + +# these are not optional +BUILD_FT2FONT = 1 +BUILD_TTCONV = 1 +BUILD_CONTOUR = 1 +BUILD_NXUTILS = 1 + for line in file('lib/matplotlib/__init__.py').readlines(): - if line[:11] == '__version__': + if (line.startswith('__version__') or + line.startswith('__revision__') or + line.startswith('__date__')): exec(line.strip()) +print_line() +print_raw("BUILDING MATPLOTLIB") +print_status('matplotlib', '%s (r%s)' % (__version__, __revision__.split()[-2])) +print_status('platform', sys.platform) +if sys.platform == 'win32': + print_status('Windows version', sys.getwindowsversion()) +print_raw("") +print_raw("REQUIRED DEPENDENCIES") + # Specify all the required mpl data package_data = {'matplotlib':['mpl-data/fonts/afm/*.afm', 'mpl-data/fonts/pdfcorefonts/*.afm', @@ -98,43 +137,19 @@ 'backends/Matplotlib.nib/*', ]} +if not check_for_numpy(): + sys.exit() + # The NUMERIX variable (a list) is left over from the days when it had # a string for each of the supported backends. Now there is only one # supported backend, so this approach could (should?) get changed for # simplicity. -try: - import numpy - NUMERIX = ['numpy'] -except ImportError: - raise RuntimeError("You must install numpy to build matplotlib") +import numpy +NUMERIX = ['numpy'] rc['numerix'] = NUMERIX[-1] -ext_modules = [] - -# these are not optional -BUILD_FT2FONT = 1 -BUILD_TTCONV = 1 -BUILD_CONTOUR = 1 -BUILD_NXUTILS = 1 - -# jdh -packages = [ - 'matplotlib', - 'matplotlib.backends', - 'matplotlib.toolkits', - 'matplotlib.numerix', - 'matplotlib.numerix.mlab', - 'matplotlib.numerix.ma', - 'matplotlib.numerix.npyma', - 'matplotlib.numerix.linear_algebra', - 'matplotlib.numerix.random_array', - 'matplotlib.numerix.fft', - 'matplotlib.config' - ] - - try: import subprocess except ImportError: havesubprocess = False else: havesubprocess = True @@ -146,12 +161,28 @@ subprocess_dir = os.path.dirname(subprocess.__file__) if subprocess_dir.endswith('.egg/subprocess'): havesubprocess = False - + if not havesubprocess: packages.append('subprocess') if sys.platform == 'win32': build_subprocess(ext_modules, packages) +if not check_for_freetype(): + sys.exit(1) + +if BUILD_FT2FONT: + build_ft2font(ext_modules, packages) + +if BUILD_TTCONV: + build_ttconv(ext_modules, packages) + +if 1: # I don't think we need to make these optional + build_contour(ext_modules, packages) + build_nxutils(ext_modules, packages) + +print_raw("") +print_raw("OPTIONAL DEPENDENCIES") + try: import datetime except ImportError: havedate = False else: havedate = True @@ -174,115 +205,70 @@ add_dateutil() else: # only add them if we need them - try: import dateutil - except ImportError: - add_dateutil() - try: import pytz + try: + import pytz except ImportError: add_pytz() + try: + import dateutil + except ImportError: + add_dateutil() + build_swigagg(ext_modules, packages) build_transforms(ext_modules, packages) build_enthought(ext_modules, packages) -def havegtk(): - 'check for the presence of pygtk' - if havegtk.gotit is not None: return havegtk.gotit - try: - import gtk - except ImportError: - print 'building for GTK requires pygtk; you must be able to "import gtk" in your build/install environment' - havegtk.gotit = False - except RuntimeError: - print 'pygtk present but import failed' - havegtk.gotit = False - else: - version = (2,2,0) - if gtk.pygtk_version < version: - print "Error: GTK backend requires PyGTK %d.%d.%d (or later), " \ - "%d.%d.%d was detected." % ( - version + gtk.pygtk_version) - havegtk.gotit = False - else: - havegtk.gotit = True - return havegtk.gotit +if check_for_gtk() and (BUILD_GTK or BUILD_GTKAGG): + if BUILD_GTK: + build_gdk(ext_modules, packages) + rc['backend'] = 'GTK' + if BUILD_GTKAGG: + BUILD_AGG = 1 + build_gtkagg(ext_modules, packages) + rc['backend'] = 'GTKAgg' -havegtk.gotit = None - -if BUILD_GTK and havegtk(): - build_gdk(ext_modules, packages) - rc['backend'] = 'GTK' - -if BUILD_GTKAGG and havegtk(): +if check_for_tk() and BUILD_TKAGG: BUILD_AGG = 1 - build_gtkagg(ext_modules, packages) - rc['backend'] = 'GTKAgg' + build_tkagg(ext_modules, packages) + rc['backend'] = 'TkAgg' -if BUILD_TKAGG: - try: - import Tkinter - except ImportError: - print 'TKAgg requires TkInter' - BUILD_TKAGG = 0 - except RuntimeError: - print 'Tkinter present but import failed' - BUILD_TKAGG = 0 +explanation = None +if check_for_wx() and BUILD_WXAGG: + BUILD_AGG = 1 + import wx + if wx.__version__ < (2.8): + build_wxagg(ext_modules, packages) + wxagg_backend_status = "yes" else: - try: - tk = Tkinter.Tk() - tk.withdraw() - except Tkinter.TclError: - print 'Tkinter present, but window failed to open' - BUILD_TKAGG = 0 - else: - BUILD_AGG = 1 - build_tkagg(ext_modules, packages) - rc['backend'] = 'TkAgg' + print_message("WxAgg extension not required for wxPython < 2.8") + rc['backend'] = 'WXAgg' -if BUILD_WXAGG: - try: - import wx - except ImportError: - if BUILD_WXAGG != 'auto': - print 'WXAgg\'s accelerator requires wxPython' - BUILD_WXAGG = 0 - else: - if getattr(wx, '__version__', '0.0')[0:3] < '2.8': - BUILD_AGG = 1 - build_wxagg(ext_modules, packages, - not (isinstance(BUILD_WXAGG, str) # don't abort if BUILD_WXAGG - and BUILD_WXAGG.lower() == 'auto')) # is "auto" - rc['backend'] = 'WXAgg' - -if BUILD_AGG: +# These are informational only. We don't build +# any extensions for them. +check_for_qt() +check_for_qt4() +check_for_cairo() + +if check_for_libpng() and BUILD_AGG: build_agg(ext_modules, packages) if rc['backend'] == 'PS': rc['backend'] = 'Agg' - - -if BUILD_FT2FONT: - build_ft2font(ext_modules, packages) - -if BUILD_TTCONV: - build_ttconv(ext_modules, packages) - if BUILD_WINDOWING and sys.platform=='win32': build_windowing(ext_modules, packages) if BUILD_IMAGE: build_image(ext_modules, packages) -if 1: # I don't think we need to make these optional - build_contour(ext_modules, packages) - build_nxutils(ext_modules, packages) - for mod in ext_modules: if VERBOSE: mod.extra_compile_args.append('-DVERBOSE') +print_raw("") +print_raw("[Edit setup.cfg to suppress the above messages]") +print_line() - # packagers: set rc['numerix'] and rc['backend'] here to override the auto # defaults, eg #rc['numerix'] = numpy Modified: trunk/matplotlib/setupext.py =================================================================== --- trunk/matplotlib/setupext.py 2007年07月31日 14:05:01 UTC (rev 3645) +++ trunk/matplotlib/setupext.py 2007年07月31日 18:42:39 UTC (rev 3646) @@ -60,8 +60,12 @@ } import sys, os, stat +import commands +from sets import Set +from textwrap import fill from distutils.core import Extension import glob +import ConfigParser major, minor1, minor2, s, tmp = sys.version_info if major<2 or (major==2 and minor1<3): @@ -81,7 +85,7 @@ BUILT_WINDOWING = False BUILT_CONTOUR = False BUILT_NXUTILS = False -BUILT_ENTHOUGHT = False +BUILT_ENTHOUGHT = False BUILT_CONTOUR = False BUILT_GDK = False @@ -90,6 +94,42 @@ # for nonstandard installation/build with --prefix variable numpy_inc_dirs = [] +# Based on the contents of setup.cfg, determine if the status block +# should be displayed +display_status = True +if os.path.exists("setup.cfg"): + config = ConfigParser.SafeConfigParser() + config.read("setup.cfg") + try: + if config.get("status", "suppress"): + display_status = False + except: + pass + +if display_status: + def print_line(char='='): + print char * 76 + + def print_status(package, status): + initial_indent = "%22s: " % package + indent = ' ' * 24 + print fill(status, width=76, + initial_indent=initial_indent, + subsequent_indent=indent) + + def print_message(message): + indent = ' ' * 24 + "* " + print fill(message, width=76, + initial_indent=indent, + subsequent_indent=indent) + + def print_raw(section): + print section +else: + def print_line(*args, **kwargs): + pass + print_status = print_message = print_raw = print_line + class CleanUpFile: """CleanUpFile deletes the specified filename when self is destroyed.""" def __init__(self, name): @@ -123,8 +163,99 @@ else: std_libs = ['stdc++', 'm'] +def has_pkgconfig(): + if has_pkgconfig.cache is not None: + return has_pkgconfig.cache + if sys.platform == 'win32': + has_pkgconfig.cache = False + else: + status, output = commands.getstatusoutput("pkg-config --help") + has_pkgconfig.cache = (status == 0) + return has_pkgconfig.cache +has_pkgconfig.cache = None + +def get_pkgconfig(module, + packages, + flags="--libs --cflags", + pkg_config_exec='pkg-config'): + """Loosely based on an article in the Python Cookbook: + http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/502261""" + if not has_pkgconfig(): + return False + + _flags = {'-I': 'include_dirs', + '-L': 'library_dirs', + '-l': 'libraries', + '-D': 'define_macros', + '-U': 'undef_macros'} + + status, output = commands.getstatusoutput( + "%s %s %s" % (pkg_config_exec, flags, packages)) + if status == 0: + for token in output.split(): + attr = _flags.get(token[:2], None) + if attr is not None: + set = getattr(module, attr) + if token[2:] not in set: + set.append(token[2:]) + else: + if token not in module.extra_link_args: + module.extra_link_args.append(token) + return True + return False + +def get_pkgconfig_version(package): + default = "unknown (no pkg-config)" + if not has_pkgconfig(): + return default + + status, output = commands.getstatusoutput( + "pkg-config %s --modversion" % (package)) + if status == 0: + return output + return default + +def try_pkgconfig(module, package, fallback): + if not get_pkgconfig(module, package): + module.libraries.append(fallback) + +def find_include_file(include_dirs, filename): + for d in include_dirs: + if os.path.exists(os.path.join(d, filename)): + return True + return False + +def check_for_freetype(): + module = Extension('test', []) + add_base_flags(module) + if not get_pkgconfig(module, 'freetype2'): + basedirs = module.include_dirs[:] # copy the list to avoid inf loop! + for d in basedirs: + module.include_dirs.append(os.path.join(d, 'freetype2')) + + if not find_include_file(module.include_dirs, 'ft2build.h'): + print_message( + "Could not find 'freetype2' headers in any of %s" % + ", ".join(["'%s'" % x for x in module.include_dirs])) + return False + + print_status("freetype2", get_pkgconfig_version('freetype2')) + return True + +def check_for_libpng(): + module = Extension("test", []) + get_pkgconfig(module, 'libpng') + add_base_flags(module) + if not find_include_file(module.include_dirs, 'png.h'): + print_message( + ", ".join("Could not find 'libpng' headers in any of %s" % + ["'%s'" % x for x in module.include_dirs])) + return False + + print_status("libpng", get_pkgconfig_version('libpng')) + return True + def add_base_flags(module): - incdirs = filter(os.path.exists, [os.path.join(p, 'include') for p in basedir[sys.platform] ]) libdirs = filter(os.path.exists, @@ -141,6 +272,57 @@ ret = os.popen(s).read().strip() return ret +def check_for_qt(): + try: + import pyqtconfig + except ImportError: + print_status("Qt", "no") + return False + else: + print_status("Qt", "Qt: %s, pyqt: %s" % + (pyqtconfig.Configuration().pyqt_version_str, + pyqtconfig.Configuration().qt_version)) + return True + +def check_for_qt4(): + try: + import PyQt4.pyqtconfig + except ImportError: + print_status("Qt4", "no") + return False + else: + print_status("Qt4", "Qt: %s, pyqt: %s" % + (PyQt4.pyqtconfig.Configuration().pyqt_version_str, + PyQt4.pyqtconfig.Configuration().qt_version)) + return True + +def check_for_cairo(): + try: + import cairo + except ImportError: + print_status("Cairo", "no") + return False + else: + print_status("Cairo", cairo.version) + +def check_for_numpy(): + gotit = False + try: + import numpy + except ImportError: + print_status("numpy", "no") + print_message("You must install numpy to build matplotlib.") + return False + module = Extension('test', []) + add_numpy_flags(module) + add_base_flags(module) + if not find_include_file(module.include_dirs, os.path.join("numpy", "arrayobject.h")): + print_status("numpy", "no") + print_message("Could not find the headers for numpy. You may need to install the development package.") + return False + print_status("numpy", numpy.__version__) + return True + def add_numpy_flags(module): "Add the modules flags to build extensions which use numpy" import numpy @@ -154,13 +336,11 @@ 'Add the module flags to build extensions which use agg' # before adding the freetype flags since -z comes later - module.libraries.append('png') + try_pkgconfig(module, 'libpng', 'png') module.libraries.append('z') add_base_flags(module) module.include_dirs.extend(['src','swig', '%s/include'%AGG_VERSION, '.']) - - # put these later for correct link order module.libraries.extend(std_libs) @@ -168,24 +348,26 @@ 'Add the module flags to build extensions which use gd' module.libraries.append('gd') - def add_ft2font_flags(module): - 'Add the module flags to build extensions which use gd' - module.libraries.extend(['freetype', 'z' ]) + 'Add the module flags to ft2font extension' + module.libraries.append('z') add_base_flags(module) - basedirs = module.include_dirs[:] # copy the list to avoid inf loop! - for d in basedirs: - module.include_dirs.append(os.path.join(d, 'freetype2')) - p = os.path.join(d, 'lib/freetype2/include') - if os.path.exists(p): module.include_dirs.append(p) - p = os.path.join(d, 'lib/freetype2/include/freetype2') - if os.path.exists(p): module.include_dirs.append(p) + if not get_pkgconfig(module, 'freetype2'): + module.libraries.append('freetype') + + basedirs = module.include_dirs[:] # copy the list to avoid inf loop! + for d in basedirs: + module.include_dirs.append(os.path.join(d, 'freetype2')) + p = os.path.join(d, 'lib/freetype2/include') + if os.path.exists(p): module.include_dirs.append(p) + p = os.path.join(d, 'lib/freetype2/include/freetype2') + if os.path.exists(p): module.include_dirs.append(p) - basedirs = module.library_dirs[:] # copy the list to avoid inf loop! - for d in basedirs: - p = os.path.join(d, 'freetype2/lib') - if os.path.exists(p): module.library_dirs.append(p) + basedirs = module.library_dirs[:] # copy the list to avoid inf loop! + for d in basedirs: + p = os.path.join(d, 'freetype2/lib') + if os.path.exists(p): module.library_dirs.append(p) if sys.platform == 'win32' and win32_compiler == 'mingw32': module.libraries.append('gw32c') @@ -193,8 +375,48 @@ # put this last for library link order module.libraries.extend(std_libs) +def check_for_gtk(): + 'check for the presence of pygtk' + gotit = False + explanation = None + try: + import gtk + except ImportError: + explanation = 'Building for Gtk+ requires pygtk; you must be able to "import gtk" in your build/install environment' + except RuntimeError: + explanation = 'pygtk present but import failed' + else: + version = (2,2,0) + if gtk.pygtk_version < version: + explanation = "Error: GTK backend requires PyGTK %d.%d.%d (or later), " \ + "%d.%d.%d was detected." % ( + version + gtk.pygtk_version) + else: + gotit = True + if gotit: + module = Extension('test', []) + add_pygtk_flags(module) + if not find_include_file(module.include_dirs, os.path.join("gtk", "gtk.h")): + explanation = ( + "Could not find Gtk+ headers in any of %s" % + ", ".join(["'%s'" % x for x in module.include_dirs])) + gotit = False + def ver2str(tup): + return ".".join([str(x) for x in tup]) + + if gotit: + import gobject + print_status("Gtk+", "gtk+: %s, glib: %s, pygtk: %s, pygobject: %s" % + (ver2str(gtk.gtk_version), ver2str(gobject.glib_version), + ver2str(gtk.pygtk_version), ver2str(gobject.pygobject_version))) + else: + print_status("Gtk+", "no") + print_message(explanation) + + return gotit + def add_pygtk_flags(module): 'Add the module flags to build extensions which use gtk' @@ -220,36 +442,61 @@ add_base_flags(module) - # set for msvc compiler if not present - if not os.environ.has_key('PKG_CONFIG_PATH'): - os.environ['PKG_CONFIG_PATH'] = 'C:\GTK\lib\pkgconfig' + if sys.platform != 'win32': + # If Gtk+ is installed, pkg-config is required to be installed + get_pkgconfig(module, 'pygtk-2.0 gtk+-2.0') - pygtkIncludes = getoutput('pkg-config --cflags-only-I pygtk-2.0').split() - gtkIncludes = getoutput('pkg-config --cflags-only-I gtk+-2.0').split() - includes = pygtkIncludes + gtkIncludes - module.include_dirs.extend([include[2:] for include in includes]) + # visual studio doesn't need the math library + if sys.platform == 'win32' and win32_compiler == 'msvc' and 'm' in module.libraries: + module.libraries.remove('m') - pygtkLinker = getoutput('pkg-config --libs pygtk-2.0').split() - gtkLinker = getoutput('pkg-config --libs gtk+-2.0').split() - linkerFlags = pygtkLinker + gtkLinker - module.libraries.extend( - [flag[2:] for flag in linkerFlags if flag.startswith('-l')]) +def check_for_wx(): + gotit = False + explanation = None + try: + import wx + except ImportError: + explanation = 'wxPython not found' + else: + if sys.platform == 'win32' and win32_compiler == 'mingw32': + explanation = "The wxAgg extension can not be built using the mingw32 compiler on Windows, since the default wxPython binary is built using MS Visual Studio" + else: + wxconfig = find_wx_config() + if wxconfig is None: + explanation = """ +WXAgg's accelerator requires `wx-config'. +The `wx-config\' executable could not be located in any directory of the +PATH environment variable. If you want to build WXAgg, and wx-config is +in some other location or has some other name, set the WX_CONFIG +environment variable to the full path of the executable like so: - module.library_dirs.extend( - [flag[2:] for flag in linkerFlags if flag.startswith('-L')]) +export WX_CONFIG=/usr/lib/wxPython-2.6.1.0-gtk2-unicode/bin/wx-config +""" + elif not check_wxpython_broken_macosx104_version(wxconfig): + explanation = 'WXAgg\'s accelerator not building because a broken wxPython (installed by Apple\'s Mac OS X) was found.' + else: + gotit = True + if gotit: + module = Extension("test", []) + add_wx_flags(module, wxconfig) + if not find_include_file( + module.include_dirs, + os.path.join("wx", "wxPython", "wxPython.h")): + explanation = ("Could not find wxPython headers in any of %s" % + ", ".join(["'%s'" % x for x in module.include_dirs])) + gotit = False - module.extra_link_args.extend( - [flag for flag in linkerFlags if not - (flag.startswith('-l') or flag.startswith('-L'))]) - - # visual studio doesn't need the math library - if sys.platform == 'win32' and win32_compiler == 'msvc' and 'm' in module.libraries: - module.libraries.remove('m') - - + if gotit: + print_status("wxPython", wx.__version__) + else: + print_status("wxPython", "no") + if explanation is not None: + print_message(explanation) + return gotit + def find_wx_config(): """If the WX_CONFIG environment variable has been set, returns it value. Otherwise, search for `wx-config' in the PATH directories and return the @@ -268,24 +515,6 @@ return None - -def check_wxpython_headers(wxconfig): - """Determines if wxPython.h can be found in one of the wxWidgets include - directories. - """ - - flags = getoutput(wxconfig + ' --cppflags').split() - incdirs = [os.path.join(p, 'include') for p in basedir[sys.platform] - if os.path.exists(p)] - - incdirs += [x[2:] for x in flags if x.startswith('-I')] - header = os.path.join('wx', 'wxPython', 'wxPython.h') - - for d in incdirs: - if os.path.exists(os.path.join(d, header)): - return True - return False - def check_wxpython_broken_macosx104_version(wxconfig): """Determines if we're using a broken wxPython installed by Mac OS X 10.4""" if sys.platform == 'darwin': @@ -308,31 +537,8 @@ module.libraries.extend(wxlibs) return - def getWX(fmt, *args): - return getoutput(wxconfig + ' ' + (fmt % args)).split() + get_pkgconfig(module, '', flags='--cppflags --libs', pkg_config_exec='wx-config') - wxFlags = getWX('--cppflags') - wxLibs = getWX('--libs') - - - add_base_flags(module) - module.include_dirs.extend( - [x[2:] for x in wxFlags if x.startswith('-I')]) - - - module.define_macros.extend( - [(x[2:], None) for x in wxFlags if x.startswith('-D')]) - module.undef_macros.extend( - [x[2:] for x in wxFlags if x.startswith('-U')]) - - module.libraries.extend( - [x[2:] for x in wxLibs if x.startswith('-l')]) - module.library_dirs.extend( - [x[2:] for x in wxLibs if x.startswith('-L')]) - module.extra_link_args.extend( - [x for x in wxLibs if not (x.startswith('-l') or x.startswith('-L'))]) - - # Make sure you use the Tk version given by Tkinter.TkVersion # or else you'll build for a wrong version of the Tcl # interpreter (leading to nasty segfaults). @@ -342,21 +548,12 @@ def find_tcltk(): """Finds Tcl/Tk includes/libraries/version by interrogating Tkinter.""" - try: - import Tkinter - except: - print "Tkinter not properly installed\n" - sys.exit(1) - if Tkinter.TkVersion < 8.3: - print "Tcl/Tk v8.3 or later required\n" - sys.exit(1) + # By this point, we already know that Tkinter imports correctly + import Tkinter o = FoundTclTk() try: tk=Tkinter.Tk() except Tkinter.TclError: - print "Using default library and include directories for Tcl and Tk because a" - print "Tk window failed to open. You may need to define DISPLAY for Tk to work" - print "so that setup can determine where your libraries are located." o.tcl_lib = "/usr/local/lib" o.tcl_inc = "/usr/local/include" o.tk_lib = "/usr/local/lib" @@ -389,24 +586,60 @@ os.path.exists('/usr/include/tk.h')): o.tcl_inc = '/usr/include/' o.tk_inc = '/usr/include/' - - if not os.path.exists(o.tcl_inc): - print 'cannot find tcl/tk headers. giving up.' - sys.exit() return o +def check_for_tk(): + gotit = False + explanation = None + try: + import Tkinter + except ImportError: + explanation = 'TKAgg requires Tkinter' + except RuntimeError: + explanation = 'Tkinter present but import failed' + else: + if Tkinter.TkVersion < 8.3: + explanation = "Tcl/Tk v8.3 or later required\n" + sys.exit(1) + else: + try: + tk = Tkinter.Tk() + tk.withdraw() + except Tkinter.TclError: + explanation = """\ +Using default library and include directories for Tcl and Tk because a +Tk window failed to open. You may need to define DISPLAY for Tk to work +so that setup can determine where your libraries are located.""" + gotit = True + if gotit: + module = Extension('test', []) + try: + add_tk_flags(module) + except RuntimeError, e: + explanation = str(e) + gotit = False + if not find_include_file(module.include_dirs, "tk.h"): + explanation = 'Tkinter present, but header files are not installed. You may need to install development packages.' + gotit = False + + if gotit: + print_status("Tkinter", "Tkinter: %s, Tk: %s, Tcl: %s" % + (Tkinter.__version__.split()[-2], Tkinter.TkVersion, Tkinter.TclVersion)) + else: + print_status("Tkinter", "no") + if explanation is not None: + print_message(explanation) + return gotit + def add_tk_flags(module): 'Add the module flags to build extensions which use tk' if sys.platform=='win32': major, minor1, minor2, s, tmp = sys.version_info - print 'building tkagg', major, minor1 if major==2 and minor1 in [3, 4, 5]: - print '\tBuilding for python2%d'%minor1 module.include_dirs.extend(['win32_static/include/tcl84']) module.libraries.extend(['tk84', 'tcl84']) elif major==2 and minor1==2: - print '\tBuilding for python22' module.include_dirs.extend(['win32_static/include/tcl83']) module.libraries.extend(['tk83', 'tcl83']) else: @@ -503,7 +736,10 @@ def build_ttconv(ext_modules, packages): global BUILT_TTCONV if BUILT_TTCONV: return # only build it if you you haven't already - deps = ['src/_ttconv.cpp', 'ttconv/pprdrv_tt.cpp', 'ttconv/pprdrv_tt2.cpp', 'ttconv/ttutil.cpp'] + deps = ['src/_ttconv.cpp', + 'ttconv/pprdrv_tt.cpp', + 'ttconv/pprdrv_tt2.cpp', + 'ttconv/ttutil.cpp'] deps.extend(glob.glob('CXX/*.cxx')) deps.extend(glob.glob('CXX/*.c')) @@ -523,11 +759,9 @@ deps, ) - # add agg flags before pygtk because agg only supports freetype1 # and pygtk includes freetype2. This is a bit fragile. - add_agg_flags(module) add_ft2font_flags(module) add_pygtk_flags(module) @@ -557,62 +791,11 @@ BUILT_TKAGG = True -def build_wxagg(ext_modules, packages, abortOnFailure): +def build_wxagg(ext_modules, packages): global BUILT_WXAGG if BUILT_WXAGG: return - wxconfig = find_wx_config() - - # Avoid aborting the whole build process if `wx-config' can't be found and - # BUILD_WXAGG in setup.py is set to "auto" - if sys.platform == 'win32': - # mingw32 cannot link against distributed wx libs - # since they are built with VisualStudio - if win32_compiler == 'mingw32': - return - else: - pass - - elif wxconfig is None: - print """ -WXAgg's accelerator requires `wx-config'. - -The `wx-config\' executable could not be located in any directory of the -PATH environment variable. If you want to build WXAgg, and wx-config is -in some other location or has some other name, set the WX_CONFIG -environment variable to the full path of the executable like so: - -export WX_CONFIG=/usr/lib/wxPython-2.6.1.0-gtk2-unicode/bin/wx-config -""" - if not abortOnFailure: - print """Building MPL without wxAgg""" - BUILT_WXAGG = True - return - else: - sys.exit(1) - elif not check_wxpython_headers(wxconfig): - print 'WXAgg\'s accelerator requires the wxPython headers.' - - if not abortOnFailure: - BUILT_WXAGG = True - return - else: - print """ -The wxPython header files could not be located in any of the standard -include -directories or include directories reported by `wx-config --cppflags'.""" - sys.exit(1) - elif not check_wxpython_broken_macosx104_version(wxconfig): - print 'WXAgg\'s accelerator not building because a broken wxPython (installed by Apple\'s Mac OS X) was found.' - if not abortOnFailure: - BUILT_WXAGG = True - return - else: - print """ -The wxPython installation is the broken version installed with Mac OS X 10.4.""" - sys.exit(1) - deps = ['src/_wxagg.cpp', 'src/mplutils.cpp'] deps.extend(glob.glob('CXX/*.cxx')) deps.extend(glob.glob('CXX/*.c')) @@ -627,8 +810,6 @@ BUILT_WXAGG = True - - def build_agg(ext_modules, packages): global BUILT_AGG if BUILT_AGG: return # only build it if you you haven't already This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
Revision: 3645 http://matplotlib.svn.sourceforge.net/matplotlib/?rev=3645&view=rev Author: dsdale Date: 2007年07月31日 07:05:01 -0700 (2007年7月31日) Log Message: ----------- minor updates to config package Modified Paths: -------------- trunk/matplotlib/lib/matplotlib/config/mplconfig.py trunk/matplotlib/lib/matplotlib/mpl-data/matplotlib.conf Added Paths: ----------- trunk/matplotlib/lib/matplotlib/mpl-data/matplotlib.conf.backup Modified: trunk/matplotlib/lib/matplotlib/config/mplconfig.py =================================================================== --- trunk/matplotlib/lib/matplotlib/config/mplconfig.py 2007年07月31日 13:11:34 UTC (rev 3644) +++ trunk/matplotlib/lib/matplotlib/config/mplconfig.py 2007年07月31日 14:05:01 UTC (rev 3645) @@ -11,7 +11,7 @@ import mpltraits as mplT import cutils import checkdep -from tconfig import TConfig, TConfigManager +from tconfig import TConfig, TConfigManager, tconf2File import pytz # Code begins @@ -503,9 +503,9 @@ rcParams = RcParamsWrapper(mplConfig) ############################################################################## -# Simple testing +# Auto-generate the mpl-data/matplotlib.conf ############################################################################## if __name__ == "__main__": mplConfig = MPLConfig() - mplConfig.backend.pdf.compression = 1.1 - print mplConfig + tconf2File(mplConfig, '../mpl-data/matplotlib.conf', force=True) + print 'Default matplotlib.conf created in ../mpl-data' Modified: trunk/matplotlib/lib/matplotlib/mpl-data/matplotlib.conf =================================================================== --- trunk/matplotlib/lib/matplotlib/mpl-data/matplotlib.conf 2007年07月31日 13:11:34 UTC (rev 3644) +++ trunk/matplotlib/lib/matplotlib/mpl-data/matplotlib.conf 2007年07月31日 14:05:01 UTC (rev 3645) @@ -1,456 +1,402 @@ -### MATPLOTLIBRC FORMAT +# MPLConfig - plaintext (in .conf format) # This is a sample matplotlib configuration file. It should be placed # in HOME/.matplotlib/matplotlibrc (unix/linux like systems) and # C:\Documents and Settings\yourname\.matplotlib (win32 systems) -# -# By default, the installer will overwrite the existing file in the -# install path, so if you want to preserve your's, please move it to -# your HOME dir and set the environment variable if necessary. -# -# This file is best viewed in a editor which supports ini or conf mode -# syntax highlighting -# +# +# By default, the installer will overwrite the existing file in the install +# path, so if you want to preserve yours, please move it to your HOME dir and +# set the environment variable if necessary. +# +# This file is best viewed in a editor which supports ini or conf mode syntax +# highlighting. +# # Blank lines, or lines starting with a comment symbol, are ignored, # as are trailing comments. Other lines must have the format -# -# key = val # optional comment -# +# +# key = val optional comment +# # val should be valid python syntax, just as you would use when setting # properties using rcParams. This should become more obvious by inspecting # the default values listed herein. -# +# # Colors: for the color values below, you can either use # - a matplotlib color string, such as r, k, or b # - an rgb tuple, such as (1.0, 0.5, 0.0) # - a hex string, such as #ff00ff or ff00ff # - a scalar grayscale intensity such as 0.75 # - a legal html color name, eg red, blue, darkslategray +# +# Interactivity: see http://matplotlib.sourceforge.net/interactive.html. +# +# ### CONFIGURATION BEGINS HERE ### -#### CONFIGURATION BEGINS HERE - -# numpy, Numeric or numarray -numerix = 'numpy' - -# True to use external maskedarray module instead of numpy.ma; this is a -# temporary setting for testing maskedarray. -maskedarray = False - -# see http://matplotlib.sourceforge.net/interactive.html +# a value of type 'str' +datapath = '/usr/lib64/python2.5/site-packages/matplotlib-0.90.1_r3640-py2.5-linux-x86_64.egg/matplotlib/mpl-data' +# one of 0, on, false, 1, no, n, y, off, yes, true interactive = False - -# None | classic | toolbar2 -toolbar = 'toolbar2' - -# a pytz timezone string, eg US/Central or Europe/Paris +# a value of type 'bool' +maskedarray = False +# 'numpy' or 'numeric' or 'numarray' +numerix = 'numpy' +# 'Africa/Abidjan' or 'Africa/Accra' or 'Africa/Addis_Ababa' or 'Africa/Algiers' +# or 'Africa/Asmara' or 'Africa/Asmera' or 'Africa/Bamako' or 'Africa/Bangui' o +# r 'Africa/Banjul' or 'Africa/Bissau' or 'Africa/Blantyre' or 'Africa/Brazzavil +# <...snipped 10590 chars...> +# or 'Turkey' or 'UCT' or 'US/Alaska' or 'US/Aleutian' or 'US/Arizona' or 'US/Ce +# ntral' or 'US/East-Indiana' or 'US/Eastern' or 'US/Hawaii' or 'US/Indiana-Star +# ke' or 'US/Michigan' or 'US/Mountain' or 'US/Pacific' or 'US/Pacific-New' or ' +# US/Samoa' or 'UTC' or 'Universal' or 'W-SU' or 'WET' or 'Zulu' or 'posixrules' timezone = 'UTC' - +# 'toolbar2' or None +toolbar = 'toolbar2' +# a value of type 'bool' units = False -# Where your matplotlib data lives if you installed to a non-default -#location. This is where the matplotlib fonts, bitmaps, etc reside -#datapath = '/home/fperez/.matplotlib' +[axes] + # a value of type 'bool' + axisbelow = False + # any valid matplotlib color, eg an abbreviation like 'r' for red, a full + # name like 'orange', a hex color like '#efefef', a grayscale intensity + # like '0.5', or an RGBA tuple (1,0,0,1) + edgecolor = 'black' + # any valid matplotlib color, eg an abbreviation like 'r' for red, a full + # name like 'orange', a hex color like '#efefef', a grayscale intensity + # like '0.5', or an RGBA tuple (1,0,0,1) + facecolor = 'white' + # one of 0, on, false, 1, no, n, y, off, yes, true + grid = False + # one of 0, on, false, 1, no, n, y, off, yes, true + hold = True + # any valid matplotlib color, eg an abbreviation like 'r' for red, a full + # name like 'orange', a hex color like '#efefef', a grayscale intensity + # like '0.5', or an RGBA tuple (1,0,0,1) + labelcolor = 'black' + # a value of type 'float' or 'xx-small' or 'x-small' or 'small' or 'medium' + # or 'large' or 'x-large' or 'xx-large' + labelsize = 'medium' + # a value of type 'float' + linewidth = 1.0 + # one of 0, on, false, 1, no, n, y, off, yes, true + polargrid = True + # a value of type 'float' or 'xx-small' or 'x-small' or 'small' or 'medium' + # or 'large' or 'x-large' or 'xx-large' + titlesize = 'large' -#bogus = 1 -#[bogus_section] -# foo = 1 + [[formatter]] + # a list of from 2 to 2 items each of which is a value of type 'float' + limits = [-7.0, 7.0] [backend] - - #[[bogus_subsection]] - # bar =1 - - # 'GTKAgg', 'GTKCairo', 'QtAgg', 'Qt4Agg', 'TkAgg', 'Agg', - # 'Cairo', 'PS', 'PDF', 'SVG' - use = 'TkAgg' - + # Valid backends are: 'GTKAgg', 'GTKCairo', 'QtAgg', 'Qt4Agg', + # 'TkAgg', 'Agg', 'Cairo', 'PS', 'PDF', 'SVG' + # one of ps, qt4agg, tkagg, gtkagg, agg, cairo, gtkcairo, wxagg, qtagg, temp + # late, svg, pdf + use = 'PS' + [[cairo]] - # png, ps, pdf, svg + # 'png' or 'ps' or 'pdf' or 'svg' format = 'png' - - [[tk]] - # Maintain shell focus for TkAgg - window_focus = False - - # tk sets PYTHONINSEPCT - pythoninspect = False - + + [[pdf]] + # 0 <= an integer <= 9 + compression = 6 + # 3 or 42 + fonttype = 3 + # a value of type 'bool' + inheritcolor = False + # a value of type 'bool' + use14corefonts = False + [[ps]] - # auto, letter, legal, ledger, A0-A10, B0-B10 + # 3 or 42 + fonttype = 3 + # 'auto' or 'letter' or 'legal' or 'ledger' or 'A0' or 'A1' or 'A2' or ' + # A3' or 'A4' or 'A5' or 'A6' or 'A7' or 'A8' or 'A9' or 'A10' or 'B0' o + # r 'B1' or 'B2' or 'B3' or 'B4' or 'B5' or 'B6' or 'B7' or 'B8' or 'B9' + # or 'B10' papersize = 'letter' - - # use of afm fonts, results in smaller files + # a value of type 'bool' useafm = False - - # 3 (Type3) or 42 (TrueType) - fonttype = 3 - + [[[distiller]]] - # can be: None, ghostscript or xpdf - # xpdf intended for production of publication quality - # files, but requires ghostscript, xpdf and ps2eps - use = None - - # distiller resolution, dpi + # a value of type 'float' resolution = 6000.0 - - [[pdf]] - # integer from 0 to 9 - # 0 disables compression (good for debugging) - compression = 6 - - # 3 (Type3) or 42 (TrueType) - fonttype = 3 - + # a bool or None or 'ghostscript' or 'xpdf' + use = None + [[svg]] - # write raster image data directly into the svg file + # a value of type 'bool' + embed_chars = False + # a value of type 'bool' image_inline = True - - # suppress scaling of raster data embedded in SVG + # a value of type 'bool' image_noscale = False - - # embed character outlines in the SVG file - embed_chars = False + [[tk]] + # window_focus : Maintain shell focus for TkAgg + # pythoninspect: tk sets PYTHONINSPECT + + # a value of type 'bool' + pythoninspect = False + # a value of type 'bool' + window_focus = False + +[contour] + # 'dashed' or 'solid' + negative_linestyle = 'dashed' + +[figure] + # a value of type 'float' + dpi = 80.0 + # any valid matplotlib color, eg an abbreviation like 'r' for red, a full + # name like 'orange', a hex color like '#efefef', a grayscale intensity + # like '0.5', or an RGBA tuple (1,0,0,1) + edgecolor = 'white' + # any valid matplotlib color, eg an abbreviation like 'r' for red, a full + # name like 'orange', a hex color like '#efefef', a grayscale intensity + # like '0.5', or an RGBA tuple (1,0,0,1) + facecolor = '0.75' + # a list of from 2 to 2 items each of which is a value of type 'float' + figsize = [8.0, 6.0] + + [[subplot]] + # The figure subplot parameters. All dimensions are fraction + # of the figure width or height + # a value of type 'float' + bottom = 0.10000000000000001 + # a value of type 'float' + hspace = 0.20000000000000001 + # a value of type 'float' + left = 0.125 + # a value of type 'float' + right = 0.90000000000000002 + # a value of type 'float' + top = 0.90000000000000002 + # a value of type 'float' + wspace = 0.20000000000000001 + +[font] + # a list of items each of which is a value of type 'str' + cursive = ['Apple Chancery', 'Textile', 'Zapf Chancery', 'Sand', 'cursive'] + # 'sans-serif' or 'serif' or 'cursive' or 'fantasy' or 'monospace' + family = 'sans-serif' + # a list of items each of which is a value of type 'str' + fantasy = ['Comic Sans MS', 'Chicago', 'Charcoal', 'Impact', 'Western', 'fantasy'] + # a list of items each of which is a value of type 'str' + monospace = ['Bitstream Vera Sans Mono', 'Andale Mono', 'Nimbus Mono L', 'Courier New', 'Courier', 'Fixed', 'Terminal', 'monospace'] + # a list of items each of which is a value of type 'str' + sans_serif = ['Bitstream Vera Sans', 'Lucida Grande', 'Verdana', 'Geneva', 'Lucid', 'Arial', 'Helvetica', 'Avant Garde', 'sans-serif'] + # a list of items each of which is a value of type 'str' + serif = ['Bitstream Vera Serif', 'New Century Schoolbook', 'Century Schoolbook L', 'Utopia', 'ITC Bookman', 'Bookman', 'Nimbus Roman No9 L', 'Times New Roman', 'Times', 'Palatino', 'Charter', 'serif'] + # a value of type 'float' + size = 12.0 + # 'ultra-condensed' or 'extra-condensed' or 'condensed' or 'semi-condensed' + # or 'normal' or 'semi-expanded' or 'expanded' or 'extra-expanded' or 'ultra + # -expanded' or 'wider' or 'narrower' + stretch = 'normal' + # 'normal' or 'italic' or 'oblique' + style = 'normal' + # 'normal' or 'small-caps' + variant = 'normal' + # 'normal' or 'bold' or 'bolder' or 'lighter' or 100 or 200 or 300 or 400 or + # 500 or 600 or 700 or 800 or 900 + weight = 'normal' + +[grid] + # any valid matplotlib color, eg an abbreviation like 'r' for red, a full + # name like 'orange', a hex color like '#efefef', a grayscale intensity + # like '0.5', or an RGBA tuple (1,0,0,1) + color = 'black' + # '-' or '--' or '-.' or ':' or 'steps' or '' or ' ' + linestyle = ':' + # a value of type 'float' + linewidth = 0.5 + +[image] + # a value of type 'float' or 'equal' or 'auto' + aspect = 'equal' + # 'Accent' or 'Accent_r' or 'Blues' or 'Blues_r' or 'BrBG' or 'BrBG_r' or 'B + # uGn' or 'BuGn_r' or 'BuPu' or 'BuPu_r' or 'Dark2' or 'Dark2_r' or 'GnBu' o + # r 'GnBu_r' or 'Greens' or 'Greens_r' or 'Greys' or 'Greys_r' or 'OrRd' or + # <...snipped 1010 chars...> + # ist_stern' or 'gist_stern_r' or 'gist_yarg' or 'gist_yarg_r' or 'gray' or + # 'gray_r' or 'hot' or 'hot_r' or 'hsv' or 'hsv_r' or 'jet' or 'jet_r' or 'p + # ink' or 'pink_r' or 'prism' or 'prism_r' or 'spectral' or 'spectral_r' or + # 'spring' or 'spring_r' or 'summer' or 'summer_r' or 'winter' or 'winter_r' + cmap = 'jet' + # 'bilinear' or 'nearest' or 'bicubic' or 'spline16' or 'spline36' or 'hanni + # ng' or 'hamming' or 'hermite' or 'kaiser' or 'quadric' or 'catrom' or 'gau + # ssian' or 'bessel' or 'mitchell' or 'sinc' or 'lanczos' or 'blackman' + interpolation = 'bilinear' + # a value of type 'int' + lut = 256 + # 'upper' or 'lower' + origin = 'upper' + +[legend] + # a value of type 'float' + axespad = 0.02 + # a value of type 'float' or 'xx-small' or 'x-small' or 'small' or 'medium' + # or 'large' or 'x-large' or 'xx-large' + fontsize = 'medium' + # a value of type 'float' + handlelen = 0.050000000000000003 + # a value of type 'float' + handletextsep = 0.02 + # a value of type 'bool' + isaxes = True + # a value of type 'float' + labelsep = 0.01 + # 'best' or 'upper right' or 'upper left' or 'lower left' or 'lower right' o + # r 'right' or 'center left' or 'center right' or 'lower center' or 'upper c + # enter' or 'center' + loc = 'upper right' + # a value of type 'float' + markerscale = 1.0 + # a value of type 'int' + numpoints = 3 + # a value of type 'float' + pad = 0.20000000000000001 + # a value of type 'bool' + shadow = False + [lines] - # See http://matplotlib.sourceforge.net/matplotlib.lines.html for more - # information on line properties. - - # line width in points - linewidth = 1.0 - - # '-','--','-.', ':', 'steps', '', ' ', or None - linestyle = '-' - + # a value of type 'bool' + antialiased = True + # any valid matplotlib color, eg an abbreviation like 'r' for red, a full + # name like 'orange', a hex color like '#efefef', a grayscale intensity + # like '0.5', or an RGBA tuple (1,0,0,1) color = 'blue' - - # The default marker: 'None', 'o', '.', ',', '^', 'v', '<', '>', 's', '+', - # 'x', 'D', 'd', '1', '2', '3', '4', 'h', 'H', 'p', '|', '_' + # 'butt' or 'round' or 'projecting' + dash_capstyle = 'butt' + # 'miter' or 'round' or 'bevel' + dash_joinstyle = 'miter' + # '-' or '--' or '-.' or ':' or 'steps' or '' or ' ' or None + linestyle = '-' + # a value of type 'float' + linewidth = 1.0 + # 'None' or 'o' or '.' or ',' or '^' or 'v' or '<' or '>' or 's' or '+' or ' + # x' or 'D' or 'd' or '1' or '2' or '3' or '4' or 'h' or 'H' or 'p' or '|' o + # r '_' marker = 'None' - - # the line width around the marker symbol + # a value of type 'float' markeredgewidth = 0.5 - - # markersize, in points + # a value of type 'float' markersize = 6.0 - - # miter|round|bevel - dash_joinstyle = 'miter' + # 'butt' or 'round' or 'projecting' + solid_capstyle = 'butt' + # 'miter' or 'round' or 'bevel' solid_joinstyle = 'miter' - - # butt|round|projecting - dash_capstyle = 'butt' - solid_capstyle = 'projecting' - - # render antialised lines (no jaggies) - antialiased = True [patch] - # Patches are graphical objects that fill 2D space, like polygons or - # circles. See - # http://matplotlib.sourceforge.net/matplotlib.patches.html for more - # information on patch properties - - # edge width in points - linewidth = 1.0 - - facecolor = 'blue' - edgecolor = 'black' - - # render antialised lines (no jaggies) + # a value of type 'bool' antialiased = True + # any valid matplotlib color, eg an abbreviation like 'r' for red, a full + # name like 'orange', a hex color like '#efefef', a grayscale intensity + # like '0.5', or an RGBA tuple (1,0,0,1) + edgecolor = 'black' + # any valid matplotlib color, eg an abbreviation like 'r' for red, a full + # name like 'orange', a hex color like '#efefef', a grayscale intensity + # like '0.5', or an RGBA tuple (1,0,0,1) + facecolor = 'blue' + # a value of type 'float' + linewidth = 1.0 -[font] - # font properties used by text.Text. See - # http://matplotlib.sourceforge.net/matplotlib.font_manager.html for more - # information on font properties. The 6 font properties used for font - # matching are given below with their default values. - # - # The font.family property has five values: 'serif' (e.g. Times), - # 'sans-serif' (e.g. Helvetica), 'cursive' (e.g. Zapf-Chancery), - # 'fantasy' (e.g. Western), and 'monospace' (e.g. Courier). Each of - # these font families has a default list of font names in decreasing - # order of priority associated with them. - family = 'sans-serif' - - # The font.style property has three values: normal (or roman), italic - # or oblique. The oblique style will be used for italic, if it is not - # present. - style = 'normal' - - # The font.variant property has two values: normal or small-caps. For - # TrueType fonts, which are scalable fonts, small-caps is equivalent - # to using a font size of 'smaller', or about 83% of the current font - # size. - variant = 'normal' - - # The font.weight property has effectively 13 values= normal, bold, - # bolder, lighter, 100, 200, 300, ..., 900. Normal is the same as - # 400, and bold is 700. bolder and lighter are relative values with - # respect to the current weight. - weight = 'normal' - - # The font.stretch property has 11 values: ultra-condensed, - # extra-condensed, condensed, semi-condensed, normal, semi-expanded, - # expanded, extra-expanded, ultra-expanded, wider, and narrower. This - # property is not currently implemented. - stretch = 'normal' - - # The font.size property is the default font size for text, given in pts. - # 12pt is the standard value. - # - # Note that font.size controls default text sizes. To configure - # special text sizes tick labels, axes, labels, title, etc, see the rc - # settings for axes and ticks. Special text sizes can be defined - # relative to font.size, using the following values: xx-small, x-small, - # small, medium, large, x-large, xx-large, larger, or smaller - size = 12.0 - - # A search list for each of the font families - serif = ['Bitstream Vera Serif', 'New Century Schoolbook', 'Century Schoolbook L', 'Utopia', 'ITC Bookman', 'Bookman', 'Nimbus Roman No9 L', 'Times New Roman', 'Times', 'Palatino', 'Charter', 'serif'] - sans_serif = ['Bitstream Vera Sans', 'Lucida Grande', 'Verdana', 'Geneva', 'Lucid', 'Arial', 'Helvetica', 'Avant Garde', 'sans-serif'] - cursive = ['Apple Chancery', 'Textile', 'Zapf Chancery', 'Sand', 'cursive'] - fantasy = ['Comic Sans MS', 'Chicago', 'Charcoal', 'Impact', 'Western', 'fantasy'] - monospace = ['Bitstream Vera Sans Mono', 'Andale Mono', 'Nimbus Mono L', 'Courier New', 'Courier', 'Fixed', 'Terminal', 'monospace'] +[savefig] + # a value of type 'float' + dpi = 100.0 + # any valid matplotlib color, eg an abbreviation like 'r' for red, a full + # name like 'orange', a hex color like '#efefef', a grayscale intensity + # like '0.5', or an RGBA tuple (1,0,0,1) + edgecolor = 'white' + # any valid matplotlib color, eg an abbreviation like 'r' for red, a full + # name like 'orange', a hex color like '#efefef', a grayscale intensity + # like '0.5', or an RGBA tuple (1,0,0,1) + facecolor = 'white' + # 'portrait' or 'landscape' + orientation = 'portrait' [text] - # text properties used by text.Text. See - # http://matplotlib.sourceforge.net/matplotlib.text.html for more - # information on text properties + # any valid matplotlib color, eg an abbreviation like 'r' for red, a full + # name like 'orange', a hex color like '#efefef', a grayscale intensity + # like '0.5', or an RGBA tuple (1,0,0,1) color = 'black' - - ### LaTeX customizations - # See http://www.scipy.org/Wiki/Cookbook/Matplotlib/UsingTex - - # use latex for all text handling. The following fonts - # are supported through the usual rc parameter settings: - # new century schoolbook, bookman, times, palatino, - # zapf chancery, charter, serif, sans-serif, helvetica, - # avant garde, courier, monospace, computer modern roman, - # computer modern sans serif, computer modern typewriter - # If another font is desired which can loaded using the - # LaTeX \usepackage command, please inquire at the - # matplotlib mailing list + # a value of type 'bool' usetex = False - + [[latex]] - # use "ucs" and "inputenc" LaTeX packages for - # handling unicode strings. - unicode = False - - # IMPROPER USE OF THE PREAMBLE WILL LEAD TO LATEX - # FAILURES AND IS THEREFORE UNSUPPORTED. PLEASE DO NOT - # ASK FOR HELP IF THIS FEATURE DOES NOT DO WHAT YOU - # EXPECT IT TO. - # preamble is a comma separated list of LaTeX - # statements that are included in the LaTeX document - # preamble. - # An example: - # text.latex.preamble = ["\usepackage{bm}", "\usepackage{euler}"] - # The following packages are always loaded with usetex, - # so beware of package collisions: color, geometry, - # graphicx, type1cm, textcomp. Adobe Postscript - # (PSSNFS) font packages may also be loaded, depending - # on your font settings - preamble = [] - - # some versions of dvipng don't handle alpha channel properly. - # Use True to correct and flush ~/.matplotlib/tex.cache before - # testing + # a value of type 'bool' dvipnghack = False + # a list of items each of which is a value of type 'str' + preamble = [] + # a value of type 'bool' + unicode = False -[axes] - # default face and edge color, default tick sizes, - # default fontsizes for ticklabels, and so on. See - # http://matplotlib.sourceforge.net/matplotlib.axes.html#Axes - - # whether to clear the axes by default - hold = True - - # axes background color - facecolor = 'white' - - # axes edge color - edgecolor = 'black' - - # edge linewidth - linewidth = 1.0 - - # display grid on regular or polar axes - grid = False - polargrid = True - - # fontsize of the axes title and labels - titlesize = 'large' - labelsize = 'medium' - - labelcolor = 'black' - - # whether axis gridlines and ticks are below the axes elements - # (lines, text, etc) - axisbelow = False - - [[formatter]] - # use scientific notation if log10 of the axis range is smaller - # than the first or larger than the second - limits = [-7.0, 7.0] + [[math]] + # a value of type 'str' + cal = 'cmsy10.ttf' + # a value of type 'str' + it = 'cmmi10.ttf' + # a value of type 'bool' + mathtext2 = False + # a value of type 'str' + mit = 'cmmi10.ttf' + # a value of type 'str' + nonascii = 'cmex10.ttf' + # a value of type 'str' + rm = 'cmr10.ttf' + # a value of type 'str' + tt = 'cmtt10.ttf' +[verbose] + # a value of type 'str' or a value of type 'unicode' or 'sys.stdout' + fileo = 'sys.stdout' + # 'silent' or 'helpful' or 'debug' or 'debug-annoying' + level = 'silent' + [xticks] - # see http://matplotlib.sourceforge.net/matplotlib.axis.html#Ticks - color = 'k' - labelsize = 'small' - - # direction: in or out + # any valid matplotlib color, eg an abbreviation like 'r' for red, a full + # name like 'orange', a hex color like '#efefef', a grayscale intensity + # like '0.5', or an RGBA tuple (1,0,0,1) + color = 'black' + # 'in' or 'out' direction = 'in' - + # a value of type 'float' or 'xx-small' or 'x-small' or 'small' or 'medium' + # or 'large' or 'x-large' or 'xx-large' + labelsize = 'small' + [[major]] - # in points - size = 4.0 + # a value of type 'float' pad = 4.0 - + # a value of type 'float' + size = 4.0 + [[minor]] - # in points - size = 2.0 + # a value of type 'float' pad = 4.0 + # a value of type 'float' + size = 2.0 [yticks] - color = 'k' - labelsize = 'small' - - # direction: in or out + # any valid matplotlib color, eg an abbreviation like 'r' for red, a full + # name like 'orange', a hex color like '#efefef', a grayscale intensity + # like '0.5', or an RGBA tuple (1,0,0,1) + color = 'black' + # 'in' or 'out' direction = 'in' - + # a value of type 'float' or 'xx-small' or 'x-small' or 'small' or 'medium' + # or 'large' or 'x-large' or 'xx-large' + labelsize = 'small' + [[major]] - # in points - size = 4.0 + # a value of type 'float' pad = 4.0 - + # a value of type 'float' + size = 4.0 + [[minor]] - # in points - size = 2.0 + # a value of type 'float' pad = 4.0 - -[grid] - color = 'black' - - # '-','--','-.', ':', 'steps', '', ' ', or None - linestyle = ':' - - linewidth = 0.5 - -[legend] - loc = 'upper right' - - isaxes = True - - # the number of points in the legend line - numpoints = 2 - - fontsize = 'medium' - - # the fractional whitespace inside the legend border - pad = 0.20000000000000001 - - # the relative size of legend markers vs. original - # the following dimensions are in axes coords - markerscale = 1.0 - - # the vertical space between the legend entries - labelsep = 0.01 - - # the length of the legend lines - handlelen = 0.050000000000000003 - - # the space between the legend line and legend text - handletextsep = 0.02 - - # the border between the axes and legend edge - axespad = 0.02 - - # Show a shadow behind the legend - shadow = False - -[figure] - # See http://matplotlib.sourceforge.net/matplotlib.figure.html#Figure - - # figure size in inches - figsize = [8.0, 6.0] - - # figure dots per inch - dpi = 80.0 - - # figure face and edge colors; '0.75' is scalar gray - facecolor = '0.75' - edgecolor = 'white' - - [[subplot]] - # The figure subplot parameters. All dimensions are fraction of the - # figure width or height - left = 0.125 - right = 0.90000000000000002 - bottom = 0.10000000000000001 - top = 0.90000000000000002 - - # the amount of width or height reserved for blank space between - #subplots - wspace = 0.20000000000000001 - hspace = 0.20000000000000001 - - -[image] - # equal | auto | a number - aspect = 'equal' - - # see help(imshow) for options - interpolation = 'bilinear' - cmap = 'jet' - - # the size of the colormap lookup table - lut = 256 - - # 'lower' or 'upper' - origin = 'upper' - - -[contour] - # 'dashed' or 'solid' - negative_linestyle = 'dashed' - -[savefig] - # Saving figures - # the default savefig params can be different for the GUI backends. - # Eg, you may want a higher resolution, or to make the figure - # background white - - # figure dots per inch - dpi = 100.0 - - # figure face and edge colors - facecolor = 'white' - edgecolor = 'white' - orientation = 'portrait' - -[verbose] - # Set the verbose flags. This controls how much information - # matplotlib gives you at runtime and where it goes. The verbosity - # levels are: silent, helpful, debug, debug-annoying. Any level is - # inclusive of all the levels below it. If you setting is debug, - # you'll get all the debug and helpful messages. When submitting - # problems to the mailing-list, please set verbose to helpful or debug - # and paste the output into your report. - # - # The fileo gives the destination for any calls to verbose.report. - # These objects can a filename, or a filehandle like sys.stdout. - # - # You can override the rc default verbosity from the command line by - # giving the flags --verbose-LEVEL where LEVEL is one of the legal - # levels, eg --verbose-helpful. - # - # You can access the verbose instance in your code - # from matplotlib import verbose. - - # 'silent', 'helpful', 'debug', or 'debug-annoying' - level = 'silent' - - # a log filename, 'sys.stdout' or 'sys.stderr' - fileo = 'sys.stdout' + # a value of type 'float' + size = 2.0 \ No newline at end of file Added: trunk/matplotlib/lib/matplotlib/mpl-data/matplotlib.conf.backup =================================================================== --- trunk/matplotlib/lib/matplotlib/mpl-data/matplotlib.conf.backup (rev 0) +++ trunk/matplotlib/lib/matplotlib/mpl-data/matplotlib.conf.backup 2007年07月31日 14:05:01 UTC (rev 3645) @@ -0,0 +1,456 @@ +### MATPLOTLIBRC FORMAT + +# This is a sample matplotlib configuration file. It should be placed +# in HOME/.matplotlib/matplotlibrc (unix/linux like systems) and +# C:\Documents and Settings\yourname\.matplotlib (win32 systems) +# +# By default, the installer will overwrite the existing file in the +# install path, so if you want to preserve your's, please move it to +# your HOME dir and set the environment variable if necessary. +# +# This file is best viewed in a editor which supports ini or conf mode +# syntax highlighting +# +# Blank lines, or lines starting with a comment symbol, are ignored, +# as are trailing comments. Other lines must have the format +# +# key = val # optional comment +# +# val should be valid python syntax, just as you would use when setting +# properties using rcParams. This should become more obvious by inspecting +# the default values listed herein. +# +# Colors: for the color values below, you can either use +# - a matplotlib color string, such as r, k, or b +# - an rgb tuple, such as (1.0, 0.5, 0.0) +# - a hex string, such as #ff00ff or ff00ff +# - a scalar grayscale intensity such as 0.75 +# - a legal html color name, eg red, blue, darkslategray + +#### CONFIGURATION BEGINS HERE + +# numpy, Numeric or numarray +numerix = 'numpy' + +# True to use external maskedarray module instead of numpy.ma; this is a +# temporary setting for testing maskedarray. +maskedarray = False + +# see http://matplotlib.sourceforge.net/interactive.html +interactive = False + +# None | classic | toolbar2 +toolbar = 'toolbar2' + +# a pytz timezone string, eg US/Central or Europe/Paris +timezone = 'UTC' + +units = False + +# Where your matplotlib data lives if you installed to a non-default +#location. This is where the matplotlib fonts, bitmaps, etc reside +#datapath = '/home/fperez/.matplotlib' + +#bogus = 1 +#[bogus_section] +# foo = 1 + +[backend] + + #[[bogus_subsection]] + # bar =1 + + # 'GTKAgg', 'GTKCairo', 'QtAgg', 'Qt4Agg', 'TkAgg', 'Agg', + # 'Cairo', 'PS', 'PDF', 'SVG' + use = 'TkAgg' + + [[cairo]] + # png, ps, pdf, svg + format = 'png' + + [[tk]] + # Maintain shell focus for TkAgg + window_focus = False + + # tk sets PYTHONINSEPCT + pythoninspect = False + + [[ps]] + # auto, letter, legal, ledger, A0-A10, B0-B10 + papersize = 'letter' + + # use of afm fonts, results in smaller files + useafm = False + + # 3 (Type3) or 42 (TrueType) + fonttype = 3 + + [[[distiller]]] + # can be: None, ghostscript or xpdf + # xpdf intended for production of publication quality + # files, but requires ghostscript, xpdf and ps2eps + use = None + + # distiller resolution, dpi + resolution = 6000.0 + + [[pdf]] + # integer from 0 to 9 + # 0 disables compression (good for debugging) + compression = 6 + + # 3 (Type3) or 42 (TrueType) + fonttype = 3 + + [[svg]] + # write raster image data directly into the svg file + image_inline = True + + # suppress scaling of raster data embedded in SVG + image_noscale = False + + # embed character outlines in the SVG file + embed_chars = False + +[lines] + # See http://matplotlib.sourceforge.net/matplotlib.lines.html for more + # information on line properties. + + # line width in points + linewidth = 1.0 + + # '-','--','-.', ':', 'steps', '', ' ', or None + linestyle = '-' + + color = 'blue' + + # The default marker: 'None', 'o', '.', ',', '^', 'v', '<', '>', 's', '+', + # 'x', 'D', 'd', '1', '2', '3', '4', 'h', 'H', 'p', '|', '_' + marker = 'None' + + # the line width around the marker symbol + markeredgewidth = 0.5 + + # markersize, in points + markersize = 6.0 + + # miter|round|bevel + dash_joinstyle = 'miter' + solid_joinstyle = 'miter' + + # butt|round|projecting + dash_capstyle = 'butt' + solid_capstyle = 'projecting' + + # render antialised lines (no jaggies) + antialiased = True + +[patch] + # Patches are graphical objects that fill 2D space, like polygons or + # circles. See + # http://matplotlib.sourceforge.net/matplotlib.patches.html for more + # information on patch properties + + # edge width in points + linewidth = 1.0 + + facecolor = 'blue' + edgecolor = 'black' + + # render antialised lines (no jaggies) + antialiased = True + +[font] + # font properties used by text.Text. See + # http://matplotlib.sourceforge.net/matplotlib.font_manager.html for more + # information on font properties. The 6 font properties used for font + # matching are given below with their default values. + # + # The font.family property has five values: 'serif' (e.g. Times), + # 'sans-serif' (e.g. Helvetica), 'cursive' (e.g. Zapf-Chancery), + # 'fantasy' (e.g. Western), and 'monospace' (e.g. Courier). Each of + # these font families has a default list of font names in decreasing + # order of priority associated with them. + family = 'sans-serif' + + # The font.style property has three values: normal (or roman), italic + # or oblique. The oblique style will be used for italic, if it is not + # present. + style = 'normal' + + # The font.variant property has two values: normal or small-caps. For + # TrueType fonts, which are scalable fonts, small-caps is equivalent + # to using a font size of 'smaller', or about 83% of the current font + # size. + variant = 'normal' + + # The font.weight property has effectively 13 values= normal, bold, + # bolder, lighter, 100, 200, 300, ..., 900. Normal is the same as + # 400, and bold is 700. bolder and lighter are relative values with + # respect to the current weight. + weight = 'normal' + + # The font.stretch property has 11 values: ultra-condensed, + # extra-condensed, condensed, semi-condensed, normal, semi-expanded, + # expanded, extra-expanded, ultra-expanded, wider, and narrower. This + # property is not currently implemented. + stretch = 'normal' + + # The font.size property is the default font size for text, given in pts. + # 12pt is the standard value. + # + # Note that font.size controls default text sizes. To configure + # special text sizes tick labels, axes, labels, title, etc, see the rc + # settings for axes and ticks. Special text sizes can be defined + # relative to font.size, using the following values: xx-small, x-small, + # small, medium, large, x-large, xx-large, larger, or smaller + size = 12.0 + + # A search list for each of the font families + serif = ['Bitstream Vera Serif', 'New Century Schoolbook', 'Century Schoolbook L', 'Utopia', 'ITC Bookman', 'Bookman', 'Nimbus Roman No9 L', 'Times New Roman', 'Times', 'Palatino', 'Charter', 'serif'] + sans_serif = ['Bitstream Vera Sans', 'Lucida Grande', 'Verdana', 'Geneva', 'Lucid', 'Arial', 'Helvetica', 'Avant Garde', 'sans-serif'] + cursive = ['Apple Chancery', 'Textile', 'Zapf Chancery', 'Sand', 'cursive'] + fantasy = ['Comic Sans MS', 'Chicago', 'Charcoal', 'Impact', 'Western', 'fantasy'] + monospace = ['Bitstream Vera Sans Mono', 'Andale Mono', 'Nimbus Mono L', 'Courier New', 'Courier', 'Fixed', 'Terminal', 'monospace'] + +[text] + # text properties used by text.Text. See + # http://matplotlib.sourceforge.net/matplotlib.text.html for more + # information on text properties + color = 'black' + + ### LaTeX customizations + # See http://www.scipy.org/Wiki/Cookbook/Matplotlib/UsingTex + + # use latex for all text handling. The following fonts + # are supported through the usual rc parameter settings: + # new century schoolbook, bookman, times, palatino, + # zapf chancery, charter, serif, sans-serif, helvetica, + # avant garde, courier, monospace, computer modern roman, + # computer modern sans serif, computer modern typewriter + # If another font is desired which can loaded using the + # LaTeX \usepackage command, please inquire at the + # matplotlib mailing list + usetex = False + + [[latex]] + # use "ucs" and "inputenc" LaTeX packages for + # handling unicode strings. + unicode = False + + # IMPROPER USE OF THE PREAMBLE WILL LEAD TO LATEX + # FAILURES AND IS THEREFORE UNSUPPORTED. PLEASE DO NOT + # ASK FOR HELP IF THIS FEATURE DOES NOT DO WHAT YOU + # EXPECT IT TO. + # preamble is a comma separated list of LaTeX + # statements that are included in the LaTeX document + # preamble. + # An example: + # text.latex.preamble = ["\usepackage{bm}", "\usepackage{euler}"] + # The following packages are always loaded with usetex, + # so beware of package collisions: color, geometry, + # graphicx, type1cm, textcomp. Adobe Postscript + # (PSSNFS) font packages may also be loaded, depending + # on your font settings + preamble = [] + + # some versions of dvipng don't handle alpha channel properly. + # Use True to correct and flush ~/.matplotlib/tex.cache before + # testing + dvipnghack = False + +[axes] + # default face and edge color, default tick sizes, + # default fontsizes for ticklabels, and so on. See + # http://matplotlib.sourceforge.net/matplotlib.axes.html#Axes + + # whether to clear the axes by default + hold = True + + # axes background color + facecolor = 'white' + + # axes edge color + edgecolor = 'black' + + # edge linewidth + linewidth = 1.0 + + # display grid on regular or polar axes + grid = False + polargrid = True + + # fontsize of the axes title and labels + titlesize = 'large' + labelsize = 'medium' + + labelcolor = 'black' + + # whether axis gridlines and ticks are below the axes elements + # (lines, text, etc) + axisbelow = False + + [[formatter]] + # use scientific notation if log10 of the axis range is smaller + # than the first or larger than the second + limits = [-7.0, 7.0] + +[xticks] + # see http://matplotlib.sourceforge.net/matplotlib.axis.html#Ticks + color = 'k' + labelsize = 'small' + + # direction: in or out + direction = 'in' + + [[major]] + # in points + size = 4.0 + pad = 4.0 + + [[minor]] + # in points + size = 2.0 + pad = 4.0 + +[yticks] + color = 'k' + labelsize = 'small' + + # direction: in or out + direction = 'in' + + [[major]] + # in points + size = 4.0 + pad = 4.0 + + [[minor]] + # in points + size = 2.0 + pad = 4.0 + +[grid] + color = 'black' + + # '-','--','-.', ':', 'steps', '', ' ', or None + linestyle = ':' + + linewidth = 0.5 + +[legend] + loc = 'upper right' + + isaxes = True + + # the number of points in the legend line + numpoints = 2 + + fontsize = 'medium' + + # the fractional whitespace inside the legend border + pad = 0.20000000000000001 + + # the relative size of legend markers vs. original + # the following dimensions are in axes coords + markerscale = 1.0 + + # the vertical space between the legend entries + labelsep = 0.01 + + # the length of the legend lines + handlelen = 0.050000000000000003 + + # the space between the legend line and legend text + handletextsep = 0.02 + + # the border between the axes and legend edge + axespad = 0.02 + + # Show a shadow behind the legend + shadow = False + +[figure] + # See http://matplotlib.sourceforge.net/matplotlib.figure.html#Figure + + # figure size in inches + figsize = [8.0, 6.0] + + # figure dots per inch + dpi = 80.0 + + # figure face and edge colors; '0.75' is scalar gray + facecolor = '0.75' + edgecolor = 'white' + + [[subplot]] + # The figure subplot parameters. All dimensions are fraction of the + # figure width or height + left = 0.125 + right = 0.90000000000000002 + bottom = 0.10000000000000001 + top = 0.90000000000000002 + + # the amount of width or height reserved for blank space between + #subplots + wspace = 0.20000000000000001 + hspace = 0.20000000000000001 + + +[image] + # equal | auto | a number + aspect = 'equal' + + # see help(imshow) for options + interpolation = 'bilinear' + cmap = 'jet' + + # the size of the colormap lookup table + lut = 256 + + # 'lower' or 'upper' + origin = 'upper' + + +[contour] + # 'dashed' or 'solid' + negative_linestyle = 'dashed' + +[savefig] + # Saving figures + # the default savefig params can be different for the GUI backends. + # Eg, you may want a higher resolution, or to make the figure + # background white + + # figure dots per inch + dpi = 100.0 + + # figure face and edge colors + facecolor = 'white' + edgecolor = 'white' + orientation = 'portrait' + +[verbose] + # Set the verbose flags. This controls how much information + # matplotlib gives you at runtime and where it goes. The verbosity + # levels are: silent, helpful, debug, debug-annoying. Any level is + # inclusive of all the levels below it. If you setting is debug, + # you'll get all the debug and helpful messages. When submitting + # problems to the mailing-list, please set verbose to helpful or debug + # and paste the output into your report. + # + # The fileo gives the destination for any calls to verbose.report. + # These objects can a filename, or a filehandle like sys.stdout. + # + # You can override the rc default verbosity from the command line by + # giving the flags --verbose-LEVEL where LEVEL is one of the legal + # levels, eg --verbose-helpful. + # + # You can access the verbose instance in your code + # from matplotlib import verbose. + + # 'silent', 'helpful', 'debug', or 'debug-annoying' + level = 'silent' + + # a log filename, 'sys.stdout' or 'sys.stderr' + fileo = 'sys.stdout' This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
Revision: 3644 http://matplotlib.svn.sourceforge.net/matplotlib/?rev=3644&view=rev Author: dsdale Date: 2007年07月31日 06:11:34 -0700 (2007年7月31日) Log Message: ----------- mplconfig was not reading .conf file in mpl-data Modified Paths: -------------- trunk/matplotlib/lib/matplotlib/config/cutils.py trunk/matplotlib/lib/matplotlib/config/mplconfig.py trunk/matplotlib/lib/matplotlib/mpl-data/matplotlib.conf Modified: trunk/matplotlib/lib/matplotlib/config/cutils.py =================================================================== --- trunk/matplotlib/lib/matplotlib/config/cutils.py 2007年07月31日 06:53:07 UTC (rev 3643) +++ trunk/matplotlib/lib/matplotlib/config/cutils.py 2007年07月31日 13:11:34 UTC (rev 3644) @@ -172,7 +172,7 @@ return fname fname = os.path.join(get_configdir(), filename) - if os.path.exists(fname) or tconfig: return fname + if os.path.exists(fname): return fname path = get_data_path() # guaranteed to exist or raise Modified: trunk/matplotlib/lib/matplotlib/config/mplconfig.py =================================================================== --- trunk/matplotlib/lib/matplotlib/config/mplconfig.py 2007年07月31日 06:53:07 UTC (rev 3643) +++ trunk/matplotlib/lib/matplotlib/config/mplconfig.py 2007年07月31日 13:11:34 UTC (rev 3644) @@ -15,6 +15,7 @@ import pytz # Code begins +DEBUG = False ############################################################################## # Main Config class follows @@ -172,7 +173,7 @@ facecolor = T.Trait('white', mplT.ColorHandler()) edgecolor = T.Trait('black', mplT.ColorHandler()) linewidth = T.Float(1.0) - grid = T.Trait(True, mplT.BoolHandler()) + grid = T.Trait(False, mplT.BoolHandler()) polargrid = T.Trait(True, mplT.BoolHandler()) titlesize = T.Trait('large', 'xx-small', 'x-small', 'small', 'medium', 'large', 'x-large', 'xx-large', T.Float) @@ -467,6 +468,8 @@ config_file = cutils.get_config_file(tconfig=True) CONVERT = False +if DEBUG: print 'loading', config_file + configManager = TConfigManager(MPLConfig, config_file, filePriority=True) Modified: trunk/matplotlib/lib/matplotlib/mpl-data/matplotlib.conf =================================================================== --- trunk/matplotlib/lib/matplotlib/mpl-data/matplotlib.conf 2007年07月31日 06:53:07 UTC (rev 3643) +++ trunk/matplotlib/lib/matplotlib/mpl-data/matplotlib.conf 2007年07月31日 13:11:34 UTC (rev 3644) @@ -124,9 +124,9 @@ color = 'blue' - # The default marker: None, 'o', '.', ',', '^', 'v', '<', '>', 's', '+', + # The default marker: 'None', 'o', '.', ',', '^', 'v', '<', '>', 's', '+', # 'x', 'D', 'd', '1', '2', '3', '4', 'h', 'H', 'p', '|', '_' - marker = None + marker = 'None' # the line width around the marker symbol markeredgewidth = 0.5 This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
Revision: 3643 http://matplotlib.svn.sourceforge.net/matplotlib/?rev=3643&view=rev Author: fer_perez Date: 2007年07月30日 23:53:07 -0700 (2007年7月30日) Log Message: ----------- Put in changes that for some reason SVN was not seeing in my local copy. Problem reported by Stefan Modified Paths: -------------- trunk/py4science/examples/spline_demo.py Modified: trunk/py4science/examples/spline_demo.py =================================================================== --- trunk/py4science/examples/spline_demo.py 2007年07月30日 23:22:48 UTC (rev 3642) +++ trunk/py4science/examples/spline_demo.py 2007年07月31日 06:53:07 UTC (rev 3643) @@ -10,13 +10,19 @@ tfine = N.arange(0.0, 5, 0.01) tcoarse = N.arange(0.0, 5, 0.1) -s = N.cos(N.pi*tcoarse) * N.sin(2*N.pi*tcoarse) +def func(t): + return N.cos(N.pi*t) * N.sin(2*N.pi*t) # create sinterp by computing the spline fitting tcoarse to s and then -evaluating it on tfine. Plot tcoarse vs s with markers and tfine vs -sinterp with a solid line +# evaluating it on tfine. Plot tcoarse vs s with markers and tfine vs +# sinterp with a solid line +s = func(tcoarse) + tck = interpolate.splrep(tcoarse, s, s=0) sinterp = interpolate.splev(tfine, tck, der=0) -P.plot(tcoarse, s, 'o', tfine, sinterp) +P.plot(tcoarse, s, 'o', label='coarse') +P.plot(tfine, sinterp, '+', label='fit') +P.plot(tfine, func(tfine), '-', label='actual') +P.legend() P.show() This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
Revision: 3642 http://matplotlib.svn.sourceforge.net/matplotlib/?rev=3642&view=rev Author: dsdale Date: 2007年07月30日 16:22:48 -0700 (2007年7月30日) Log Message: ----------- minor change to mplconfig module Modified Paths: -------------- trunk/matplotlib/lib/matplotlib/config/mplconfig.py trunk/matplotlib/lib/matplotlib/mpl-data/matplotlibrc Modified: trunk/matplotlib/lib/matplotlib/config/mplconfig.py =================================================================== --- trunk/matplotlib/lib/matplotlib/config/mplconfig.py 2007年07月30日 23:05:06 UTC (rev 3641) +++ trunk/matplotlib/lib/matplotlib/config/mplconfig.py 2007年07月30日 23:22:48 UTC (rev 3642) @@ -214,7 +214,7 @@ class grid(TConfig): color = T.Trait('black', mplT.ColorHandler()) - linestyle = T.Trait('-','--','-.', ':', 'steps', '', ' ') + linestyle = T.Trait(':','-','--','-.', ':', 'steps', '', ' ') linewidth = T.Float(0.5) class legend(TConfig): Modified: trunk/matplotlib/lib/matplotlib/mpl-data/matplotlibrc =================================================================== --- trunk/matplotlib/lib/matplotlib/mpl-data/matplotlibrc 2007年07月30日 23:05:06 UTC (rev 3641) +++ trunk/matplotlib/lib/matplotlib/mpl-data/matplotlibrc 2007年07月30日 23:22:48 UTC (rev 3642) @@ -243,7 +243,6 @@ #savefig.dpi : 100 # figure dots per inch #savefig.facecolor : white # figure facecolor when saving #savefig.edgecolor : white # figure edgecolor when saving -#savefig.orientation : portrait # portrait or landscape #cairo.format : png # png, ps, pdf, svg This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
Revision: 3641 http://matplotlib.svn.sourceforge.net/matplotlib/?rev=3641&view=rev Author: efiring Date: 2007年07月30日 16:05:06 -0700 (2007年7月30日) Log Message: ----------- bar plotting patch by Michael Forbes Modified Paths: -------------- trunk/matplotlib/lib/matplotlib/axes.py Modified: trunk/matplotlib/lib/matplotlib/axes.py =================================================================== --- trunk/matplotlib/lib/matplotlib/axes.py 2007年07月30日 21:41:09 UTC (rev 3640) +++ trunk/matplotlib/lib/matplotlib/axes.py 2007年07月30日 23:05:06 UTC (rev 3641) @@ -3557,7 +3557,21 @@ barcols = [] caplines = [] + lines_kw = {'label':'_nolegend_'} + if 'linewidth' in kwargs: + lines_kw['linewidth']=kwargs['linewidth'] + if 'lw' in kwargs: + lines_kw['lw']=kwargs['lw'] + if capsize > 0: + plot_kw = { + 'ms':2*capsize, + 'label':'_nolegend_'} + if 'markeredgewidth' in kwargs: + plot_kw['markeredgewidth']=kwargs['markeredgewidth'] + if 'mew' in kwargs: + plot_kw['mew']=kwargs['mew'] + if xerr is not None: if len(xerr.shape) == 1: left = x-xerr @@ -3566,12 +3580,10 @@ left = x-xerr[0] right = x+xerr[1] - barcols.append( self.hlines(y, left, right, label='_nolegend_' )) + barcols.append( self.hlines(y, left, right, **lines_kw ) ) if capsize > 0: - caplines.extend( - self.plot(left, y, 'k|', ms=2*capsize, label='_nolegend_') ) - caplines.extend( - self.plot(right, y, 'k|', ms=2*capsize, label='_nolegend_') ) + caplines.extend( self.plot(left, y, 'k|', **plot_kw) ) + caplines.extend( self.plot(right, y, 'k|', **plot_kw) ) if yerr is not None: if len(yerr.shape) == 1: @@ -3581,21 +3593,8 @@ lower = y-yerr[0] upper = y+yerr[1] - vlines_kw = {'label':'_nolegend_'} - if 'linewidth' in kwargs: - vlines_kw['linewidth']=kwargs['linewidth'] - if 'lw' in kwargs: - vlines_kw['lw']=kwargs['lw'] - barcols.append( self.vlines(x, lower, upper, **vlines_kw) ) - + barcols.append( self.vlines(x, lower, upper, **lines_kw) ) if capsize > 0: - plot_kw = { - 'ms':2*capsize, - 'label':'_nolegend_'} - if 'markeredgewidth' in kwargs: - plot_kw['markeredgewidth']=kwargs['markeredgewidth'] - if 'mew' in kwargs: - plot_kw['mew']=kwargs['mew'] caplines.extend( self.plot(x, lower, 'k_', **plot_kw) ) caplines.extend( self.plot(x, upper, 'k_', **plot_kw) ) This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
Revision: 3640 http://matplotlib.svn.sourceforge.net/matplotlib/?rev=3640&view=rev Author: dsdale Date: 2007年07月30日 14:41:09 -0700 (2007年7月30日) Log Message: ----------- remove a print statement in mplconfig Modified Paths: -------------- trunk/matplotlib/lib/matplotlib/config/mplconfig.py Modified: trunk/matplotlib/lib/matplotlib/config/mplconfig.py =================================================================== --- trunk/matplotlib/lib/matplotlib/config/mplconfig.py 2007年07月30日 21:37:11 UTC (rev 3639) +++ trunk/matplotlib/lib/matplotlib/config/mplconfig.py 2007年07月30日 21:41:09 UTC (rev 3640) @@ -462,7 +462,6 @@ config_file = os.path.join(old_config_path, 'matplotlib.conf') if os.path.exists(old_config_file) and not os.path.exists(config_file): - print 'convert!' CONVERT = True else: config_file = cutils.get_config_file(tconfig=True) This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
Revision: 3639 http://matplotlib.svn.sourceforge.net/matplotlib/?rev=3639&view=rev Author: dsdale Date: 2007年07月30日 14:37:11 -0700 (2007年7月30日) Log Message: ----------- install matplotlib.conf in mpl-data for config package Modified Paths: -------------- trunk/matplotlib/lib/matplotlib/mpl-data/matplotlib.conf trunk/matplotlib/setup.py Modified: trunk/matplotlib/lib/matplotlib/mpl-data/matplotlib.conf =================================================================== --- trunk/matplotlib/lib/matplotlib/mpl-data/matplotlib.conf 2007年07月30日 20:48:06 UTC (rev 3638) +++ trunk/matplotlib/lib/matplotlib/mpl-data/matplotlib.conf 2007年07月30日 21:37:11 UTC (rev 3639) @@ -49,7 +49,7 @@ # Where your matplotlib data lives if you installed to a non-default #location. This is where the matplotlib fonts, bitmaps, etc reside -datapath = '/home/fperez/.matplotlib' +#datapath = '/home/fperez/.matplotlib' #bogus = 1 #[bogus_section] @@ -62,7 +62,7 @@ # 'GTKAgg', 'GTKCairo', 'QtAgg', 'Qt4Agg', 'TkAgg', 'Agg', # 'Cairo', 'PS', 'PDF', 'SVG' - use = 'Qt4Agg' + use = 'TkAgg' [[cairo]] # png, ps, pdf, svg @@ -453,4 +453,4 @@ level = 'silent' # a log filename, 'sys.stdout' or 'sys.stderr' - fileo = 'sys.stdout' \ No newline at end of file + fileo = 'sys.stdout' Modified: trunk/matplotlib/setup.py =================================================================== --- trunk/matplotlib/setup.py 2007年07月30日 20:48:06 UTC (rev 3638) +++ trunk/matplotlib/setup.py 2007年07月30日 21:37:11 UTC (rev 3639) @@ -93,6 +93,7 @@ 'mpl-data/images/*.png', 'mpl-data/images/*.ppm', 'mpl-data/matplotlibrc', + 'mpl-data/matplotlib.conf', 'mpl-data/*.glade', 'backends/Matplotlib.nib/*', ]} This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
Revision: 3638 http://matplotlib.svn.sourceforge.net/matplotlib/?rev=3638&view=rev Author: mdboom Date: 2007年07月30日 13:48:06 -0700 (2007年7月30日) Log Message: ----------- Improve vertical alignment of large delimiters and n-ary operators. Modified Paths: -------------- trunk/matplotlib/lib/matplotlib/_mathtext_data.py trunk/matplotlib/lib/matplotlib/mathtext.py Modified: trunk/matplotlib/lib/matplotlib/_mathtext_data.py =================================================================== --- trunk/matplotlib/lib/matplotlib/_mathtext_data.py 2007年07月30日 20:45:09 UTC (rev 3637) +++ trunk/matplotlib/lib/matplotlib/_mathtext_data.py 2007年07月30日 20:48:06 UTC (rev 3638) @@ -2235,7 +2235,7 @@ 'biguplus': 10756, 'epsilon': 949, 'vartheta': 977, -'bigotimes': 10754 +'bigotimes': 10754 } uni2tex = dict([(v,k) for k,v in tex2uni.items()]) Modified: trunk/matplotlib/lib/matplotlib/mathtext.py =================================================================== --- trunk/matplotlib/lib/matplotlib/mathtext.py 2007年07月30日 20:45:09 UTC (rev 3637) +++ trunk/matplotlib/lib/matplotlib/mathtext.py 2007年07月30日 20:48:06 UTC (rev 3638) @@ -174,6 +174,13 @@ or a Type1 symbol name (i.e. 'phi'). """ + # From UTF #25: U+2212 − minus sign is the preferred + # representation of the unary and binary minus sign rather than + # the ASCII-derived U+002D - hyphen-minus, because minus sign is + # unambiguous and because it is rendered with a more desirable + # length, usually longer than a hyphen. + if symbol == '-': + return 0x2212 try:# This will succeed if symbol is a single unicode char return ord(symbol) except TypeError: @@ -484,7 +491,7 @@ offset = self._get_offset(cached_font, glyph, fontsize, dpi) metrics = Bunch( advance = glyph.linearHoriAdvance/65536.0, - height = glyph.height/64.0 + offset, + height = glyph.height/64.0, width = glyph.width/64.0, xmin = xmin, xmax = xmax, @@ -545,7 +552,7 @@ } def _get_offset(self, cached_font, glyph, fontsize, dpi): - if cached_font.font.postscript_name == 'cmex10': + if cached_font.font.postscript_name == 'Cmex10': return glyph.height/64.0/2 + 256.0/64.0 * dpi/72.0 return 0. @@ -577,8 +584,8 @@ ('ex', '\xbd'), ('ex', '\x28')], '}' : [('cal', '}'), ('ex', '\xaa'), ('ex', '\x6f'), ('ex', '\xbe'), ('ex', '\x29')], - # The fourth size of '[' is mysteriously missing from the BaKoMa font, - # so I've ommitted it for both + # The fourth size of '[' is mysteriously missing from the BaKoMa + # font, so I've ommitted it for both '[' and ']' '[' : [('rm', '['), ('ex', '\xa3'), ('ex', '\x68'), ('ex', '\x22')], ']' : [('rm', ']'), ('ex', '\xa4'), ('ex', '\x69'), @@ -839,7 +846,7 @@ INV_SHRINK_FACTOR = 1.0 / SHRINK_FACTOR # The number of different sizes of chars to use, beyond which they will not # get any smaller -NUM_SIZE_LEVELS = 3 +NUM_SIZE_LEVELS = 4 # Percentage of x-height of additional horiz. space after sub/superscripts SCRIPT_SPACE = 0.3 # Percentage of x-height that sub/superscripts drop below the baseline @@ -1650,7 +1657,7 @@ _punctuation_symbols = Set(r', ; . ! \ldotp \cdotp'.split()) _overunder_symbols = Set(r''' - \sum \int \prod \coprod \oint \bigcap \bigcup \bigsqcup \bigvee + \sum \prod \int \coprod \oint \bigcap \bigcup \bigsqcup \bigvee \bigwedge \bigodot \bigotimes \bigoplus \biguplus '''.split() ) @@ -1758,9 +1765,11 @@ ) + Optional( Suppress(Literal("[")) - + OneOrMore( - symbol - ^ font + + Group( + OneOrMore( + symbol + ^ font + ) ) + Suppress(Literal("]")), default = None @@ -1881,12 +1890,13 @@ #~ print "non_math", toks symbols = [Char(c, self.get_state()) for c in toks[0]] hlist = Hlist(symbols) + # We're going into math now, so set font to 'it' self.push_state() - # We're going into math now, so set font to 'it' self.get_state().font = 'it' return [hlist] def _make_space(self, percentage): + # All spaces are relative to em width state = self.get_state() metrics = state.font_output.get_metrics( state.font, 'm', state.fontsize, state.dpi) @@ -1910,12 +1920,12 @@ # print "symbol", toks c = toks[0] if c in self._spaced_symbols: - return [Hlist([self._make_space(0.3), - Char(c, self.get_state()), - self._make_space(0.3)])] + return [Hlist( [self._make_space(0.2), + Char(c, self.get_state()), + self._make_space(0.2)] )] elif c in self._punctuation_symbols: - return [Hlist([Char(c, self.get_state()), - self._make_space(0.3)])] + return [Hlist( [Char(c, self.get_state()), + self._make_space(0.2)] )] try: return [Char(toks[0], self.get_state())] except ValueError: @@ -1944,6 +1954,8 @@ state = self.get_state() thickness = state.font_output.get_underline_thickness( state.font, state.fontsize, state.dpi) + if len(toks[0]) != 2: + raise ParseFatalException("Error parsing accent") accent, sym = toks[0] accent = Accent(self._accent_map[accent], self.get_state()) centered = HCentered([accent]) @@ -2030,7 +2042,7 @@ super = next1 sub = next2 else: - raise ParseFatalException("Subscript/superscript string is too long.") + raise ParseFatalException("Subscript/superscript sequence is too long.") state = self.get_state() rule_thickness = state.font_output.get_underline_thickness( @@ -2052,17 +2064,17 @@ if super is not None: hlist = HCentered([super]) hlist.hpack(width, 'exactly') - vlist.extend([hlist, Vbox(0., rule_thickness * 2.0)]) + vlist.extend([hlist, Kern(rule_thickness * 2.0)]) hlist = HCentered([nucleus]) hlist.hpack(width, 'exactly') vlist.append(hlist) if sub is not None: hlist = HCentered([sub]) hlist.hpack(width, 'exactly') - vlist.extend([Vbox(0., rule_thickness), hlist]) + vlist.extend([Kern(rule_thickness * 2.0), hlist]) shift = hlist.height + hlist.depth + rule_thickness * 2.0 vlist = Vlist(vlist) - vlist.shift_amount = shift + vlist.shift_amount = shift + nucleus.depth * 0.5 result = Hlist([vlist]) return [result] @@ -2120,11 +2132,11 @@ width = max(num.width, den.width) + thickness * 10. cnum.hpack(width, 'exactly') cden.hpack(width, 'exactly') - vlist = Vlist([cnum, - Vbox(0, thickness * 2.0), - Hrule(state), - Vbox(0, thickness * 4.0), - cden + vlist = Vlist([cnum, # numerator + Vbox(0, thickness * 2.0), # space + Hrule(state), # rule + Vbox(0, thickness * 4.0), # space + cden # denominator ]) # Shift so the fraction line sits in the middle of the @@ -2149,35 +2161,42 @@ if root is None: root = Box() else: + if not isinstance(root, ParseResults): + raise ParseFatalException( + "Can not parse root of radical. Only simple symbols are allowed.") + root = Hlist(root.asList()) root.shrink() root.shrink() - # Add a little extra to the height so the body - # doesn't seem cramped + # Determine the height of the body, and add a little extra to + # the height so it doesn't seem cramped height = body.height - body.shift_amount + thickness * 5.0 depth = body.depth + body.shift_amount check = AutoSizedDelim(r'\sqrt', height, depth, state, always=True) - height = check.height - check.shift_amount depth = check.depth + check.shift_amount + + # Put a little extra space to the left and right of the body + padded_body = Hlist([Hbox(thickness * 2.0), + body, + Hbox(thickness * 2.0)]) rightside = Vlist([Hrule(state), Fill(), - # Pack a little extra to the left and right - # of the body - Hlist([Hbox(thickness * 2.0), - body, - Hbox(thickness * 2.0)])]) + padded_body]) # Stretch the glue between the hrule and the body rightside.vpack(height + 1.0, depth, 'exactly') + # Add the root and shift it upward so it is above the tick. + # The value of 0.6 is a hard-coded hack ;) root_vlist = Vlist([Hlist([root])]) root_vlist.shift_amount = -height * 0.6 - hlist = Hlist([root_vlist, - Kern(-check.width * 0.5), - check, - Kern(-thickness * 0.3), - rightside]) + hlist = Hlist([root_vlist, # Root + # Negative kerning to put root over tick + Kern(-check.width * 0.5), + check, # Check + Kern(-thickness * 0.3), # Push check into rule slightly + rightside]) # Body return [hlist] def auto_sized_delimiter(self, s, loc, toks): @@ -2187,6 +2206,7 @@ height = max([x.height for x in middle]) depth = max([x.depth for x in middle]) parts = [] + # \left. and \right. aren't supposed to produce any symbols if front != '.': parts.append(AutoSizedDelim(front, height, depth, state)) parts.extend(middle.asList()) This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
Revision: 3637 http://matplotlib.svn.sourceforge.net/matplotlib/?rev=3637&view=rev Author: mdboom Date: 2007年07月30日 13:45:09 -0700 (2007年7月30日) Log Message: ----------- Fix mathtext bug when svg.embed_char_paths is False Modified Paths: -------------- trunk/matplotlib/lib/matplotlib/backends/backend_svg.py Modified: trunk/matplotlib/lib/matplotlib/backends/backend_svg.py =================================================================== --- trunk/matplotlib/lib/matplotlib/backends/backend_svg.py 2007年07月30日 19:46:53 UTC (rev 3636) +++ trunk/matplotlib/lib/matplotlib/backends/backend_svg.py 2007年07月30日 20:45:09 UTC (rev 3637) @@ -375,7 +375,7 @@ new_y = - new_y_mtc svg.append('<tspan style="font-size: %f; font-family: %s"' % - (fontsize, fontname)) + (fontsize, font.family_name)) xadvance = metrics.advance svg.append(' textLength="%f"' % xadvance) This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
Revision: 3636 http://matplotlib.svn.sourceforge.net/matplotlib/?rev=3636&view=rev Author: mdboom Date: 2007年07月30日 12:46:53 -0700 (2007年7月30日) Log Message: ----------- Fix numpification typo affecting mathtext output with Cairo backend. Modified Paths: -------------- trunk/matplotlib/lib/matplotlib/backends/backend_cairo.py Modified: trunk/matplotlib/lib/matplotlib/backends/backend_cairo.py =================================================================== --- trunk/matplotlib/lib/matplotlib/backends/backend_cairo.py 2007年07月30日 18:57:09 UTC (rev 3635) +++ trunk/matplotlib/lib/matplotlib/backends/backend_cairo.py 2007年07月30日 19:46:53 UTC (rev 3636) @@ -335,7 +335,7 @@ Xall[:,i] = npy.fromstring(s, npy.uint8) # get the max alpha at each pixel - Xs = npy.mlab.max (Xall,1) + Xs = npy.max (Xall,1) # convert it to it's proper shape Xs.shape = imh, imw This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
Revision: 3635 http://matplotlib.svn.sourceforge.net/matplotlib/?rev=3635&view=rev Author: mdboom Date: 2007年07月30日 11:57:09 -0700 (2007年7月30日) Log Message: ----------- Improving spacing operators. Modified Paths: -------------- trunk/matplotlib/lib/matplotlib/mathtext.py Modified: trunk/matplotlib/lib/matplotlib/mathtext.py =================================================================== --- trunk/matplotlib/lib/matplotlib/mathtext.py 2007年07月30日 18:44:36 UTC (rev 3634) +++ trunk/matplotlib/lib/matplotlib/mathtext.py 2007年07月30日 18:57:09 UTC (rev 3635) @@ -1698,13 +1698,17 @@ space =(FollowedBy(bslash) + (Literal(r'\ ') | Literal(r'\/') - | Group(Literal(r'\hspace{') + number + Literal('}')) - ) + | Literal(r',円') + | Literal(r'\;') + | Literal(r'\quad') + | Literal(r'\qquad') + | Literal(r'\!') + ) ).setParseAction(self.space).setName('space') symbol = Regex("(" + ")|(".join( [ - r"\\(?!left[^a-z])(?!right[^a-z])[a-zA-Z0-9]+(?!{)", + r"\\(?!quad)(?!qquad)(?!left[^a-z])(?!right[^a-z])[a-zA-Z0-9]+(?!{)", r"[a-zA-Z0-9 ]", r"[+\-*/]", r"[<>=]", @@ -1794,7 +1798,7 @@ ambiDelim = oneOf(r"""| \| / \backslash \uparrow \downarrow \updownarrow \Uparrow \Downarrow - \Updownarrow""") + \Updownarrow .""") leftDelim = oneOf(r"( [ { \lfloor \langle \lceil") rightDelim = oneOf(r") ] } \rfloor \rangle \rceil") autoDelim <<(Suppress(Literal(r"\left")) @@ -1886,16 +1890,19 @@ state = self.get_state() metrics = state.font_output.get_metrics( state.font, 'm', state.fontsize, state.dpi) - em = metrics.width - return Hbox(em * percentage) - + em = metrics.advance + return Kern(em * percentage) + + _space_widths = { r'\ ' : 0.3, + r',円' : 0.4, + r'\;' : 0.8, + r'\quad' : 1.6, + r'\qquad' : 3.2, + r'\!' : -0.4, + r'\/' : 0.4 } def space(self, s, loc, toks): assert(len(toks)==1) - if toks[0]==r'\ ': num = 0.30 # 30% of fontsize - elif toks[0]==r'\/': num = 0.1 # 10% of fontsize - else: # hspace - num = float(toks[0][1]) # get the num out of \hspace{num} - + num = self._space_widths[toks[0]] box = self._make_space(num) return [box] @@ -2179,10 +2186,13 @@ state = self.get_state() height = max([x.height for x in middle]) depth = max([x.depth for x in middle]) - hlist = Hlist( - [AutoSizedDelim(front, height, depth, state)] + - middle.asList() + - [AutoSizedDelim(back, height, depth, state)]) + parts = [] + if front != '.': + parts.append(AutoSizedDelim(front, height, depth, state)) + parts.extend(middle.asList()) + if back != '.': + parts.append(AutoSizedDelim(back, height, depth, state)) + hlist = Hlist(parts) return hlist #### This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
Revision: 3634 http://matplotlib.svn.sourceforge.net/matplotlib/?rev=3634&view=rev Author: dsdale Date: 2007年07月30日 11:44:36 -0700 (2007年7月30日) Log Message: ----------- minor changes to traited configs Modified Paths: -------------- trunk/matplotlib/lib/matplotlib/__init__.py trunk/matplotlib/lib/matplotlib/config/__init__.py trunk/matplotlib/lib/matplotlib/config/mplconfig.py trunk/matplotlib/lib/matplotlib/config/mpltraits.py trunk/matplotlib/lib/matplotlib/mpl-data/matplotlibrc Modified: trunk/matplotlib/lib/matplotlib/__init__.py =================================================================== --- trunk/matplotlib/lib/matplotlib/__init__.py 2007年07月30日 18:05:14 UTC (rev 3633) +++ trunk/matplotlib/lib/matplotlib/__init__.py 2007年07月30日 18:44:36 UTC (rev 3634) @@ -708,7 +708,7 @@ rcParams.update(rcParamsDefault) if NEWCONFIG: - print "importing from reorganized config system!" + #print "importing from reorganized config system!" from config import rcParams, rcdefaults try: from config import mplConfig, save_config Modified: trunk/matplotlib/lib/matplotlib/config/__init__.py =================================================================== --- trunk/matplotlib/lib/matplotlib/config/__init__.py 2007年07月30日 18:05:14 UTC (rev 3633) +++ trunk/matplotlib/lib/matplotlib/config/__init__.py 2007年07月30日 18:44:36 UTC (rev 3634) @@ -1,12 +1,12 @@ # Please keep this file empty -USE_TRAITED_CONFIG = False +USE_TRAITED_CONFIG = True from rcparams import rc from cutils import get_config_file if USE_TRAITED_CONFIG: - print 'Using new config system!' + #print 'Using new config system!' from mplconfig import rcParams, mplConfig, save_config, rcdefaults else: from rcparams import rcParams, rcdefaults Modified: trunk/matplotlib/lib/matplotlib/config/mplconfig.py =================================================================== --- trunk/matplotlib/lib/matplotlib/config/mplconfig.py 2007年07月30日 18:05:14 UTC (rev 3633) +++ trunk/matplotlib/lib/matplotlib/config/mplconfig.py 2007年07月30日 18:44:36 UTC (rev 3634) @@ -88,7 +88,7 @@ fonttype = T.Trait(3, 42) class distiller(TConfig): - use = T.Trait(None, None, 'ghostscript', 'xpdf') + use = T.Trait(None, None, 'ghostscript', 'xpdf', False) resolution = T.Float(6000) class pdf(TConfig): @@ -267,7 +267,7 @@ dpi = T.Float(100) facecolor = T.Trait('white', mplT.ColorHandler()) edgecolor = T.Trait('white', mplT.ColorHandler()) - orientation = T.Trait('portrait', 'portrait', 'landscape') + orientation = T.Trait('portrait', 'portrait', 'landscape') class verbose(TConfig): level = T.Trait('silent', 'silent', 'helpful', 'debug', 'debug-annoying') @@ -457,13 +457,19 @@ return self.tconfig_map.has_key(val) -config_file = cutils.get_config_file(tconfig=True) old_config_file = cutils.get_config_file(tconfig=False) +old_config_path = os.path.split(old_config_file)[0] +config_file = os.path.join(old_config_path, 'matplotlib.conf') + if os.path.exists(old_config_file) and not os.path.exists(config_file): + print 'convert!' CONVERT = True -else: CONVERT = False +else: + config_file = cutils.get_config_file(tconfig=True) + CONVERT = False + configManager = TConfigManager(MPLConfig, - cutils.get_config_file(tconfig=True), + config_file, filePriority=True) mplConfig = configManager.tconf mplConfigDefault = MPLConfig() Modified: trunk/matplotlib/lib/matplotlib/config/mpltraits.py =================================================================== --- trunk/matplotlib/lib/matplotlib/config/mpltraits.py 2007年07月30日 18:05:14 UTC (rev 3633) +++ trunk/matplotlib/lib/matplotlib/config/mpltraits.py 2007年07月30日 18:44:36 UTC (rev 3634) @@ -32,7 +32,7 @@ 'ps': 'PS', 'pdf': 'PDF', 'svg': 'SVG', - 'template': 'Templates' } + 'template': 'Template' } def validate(self, object, name, value): try: @@ -143,4 +143,4 @@ 'gist_yarg', 'gist_yarg_r', 'gray', 'gray_r', 'hot', 'hot_r', 'hsv', 'hsv_r', 'jet', 'jet_r', 'pink', 'pink_r', 'prism', 'prism_r', 'spectral', 'spectral_r', 'spring', - 'spring_r', 'summer', 'summer_r', 'winter', 'winter_r'] \ No newline at end of file + 'spring_r', 'summer', 'summer_r', 'winter', 'winter_r'] Modified: trunk/matplotlib/lib/matplotlib/mpl-data/matplotlibrc =================================================================== --- trunk/matplotlib/lib/matplotlib/mpl-data/matplotlibrc 2007年07月30日 18:05:14 UTC (rev 3633) +++ trunk/matplotlib/lib/matplotlib/mpl-data/matplotlibrc 2007年07月30日 18:44:36 UTC (rev 3634) @@ -243,6 +243,7 @@ #savefig.dpi : 100 # figure dots per inch #savefig.facecolor : white # figure facecolor when saving #savefig.edgecolor : white # figure edgecolor when saving +#savefig.orientation : portrait # portrait or landscape #cairo.format : png # png, ps, pdf, svg This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
Revision: 3633 http://matplotlib.svn.sourceforge.net/matplotlib/?rev=3633&view=rev Author: mdboom Date: 2007年07月30日 11:05:14 -0700 (2007年7月30日) Log Message: ----------- Various minor bugfixes. Modified Paths: -------------- trunk/matplotlib/lib/matplotlib/_mathtext_data.py trunk/matplotlib/lib/matplotlib/mathtext.py Modified: trunk/matplotlib/lib/matplotlib/_mathtext_data.py =================================================================== --- trunk/matplotlib/lib/matplotlib/_mathtext_data.py 2007年07月30日 17:41:14 UTC (rev 3632) +++ trunk/matplotlib/lib/matplotlib/_mathtext_data.py 2007年07月30日 18:05:14 UTC (rev 3633) @@ -2214,7 +2214,7 @@ 'combiningbreve' : 774, 'combiningoverline' : 772, 'combininggraveaccent' : 768, -'combiningacuteaccent' : 764, +'combiningacuteaccent' : 714, 'combiningdiaeresis' : 776, 'combiningtilde' : 771, 'combiningrightarrowabove' : 8407, Modified: trunk/matplotlib/lib/matplotlib/mathtext.py =================================================================== --- trunk/matplotlib/lib/matplotlib/mathtext.py 2007年07月30日 17:41:14 UTC (rev 3632) +++ trunk/matplotlib/lib/matplotlib/mathtext.py 2007年07月30日 18:05:14 UTC (rev 3633) @@ -617,7 +617,7 @@ return alternatives return [(fontname, sym)] -class UnicodeFonts(BakomaFonts): +class UnicodeFonts(TruetypeFonts): """An abstract base class for handling Unicode fonts. """ fontmap = { 'cal' : 'cmsy10', @@ -628,7 +628,7 @@ 'sf' : 'DejaVuSans', None : 'DejaVuSerif-Italic' } - + def _get_offset(self, cached_font, glyph, fontsize, dpi): return 0. @@ -637,6 +637,7 @@ try: uniindex = get_unicode_index(sym) + found_symbol = True except ValueError: # This is a total hack, but it works for now if sym.startswith('\\big'): @@ -658,7 +659,7 @@ glyphindex = cached_font.charmap[uniindex] except KeyError: warn("Font '%s' does not have a glyph for '%s'" % - (cached_font.postscript_name, sym), + (cached_font.font.postscript_name, sym), MathTextWarning) found_symbol = False @@ -2228,7 +2229,7 @@ font_output = BakomaFonts(prop, backend) # When we have a decent Unicode font, we should test and # then make this available as an option - # font_output = UnicodeFonts(prop, backend) + #~ font_output = UnicodeFonts(prop, backend) fontsize = prop.get_size_in_points() if self._parser is None: This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
Revision: 3632 http://matplotlib.svn.sourceforge.net/matplotlib/?rev=3632&view=rev Author: dsdale Date: 2007年07月30日 10:41:14 -0700 (2007年7月30日) Log Message: ----------- Ability to use new, traited configuration system in mpl Modified Paths: -------------- trunk/matplotlib/CHANGELOG trunk/matplotlib/lib/matplotlib/__init__.py trunk/matplotlib/lib/matplotlib/config/__init__.py trunk/matplotlib/lib/matplotlib/config/cutils.py trunk/matplotlib/lib/matplotlib/config/mplconfig.py trunk/matplotlib/lib/matplotlib/mpl-data/matplotlibrc trunk/matplotlib/setup.py Removed Paths: ------------- trunk/matplotlib/lib/matplotlib/config/api.py Modified: trunk/matplotlib/CHANGELOG =================================================================== --- trunk/matplotlib/CHANGELOG 2007年07月30日 16:41:53 UTC (rev 3631) +++ trunk/matplotlib/CHANGELOG 2007年07月30日 17:41:14 UTC (rev 3632) @@ -1,3 +1,12 @@ +2007年07月30日 Reorganized configuration code to work with traited config + objects. The new config system is located in the + matplotlib.config package, but it is disabled by default. + To enable it, set NEWCONFIG=True in matplotlib.__init__.py. + The new configuration system will still use the old + matplotlibrc files by default. To switch to the experimental, + traited configuration, set USE_TRAITED_CONFIG=True in + config.__init__.py. + 2007年07月29日 Changed default pcolor shading to flat; added aliases to make collection kwargs agree with setter names, so updating works; related minor cleanups. Modified: trunk/matplotlib/lib/matplotlib/__init__.py =================================================================== --- trunk/matplotlib/lib/matplotlib/__init__.py 2007年07月30日 16:41:53 UTC (rev 3631) +++ trunk/matplotlib/lib/matplotlib/__init__.py 2007年07月30日 17:41:14 UTC (rev 3632) @@ -55,6 +55,7 @@ """ from __future__ import generators +NEWCONFIG = False __version__ = '0.90.1' __revision__ = '$Revision$' @@ -706,6 +707,13 @@ """ rcParams.update(rcParamsDefault) +if NEWCONFIG: + print "importing from reorganized config system!" + from config import rcParams, rcdefaults + try: + from config import mplConfig, save_config + except: + pass def use(arg): """ Modified: trunk/matplotlib/lib/matplotlib/config/__init__.py =================================================================== --- trunk/matplotlib/lib/matplotlib/config/__init__.py 2007年07月30日 16:41:53 UTC (rev 3631) +++ trunk/matplotlib/lib/matplotlib/config/__init__.py 2007年07月30日 17:41:14 UTC (rev 3632) @@ -1 +1,12 @@ -# Please keep this file empty \ No newline at end of file +# Please keep this file empty + +USE_TRAITED_CONFIG = False + +from rcparams import rc +from cutils import get_config_file + +if USE_TRAITED_CONFIG: + print 'Using new config system!' + from mplconfig import rcParams, mplConfig, save_config, rcdefaults +else: + from rcparams import rcParams, rcdefaults Deleted: trunk/matplotlib/lib/matplotlib/config/api.py =================================================================== --- trunk/matplotlib/lib/matplotlib/config/api.py 2007年07月30日 16:41:53 UTC (rev 3631) +++ trunk/matplotlib/lib/matplotlib/config/api.py 2007年07月30日 17:41:14 UTC (rev 3632) @@ -1,12 +0,0 @@ -""" -""" - -USE_NEW_CONFIG = True - -from rcparams import rc -from cutils import get_config_file - -if USE_NEW_CONFIG: - from mplconfig import rcParams, mplConfig, save_config -else: - from rcparams import rcParams Modified: trunk/matplotlib/lib/matplotlib/config/cutils.py =================================================================== --- trunk/matplotlib/lib/matplotlib/config/cutils.py 2007年07月30日 16:41:53 UTC (rev 3631) +++ trunk/matplotlib/lib/matplotlib/config/cutils.py 2007年07月30日 17:41:14 UTC (rev 3632) @@ -179,4 +179,4 @@ fname = os.path.join(path, filename) if not os.path.exists(fname): warnings.warn('Could not find %s; using defaults'%filename) - return fname \ No newline at end of file + return fname Modified: trunk/matplotlib/lib/matplotlib/config/mplconfig.py =================================================================== --- trunk/matplotlib/lib/matplotlib/config/mplconfig.py 2007年07月30日 16:41:53 UTC (rev 3631) +++ trunk/matplotlib/lib/matplotlib/config/mplconfig.py 2007年07月30日 17:41:14 UTC (rev 3632) @@ -10,6 +10,7 @@ # internal imports import mpltraits as mplT import cutils +import checkdep from tconfig import TConfig, TConfigManager import pytz @@ -266,210 +267,220 @@ dpi = T.Float(100) facecolor = T.Trait('white', mplT.ColorHandler()) edgecolor = T.Trait('white', mplT.ColorHandler()) - orientation = T.Trait('portrait', 'portrait', 'landscape') + orientation = T.Trait('portrait', 'portrait', 'landscape') class verbose(TConfig): level = T.Trait('silent', 'silent', 'helpful', 'debug', 'debug-annoying') fileo = T.Trait('sys.stdout', 'sys.stdout', T.File) -config_file = cutils.get_config_file(tconfig=True) -old_config_file = cutils.get_config_file(tconfig=False) -print -if os.path.exists(old_config_file) and not os.path.exists(config_file): - CONVERT = True -else: CONVERT = False -configManager = TConfigManager(MPLConfig, - cutils.get_config_file(tconfig=True), - filePriority=True) -mplConfig = configManager.tconf - - -def save_config(): - """Save mplConfig customizations to current matplotlib.conf - """ - configManager.write() - - class RcParamsWrapper(dict): """A backwards-compatible interface to a traited config object """ - tconf = { - 'backend' : (mplConfig.backend, 'use'), - 'numerix' : (mplConfig, 'numerix'), - 'maskedarray' : (mplConfig, 'maskedarray'), - 'toolbar' : (mplConfig, 'toolbar'), - 'datapath' : (mplConfig, 'datapath'), - 'units' : (mplConfig, 'units'), - 'interactive' : (mplConfig, 'interactive'), - 'timezone' : (mplConfig, 'timezone'), + def __init__(self, tconfig): + self.tconfig = tconfig + + self.tconfig_map = { + 'backend' : (self.tconfig.backend, 'use'), + 'numerix' : (self.tconfig, 'numerix'), + 'maskedarray' : (self.tconfig, 'maskedarray'), + 'toolbar' : (self.tconfig, 'toolbar'), + 'datapath' : (self.tconfig, 'datapath'), + 'units' : (self.tconfig, 'units'), + 'interactive' : (self.tconfig, 'interactive'), + 'timezone' : (self.tconfig, 'timezone'), - # the verbosity setting - 'verbose.level' : (mplConfig.verbose, 'level'), - 'verbose.fileo' : (mplConfig.verbose, 'fileo'), + # the verbosity setting + 'verbose.level' : (self.tconfig.verbose, 'level'), + 'verbose.fileo' : (self.tconfig.verbose, 'fileo'), - # line props - 'lines.linewidth' : (mplConfig.lines, 'linewidth'), - 'lines.linestyle' : (mplConfig.lines, 'linestyle'), - 'lines.color' : (mplConfig.lines, 'color'), - 'lines.marker' : (mplConfig.lines, 'marker'), - 'lines.markeredgewidth' : (mplConfig.lines, 'markeredgewidth'), - 'lines.markersize' : (mplConfig.lines, 'markersize'), - 'lines.antialiased' : (mplConfig.lines, 'antialiased'), - 'lines.dash_joinstyle' : (mplConfig.lines, 'dash_joinstyle'), - 'lines.solid_joinstyle' : (mplConfig.lines, 'solid_joinstyle'), - 'lines.dash_capstyle' : (mplConfig.lines, 'dash_capstyle'), - 'lines.solid_capstyle' : (mplConfig.lines, 'solid_capstyle'), + # line props + 'lines.linewidth' : (self.tconfig.lines, 'linewidth'), + 'lines.linestyle' : (self.tconfig.lines, 'linestyle'), + 'lines.color' : (self.tconfig.lines, 'color'), + 'lines.marker' : (self.tconfig.lines, 'marker'), + 'lines.markeredgewidth' : (self.tconfig.lines, 'markeredgewidth'), + 'lines.markersize' : (self.tconfig.lines, 'markersize'), + 'lines.antialiased' : (self.tconfig.lines, 'antialiased'), + 'lines.dash_joinstyle' : (self.tconfig.lines, 'dash_joinstyle'), + 'lines.solid_joinstyle' : (self.tconfig.lines, 'solid_joinstyle'), + 'lines.dash_capstyle' : (self.tconfig.lines, 'dash_capstyle'), + 'lines.solid_capstyle' : (self.tconfig.lines, 'solid_capstyle'), - # patch props - 'patch.linewidth' : (mplConfig.patch, 'linewidth'), - 'patch.edgecolor' : (mplConfig.patch, 'edgecolor'), - 'patch.facecolor' : (mplConfig.patch, 'facecolor'), - 'patch.antialiased' : (mplConfig.patch, 'antialiased'), + # patch props + 'patch.linewidth' : (self.tconfig.patch, 'linewidth'), + 'patch.edgecolor' : (self.tconfig.patch, 'edgecolor'), + 'patch.facecolor' : (self.tconfig.patch, 'facecolor'), + 'patch.antialiased' : (self.tconfig.patch, 'antialiased'), - # font props - 'font.family' : (mplConfig.font, 'family'), - 'font.style' : (mplConfig.font, 'style'), - 'font.variant' : (mplConfig.font, 'variant'), - 'font.stretch' : (mplConfig.lines, 'color'), - 'font.weight' : (mplConfig.font, 'weight'), - 'font.size' : (mplConfig.font, 'size'), - 'font.serif' : (mplConfig.font, 'serif'), - 'font.sans-serif' : (mplConfig.font, 'sans_serif'), - 'font.cursive' : (mplConfig.font, 'cursive'), - 'font.fantasy' : (mplConfig.font, 'fantasy'), - 'font.monospace' : (mplConfig.font, 'monospace'), + # font props + 'font.family' : (self.tconfig.font, 'family'), + 'font.style' : (self.tconfig.font, 'style'), + 'font.variant' : (self.tconfig.font, 'variant'), + 'font.stretch' : (self.tconfig.lines, 'color'), + 'font.weight' : (self.tconfig.font, 'weight'), + 'font.size' : (self.tconfig.font, 'size'), + 'font.serif' : (self.tconfig.font, 'serif'), + 'font.sans-serif' : (self.tconfig.font, 'sans_serif'), + 'font.cursive' : (self.tconfig.font, 'cursive'), + 'font.fantasy' : (self.tconfig.font, 'fantasy'), + 'font.monospace' : (self.tconfig.font, 'monospace'), - # text props - 'text.color' : (mplConfig.text, 'color'), - 'text.usetex' : (mplConfig.text, 'usetex'), - 'text.latex.unicode' : (mplConfig.text.latex, 'unicode'), - 'text.latex.preamble' : (mplConfig.text.latex, 'preamble'), - 'text.dvipnghack' : (mplConfig.text.latex, 'dvipnghack'), + # text props + 'text.color' : (self.tconfig.text, 'color'), + 'text.usetex' : (self.tconfig.text, 'usetex'), + 'text.latex.unicode' : (self.tconfig.text.latex, 'unicode'), + 'text.latex.preamble' : (self.tconfig.text.latex, 'preamble'), + 'text.dvipnghack' : (self.tconfig.text.latex, 'dvipnghack'), - 'image.aspect' : (mplConfig.image, 'aspect'), - 'image.interpolation' : (mplConfig.image, 'interpolation'), - 'image.cmap' : (mplConfig.image, 'cmap'), - 'image.lut' : (mplConfig.image, 'lut'), - 'image.origin' : (mplConfig.image, 'origin'), + 'image.aspect' : (self.tconfig.image, 'aspect'), + 'image.interpolation' : (self.tconfig.image, 'interpolation'), + 'image.cmap' : (self.tconfig.image, 'cmap'), + 'image.lut' : (self.tconfig.image, 'lut'), + 'image.origin' : (self.tconfig.image, 'origin'), - 'contour.negative_linestyle' : (mplConfig.contour, 'negative_linestyle'), + 'contour.negative_linestyle' : (self.tconfig.contour, 'negative_linestyle'), - # axes props - 'axes.axisbelow' : (mplConfig.axes, 'axisbelow'), - 'axes.hold' : (mplConfig.axes, 'hold'), - 'axes.facecolor' : (mplConfig.axes, 'facecolor'), - 'axes.edgecolor' : (mplConfig.axes, 'edgecolor'), - 'axes.linewidth' : (mplConfig.axes, 'linewidth'), - 'axes.titlesize' : (mplConfig.axes, 'titlesize'), - 'axes.grid' : (mplConfig.axes, 'grid'), - 'axes.labelsize' : (mplConfig.axes, 'labelsize'), - 'axes.labelcolor' : (mplConfig.axes, 'labelcolor'), - 'axes.formatter.limits' : (mplConfig.axes.formatter, 'limits'), + # axes props + 'axes.axisbelow' : (self.tconfig.axes, 'axisbelow'), + 'axes.hold' : (self.tconfig.axes, 'hold'), + 'axes.facecolor' : (self.tconfig.axes, 'facecolor'), + 'axes.edgecolor' : (self.tconfig.axes, 'edgecolor'), + 'axes.linewidth' : (self.tconfig.axes, 'linewidth'), + 'axes.titlesize' : (self.tconfig.axes, 'titlesize'), + 'axes.grid' : (self.tconfig.axes, 'grid'), + 'axes.labelsize' : (self.tconfig.axes, 'labelsize'), + 'axes.labelcolor' : (self.tconfig.axes, 'labelcolor'), + 'axes.formatter.limits' : (self.tconfig.axes.formatter, 'limits'), - 'polaraxes.grid' : (mplConfig.axes, 'polargrid'), + 'polaraxes.grid' : (self.tconfig.axes, 'polargrid'), - #legend properties - 'legend.loc' : (mplConfig.legend, 'loc'), - 'legend.isaxes' : (mplConfig.legend, 'isaxes'), - 'legend.numpoints' : (mplConfig.legend, 'numpoints'), - 'legend.fontsize' : (mplConfig.legend, 'fontsize'), - 'legend.pad' : (mplConfig.legend, 'pad'), - 'legend.markerscale' : (mplConfig.legend, 'markerscale'), - 'legend.labelsep' : (mplConfig.legend, 'labelsep'), - 'legend.handlelen' : (mplConfig.legend, 'handlelen'), - 'legend.handletextsep' : (mplConfig.legend, 'handletextsep'), - 'legend.axespad' : (mplConfig.legend, 'axespad'), - 'legend.shadow' : (mplConfig.legend, 'shadow'), + #legend properties + 'legend.loc' : (self.tconfig.legend, 'loc'), + 'legend.isaxes' : (self.tconfig.legend, 'isaxes'), + 'legend.numpoints' : (self.tconfig.legend, 'numpoints'), + 'legend.fontsize' : (self.tconfig.legend, 'fontsize'), + 'legend.pad' : (self.tconfig.legend, 'pad'), + 'legend.markerscale' : (self.tconfig.legend, 'markerscale'), + 'legend.labelsep' : (self.tconfig.legend, 'labelsep'), + 'legend.handlelen' : (self.tconfig.legend, 'handlelen'), + 'legend.handletextsep' : (self.tconfig.legend, 'handletextsep'), + 'legend.axespad' : (self.tconfig.legend, 'axespad'), + 'legend.shadow' : (self.tconfig.legend, 'shadow'), - # tick properties - 'xtick.major.size' : (mplConfig.xticks.major, 'size'), - 'xtick.minor.size' : (mplConfig.xticks.minor, 'size'), - 'xtick.major.pad' : (mplConfig.xticks.major, 'pad'), - 'xtick.minor.pad' : (mplConfig.xticks.minor, 'pad'), - 'xtick.color' : (mplConfig.xticks, 'color'), - 'xtick.labelsize' : (mplConfig.xticks, 'labelsize'), - 'xtick.direction' : (mplConfig.xticks, 'direction'), + # tick properties + 'xtick.major.size' : (self.tconfig.xticks.major, 'size'), + 'xtick.minor.size' : (self.tconfig.xticks.minor, 'size'), + 'xtick.major.pad' : (self.tconfig.xticks.major, 'pad'), + 'xtick.minor.pad' : (self.tconfig.xticks.minor, 'pad'), + 'xtick.color' : (self.tconfig.xticks, 'color'), + 'xtick.labelsize' : (self.tconfig.xticks, 'labelsize'), + 'xtick.direction' : (self.tconfig.xticks, 'direction'), - 'ytick.major.size' : (mplConfig.yticks.major, 'size'), - 'ytick.minor.size' : (mplConfig.yticks.minor, 'size'), - 'ytick.major.pad' : (mplConfig.yticks.major, 'pad'), - 'ytick.minor.pad' : (mplConfig.yticks.minor, 'pad'), - 'ytick.color' : (mplConfig.yticks, 'color'), - 'ytick.labelsize' : (mplConfig.yticks, 'labelsize'), - 'ytick.direction' : (mplConfig.yticks, 'direction'), + 'ytick.major.size' : (self.tconfig.yticks.major, 'size'), + 'ytick.minor.size' : (self.tconfig.yticks.minor, 'size'), + 'ytick.major.pad' : (self.tconfig.yticks.major, 'pad'), + 'ytick.minor.pad' : (self.tconfig.yticks.minor, 'pad'), + 'ytick.color' : (self.tconfig.yticks, 'color'), + 'ytick.labelsize' : (self.tconfig.yticks, 'labelsize'), + 'ytick.direction' : (self.tconfig.yticks, 'direction'), - 'grid.color' : (mplConfig.grid, 'color'), - 'grid.linestyle' : (mplConfig.grid, 'linestyle'), - 'grid.linewidth' : (mplConfig.grid, 'linewidth'), + 'grid.color' : (self.tconfig.grid, 'color'), + 'grid.linestyle' : (self.tconfig.grid, 'linestyle'), + 'grid.linewidth' : (self.tconfig.grid, 'linewidth'), - # figure props - 'figure.figsize' : (mplConfig.figure, 'figsize'), - 'figure.dpi' : (mplConfig.figure, 'dpi'), - 'figure.facecolor' : (mplConfig.figure, 'facecolor'), - 'figure.edgecolor' : (mplConfig.figure, 'edgecolor'), + # figure props + 'figure.figsize' : (self.tconfig.figure, 'figsize'), + 'figure.dpi' : (self.tconfig.figure, 'dpi'), + 'figure.facecolor' : (self.tconfig.figure, 'facecolor'), + 'figure.edgecolor' : (self.tconfig.figure, 'edgecolor'), - 'figure.subplot.left' : (mplConfig.figure.subplot, 'left'), - 'figure.subplot.right' : (mplConfig.figure.subplot, 'right'), - 'figure.subplot.bottom' : (mplConfig.figure.subplot, 'bottom'), - 'figure.subplot.top' : (mplConfig.figure.subplot, 'top'), - 'figure.subplot.wspace' : (mplConfig.figure.subplot, 'wspace'), - 'figure.subplot.hspace' : (mplConfig.figure.subplot, 'hspace'), + 'figure.subplot.left' : (self.tconfig.figure.subplot, 'left'), + 'figure.subplot.right' : (self.tconfig.figure.subplot, 'right'), + 'figure.subplot.bottom' : (self.tconfig.figure.subplot, 'bottom'), + 'figure.subplot.top' : (self.tconfig.figure.subplot, 'top'), + 'figure.subplot.wspace' : (self.tconfig.figure.subplot, 'wspace'), + 'figure.subplot.hspace' : (self.tconfig.figure.subplot, 'hspace'), - 'savefig.dpi' : (mplConfig.savefig, 'dpi'), - 'savefig.facecolor' : (mplConfig.savefig, 'facecolor'), - 'savefig.edgecolor' : (mplConfig.savefig, 'edgecolor'), - 'savefig.orientation' : (mplConfig.savefig, 'orientation'), + 'savefig.dpi' : (self.tconfig.savefig, 'dpi'), + 'savefig.facecolor' : (self.tconfig.savefig, 'facecolor'), + 'savefig.edgecolor' : (self.tconfig.savefig, 'edgecolor'), + 'savefig.orientation' : (self.tconfig.savefig, 'orientation'), - 'cairo.format' : (mplConfig.backend.cairo, 'format'), - 'tk.window_focus' : (mplConfig.backend.tk, 'window_focus'), - 'tk.pythoninspect' : (mplConfig.backend.tk, 'pythoninspect'), - 'ps.papersize' : (mplConfig.backend.ps, 'papersize'), - 'ps.useafm' : (mplConfig.backend.ps, 'useafm'), - 'ps.usedistiller' : (mplConfig.backend.ps.distiller, 'use'), - 'ps.distiller.res' : (mplConfig.backend.ps.distiller, 'resolution'), - 'ps.fonttype' : (mplConfig.backend.ps, 'fonttype'), - 'pdf.compression' : (mplConfig.backend.pdf, 'compression'), - 'pdf.inheritcolor' : (mplConfig.backend.pdf, 'inheritcolor'), - 'pdf.use14corefonts' : (mplConfig.backend.pdf, 'use14corefonts'), - 'pdf.fonttype' : (mplConfig.backend.pdf, 'fonttype'), - 'svg.image_inline' : (mplConfig.backend.svg, 'image_inline'), - 'svg.image_noscale' : (mplConfig.backend.svg, 'image_noscale'), - 'svg.embed_char_paths' : (mplConfig.backend.svg, 'embed_chars'), + 'cairo.format' : (self.tconfig.backend.cairo, 'format'), + 'tk.window_focus' : (self.tconfig.backend.tk, 'window_focus'), + 'tk.pythoninspect' : (self.tconfig.backend.tk, 'pythoninspect'), + 'ps.papersize' : (self.tconfig.backend.ps, 'papersize'), + 'ps.useafm' : (self.tconfig.backend.ps, 'useafm'), + 'ps.usedistiller' : (self.tconfig.backend.ps.distiller, 'use'), + 'ps.distiller.res' : (self.tconfig.backend.ps.distiller, 'resolution'), + 'ps.fonttype' : (self.tconfig.backend.ps, 'fonttype'), + 'pdf.compression' : (self.tconfig.backend.pdf, 'compression'), + 'pdf.inheritcolor' : (self.tconfig.backend.pdf, 'inheritcolor'), + 'pdf.use14corefonts' : (self.tconfig.backend.pdf, 'use14corefonts'), + 'pdf.fonttype' : (self.tconfig.backend.pdf, 'fonttype'), + 'svg.image_inline' : (self.tconfig.backend.svg, 'image_inline'), + 'svg.image_noscale' : (self.tconfig.backend.svg, 'image_noscale'), + 'svg.embed_char_paths' : (self.tconfig.backend.svg, 'embed_chars'), - # mathtext settings - 'mathtext.mathtext2' : (mplConfig.text.math, 'mathtext2'), - 'mathtext.rm' : (mplConfig.text.math, 'rm'), - 'mathtext.it' : (mplConfig.text.math, 'it'), - 'mathtext.tt' : (mplConfig.text.math, 'tt'), - 'mathtext.mit' : (mplConfig.text.math, 'mit'), - 'mathtext.cal' : (mplConfig.text.math, 'cal'), - 'mathtext.nonascii' : (mplConfig.text.math, 'nonascii'), - } + # mathtext settings + 'mathtext.mathtext2' : (self.tconfig.text.math, 'mathtext2'), + 'mathtext.rm' : (self.tconfig.text.math, 'rm'), + 'mathtext.it' : (self.tconfig.text.math, 'it'), + 'mathtext.tt' : (self.tconfig.text.math, 'tt'), + 'mathtext.mit' : (self.tconfig.text.math, 'mit'), + 'mathtext.cal' : (self.tconfig.text.math, 'cal'), + 'mathtext.nonascii' : (self.tconfig.text.math, 'nonascii'), + } def __setitem__(self, key, val): try: - obj, attr = self.tconf[key] + obj, attr = self.tconfig_map[key] setattr(obj, attr, val) except KeyError: raise KeyError('%s is not a valid rc parameter.\ See rcParams.keys() for a list of valid parameters.'%key) def __getitem__(self, key): - obj, attr = self.tconf[key] + obj, attr = self.tconfig_map[key] return getattr(obj, attr) - def keys(): - return self.tconf.keys() + def keys(self): + return self.tconfig_map.keys() + + def has_key(self, val): + return self.tconfig_map.has_key(val) -rcParams = RcParamsWrapper() +config_file = cutils.get_config_file(tconfig=True) +old_config_file = cutils.get_config_file(tconfig=False) +if os.path.exists(old_config_file) and not os.path.exists(config_file): + CONVERT = True +else: CONVERT = False +configManager = TConfigManager(MPLConfig, + cutils.get_config_file(tconfig=True), + filePriority=True) +mplConfig = configManager.tconf +mplConfigDefault = MPLConfig() +# TODO: move into traits validation +mplConfig.backend.ps.distiller.use = \ + checkdep.ps_distiller(mplConfig.backend.ps.distiller.use) +mplConfig.text.usetex = checkdep.usetex(mplConfig.text.usetex) + +def save_config(): + """Save mplConfig customizations to current matplotlib.conf + """ + configManager.write() + +rcParams = RcParamsWrapper(mplConfig) +rcParamsDefault = RcParamsWrapper(mplConfigDefault) + # convert old matplotlibrc to new matplotlib.conf if CONVERT: from rcparams import rcParams as old_rcParams @@ -479,6 +490,10 @@ print '%s converted to %s'%(cutils.get_config_file(tconfig=False), config_file) +def rcdefaults(): + mplConfig = MPLConfig() + rcParams = RcParamsWrapper(mplConfig) + ############################################################################## # Simple testing ############################################################################## Modified: trunk/matplotlib/lib/matplotlib/mpl-data/matplotlibrc =================================================================== --- trunk/matplotlib/lib/matplotlib/mpl-data/matplotlibrc 2007年07月30日 16:41:53 UTC (rev 3631) +++ trunk/matplotlib/lib/matplotlib/mpl-data/matplotlibrc 2007年07月30日 17:41:14 UTC (rev 3632) @@ -34,7 +34,6 @@ #interactive : False # see http://matplotlib.sourceforge.net/interactive.html #toolbar : toolbar2 # None | classic | toolbar2 #timezone : UTC # a pytz timezone string, eg US/Central or Europe/Paris -#units : False # Where your matplotlib data lives if you installed to a non-default # location. This is where the matplotlib fonts, bitmaps, etc reside @@ -197,7 +196,6 @@ #grid.linewidth : 0.5 # in points ### Legend -#legend.loc : upper right #legend.isaxes : True #legend.numpoints : 2 # the number of points in the legend line #legend.fontsize : 14 @@ -245,7 +243,6 @@ #savefig.dpi : 100 # figure dots per inch #savefig.facecolor : white # figure facecolor when saving #savefig.edgecolor : white # figure edgecolor when saving -#savefig.orientation: portrait #cairo.format : png # png, ps, pdf, svg @@ -267,8 +264,6 @@ #pdf.compression : 6 # integer from 0 to 9 # 0 disables compression (good for debugging) #pdf.fonttype : 3 # Output Type 3 (Type3) or Type 42 (TrueType) -#pdf.inheritcolor : False -#pdf.use14corefonts : False # svg backend params #svg.image_inline : True # write raster image data directly into the svg file Modified: trunk/matplotlib/setup.py =================================================================== --- trunk/matplotlib/setup.py 2007年07月30日 16:41:53 UTC (rev 3631) +++ trunk/matplotlib/setup.py 2007年07月30日 17:41:14 UTC (rev 3632) @@ -130,7 +130,7 @@ 'matplotlib.numerix.linear_algebra', 'matplotlib.numerix.random_array', 'matplotlib.numerix.fft', - + 'matplotlib.config' ] This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
Revision: 3631 http://matplotlib.svn.sourceforge.net/matplotlib/?rev=3631&view=rev Author: mdboom Date: 2007年07月30日 09:41:53 -0700 (2007年7月30日) Log Message: ----------- Major refactor to separate out backend-specific stuff from fontset-specific stuff. What used to be the Fonts class heirarchy is now both a Fonts heirarchy and MathtextBackend heirarchy. This should be further improved in the future when the backends themselves are refactored to be more consistent. Now uses the multi-sized delimiters in the BaKoMa fonts. This prevents the square root symbol from getting overly wide as it gets tall. (As auto-sized parens, brackets and braces etc.) Modified Paths: -------------- trunk/matplotlib/lib/matplotlib/_mathtext_data.py trunk/matplotlib/lib/matplotlib/mathtext.py Modified: trunk/matplotlib/lib/matplotlib/_mathtext_data.py =================================================================== --- trunk/matplotlib/lib/matplotlib/_mathtext_data.py 2007年07月30日 07:03:47 UTC (rev 3630) +++ trunk/matplotlib/lib/matplotlib/_mathtext_data.py 2007年07月30日 16:41:53 UTC (rev 3631) @@ -14,8 +14,9 @@ print charcode, glyphind """ -latex_to_bakoma = { +from sets import Set +latex_to_bakoma = { r'\oint' : ('cmex10', 45), r'\bigodot' : ('cmex10', 50), r'\bigoplus' : ('cmex10', 55), @@ -29,13 +30,7 @@ r'\bigwedge' : ('cmex10', 4), r'\bigvee' : ('cmex10', 37), r'\coprod' : ('cmex10', 42), - r'\Leftbracket' : ('cmex10', 29), - r'\Rightbracket' : ('cmex10', 61), - r'\Leftbrace' : ('cmex10', 43), - r'\Rightbrace' : ('cmex10', 16), r'\sqrt' : ('cmex10', 48), - r'\Sqrt' : ('cmex10', 21), - r'\SQRT' : ('cmex10', 53), r'\leftbrace' : ('cmex10', 92), r'{' : ('cmex10', 92), r'\{' : ('cmex10', 92), @@ -44,16 +39,6 @@ r'\}' : ('cmex10', 130), r'\leftangle' : ('cmex10', 97), r'\rightangle' : ('cmex10', 64), - r'\Leftparen' : ('cmex10', 112), - r'\Rightparen' : ('cmex10', 81), - r'\LEFTparen' : ('cmex10', 119), - r'\RIGHTparen' : ('cmex10', 87), - r'\LEFTbracket' : ('cmex10', 125), - r'\RIGHTbracket' : ('cmex10', 93), - r'\LEFTbrace' : ('cmex10', 70), - r'\RIGHTbrace' : ('cmex10', 107), - r'\LEFTangle' : ('cmex10', 76), - r'\RIGHTangle' : ('cmex10', 113), r'\omega' : ('cmmi10', 29), r'\varepsilon' : ('cmmi10', 20), @@ -144,15 +129,15 @@ # these are mathml names, I think. I'm just using them for the # tex methods noted - r'\circumflexaccent' : ('cmr10', 124), # for \hat - r'\combiningbreve' : ('cmr10', 81), # for \breve - r'\combiningoverline' : ('cmr10', 131), # for \bar - r'\combininggraveaccent' : ('cmr10', 114), # for \grave - r'\combiningacuteaccent' : ('cmr10', 63), # for \accute - r'\combiningdiaeresis' : ('cmr10', 91), # for \ddot - r'\combiningtilde' : ('cmr10', 75), # for \tilde + r'\circumflexaccent' : ('cmr10', 124), # for \hat + r'\combiningbreve' : ('cmr10', 81), # for \breve + r'\combiningoverline' : ('cmr10', 131), # for \bar + r'\combininggraveaccent' : ('cmr10', 114), # for \grave + r'\combiningacuteaccent' : ('cmr10', 63), # for \accute + r'\combiningdiaeresis' : ('cmr10', 91), # for \ddot + r'\combiningtilde' : ('cmr10', 75), # for \tilde r'\combiningrightarrowabove' : ('cmmi10', 110), # for \vec - r'\combiningdotabove' : ('cmr10', 26), # for \dot + r'\combiningdotabove' : ('cmr10', 26), # for \dot r'\leftarrow' : ('cmsy10', 10), r'\uparrow' : ('cmsy10', 25), @@ -199,8 +184,6 @@ r'\rceil' : ('cmsy10', 81), r'\lbrace' : ('cmsy10', 92), r'\rbrace' : ('cmsy10', 105), - r'\langle' : ('cmsy10', 3), - r'\rangle' : ('cmsy10', 88), r'\mid' : ('cmsy10', 47), r'\vert' : ('cmsy10', 47), r'\Vert' : ('cmsy10', 44), @@ -258,417 +241,6 @@ r'\spadesuit' : ('cmsy10', 7), } -# the kerning dictionary in design space units -cmkern = { - 'cmr10' : - { - ('A', 't') : -0.027779, - ('A', 'C') : -0.027779, - ('A', 'O') : -0.027779, - ('A', 'G') : -0.027779, - ('A', 'U') : -0.027779, - ('A', 'Q') : -0.027779, - ('A', 'T') : -0.083334, - ('A', 'Y') : -0.083334, - ('A', 'V') : -0.111112, - ('A', 'W') : -0.111112, - ('D', 'X') : -0.027779, - ('D', 'W') : -0.027779, - ('D', 'A') : -0.027779, - ('D', 'V') : -0.027779, - ('D', 'Y') : -0.027779, - ('F', 'o') : -0.083334, - ('F', 'e') : -0.083334, - ('F', 'u') : -0.083334, - ('F', 'r') : -0.083334, - ('F', 'a') : -0.083334, - ('F', 'A') : -0.111112, - ('F', 'O') : -0.027779, - ('F', 'C') : -0.027779, - ('F', 'G') : -0.027779, - ('F', 'Q') : -0.027779, - ('I', 'I') : 0.027779, - ('K', 'O') : -0.027779, - ('K', 'C') : -0.027779, - ('K', 'G') : -0.027779, - ('K', 'Q') : -0.027779, - ('L', 'T') : -0.083334, - ('L', 'Y') : -0.083334, - ('L', 'V') : -0.111112, - ('L', 'W') : -0.111112, - ('O', 'X') : -0.027779, - ('O', 'W') : -0.027779, - ('O', 'A') : -0.027779, - ('O', 'V') : -0.027779, - ('O', 'Y') : -0.027779, - ('P', 'A') : -0.083334, - ('P', 'o') : -0.027779, - ('P', 'e') : -0.027779, - ('P', 'a') : -0.027779, - ('R', 't') : -0.027779, - ('R', 'C') : -0.027779, - ('R', 'O') : -0.027779, - ('R', 'G') : -0.027779, - ('R', 'U') : -0.027779, - ('R', 'Q') : -0.027779, - ('R', 'T') : -0.083334, - ('R', 'Y') : -0.083334, - ('R', 'V') : -0.111112, - ('R', 'W') : -0.111112, - ('T', 'y') : -0.027779, - ('T', 'e') : -0.083334, - ('T', 'o') : -0.083334, - ('T', 'r') : -0.083334, - ('T', 'a') : -0.083334, - ('T', 'A') : -0.083334, - ('T', 'u') : -0.083334, - ('V', 'o') : -0.083334, - ('V', 'e') : -0.083334, - ('V', 'u') : -0.083334, - ('V', 'r') : -0.083334, - ('V', 'a') : -0.083334, - ('V', 'A') : -0.111112, - ('V', 'O') : -0.027779, - ('V', 'C') : -0.027779, - ('V', 'G') : -0.027779, - ('V', 'Q') : -0.027779, - ('W', 'o') : -0.083334, - ('W', 'e') : -0.083334, - ('W', 'u') : -0.083334, - ('W', 'r') : -0.083334, - ('W', 'a') : -0.083334, - ('W', 'A') : -0.111112, - ('W', 'O') : -0.027779, - ('W', 'C') : -0.027779, - ('W', 'G') : -0.027779, - ('W', 'Q') : -0.027779, - ('X', 'O') : -0.027779, - ('X', 'C') : -0.027779, - ('X', 'G') : -0.027779, - ('X', 'Q') : -0.027779, - ('Y', 'e') : -0.083334, - ('Y', 'o') : -0.083334, - ('Y', 'r') : -0.083334, - ('Y', 'a') : -0.083334, - ('Y', 'A') : -0.083334, - ('Y', 'u') : -0.083334, - ('a', 'v') : -0.027779, - ('a', 'j') : 0.055555, - ('a', 'y') : -0.027779, - ('a', 'w') : -0.027779, - ('b', 'e') : 0.027779, - ('b', 'o') : 0.027779, - ('b', 'x') : -0.027779, - ('b', 'd') : 0.027779, - ('b', 'c') : 0.027779, - ('b', 'q') : 0.027779, - ('b', 'v') : -0.027779, - ('b', 'j') : 0.055555, - ('b', 'y') : -0.027779, - ('b', 'w') : -0.027779, - ('c', 'h') : -0.027779, - ('c', 'k') : -0.027779, - ('g', 'j') : 0.027779, - ('h', 't') : -0.027779, - ('h', 'u') : -0.027779, - ('h', 'b') : -0.027779, - ('h', 'y') : -0.027779, - ('h', 'v') : -0.027779, - ('h', 'w') : -0.027779, - ('k', 'a') : -0.055555, - ('k', 'e') : -0.027779, - ('k', 'a') : -0.027779, - ('k', 'o') : -0.027779, - ('k', 'c') : -0.027779, - ('m', 't') : -0.027779, - ('m', 'u') : -0.027779, - ('m', 'b') : -0.027779, - ('m', 'y') : -0.027779, - ('m', 'v') : -0.027779, - ('m', 'w') : -0.027779, - ('n', 't') : -0.027779, - ('n', 'u') : -0.027779, - ('n', 'b') : -0.027779, - ('n', 'y') : -0.027779, - ('n', 'v') : -0.027779, - ('n', 'w') : -0.027779, - ('o', 'e') : 0.027779, - ('o', 'o') : 0.027779, - ('o', 'x') : -0.027779, - ('o', 'd') : 0.027779, - ('o', 'c') : 0.027779, - ('o', 'q') : 0.027779, - ('o', 'v') : -0.027779, - ('o', 'j') : 0.055555, - ('o', 'y') : -0.027779, - ('o', 'w') : -0.027779, - ('p', 'e') : 0.027779, - ('p', 'o') : 0.027779, - ('p', 'x') : -0.027779, - ('p', 'd') : 0.027779, - ('p', 'c') : 0.027779, - ('p', 'q') : 0.027779, - ('p', 'v') : -0.027779, - ('p', 'j') : 0.055555, - ('p', 'y') : -0.027779, - ('p', 'w') : -0.027779, - ('t', 'y') : -0.027779, - ('t', 'w') : -0.027779, - ('u', 'w') : -0.027779, - ('v', 'a') : -0.055555, - ('v', 'e') : -0.027779, - ('v', 'a') : -0.027779, - ('v', 'o') : -0.027779, - ('v', 'c') : -0.027779, - ('w', 'e') : -0.027779, - ('w', 'a') : -0.027779, - ('w', 'o') : -0.027779, - ('w', 'c') : -0.027779, - ('y', 'o') : -0.027779, - ('y', 'e') : -0.027779, - ('y', 'a') : -0.027779, - }, - 'cmex10' : {}, - 'cmtt10' : {}, - 'cmsy10' : {}, - 'cmmi10' : - { - ('9', 'A') : -0.055555, - ('9', 'M') : -0.055555, - ('9', 'N') : -0.055555, - ('9', 'Y') : 0.055555, - ('9', 'Z') : -0.055555, - ('d', 'Y') : 0.055555, - ('d', 'Z') : -0.055555, - ('d', 'j') : -0.111112, - ('d', 'f') : -0.166667, - }, - } -ams_type1 = { - r'\Leftbracket' : ( 'cmex10', '02'), - r'\Rightbracket' : ( 'cmex10', '03'), - r'\Leftbrace' : ( 'cmex10', '08'), - r'\leftbrace' : ( 'cmex10', '08'), - '{' : ( 'cmex10', '08'), - r'\Rightbrace' : ( 'cmex10', '09'), - r'\rightbrace' : ( 'cmex10', '09'), - '}' : ( 'cmex10', '09'), - r'\Leftparen' : ( 'cmex10', '10'), - r'\Rightparen' : ( 'cmex10', '11'), - r'\LEFTparen' : ( 'cmex10', '20'), - r'\RIGHTparen' : ( 'cmex10', '21'), - r'\LEFTbracket' : ( 'cmex10', '22'), - r'\RIGHTbracket' : ( 'cmex10', '23'), - '6' : ( 'cmex10', '26'), - '(' : ( 'cmex10', '28'), - r'\LEFTbrace' : ( 'cmex10', '28'), - r'\leftparen' : ( 'cmex10', '28'), - ')' : ( 'cmex10', '29'), - r'\RIGHTbrace' : ( 'cmex10', '29'), - r'\rightparen' : ( 'cmex10', '29'), - r'\LEFTangle' : ( 'cmex10', '2A'), - '+' : ( 'cmex10', '2B'), - '0' : ( 'cmex10', '30'), - '1' : ( 'cmex10', '31'), - '2' : ( 'cmex10', '32'), - '3' : ( 'cmex10', '33'), - '4' : ( 'cmex10', '34'), - '5' : ( 'cmex10', '35'), - '7' : ( 'cmex10', '37'), - '8' : ( 'cmex10', '38'), - '9' : ( 'cmex10', '39'), - ':' : ( 'cmex10', '3A'), - ';' : ( 'cmex10', '3B'), - '=' : ( 'cmex10', '3D'), - r'\leftangle' : ( 'cmex10', '44'), - r'\rightangle' : ( 'cmex10', '45'), - r'\oint' : ( 'cmex10', '49'), - r'\bigodot' : ( 'cmex10', '4B'), - r'\bigoplus' : ( 'cmex10', '4D'), - r'\bigotimes' : ( 'cmex10', '4F'), - r'\sum' : ( 'cmex10', '58'), - r'\prod' : ( 'cmex10', '59'), - r'\int' : ( 'cmex10', '5A'), - '[' : ( 'cmex10', '5B'), - r'\bigcup' : ( 'cmex10', '5B'), - r'\leftbracket' : ( 'cmex10', '5B'), - r'\bigcap' : ( 'cmex10', '5C'), - r'\biguplus' : ( 'cmex10', '5D'), - r'\rightbracket' : ( 'cmex10', '5D'), - ']' : ( 'cmex10', '5D'), - r'\bigwedge' : ( 'cmex10', '5E'), - r'\bigvee' : ( 'cmex10', '5F'), - r'\coprod' : ( 'cmex10', '61'), - r'\Sqrt' : ( 'cmex10', '70'), - r'\sqrt' : ( 'cmex10', '70'), - r'\SQRT' : ( 'cmex10', '72'), - r'\Sigma' : ( 'cmmi10', '06'), - r'\Upsilon' : ( 'cmmi10', '07'), - r'\Phi' : ( 'cmmi10', '08'), - r'\Psi' : ( 'cmmi10', '09'), - r'\alpha' : ( 'cmmi10', '0B'), - r'\beta' : ( 'cmmi10', '0C'), - r'\gamma' : ( 'cmmi10', '0D'), - r'\delta' : ( 'cmmi10', '0E'), - r'\epsilon' : ( 'cmmi10', '0F'), - r'\zeta' : ( 'cmmi10', '10'), - r'\eta' : ( 'cmmi10', '11'), - r'\theta' : ( 'cmmi10', '12'), - r'\iota' : ( 'cmmi10', '13'), - r'\lambda' : ( 'cmmi10', '15'), - r'\mu' : ( 'cmmi10', '16'), - r'\nu' : ( 'cmmi10', '17'), - r'\xi' : ( 'cmmi10', '18'), - r'\pi' : ( 'cmmi10', '19'), - r'\kappa' : ( 'cmmi10', '19'), - r'\rho' : ( 'cmmi10', '1A'), - r'\sigma' : ( 'cmmi10', '1B'), - r'\tau' : ( 'cmmi10', '1C'), - r'\upsilon' : ( 'cmmi10', '1D'), - r'\phi' : ( 'cmmi10', '1E'), - r'\chi' : ( 'cmmi10', '1F'), - r'\psi' : ( 'cmmi10', '20'), - r'\omega' : ( 'cmmi10', '21'), - r'\varepsilon' : ( 'cmmi10', '22'), - r'\vartheta' : ( 'cmmi10', '23'), - r'\varrho' : ( 'cmmi10', '25'), - r'\varsigma' : ( 'cmmi10', '26'), - r'\varphi' : ( 'cmmi10', '27'), - r'\leftharpoonup' : ( 'cmmi10', '28'), - r'\leftharpoondown' : ( 'cmmi10', '29'), - r'\rightharpoonup' : ( 'cmmi10', '2A'), - r'\rightharpoondown' : ( 'cmmi10', '2B'), - r'\triangleright' : ( 'cmmi10', '2E'), - r'\triangleleft' : ( 'cmmi10', '2F'), - '.' : ( 'cmmi10', '3A'), - ',' : ( 'cmmi10', '3B'), - '<' : ( 'cmmi10', '3C'), - '/' : ( 'cmmi10', '3D'), - '>' : ( 'cmmi10', '3E'), - r'\flat' : ( 'cmmi10', '5B'), - r'\natural' : ( 'cmmi10', '5C'), - r'\sharp' : ( 'cmmi10', '5D'), - r'\smile' : ( 'cmmi10', '5E'), - r'\frown' : ( 'cmmi10', '5F'), - r'\ell' : ( 'cmmi10', '60'), - r'\imath' : ( 'cmmi10', '7B'), - r'\jmath' : ( 'cmmi10', '7C'), - r'\wp' : ( 'cmmi10', '7D'), - r'\Gamma' : ( 'cmr10', '00'), - r'\Delta' : ( 'cmr10', '01'), - r'\Theta' : ( 'cmr10', '02'), - r'\Lambda' : ( 'cmr10', '03'), - r'\Xi' : ( 'cmr10', '04'), - r'\Pi' : ( 'cmr10', '05'), - r'\Omega' : ( 'cmr10', '0A'), - '-' : ( 'cmsy10', '00'), - r'\cdot' : ( 'cmsy10', '01'), - r'\times' : ( 'cmsy10', '02'), - '*' : ( 'cmsy10', '03'), - r'\ast' : ( 'cmsy10', '03'), - r'\div' : ( 'cmsy10', '04'), - r'\diamond' : ( 'cmsy10', '05'), - r'\pm' : ( 'cmsy10', '06'), - r'\mp' : ( 'cmsy10', '07'), - r'\oplus' : ( 'cmsy10', '08'), - r'\ominus' : ( 'cmsy10', '09'), - r'\otimes' : ( 'cmsy10', '0A'), - r'\oslash' : ( 'cmsy10', '0B'), - r'\odot' : ( 'cmsy10', '0C'), - r'\bigcirc' : ( 'cmsy10', '0D'), - r'\circ' : ( 'cmsy10', '0E'), - r'\bullet' : ( 'cmsy10', '0F'), - r'\simeq' : ( 'cmsy10', '10'), - r'\asymp' : ( 'cmsy10', '11'), - r'\subseteq' : ( 'cmsy10', '12'), - r'\supseteq' : ( 'cmsy10', '13'), - r'\leq' : ( 'cmsy10', '14'), - r'\geq' : ( 'cmsy10', '15'), - r'\preceq' : ( 'cmsy10', '16'), - r'\succeq' : ( 'cmsy10', '17'), - r'\sim' : ( 'cmsy10', '18'), - r'\approx' : ( 'cmsy10', '19'), - r'\subset' : ( 'cmsy10', '1A'), - r'\supset' : ( 'cmsy10', '1B'), - r'\ll' : ( 'cmsy10', '1C'), - r'\gg' : ( 'cmsy10', '1D'), - r'\prec' : ( 'cmsy10', '1E'), - r'\succ' : ( 'cmsy10', '1F'), - r'\rightarrow' : ( 'cmsy10', '20'), - r'\leftarrow' : ( 'cmsy10', '21'), - r'\uparrow' : ( 'cmsy10', '22'), - r'\downarrow' : ( 'cmsy10', '23'), - r'\leftrightarrow' : ( 'cmsy10', '24'), - r'\nearrow' : ( 'cmsy10', '25'), - r'\searrow' : ( 'cmsy10', '26'), - r'\Leftarrow' : ( 'cmsy10', '28'), - r'\Rightarrow' : ( 'cmsy10', '29'), - r'\Uparrow' : ( 'cmsy10', '2A'), - r'\Downarrow' : ( 'cmsy10', '2B'), - r'\Leftrightarrow' : ( 'cmsy10', '2C'), - r'\nwarrow' : ( 'cmsy10', '2D'), - r'\swarrow' : ( 'cmsy10', '2E'), - r'\propto' : ( 'cmsy10', '2F'), - r'\prime' : ( 'cmsy10', '30'), - r'\infty' : ( 'cmsy10', '31'), - r'\in' : ( 'cmsy10', '32'), - r'\ni' : ( 'cmsy10', '33'), - r'\bigtriangleup' : ( 'cmsy10', '34'), - r'\bigtriangledown' : ( 'cmsy10', '35'), - r'\slash' : ( 'cmsy10', '36'), - r'\forall' : ( 'cmsy10', '38'), - r'\exists' : ( 'cmsy10', '39'), - r'\neg' : ( 'cmsy10', '3A'), - r'\emptyset' : ( 'cmsy10', '3B'), - r'\Re' : ( 'cmsy10', '3C'), - r'\Im' : ( 'cmsy10', '3D'), - r'\top' : ( 'cmsy10', '3E'), - r'\bot' : ( 'cmsy10', '3F'), - r'\aleph' : ( 'cmsy10', '40'), - r'\cup' : ( 'cmsy10', '5B'), - r'\cap' : ( 'cmsy10', '5C'), - r'\uplus' : ( 'cmsy10', '5D'), - r'\wedge' : ( 'cmsy10', '5E'), - r'\vee' : ( 'cmsy10', '5F'), - r'\vdash' : ( 'cmsy10', '60'), - r'\dashv' : ( 'cmsy10', '61'), - r'\lfloor' : ( 'cmsy10', '62'), - r'\rfloor' : ( 'cmsy10', '63'), - r'\lceil' : ( 'cmsy10', '64'), - r'\rceil' : ( 'cmsy10', '65'), - r'\lbrace' : ( 'cmsy10', '66'), - r'\rbrace' : ( 'cmsy10', '67'), - r'\langle' : ( 'cmsy10', '68'), - r'\rangle' : ( 'cmsy10', '69'), - r'\mid' : ( 'cmsy10', '6A'), - r'\vert' : ( 'cmsy10', '6A'), - r'\Vert' : ( 'cmsy10', '6B'), - r'\updownarrow' : ( 'cmsy10', '6C'), - r'\Updownarrow' : ( 'cmsy10', '6D'), - r'\backslash' : ( 'cmsy10', '6E'), - r'\wr' : ( 'cmsy10', '6F'), - r'\nabla' : ( 'cmsy10', '72'), - r'\sqcup' : ( 'cmsy10', '74'), - r'\sqcap' : ( 'cmsy10', '75'), - r'\sqsubseteq' : ( 'cmsy10', '76'), - r'\sqsupseteq' : ( 'cmsy10', '77'), - r'\S' : ( 'cmsy10', '78'), - r'\dag' : ( 'cmsy10', '79'), - r'\ddag' : ( 'cmsy10', '7A'), - r'\P' : ( 'cmsy10', '7B'), - r'\clubsuit' : ( 'cmsy10', '7C'), - r'\diamondsuit' : ( 'cmsy10', '7D'), - r'\heartsuit' : ( 'cmsy10', '7E'), - r'\spadesuit' : ( 'cmsy10', '7F'), -} - -""" -no mlname for \RIGHTangle -no type1 key \equiv # could not find in ASM -no type1 key \kappa # could not find kappa -no type1 key \RIGHTangle # could not find -""" - latex_to_standard = { r'\cong' : ('psyr', 64), r'\Delta' : ('psyr', 68), @@ -757,17 +329,60 @@ r'\langle' : ('psyr', 225), r'\Sigma' : ('psyr', 229), r'\sum' : ('psyr', 229), - # these are mathml names, I think. I'm just using them for the - # tex methods noted - r'\circumflexaccent' : ('pncri8a', 124), # for \hat - r'\combiningbreve' : ('pncri8a', 81), # for \breve - r'\combininggraveaccent' : ('pncri8a', 114), # for \grave - r'\combiningacuteaccent' : ('pncri8a', 63), # for \accute - r'\combiningdiaeresis' : ('pncri8a', 91), # for \ddot - r'\combiningtilde' : ('pncri8a', 75), # for \tilde + r'\forall' : ('psyr', 34), + r'\exists' : ('psyr', 36), + r'\lceil' : ('psyr', 233), + r'\lbrace' : ('psyr', 123), + r'\Psi' : ('psyr', 89), + r'\bot' : ('psyr', 0136), + r'\Omega' : ('psyr', 0127), + r'\leftbracket' : ('psyr', 0133), + r'\rightbracket' : ('psyr', 0135), + r'\leftbrace' : ('psyr', 123), + r'\leftparen' : ('psyr', 050), + r'\prime' : ('psyr', 0242), + r'\sharp' : ('psyr', 043), + r'\slash' : ('psyr', 057), + r'\Lamda' : ('psyr', 0114), + r'\neg' : ('psyr', 0330), + r'\Upsilon' : ('psyr', 0241), + r'\rightbrace' : ('psyr', 0175), + r'\rfloor' : ('psyr', 0373), + r'\lambda' : ('psyr', 0154), + r'\to' : ('psyr', 0256), + r'\Xi' : ('psyr', 0130), + r'\emptyset' : ('psyr', 0306), + r'\lfloor' : ('psyr', 0353), + r'\rightparen' : ('psyr', 051), + r'\rceil' : ('psyr', 0371), + r'\ni' : ('psyr', 047), + r'\epsilon' : ('psyr', 0145), + r'\Theta' : ('psyr', 0121), + r'\langle' : ('psyr', 0341), + r'\leftangle' : ('psyr', 0341), + r'\rangle' : ('psyr', 0361), + r'\rightangle' : ('psyr', 0361), + r'\rbrace' : ('psyr', 0175), + r'\circ' : ('psyr', 0260), + r'\diamond' : ('psyr', 0340), + r'\mu' : ('psyr', 0155), + r'\mid' : ('psyr', 0352), + r'\imath' : ('pncri8a', 105), + r'\%' : ('pncr8a', 37), + r'\$' : ('pncr8a', 36), + r'\{' : ('pncr8a', 123), + r'\}' : ('pncr8a', 125), + r'\backslash' : ('pncr8a', 92), + r'\ast' : ('pncr8a', 42), + + r'\circumflexaccent' : ('pncri8a', 124), # for \hat + r'\combiningbreve' : ('pncri8a', 81), # for \breve + r'\combininggraveaccent' : ('pncri8a', 114), # for \grave + r'\combiningacuteaccent' : ('pncri8a', 63), # for \accute + r'\combiningdiaeresis' : ('pncri8a', 91), # for \ddot + r'\combiningtilde' : ('pncri8a', 75), # for \tilde r'\combiningrightarrowabove' : ('pncri8a', 110), # for \vec - r'\combiningdotabove' : ('pncri8a', 26), # for \dot - r'\imath' : ('pncri8a', 105) + r'\combiningdotabove' : ('pncri8a', 26), # for \dot } # Automatically generated. @@ -2214,7 +1829,7 @@ 'updownarrows': 8645, 'heartsuit': 9825, 'trianglelefteq': 8884, -'ddagger': 8225, +'ddag': 8225, 'sqsubseteq': 8849, 'mapsfrom': 8612, 'boxbar': 9707, @@ -2516,7 +2131,7 @@ 'succcurlyeq': 8829, 'gamma': 947, 'scrR': 8475, -'dagger': 8224, +'dag': 8224, 'thickspace': 8197, 'frakZ': 8488, 'lessdot': 8918, @@ -2589,7 +2204,39 @@ 'divideontimes': 8903, 'lbrack': 91, 'textquotedblright': 8221, -'Colon': 8759} +'Colon': 8759, +'%': 37, +'$': 36, +'{': 123, +'}': 125, +'imath': 0xfd, +'circumflexaccent' : 770, +'combiningbreve' : 774, +'combiningoverline' : 772, +'combininggraveaccent' : 768, +'combiningacuteaccent' : 764, +'combiningdiaeresis' : 776, +'combiningtilde' : 771, +'combiningrightarrowabove' : 8407, +'combiningdotabove' : 775, +'to': 8594, +'succeq': 8829, +'emptyset': 8709, +'leftparen': 40, +'rightparen': 41, +'bigoplus': 10753, +'leftangle': 10216, +'rightangle': 10217, +'leftbrace': 124, +'rightbrace': 125, +'jmath': 567, +'bigodot': 10752, +'preceq': 8828, +'biguplus': 10756, +'epsilon': 949, +'vartheta': 977, +'bigotimes': 10754 +} uni2tex = dict([(v,k) for k,v in tex2uni.items()]) @@ -2692,7 +2339,7 @@ 'updownarrows': 'uni21C5', 'heartsuit': 'uni2661', 'trianglelefteq': 'uni22B4', -'ddagger': 'daggerdbl', +'ddag': 'daggerdbl', 'sqsubseteq': 'uni2291', 'mapsfrom': 'uni21A4', 'boxbar': 'uni25EB', @@ -2994,7 +2641,7 @@ 'succcurlyeq': 'uni227D', 'gamma': 'uni03B3', 'scrR': 'uni211B', -'dagger': 'dagger', +'dag': 'dagger', 'thickspace': 'uni2005', 'frakZ': 'uni2128', 'lessdot': 'uni22D6', @@ -3070,4 +2717,3 @@ 'Colon': 'uni2237'} type12tex = dict([(v,k) for k,v in tex2type1.items()]) - Modified: trunk/matplotlib/lib/matplotlib/mathtext.py =================================================================== --- trunk/matplotlib/lib/matplotlib/mathtext.py 2007年07月30日 07:03:47 UTC (rev 3630) +++ trunk/matplotlib/lib/matplotlib/mathtext.py 2007年07月30日 16:41:53 UTC (rev 3631) @@ -131,7 +131,9 @@ from __future__ import division import os, sys from cStringIO import StringIO +from math import floor, ceil from sets import Set +from unicodedata import category from warnings import warn from matplotlib import verbose @@ -146,7 +148,7 @@ is_string_like from matplotlib.ft2font import FT2Font, KERNING_UNFITTED from matplotlib.font_manager import fontManager, FontProperties -from matplotlib._mathtext_data import latex_to_bakoma, cmkern, \ +from matplotlib._mathtext_data import latex_to_bakoma, \ latex_to_standard, tex2uni, type12uni, tex2type1, uni2type1 from matplotlib import get_data_path, rcParams @@ -164,14 +166,6 @@ ############################################################################## # FONTS -def font_open(filename): - ext = filename.rsplit('.',1)[1] - if ext == 'afm': - return AFM(str(filename)) - else: - return FT2Font(str(filename)) - - def get_unicode_index(symbol): """get_unicode_index(symbol) -> integer @@ -187,10 +181,6 @@ try:# Is symbol a TeX symbol (i.e. \alpha) return tex2uni[symbol.strip("\\")] except KeyError: - pass - try:# Is symbol a Type1 name (i.e. degree)? If not raise error - return type12uni[symbol] - except KeyError: message = """'%(symbol)s' is not a valid Unicode character or TeX/Type1 symbol"""%locals() raise ValueError, message @@ -219,574 +209,473 @@ # The user did not suply a valid symbol, show usage raise ValueError, get_type1_name.__doc__ +class MathtextBackend(object): + def __init__(self): + fonts_object = None -class Fonts: - """ - An abstract base class for fonts that want to render mathtext + def set_canvas_size(self, w, h): + 'Dimension the drawing canvas; may be a noop' + self.width = w + self.height = h - The class must be able to take symbol keys and font file names and - return the character metrics as well as do the drawing - """ - - def get_kern(self, facename, symleft, symright, fontsize, dpi): - """ - Get the kerning distance for font between symleft and symright. + def render_glyph(self, ox, oy, info): + raise NotImplementedError() - facename is one of tt, it, rm, cal or None + def render_filled_rect(self, x1, y1, x2, y2): + raise NotImplementedError() - sym is a single symbol(alphanum, punct) or a special symbol - like \sigma. - - """ - return 0 - - def get_metrics(self, facename, sym, fontsize, dpi): - """ - facename is one of tt, it, rm, cal or None - - sym is a single symbol(alphanum, punct) or a special symbol - like \sigma. - - fontsize is in points - - Return object has attributes - see - http://www.freetype.org/freetype2/docs/tutorial/step2.html for - a pictoral representation of these attributes - - advance - height - width - xmin, xmax, ymin, ymax - the ink rectangle of the glyph - """ - raise NotImplementedError('Derived must override') - + def get_results(self): + """Return a backend specific tuple of things to return to the + backend after all processing is done.""" + raise NotImplementedError() + +class MathtextBackendAgg(MathtextBackend): def set_canvas_size(self, w, h): - 'Dimension the drawing canvas; may be a noop' - self.width, self.height = w, h + MathtextBackend.set_canvas_size(self, w, h) + for font in self.fonts_object.get_fonts(): + font.set_bitmap_size(int(w), int(h)) - def render(self, ox, oy, facename, sym, fontsize, dpi): - pass + def render_glyph(self, ox, oy, info): + info.font.draw_glyph_to_bitmap( + int(ox), int(oy - info.metrics.ymax), info.glyph) def render_rect_filled(self, x1, y1, x2, y2): - pass + font = self.fonts_object.get_fonts()[0] + font.draw_rect_filled( + floor(max(0, x1 - 1)), + floor(y1), + ceil(max(x2 - 1, x1)), + ceil(max(y2 - 1, y1))) + + def get_results(self): + return (self.width, + self.height, + self.fonts_object.get_fonts(), + self.fonts_object.get_used_characters()) - def get_used_characters(self): - return {} +class MathtextBackendPs(MathtextBackend): + def __init__(self): + self.pswriter = StringIO() - -class DummyFonts(Fonts): - 'dummy class for debugging parser' - def get_metrics(self, font, sym, fontsize, dpi): - - metrics = Bunch( - advance = 0, - height = 0, - width = 0, - xmin = 0, - xmax = 0, - ymin = 0, - ymax = 0, - ) - return metrics - - -class UnicodeFonts(Fonts): - """An abstract base class for handling Unicode fonts. - -Specific terminology: - * fontface: an FT2Font object, corresponding to a facename - * facename: a string that defines the (type)face's name - 'rm', 'it' etc. - * filename: a string that is used for generating a fontface object - * symbol*: a single Unicode character or a TeX command, - or to be precise, a TeX symbol command like \alpha (but not \frac) or - even a Type1/PS name - * filenamesd: a dict that maps the face's name to the filename: - filenamesd = { 'cal' : 'fontnamecal.ext', - 'rm' : 'fontnamerm.ext', - 'tt' : 'fontnamett.ext', - 'it' : 'fontnameit.ext', - None : 'fontnamesmth.ext'} - filenamesd should be declared as a class atribute - * glyphdict: a dict used for caching of glyph specific data - * fonts: a dict of facename -> fontface pairs - * charmaps: a dict of facename -> charmap pairs. Charmap maps character - codes to glyph indices - * glyphmaps: a dict of facename -> glyphmap pairs. A glyphmap is an - inverted charmap - * output: a string in ['Agg','SVG','PS'], coresponding to the backends - * index: Fontfile specific index of a glyph. - -""" - - # The path to the dir with the fontfiles - def __init__(self, output='Agg'): - self.facenames = self.filenamesd.keys() - # Set the filenames to full path - for facename in self.filenamesd: - self.filenamesd[facename] = self.filenamesd[facename] - if output: - self.output = output - # self.glyphdict[key] = facename, metrics, glyph, offset - self.glyphdict = {} - - self.fonts = dict( - [ (facename, font_open(self.filenamesd[facename])) for - facename in self.facenames]) - # a dict of charcode -> glyphindex pairs - self.charmaps = dict( - [ (facename, self.fonts[facename].get_charmap()) - for facename in self.facenames]) - # a dict of glyphindex -> charcode pairs - self.glyphmaps = {} - for facename in self.facenames: - charmap = self.charmaps[facename] - self.glyphmaps[facename] = dict([(glyphind, charcode) - for charcode, glyphind in charmap.items()]) - for fontface in self.fonts.values(): - fontface.clear() - if self.output == 'SVG': - # a list of "glyphs" we need to render this thing in SVG - self.svg_glyphs=[] - - def set_canvas_size(self, w, h, pswriter=None): - 'Dimension the drawing canvas; may be a noop' - # self.width = int(w) - # self.height = int(h) - # I don't know why this was different than the PS version - self.width = w - self.height = h - if pswriter: - self.pswriter = pswriter - else: - for fontface in self.fonts.values(): - fontface.set_bitmap_size(int(w), int(h)) - - def render(self, ox, oy, facename, symbol, fontsize, dpi): - filename = self.filenamesd[facename] - uniindex, metrics, glyph, offset = self._get_info(facename, - symbol, fontsize, dpi) - if self.output == 'SVG': - oy += offset - 512/2048.*10. - # TO-DO - make a method for it - # This gets the name of the font. - familyname = self.fonts[facename].get_sfnt()[(1,0,0,1)] - thetext = unichr(uniindex) - thetext.encode('utf-8') - self.svg_glyphs.append((familyname, fontsize, thetext, ox, oy, - metrics)) - elif self.output == 'PS': - # This should be changed to check for math mode or smth. - #if filename == 'cmex10.ttf': - # oy += offset - 512/2048.*10. - - # Get the PS name of a glyph (his unicode integer code) - # from the font object - symbolname = self._get_glyph_name(uniindex, facename) - psfontname = self.fonts[facename].postscript_name - ps = """/%(psfontname)s findfont + def render_glyph(self, ox, oy, info): + oy = self.height - oy + info.offset + postscript_name = info.postscript_name + fontsize = info.fontsize + symbol_name = info.symbol_name + + ps = """/%(postscript_name)s findfont %(fontsize)s scalefont setfont %(ox)f %(oy)f moveto -/%(symbolname)s glyphshow +/%(symbol_name)s glyphshow """ % locals() - self.pswriter.write(ps) - else: # Agg - fontface = self.fonts[facename] - fontface.draw_glyph_to_bitmap( - int(ox), int(self.height - oy - metrics.ymax), glyph) + self.pswriter.write(ps) - def get_metrics(self, facename, symbol, fontsize, dpi): - uniindex, metrics, glyph, offset = \ - self._get_info(facename, symbol, fontsize, dpi) - return metrics + def render_rect_filled(self, x1, y1, x2, y2): + ps = "%f %f %f %f rectfill" % (x1, self.height - y2, x2 - x1, y2 - y1) + self.pswriter.write(ps) - # Methods that must be overridden for fonts that are not unicode aware + def get_results(self): + return (self.width, + self.height, + self.pswriter, + self.fonts_object.get_used_characters()) + +class MathtextBackendPdf(MathtextBackend): + def __init__(self): + self.pswriter = [] + + def render_glyph(self, ox, oy, info): + filename = info.font.fname + oy = self.height - oy + info.offset - def _get_unicode_index(self, symbol): - return get_unicode_index(symbol) + self.pswriter.append(('glyph', ox, oy, filename, info.fontsize, info.num)) - def _get_glyph_name(self, uniindex, facename): - """get_glyph_name(self, uniindex, facename) -> string + def render_rect_filled(self, x1, y1, x2, y2): + self.pswriter.append(('rect', x1, self.height - y2, x2 - x1, y2 - y1)) -Returns the name of the glyph directly from the font object. + def get_results(self): + return (self.width, + self.height, + self.pswriter, + self.fonts_object.get_used_characters()) -""" - font = self.fonts[facename] - glyphindex = self.glyphmaps[facename][uniindex] - return font.get_glyph_name(glyphindex) - - def _get_info(self, facename, symbol, fontsize, dpi): - 'load the facename, metrics and glyph' - #print hex(index), symbol, filename, facename - key = facename, symbol, fontsize, dpi - tup = self.glyphdict.get(key) - if tup is not None: - return tup - filename = self.filenamesd[facename] - fontface = self.fonts[facename] - fontface.set_size(fontsize, dpi) - head = fontface.get_sfnt_table('head') - uniindex = self._get_unicode_index(symbol) - glyphindex = self.glyphmaps[facename][uniindex] - glyph = fontface.load_char(uniindex) - xmin, ymin, xmax, ymax = [val/64.0 for val in glyph.bbox] - # This is black magic to me (Edin) - if filename == 'cmex10.ttf': - if self.output == 'PS': - offset = -(head['yMin']+512)/head['unitsPerEm']*10. - else: - offset = glyph.height/64.0/2 + 256.0/64.0*dpi/72.0 - 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.glyphdict[key] = uniindex, metrics, glyph, offset - return self.glyphdict[key] - - -class MyUnicodeFonts(UnicodeFonts): - _initialized = False +class MathtextBackendSvg(MathtextBackend): def __init__(self): - if not MyUnicodeFonts._initialized: - prop = FontProperties() - prop.set_family('serif') - self.rmfile = fontManager.findfont(prop) + self.svg_glyphs = [] + self.svg_rects = [] + + def render_glyph(self, ox, oy, info): + oy = self.height - oy + info.offset + thetext = unichr(info.num) + self.svg_glyphs.append( + (info.font, info.fontsize, thetext, ox, oy, info.metrics)) - prop.set_family('fantasy') - self.calfile = fontManager.findfont(prop) + def render_rect_filled(self, x1, y1, x2, y2): + self.svg_rects.append( + (x1, self.height - y1, x2 - x1, y2 - y1)) - prop.set_family('monospace') - self.ttfile = fontManager.findfont(prop) + def get_results(self): + svg_elements = Bunch(svg_glyphs = self.svg_glyphs, + svg_rects = self.svg_rects) + return (self.width, + self.height, + svg_elements, + self.fonts_object.get_used_characters()) + +class Fonts(object): + """ + An abstract base class for fonts that want to render mathtext - prop.set_family('serif') - prop.set_style('italic') - self.itfile = fontManager.findfont(prop) - self.filenamesd = { 'rm' : self.rmfile, - 'it' : self.itfile, - 'cal' : self.calfile, - 'tt' : self.ttfile, - } - MyUnicodeFonts._initialized = True + The class must be able to take symbol keys and font file names and + return the character metrics. It also delegates to a backend class + to do the actual drawing. + """ + def __init__(self, default_font_prop, mathtext_backend): + """default_font_prop: A FontProperties object to use for the + default non-math font, or the base font for Unicode font + rendering. + mathtext_backend: A subclass of MathTextBackend used to + delegate the actual rendering.""" + self.default_font_prop = default_font_prop + self.mathtext_backend = mathtext_backend + # Make these classes doubly-linked + self.mathtext_backend.fonts_object = self + self.used_characters = {} + + def get_kern(self, font1, sym1, fontsize1, + font2, sym2, fontsize2, dpi): + """ + Get the kerning distance for font between sym1 and sym2. -# TO-DO: pretty much everything -class BakomaUnicodeFonts(UnicodeFonts): - """A class that simulates Unicode support in the BaKoMa fonts""" + fontX: one of the TeX font names, tt, it, rm, cal, sf, bf or + default (non-math) + symX: a symbol in raw TeX form. e.g. '1', 'x' or '\sigma' + fontsizeX: the fontsize in points + dpi: the current dots-per-inch + + sym is a single symbol(alphanum, punct) or a special symbol + like \sigma. - filenamesd = { 'cal' : 'cmsy10.ttf', - 'rm' : 'cmr10.ttf', - 'tt' : 'cmtt10.ttf', - 'it' : 'cmmi10.ttf', - 'bf' : 'cmb10.ttf', - 'sf' : 'cmss10.ttf', - None : 'cmmi10.ttf', - } + """ + return 0. - # We override the UnicodeFonts methods, that depend on Unicode support - def _get_unicode_index(self, symbol): - uniindex = get_unicode_index(symbol) + def get_metrics(self, font, sym, fontsize, dpi): + """ + font: one of the TeX font names, tt, it, rm, cal, sf, bf or + default (non-math) + sym: a symbol in raw TeX form. e.g. '1', 'x' or '\sigma' + fontsize: font size in points + dpi: current dots-per-inch - # Should be deleted - def _get_glyph_name(self, uniindex, facename): - """get_glyph_name(self, uniindex, facename) -> string + advance + height + width + xmin, xmax, ymin, ymax - the ink rectangle of the glyph + iceberg - the distance from the baseline to the top of the glyph. + horiBearingY in Truetype parlance, height in TeX parlance + """ + info = self._get_info(font, sym, fontsize, dpi) + return info.metrics -Returns the name of the glyph directly from the font object. -Because BaKoma fonts don't support Unicode, 'uniindex' is misleading + def set_canvas_size(self, w, h): + 'Dimension the drawing canvas; may be a noop' + self.width, self.height = ceil(w), ceil(h) + self.mathtext_backend.set_canvas_size(self.width, self.height) -""" - font = self.fonts[facename] - glyphindex = self.glyphmaps[facename][uniindex] - return font.get_glyph_name(glyphindex) + def render_glyph(self, ox, oy, facename, sym, fontsize, dpi): + info = self._get_info(facename, sym, fontsize, dpi) + realpath, stat_key = get_realpath_and_stat(info.font.fname) + used_characters = self.used_characters.setdefault( + stat_key, (realpath, Set())) + used_characters[1].update(unichr(info.num)) + self.mathtext_backend.render_glyph(ox, oy, info) - def _get_info(self, facename, symbol, fontsize, dpi): - 'load the facename, metrics and glyph' - #print hex(index), symbol, filename, facename - key = facename, symbol, fontsize, dpi - tup = self.glyphdict.get(key) - if tup is not None: - return tup - filename = self.filenamesd[facename] - fontface = self.fonts[facename] - fontface.set_size(fontsize, dpi) - head = fontface.get_sfnt_table('head') - uniindex = self._get_unicode_index(symbol) - glyphindex = self.glyphmaps[facename][uniindex] - glyph = fontface.load_char(uniindex) - xmin, ymin, xmax, ymax = [val/64.0 for val in glyph.bbox] - # This is black magic to me (Edin) - if filename == 'cmex10.ttf': - if self.output == 'PS': - offset = -(head['yMin']+512)/head['unitsPerEm']*10. - else: - offset = glyph.height/64.0/2 + 256.0/64.0*dpi/72.0 - 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.glyphdict[key] = uniindex, metrics, glyph, offset - return self.glyphdict[key] + def render_rect_filled(self, x1, y1, x2, y2): + self.mathtext_backend.render_rect_filled(x1, y1, x2, y2) + def get_xheight(self, font, fontsize, dpi): + raise NotImplementedError() -# TO-DO: Implement all methods -class CMUUnicodeFonts(UnicodeFonts): - """A class representing Computer Modern Unicode Fonts, made by -Andrey V. Panov -panov /at/ canopus. iacp. dvo. ru -They are distributed under the X11 License. + def get_underline_thickness(self, font, fontsize, dpi): + raise NotImplementedError() + + def get_used_characters(self): + return self.used_characters -""" + def get_results(self): + return self.mathtext_backend.get_results() - -# Old classes - -class BakomaFonts(Fonts): + def get_sized_alternatives_for_symbol(self, fontname, sym): + """Override if your font provides multiple sizes of the same + symbol.""" + return [(fontname, sym)] + +class TruetypeFonts(Fonts): """ + A generic base class for all font setups that use Truetype fonts + (through ft2font) + """ + """ Use the Bakoma true type fonts for rendering """ # allocate a new set of fonts basepath = os.path.join( get_data_path(), 'fonts', 'ttf' ) - fontmap = { 'cal' : 'Cmsy10', - 'rm' : 'Cmr10', - 'tt' : 'Cmtt10', - 'it' : 'Cmmi10', - 'bf' : 'Cmb10', - 'sf' : 'Cmss10', - None : 'Cmmi10', - 'ex' : 'Cmex10' - } - class CachedFont: def __init__(self, font): self.font = font self.charmap = font.get_charmap() self.glyphmap = dict( [(glyphind, ccode) for ccode, glyphind in self.charmap.items()]) - - def __init__(self): - self.glyphd = {} - self.fonts = {} - self.used_characters = {} + def __repr__(self): + return repr(self.font) + + def __init__(self, default_font_prop, mathtext_backend): + Fonts.__init__(self, default_font_prop, mathtext_backend) + self.glyphd = {} + self.fonts = {} + + filename = fontManager.findfont(default_font_prop) + default_font = self.CachedFont(FT2Font(str(filename))) + + self.fonts['default'] = default_font + def _get_font(self, font): """Looks up a CachedFont with its charmap and inverse charmap. - font may be a TeX font name (cal, rm, it etc.), a Computer Modern - font name (cmtt10, cmr10, etc.) or an FT2Font object.""" - if isinstance(font, str): - if font not in self.fontmap.values(): - basename = self.fontmap[font] - else: - basename = font + font may be a TeX font name (cal, rm, it etc.), or postscript name.""" + if font in self.fontmap: + basename = self.fontmap[font] else: - basename = font.postscript_name + basename = font cached_font = self.fonts.get(basename) if cached_font is None: - if isinstance(font, str): - font = FT2Font(os.path.join(self.basepath, basename.lower() + ".ttf")) - basename = font.postscript_name + font = FT2Font(os.path.join(self.basepath, basename + ".ttf")) cached_font = self.CachedFont(font) self.fonts[basename] = cached_font - return basename, cached_font + self.fonts[font.postscript_name] = cached_font + self.fonts[font.postscript_name.lower()] = cached_font + return cached_font - def get_font(self, font): - return self._get_font(font)[1].font - def get_fonts(self): - return [x.font for x in self.fonts.values()] - - def get_metrics(self, font, sym, fontsize, dpi): - basename, font, metrics, symbol_name, num, glyph, offset = \ - self._get_info(font, sym, fontsize, dpi) - return metrics + return list(set([x.font for x in self.fonts.values()])) - def _get_offset(self, basename, cached_font, glyph, fontsize, dpi): - if basename.lower() == 'cmex10': - return glyph.height/64.0/2 + 256.0/64.0*dpi/72.0 + def _get_offset(self, cached_font, glyph, fontsize, dpi): return 0. - - def _get_info (self, font, sym, fontsize, dpi): + + def _get_info (self, fontname, sym, fontsize, dpi, mark_as_used=True): 'load the cmfont, metrics and glyph with caching' - if hasattr(font, 'postscript_name'): - fontname = font.postscript_name - else: - fontname = font - key = fontname, sym, fontsize, dpi - tup = self.glyphd.get(key) + bunch = self.glyphd.get(key) + if bunch is not None: + return bunch - if tup is not None: return tup - - if font in self.fontmap and latex_to_bakoma.has_key(sym): - basename, num = latex_to_bakoma[sym] - basename, cached_font = self._get_font(basename.capitalize()) - symbol_name = cached_font.font.get_glyph_name(num) - num = cached_font.glyphmap[num] - elif len(sym) == 1: - basename, cached_font = self._get_font(font) - num = ord(sym) - symbol_name = cached_font.font.get_glyph_name(cached_font.charmap[num]) - else: - num = 0 - raise ValueError('unrecognized symbol "%s"' % sym) + cached_font, num, symbol_name, fontsize = \ + self._get_glyph(fontname, sym, fontsize) font = cached_font.font font.set_size(fontsize, dpi) glyph = font.load_char(num) - realpath, stat_key = get_realpath_and_stat(font.fname) - used_characters = self.used_characters.setdefault( - stat_key, (realpath, Set())) - used_characters[1].update(unichr(num)) - xmin, ymin, xmax, ymax = [val/64.0 for val in glyph.bbox] - offset = self._get_offset(basename, cached_font, glyph, fontsize, dpi) + offset = self._get_offset(cached_font, glyph, fontsize, dpi) 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, + advance = glyph.linearHoriAdvance/65536.0, + height = glyph.height/64.0 + offset, + width = glyph.width/64.0, + xmin = xmin, + xmax = xmax, + ymin = ymin+offset, + ymax = ymax+offset, # iceberg is the equivalent of TeX's "height" iceberg = glyph.horiBearingY/64.0 + offset ) - self.glyphd[key] = basename, font, metrics, symbol_name, num, glyph, offset + self.glyphd[key] = Bunch( + font = font, + fontsize = fontsize, + postscript_name = font.postscript_name, + metrics = metrics, + symbol_name = symbol_name, + num = num, + glyph = glyph, + offset = 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 cached_font in self.fonts.values(): - cached_font.font.set_bitmap_size(int(w), int(h)) - - def render(self, ox, oy, font, sym, fontsize, dpi): - basename, font, metrics, symbol_name, num, glyph, offset = \ - self._get_info(font, sym, fontsize, dpi) - - font.draw_glyph_to_bitmap( - int(ox), int(oy - metrics.ymax), glyph) - - def render_rect_filled(self, x1, y1, x2, y2): - assert len(self.fonts) - font = self.fonts.values()[0] - font.font.draw_rect_filled( - max(0, x1 - 1), - y1, - max(x2 - 1, x1), - max(y2 - 1, y1)) - - def get_used_characters(self): - return self.used_characters - def get_xheight(self, font, fontsize, dpi): - basename, cached_font = self._get_font(font) + cached_font = self._get_font(font) cached_font.font.set_size(fontsize, dpi) pclt = cached_font.font.get_sfnt_table('pclt') + if pclt is None: + # Some fonts don't store the xHeight, so we do a poor man's xHeight + metrics = self.get_metrics(font, 'x', fontsize, dpi) + return metrics.iceberg xHeight = pclt['xHeight'] / 64.0 return xHeight def get_underline_thickness(self, font, fontsize, dpi): - basename, cached_font = self._get_font(font) + cached_font = self._get_font(font) cached_font.font.set_size(fontsize, dpi) return max(1.0, cached_font.font.underline_thickness / 64.0) - def get_kern(self, fontleft, symleft, fontsizeleft, - fontright, symright, fontsizeright, dpi): - if fontsizeleft == fontsizeright: - basename, font1, metrics, symbol_name, num1, glyph1, offset = \ - self._get_info(fontleft, symleft, fontsizeleft, dpi) - basename, font2, metrics, symbol_name, num2, glyph2, offset = \ - self._get_info(fontright, symright, fontsizeright, dpi) - if font1 == font2: - basename, font = self._get_font(font1) - return font.font.get_kerning(num1, num2, KERNING_UNFITTED) / 64.0 + def get_kern(self, font1, sym1, fontsize1, + font2, sym2, fontsize2, dpi): + if font1 == font2 and fontsize1 == fontsize2: + info1 = self._get_info(font1, sym1, fontsize1, dpi) + info2 = self._get_info(font2, sym2, fontsize2, dpi) + font = info1.font + return font.get_kerning(info1.num, info2.num, KERNING_UNFITTED) / 64.0 return 0.0 -class BakomaPSFonts(BakomaFonts): +class BakomaFonts(TruetypeFonts): """ - Use the Bakoma postscript fonts for rendering to backend_ps + Use the Bakoma true type fonts for rendering """ - - 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 render(self, ox, oy, font, sym, fontsize, dpi): - basename, font, metrics, symbol_name, num, glyph, offset = \ - self._get_info(font, sym, fontsize, dpi) - oy = self.height - oy + offset - - ps = """/%(basename)s findfont -%(fontsize)s scalefont -setfont -%(ox)f %(oy)f moveto -/%(symbol_name)s glyphshow -""" % locals() - self.pswriter.write(ps) - - def render_rect_filled(self, x1, y1, x2, y2): - ps = "%f %f %f %f rectfill" % (x1, self.height - y2, x2 - x1, y2 - y1) - self.pswriter.write(ps) + fontmap = { 'cal' : 'cmsy10', + 'rm' : 'cmr10', + 'tt' : 'cmtt10', + 'it' : 'cmmi10', + 'bf' : 'cmb10', + 'sf' : 'cmss10', + 'ex' : 'cmex10' + } -class BakomaPDFFonts(BakomaPSFonts): - """Hack of BakomaPSFonts for PDF support.""" + def _get_offset(self, cached_font, glyph, fontsize, dpi): + if cached_font.font.postscript_name == 'cmex10': + return glyph.height/64.0/2 + 256.0/64.0 * dpi/72.0 + return 0. - def render(self, ox, oy, font, sym, fontsize, dpi): - basename, font, metrics, symbol_name, num, glyph, offset = \ - self._get_info(font, sym, fontsize, dpi) - filename = font.fname - oy = self.height - oy + offset + def _get_glyph(self, fontname, sym, fontsize): + if fontname in self.fontmap and latex_to_bakoma.has_key(sym): + basename, num = latex_to_bakoma[sym] + cached_font = self._get_font(basename) + symbol_name = cached_font.font.get_glyph_name(num) + num = cached_font.glyphmap[num] + elif len(sym) == 1: + cached_font = self._get_font(fontname) + num = ord(sym) + symbol_name = cached_font.font.get_glyph_name( + cached_font.charmap[num]) + else: + raise ValueError('unrecognized symbol "%s"' % sym) - self.pswriter.append(('glyph', ox, oy, filename, fontsize, num)) + return cached_font, num, symbol_name, fontsize - def render_rect_filled(self, x1, y1, x2, y2): - self.pswriter.append(('rect', x1, self.height - y2, x2 - x1, y2 - y1)) + # The Bakoma fonts contain many pre-sized alternatives for the + # delimiters. The AutoSizedChar class will use these alternatives + # and select the best (closest sized) glyph. + _size_alternatives = { + '(' : [('rm', '('), ('ex', '\xa1'), ('ex', '\xb3'), + ('ex', '\xb5'), ('ex', '\xc3')], + ')' : [('rm', ')'), ('ex', '\xa2'), ('ex', '\xb4'), + ('ex', '\xb6'), ('ex', '\x21')], + '{' : [('cal', '{'), ('ex', '\xa9'), ('ex', '\x6e'), + ('ex', '\xbd'), ('ex', '\x28')], + '}' : [('cal', '}'), ('ex', '\xaa'), ('ex', '\x6f'), + ('ex', '\xbe'), ('ex', '\x29')], + # The fourth size of '[' is mysteriously missing from the BaKoMa font, + # so I've ommitted it for both + '[' : [('rm', '['), ('ex', '\xa3'), ('ex', '\x68'), + ('ex', '\x22')], + ']' : [('rm', ']'), ('ex', '\xa4'), ('ex', '\x69'), + ('ex', '\x23')], + r'\lfloor' : [('cal', '\x62'), ('ex', '\xa5'), ('ex', '\x6a'), + ('ex', '\xb9'), ('ex', '\x24')], + r'\rfloor' : [('cal', '\x63'), ('ex', '\xa6'), ('ex', '\x6b'), + ('ex', '\xba'), ('ex', '\x25')], + r'\lceil' : [('cal', '\x64'), ('ex', '\xa7'), ('ex', '\x6c'), + ('ex', '\xbb'), ('ex', '\x26')], + r'\rceil' : [('cal', '\x65'), ('ex', '\xa8'), ('ex', '\x6d'), + ('ex', '\xbc'), ('ex', '\x27')], + r'\langle' : [('cal', '\x68'), ('ex', '\xad'), ('ex', '\x44'), + ('ex', '\xbf'), ('ex', '\x2a')], + r'\rangle' : [('cal', '\x69'), ('ex', '\xae'), ('ex', '\x45'), + ... [truncated message content]
Revision: 3630 http://matplotlib.svn.sourceforge.net/matplotlib/?rev=3630&view=rev Author: efiring Date: 2007年07月30日 00:03:47 -0700 (2007年7月30日) Log Message: ----------- Removed last vestiges of old pcolor, scatter, quiver versions. Modified Paths: -------------- trunk/matplotlib/CHANGELOG trunk/matplotlib/boilerplate.py trunk/matplotlib/lib/matplotlib/axes.py trunk/matplotlib/lib/matplotlib/pylab.py Modified: trunk/matplotlib/CHANGELOG =================================================================== --- trunk/matplotlib/CHANGELOG 2007年07月30日 06:04:41 UTC (rev 3629) +++ trunk/matplotlib/CHANGELOG 2007年07月30日 07:03:47 UTC (rev 3630) @@ -1,6 +1,7 @@ 2007年07月29日 Changed default pcolor shading to flat; added aliases to make collection kwargs agree with setter names, so updating works; related minor cleanups. + Removed quiver_classic, scatter_classic, pcolor_classic. - EF 2007年07月26日 Major rewrite of mathtext.py, using the TeX box layout model. Modified: trunk/matplotlib/boilerplate.py =================================================================== --- trunk/matplotlib/boilerplate.py 2007年07月30日 06:04:41 UTC (rev 3629) +++ trunk/matplotlib/boilerplate.py 2007年07月30日 07:03:47 UTC (rev 3630) @@ -82,7 +82,6 @@ 'stem', 'vlines', 'quiver', - 'quiver2', 'quiverkey', 'xcorr', ) Modified: trunk/matplotlib/lib/matplotlib/axes.py =================================================================== --- trunk/matplotlib/lib/matplotlib/axes.py 2007年07月30日 06:04:41 UTC (rev 3629) +++ trunk/matplotlib/lib/matplotlib/axes.py 2007年07月30日 07:03:47 UTC (rev 3630) @@ -4051,34 +4051,6 @@ scatter.__doc__ = cbook.dedent(scatter.__doc__) % martist.kwdocd - def scatter_classic(self, x, y, s=None, c='b'): - """ - scatter_classic is no longer available; please use scatter. - To help in porting, for comparison to the scatter docstring, - here is the scatter_classic docstring: - - SCATTER_CLASSIC(x, y, s=None, c='b') - - Make a scatter plot of x versus y. s is a size (in data coords) and - can be either a scalar or an array of the same length as x or y. c is - a color and can be a single color format string or an length(x) array - of intensities which will be mapped by the colormap jet. - - If size is None a default size will be used - """ - raise NotImplementedError('scatter_classic has been removed;\n' - + 'please use scatter instead') - - def pcolor_classic(self, *args): - """ - pcolor_classic is no longer available; please use pcolor, - which is a drop-in replacement. - """ - raise NotImplementedError('pcolor_classic has been removed;\n' - + 'please use pcolor instead') - - - def arrow(self, x, y, dx, dy, **kwargs): """ Draws arrow on specified axis from (x,y) to (x+dx,y+dy). @@ -4097,164 +4069,14 @@ return qk quiverkey.__doc__ = mquiver.QuiverKey.quiverkey_doc - def quiver2(self, *args, **kw): + def quiver(self, *args, **kw): q = mquiver.Quiver(self, *args, **kw) self.add_collection(q) self.update_datalim_numerix(q.X, q.Y) self.autoscale_view() return q - quiver2.__doc__ = mquiver.Quiver.quiver_doc - - def quiver(self, *args, **kw): - if (len(args) == 3 or len(args) == 5) and not iterable(args[-1]): - return self.quiver_classic(*args, **kw) - c = kw.get('color', None) - if c is not None: - if not mcolors.is_color_like(c): - assert npy.shape(npy.asarray(c)) == npy.shape(npy.asarray(args[-1])) - return self.quiver_classic(*args, **kw) - return self.quiver2(*args, **kw) quiver.__doc__ = mquiver.Quiver.quiver_doc - def quiver_classic(self, U, V, *args, **kwargs ): - """ - QUIVER( X, Y, U, V ) - QUIVER( U, V ) - QUIVER( X, Y, U, V, S) - QUIVER( U, V, S ) - QUIVER( ..., color=None, width=1.0, cmap=None, norm=None ) - - Make a vector plot (U, V) with arrows on a grid (X, Y) - - If X and Y are not specified, U and V must be 2D arrays. - Equally spaced X and Y grids are then generated using the - meshgrid command. - - color can be a color value or an array of colors, so that the - arrows can be colored according to another dataset. If cmap - is specified and color is 'length', the colormap is used to - give a color according to the vector's length. - - If color is a scalar field, the colormap is used to map the - scalar to a color If a colormap is specified and color is an - array of color triplets, then the colormap is ignored - - width is a scalar that controls the width of the arrows - - if S is specified it is used to scale the vectors. Use S=0 to - disable automatic scaling. If S!=0, vectors are scaled to fit - within the grid and then are multiplied by S. - - - """ - msg = '''This version of quiver is obsolete and will be - phased out; please use the new quiver. - ''' - warnings.warn(msg, DeprecationWarning) - if not self._hold: self.cla() - do_scale = True - S = 1.0 - if len(args)==0: - # ( U, V ) - U = npy.asarray(U) - V = npy.asarray(V) - X,Y = mlab.meshgrid( npy.arange(U.shape[1]), npy.arange(U.shape[0]) ) - elif len(args)==1: - # ( U, V, S ) - U = npy.asarray(U) - V = npy.asarray(V) - X,Y = mlab.meshgrid( npy.arange(U.shape[1]), npy.arange(U.shape[0]) ) - S = float(args[0]) - do_scale = ( S != 0.0 ) - elif len(args)==2: - # ( X, Y, U, V ) - X = npy.asarray(U) - Y = npy.asarray(V) - U = npy.asarray(args[0]) - V = npy.asarray(args[1]) - elif len(args)==3: - # ( X, Y, U, V ) - X = npy.asarray(U) - Y = npy.asarray(V) - U = npy.asarray(args[0]) - V = npy.asarray(args[1]) - S = float(args[2]) - do_scale = ( S != 0.0 ) - - assert U.shape == V.shape - assert X.shape == Y.shape - assert U.shape == X.shape - - U = U.ravel() - V = V.ravel() - X = X.ravel() - Y = Y.ravel() - - arrows = [] - N = npy.sqrt( U**2+V**2 ) - if do_scale: - Nmax = maximum.reduce(N) or 1 # account for div by zero - U = U*(S/Nmax) - V = V*(S/Nmax) - N = N*Nmax - - alpha = kwargs.pop('alpha', 1.0) - width = kwargs.pop('width', .5) - norm = kwargs.pop('norm', None) - cmap = kwargs.pop('cmap', None) - vmin = kwargs.pop('vmin', None) - vmax = kwargs.pop('vmax', None) - color = kwargs.pop('color', None) - shading = kwargs.pop('shading', 'faceted') - - if len(kwargs): - raise TypeError( - "quiver() got an unexpected keyword argument '%s'"%kwargs.keys()[0]) - - C = None - if color == 'length' or color is True: - if color is True: - warnings.warn('''Use "color='length'", - not "color=True"''', DeprecationWarning) - C = N - elif color is None: - color = (0,0,0,1) - else: - clr = npy.asarray(color).ravel() - if clr.shape == U.shape: - C = clr - - I = U.shape[0] - arrows = [mpatches.FancyArrow(X[i],Y[i],U[i],V[i],0.1*S ).get_verts() - for i in xrange(I)] - - collection = mcoll.PolyCollection( - arrows, - edgecolors = 'None', - antialiaseds = (1,), - linewidths = (width,), - ) - if C is not None: - collection.set_array( C.ravel() ) - collection.set_cmap(cmap) - collection.set_norm(norm) - if norm is not None: - collection.set_clim( vmin, vmax ) - else: - collection.set_facecolor(color) - self.add_collection( collection ) - - lims = npy.asarray(arrows) - _max = maximum.reduce( maximum.reduce( lims )) - _min = minimum.reduce( minimum.reduce( lims )) - self.update_datalim( [ tuple(_min), tuple(_max) ] ) - self.autoscale_view() - return collection - - - - - def fill(self, *args, **kwargs): """ FILL(*args, **kwargs) Modified: trunk/matplotlib/lib/matplotlib/pylab.py =================================================================== --- trunk/matplotlib/lib/matplotlib/pylab.py 2007年07月30日 06:04:41 UTC (rev 3629) +++ trunk/matplotlib/lib/matplotlib/pylab.py 2007年07月30日 07:03:47 UTC (rev 3630) @@ -335,64 +335,6 @@ colorbar.__doc__ = colorbar_doc -def colorbar_classic(mappable = None, - cax=None, - orientation='vertical', - tickfmt='%1.1f', - cspacing='proportional', - clabels=None, - drawedges=False, - edgewidth=0.5, - edgecolor='k'): - """ - Create a colorbar for mappable; if mappable is None, - use current image. - - tickfmt is a format string to format the colorbar ticks - - cax is a colorbar axes instance in which the colorbar will be - placed. If None, as default axesd will be created resizing the - current aqxes to make room for it. If not None, the supplied axes - will be used and the other axes positions will be unchanged. - - orientation is the colorbar orientation: one of 'vertical' | 'horizontal' - - cspacing controls how colors are distributed on the colorbar. - if cspacing == 'linear', each color occupies an equal area - on the colorbar, regardless of the contour spacing. - if cspacing == 'proportional' (Default), the area each color - occupies on the the colorbar is proportional to the contour interval. - Only relevant for a Contour image. - - clabels can be a sequence containing the - contour levels to be labelled on the colorbar, or None (Default). - If clabels is None, labels for all contour intervals are - displayed. Only relevant for a Contour image. - - if drawedges == True, lines are drawn at the edges between - each color on the colorbar. Default False. - - edgecolor is the line color delimiting the edges of the colors - on the colorbar (if drawedges == True). Default black ('k') - - edgewidth is the width of the lines delimiting the edges of - the colors on the colorbar (if drawedges == True). Default 0.5 - - return value is the colorbar axes instance - """ - if mappable is None: - mappable = gci() - ret = gcf().colorbar_classic(mappable, cax = cax, - orientation = orientation, - tickfmt = tickfmt, - cspacing=cspacing, - clabels=clabels, - drawedges=drawedges, - edgewidth=edgewidth, - edgecolor=edgecolor) - draw_if_interactive() - return ret - def colors(): """ This is a do nothing function to provide you with help on how @@ -1606,19 +1548,6 @@ draw_if_interactive() -### Deprecated functions: -def scatter_classic(*args, **kwargs): - return gca().scatter_classic(*args, **kwargs) -if Axes.scatter_classic.__doc__ is not None: - scatter_classic.__doc__ = dedent(Axes.scatter_classic.__doc__) - -def pcolor_classic(*args, **kwargs): - return gca().pcolor_classic(*args, **kwargs) -if Axes.pcolor_classic.__doc__ is not None: - pcolor_classic.__doc__ = dedent(Axes.pcolor_classic.__doc__) - - - ### Do not edit below this point # This function was autogenerated by boilerplate.py. Do not edit as # changes will be lost @@ -2357,27 +2286,6 @@ # This function was autogenerated by boilerplate.py. Do not edit as # changes will be lost -def quiver2(*args, **kwargs): - # allow callers to override the hold state by passing hold=True|False - b = ishold() - h = popd(kwargs, 'hold', None) - if h is not None: - hold(h) - try: - ret = gca().quiver2(*args, **kwargs) - draw_if_interactive() - except: - hold(b) - raise - gci._current = ret - hold(b) - return ret -if Axes.quiver2.__doc__ is not None: - quiver2.__doc__ = dedent(Axes.quiver2.__doc__) + """ -Addition kwargs: hold = [True|False] overrides default hold state""" - -# This function was autogenerated by boilerplate.py. Do not edit as -# changes will be lost def quiverkey(*args, **kwargs): # allow callers to override the hold state by passing hold=True|False b = ishold() This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
Revision: 3629 http://matplotlib.svn.sourceforge.net/matplotlib/?rev=3629&view=rev Author: fer_perez Date: 2007年07月29日 23:04:41 -0700 (2007年7月29日) Log Message: ----------- cleaner fill implementation Modified Paths: -------------- trunk/py4science/examples/schrodinger/schrod_fdtd.py Modified: trunk/py4science/examples/schrodinger/schrod_fdtd.py =================================================================== --- trunk/py4science/examples/schrodinger/schrod_fdtd.py 2007年07月30日 02:04:46 UTC (rev 3628) +++ trunk/py4science/examples/schrodinger/schrod_fdtd.py 2007年07月30日 06:04:41 UTC (rev 3629) @@ -80,6 +80,16 @@ v[npts/2:npts/2+thickness] = v0 return v +def fillax(x,y,*args,**kw): + """Fill the space between an array of y values and the x axis. + + All args/kwargs are passed to the pylab.fill function. + Returns the value of the pylab.fill() call. + """ + xx = np.concatenate((x,np.array([x[-1],x[0]],x.dtype))) + yy = np.concatenate((y,np.zeros(2,y.dtype))) + return pylab.fill(xx, yy, *args,**kw) + #============================================================================= # # Simulation Constants. Be sure to include decimal points on appropriate @@ -213,14 +223,12 @@ # in light red, as well as drawing a green line at the wavepacket's total # energy, in the same units the potential is being plotted. if Vmax !=0 : + # Scaling factor for energies, so they fit in the same plot as the + # wavefunctions Efac = ymax/2.0/Vmax V_plot = V*Efac pylab.plot(X,V_plot,':k',zorder=0) # Potential line. - # reverse x and y2 so the polygon fills in order - y1 = free(N) # lower boundary for polygon drawing - x = np.concatenate( (X,X[::-1]) ) - y = np.concatenate( (y1,V_plot[::-1]) ) - pylab.fill(x, y, facecolor='y', alpha=0.2,zorder=0) + fillax(X,V_plot, facecolor='y', alpha=0.2,zorder=0) # Plot the wavefunction energy, in the same scale as the potential pylab.axhline(E*Efac,color='g',label='Energy',zorder=1) pylab.legend(loc='lower right') This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
Revision: 3628 http://matplotlib.svn.sourceforge.net/matplotlib/?rev=3628&view=rev Author: efiring Date: 2007年07月29日 19:04:46 -0700 (2007年7月29日) Log Message: ----------- changed pcolor default to shading='flat'; related cleanups Modified Paths: -------------- trunk/matplotlib/API_CHANGES trunk/matplotlib/CHANGELOG trunk/matplotlib/examples/pcolor_demo.py trunk/matplotlib/examples/pcolor_log.py trunk/matplotlib/examples/pcolor_small.py trunk/matplotlib/lib/matplotlib/artist.py trunk/matplotlib/lib/matplotlib/axes.py trunk/matplotlib/lib/matplotlib/collections.py Modified: trunk/matplotlib/API_CHANGES =================================================================== --- trunk/matplotlib/API_CHANGES 2007年07月29日 08:03:12 UTC (rev 3627) +++ trunk/matplotlib/API_CHANGES 2007年07月30日 02:04:46 UTC (rev 3628) @@ -1,3 +1,6 @@ + Changed pcolor default to shading='flat'; but as noted now in the + docstring, it is preferable to simply use the edgecolor kwarg. + The mathtext font commands (\cal, \rm, \it, \tt) now behave as TeX does: they are in effect until the next font change command or the end of the grouping. Therefore uses of $\cal{R}$ should be Modified: trunk/matplotlib/CHANGELOG =================================================================== --- trunk/matplotlib/CHANGELOG 2007年07月29日 08:03:12 UTC (rev 3627) +++ trunk/matplotlib/CHANGELOG 2007年07月30日 02:04:46 UTC (rev 3628) @@ -1,54 +1,58 @@ +2007年07月29日 Changed default pcolor shading to flat; added aliases + to make collection kwargs agree with setter names, so + updating works; related minor cleanups. + 2007年07月26日 Major rewrite of mathtext.py, using the TeX box layout model. - There is one (known) backward incompatible change. The - font commands (\cal, \rm, \it, \tt) now behave as TeX does: - they are in effect until the next font change command or - the end of the grouping. Therefore uses of $\cal{R}$ - should be changed to ${\cal R}$. Alternatively, you may - use the new LaTeX-style font commands (\mathcal, \mathrm, - \mathit, \mathtt) which do affect the following group, - eg. $\mathcal{R}$. + There is one (known) backward incompatible change. The + font commands (\cal, \rm, \it, \tt) now behave as TeX does: + they are in effect until the next font change command or + the end of the grouping. Therefore uses of $\cal{R}$ + should be changed to ${\cal R}$. Alternatively, you may + use the new LaTeX-style font commands (\mathcal, \mathrm, + \mathit, \mathtt) which do affect the following group, + eg. $\mathcal{R}$. - Other new features include: + Other new features include: - - Math may be interspersed with non-math text. Any text + - Math may be interspersed with non-math text. Any text with an even number of $'s (non-escaped) will be sent to - the mathtext parser for layout. + the mathtext parser for layout. - - Sub/superscripts are less likely to accidentally overlap. + - Sub/superscripts are less likely to accidentally overlap. - - Support for sub/superscripts in either order, eg. $x^i_j$ + - Support for sub/superscripts in either order, eg. $x^i_j$ and $x_j^i$ are equivalent. - - Double sub/superscripts (eg. $x_i_j$) are considered + - Double sub/superscripts (eg. $x_i_j$) are considered ambiguous and raise an exception. Use braces to disambiguate. - - $\frac{x}{y}$ can be used for displaying fractions. + - $\frac{x}{y}$ can be used for displaying fractions. - - $\sqrt[3]{x}$ can be used to display the radical symbol + - $\sqrt[3]{x}$ can be used to display the radical symbol with a root number and body. - - $\left(\frac{x}{y}\right)$ may be used to create + - $\left(\frac{x}{y}\right)$ may be used to create parentheses and other delimiters that automatically resize to the height of their contents. - - Spacing around operators etc. is now generally more like + - Spacing around operators etc. is now generally more like TeX. - - Added support (and fonts) for boldface (\bf) and + - Added support (and fonts) for boldface (\bf) and sans-serif (\sf) symbols. - - Log-like function name shortcuts are supported. For + - Log-like function name shortcuts are supported. For example, $\sin(x)$ may be used instead of ${\rm sin}(x)$ - - Limited use of kerning for the easy case (same font) + - Limited use of kerning for the easy case (same font) - Behind the scenes, the pyparsing.py module used for doing - the math parsing was updated to the latest stable version - (1.4.6). A lot of duplicate code was refactored out of the - Font classes. + Behind the scenes, the pyparsing.py module used for doing + the math parsing was updated to the latest stable version + (1.4.6). A lot of duplicate code was refactored out of the + Font classes. - - MGD + - MGD 2007年07月19日 completed numpification of most trivial cases - NN @@ -56,11 +60,11 @@ 2007年07月19日 replaced the Python code in numerix/ by a minimal wrapper around numpy that explicitly mentions all symbols that need to be - addressed for further numpification - NN + addressed for further numpification - NN -2007年07月18日 make usetex respect changes to rcParams. texmanager used to - only configure itself when it was created, now it - reconfigures when rcParams are changed. Thank you Alexander +2007年07月18日 make usetex respect changes to rcParams. texmanager used to + only configure itself when it was created, now it + reconfigures when rcParams are changed. Thank you Alexander Schmolck for contributing a patch - DSD 2007年07月17日 added validation to setting and changing rcParams - DSD @@ -71,7 +75,7 @@ 2007年07月16日 clean up some code in ticker.ScalarFormatter, use unicode to render multiplication sign in offset ticklabel - DSD -2007年07月16日 fixed a formatting bug in ticker.ScalarFormatter's scientific +2007年07月16日 fixed a formatting bug in ticker.ScalarFormatter's scientific notation (10^0 was being rendered as 10 in some cases) - DSD 2007年07月13日 Add MPL_isfinite64() and MPL_isinf64() for testing @@ -83,7 +87,7 @@ 2007年07月13日 Removed the rest of the numerix extension code detritus, numpified axes.py, and cleaned up the imports in axes.py - - JDH + - JDH 2007年07月13日 Added legend.loc as configurable option that could in future default to 'best'. - NN @@ -552,35 +556,35 @@ 2006年10月10日 deactivated rcfile-configurability of markerfacecolor and markeredgecolor. Both are now hardcoded to the special value - 'auto' to follow the line color. Configurability at run-time - (using function arguments) remains functional. - NN + 'auto' to follow the line color. Configurability at run-time + (using function arguments) remains functional. - NN 2006年10月07日 introduced dummy argument magnification=1.0 to FigImage.make_image to satisfy unit test figimage_demo.py The argument is not yet handled correctly, which should only - show up when using non-standard DPI settings in PS backend, - introduced by patch #1562394. - NN + show up when using non-standard DPI settings in PS backend, + introduced by patch #1562394. - NN 2006年10月06日 add backend-agnostic example: simple3d.py - NN 2006年09月29日 fix line-breaking for SVG-inline images (purely cosmetic) - NN 2006年09月29日 reworked set_linestyle and set_marker - markeredgecolor and markerfacecolor now default to - a special value "auto" that keeps the color in sync with - the line color - further, the intelligence of axes.plot is cleaned up, - improved and simplified. Complete compatibility cannot be - guaranteed, but the new behavior should be much more predictable - (see patch #1104615 for details) - NN + markeredgecolor and markerfacecolor now default to + a special value "auto" that keeps the color in sync with + the line color + further, the intelligence of axes.plot is cleaned up, + improved and simplified. Complete compatibility cannot be + guaranteed, but the new behavior should be much more predictable + (see patch #1104615 for details) - NN 2006年09月29日 changed implementation of clip-path in SVG to work around a limitation in inkscape - NN 2006年09月29日 added two options to matplotlibrc: - svg.image_inline - svg.image_noscale - see patch #1533010 for details - NN + svg.image_inline + svg.image_noscale + see patch #1533010 for details - NN 2006年09月29日 axes.py: cleaned up kwargs checking - NN @@ -611,8 +615,8 @@ 2006年09月05日 Released 0.87.5 at revision 2761 2006年09月04日 Added nxutils for some numeric add-on extension code -- - specifically a better/more efficient inside polygon tester (see - unit/inside_poly_*.py) - JDH + specifically a better/more efficient inside polygon tester (see + unit/inside_poly_*.py) - JDH 2006年09月04日 Made bitstream fonts the rc default - JDH @@ -957,7 +961,7 @@ 2006年03月20日 Added contour.negative_linestyle rcParam - ADS 2006年03月20日 Added _isnan extension module to test for nan with Numeric - - ADS + - ADS 2006年03月17日 Added Paul and Alex's support for faceting with quadmesh in sf patch 1411223 - JDH @@ -1304,7 +1308,7 @@ 2005年11月09日 added axisbelow attr for Axes to determine whether ticks and such - are above or below the actors + are above or below the actors 2005年11月08日 Added Nicolas' irregularly spaced image patch @@ -1461,7 +1465,7 @@ 2005年07月24日 backend_gtk.py: modify print_figure() use own pixmap, fixing problems where print_figure() overwrites the display pixmap. - return False from all button/key etc events - to allow the event + return False from all button/key etc events - to allow the event to propagate further - SC 2005年07月23日 backend_gtk.py: change expose_event from using set_back_pixmap(); @@ -1483,7 +1487,7 @@ 2005年07月14日 Fixed a Windows related bug (#1238412) in texmanager - DSD 2005年07月11日 Fixed color kwarg bug, setting color=1 or 0 caused an - exception - DSD + exception - DSD 2005年07月07日 Added Eric's MA set_xdata Line2D fix - JDH @@ -1585,10 +1589,10 @@ 2005年06月13日 Exposed cap and join style for lines with new rc params and line properties - lines.dash_joinstyle : miter # miter|round|bevel - lines.dash_capstyle : butt # butt|round|projecting - lines.solid_joinstyle : miter # miter|round|bevel - lines.solid_capstyle : projecting # butt|round|projecting + lines.dash_joinstyle : miter # miter|round|bevel + lines.dash_capstyle : butt # butt|round|projecting + lines.solid_joinstyle : miter # miter|round|bevel + lines.solid_capstyle : projecting # butt|round|projecting 2005年06月13日 Added kwargs to Axes init @@ -1702,9 +1706,9 @@ for the interp kwarg are 'nearest', 'bilinear', 'bicubic', 'spline16', 'spline36', - 'hanning', 'hamming', 'hermite', 'kaiser', 'quadric', - 'catrom', 'gaussian', 'bessel', 'mitchell', 'sinc', - 'lanczos', 'blackman' + 'hanning', 'hamming', 'hermite', 'kaiser', 'quadric', + 'catrom', 'gaussian', 'bessel', 'mitchell', 'sinc', + 'lanczos', 'blackman' See help(imshow) for details, particularly the interpolation, filternorm and filterrad kwargs Modified: trunk/matplotlib/examples/pcolor_demo.py =================================================================== --- trunk/matplotlib/examples/pcolor_demo.py 2007年07月29日 08:03:12 UTC (rev 3627) +++ trunk/matplotlib/examples/pcolor_demo.py 2007年07月30日 02:04:46 UTC (rev 3628) @@ -19,7 +19,7 @@ X,Y = meshgrid(x, y) Z = func3(X, Y) -pcolor(X, Y, Z, shading='flat') +pcolor(X, Y, Z) colorbar() axis([-3,3,-3,3]) savefig('pcolor_demo') Modified: trunk/matplotlib/examples/pcolor_log.py =================================================================== --- trunk/matplotlib/examples/pcolor_log.py 2007年07月29日 08:03:12 UTC (rev 3627) +++ trunk/matplotlib/examples/pcolor_log.py 2007年07月30日 02:04:46 UTC (rev 3628) @@ -15,11 +15,11 @@ Z1 = bivariate_normal(X, Y, 0.1, 0.2, 1.0, 1.0) + 0.1*bivariate_normal(X, Y, 1.0, 1.0, 0.0, 0.0) subplot(2,1,1) -pcolor(X, Y, Z1, shading='flat', norm=LogNorm(vmin=Z1.min(), vmax=Z1.max())) +pcolor(X, Y, Z1, norm=LogNorm(vmin=Z1.min(), vmax=Z1.max())) colorbar() subplot(2,1,2) -pcolor(X, Y, Z1, shading='flat') +pcolor(X, Y, Z1) colorbar() Modified: trunk/matplotlib/examples/pcolor_small.py =================================================================== --- trunk/matplotlib/examples/pcolor_small.py 2007年07月29日 08:03:12 UTC (rev 3627) +++ trunk/matplotlib/examples/pcolor_small.py 2007年07月30日 02:04:46 UTC (rev 3628) @@ -2,15 +2,14 @@ from pylab import * -#Z = arange(60) -#Z.shape = 6,10 -#Z.shape = 10,6 -#print Z -Z = rand(10,6) +Z = rand(6,10) -#c = pcolor(Z, shading='flat') # default 'faceted' +subplot(2,1,1) c = pcolor(Z) -c.set_linewidth(4) +title('default: no edges') -#savefig('pcolor_small') +subplot(2,1,2) +c = pcolor(Z, edgecolors='k', linewidths=4) +title('thick edges') + show() Modified: trunk/matplotlib/lib/matplotlib/artist.py =================================================================== --- trunk/matplotlib/lib/matplotlib/artist.py 2007年07月29日 08:03:12 UTC (rev 3627) +++ trunk/matplotlib/lib/matplotlib/artist.py 2007年07月30日 02:04:46 UTC (rev 3628) @@ -55,7 +55,7 @@ Remove the artist from the figure if possible. The effect will not be visible until the figure is redrawn, e.g., with ax.draw_idle(). Call ax.relim() to update the axes limits if desired. - + Note: relim() will not see collections even if the collection was added to axes with autolim=True. @@ -63,10 +63,10 @@ ''' # There is no method to set the callback. Instead the parent should set - # the _remove_method attribute directly. This would be a protected + # the _remove_method attribute directly. This would be a protected # attribute if Python supported that sort of thing. The callback # has one parameter, which is the child to be removed. - if self._remove_method != None: + if self._remove_method != None: self._remove_method(self) else: raise NotImplementedError('cannot remove artist') Modified: trunk/matplotlib/lib/matplotlib/axes.py =================================================================== --- trunk/matplotlib/lib/matplotlib/axes.py 2007年07月29日 08:03:12 UTC (rev 3627) +++ trunk/matplotlib/lib/matplotlib/axes.py 2007年07月30日 02:04:46 UTC (rev 3628) @@ -3853,7 +3853,7 @@ will be plotted. Other keyword args; the color mapping and normalization arguments will - on be used if c is an array of floats + be used only if c is an array of floats * cmap = cm.jet : a colors.Colormap instance from cm. defaults to rc image.cmap @@ -3876,7 +3876,12 @@ * faceted: if True, will use the default edgecolor for the markers. If False, will set the edgecolors to be the same - as the facecolors + as the facecolors. + This kwarg is deprecated; + please use the edgecolors kwarg instead: + shading='flat' --> edgecolors='None' + shading='faceted --> edgecolors=None + edgecolors also can be any mpl color or sequence of colors. Optional kwargs control the PatchCollection properties: %(PatchCollection)s @@ -4468,7 +4473,14 @@ instance, vmin and vmax will be None * shading = 'flat' : or 'faceted'. If 'faceted', a black grid is - drawn around each rectangle; if 'flat', edges are not drawn + drawn around each rectangle; if 'flat', edges are not drawn. + Default is 'flat', contrary to Matlab(TM). + This kwarg is deprecated; + please use the edgecolors kwarg instead: + shading='flat' --> edgecolors='None' + shading='faceted --> edgecolors='k' + edgecolors can also be None to specify the rcParams + default, or any mpl color or sequence of colors. * alpha=1.0 : the alpha blending value @@ -4526,7 +4538,7 @@ cmap = kwargs.pop('cmap', None) vmin = kwargs.pop('vmin', None) vmax = kwargs.pop('vmax', None) - shading = kwargs.pop('shading', 'faceted') + shading = kwargs.pop('shading', 'flat') if len(args)==1: C = args[0] @@ -4586,14 +4598,11 @@ edgecolors = (0,0,0,1), else: edgecolors = 'None' + kwargs.setdefault('edgecolors', edgecolors) + kwargs.setdefault('antialiaseds', (0,)) + kwargs.setdefault('linewidths', (0.25,)) - collection = mcoll.PolyCollection( - verts, - edgecolors = edgecolors, - antialiaseds = (0,), - linewidths = (0.25,), - **kwargs - ) + collection = mcoll.PolyCollection(verts, **kwargs) collection.set_alpha(alpha) collection.set_array(C) @@ -4652,8 +4661,14 @@ min and max of the color array C is used. * shading = 'flat' : or 'faceted'. If 'faceted', a black grid is - drawn around each rectangle; if 'flat', edge colors are same as - face colors + drawn around each rectangle; if 'flat', edges are not drawn. + Default is 'flat', contrary to Matlab(TM). + This kwarg is deprecated; + please use the edgecolors kwarg instead: + shading='flat' --> edgecolors='None' + shading='faceted --> edgecolors='k' + More flexible specification of edgecolors, as in pcolor, + is not presently supported. * alpha=1.0 : the alpha blending value @@ -4675,7 +4690,8 @@ cmap = kwargs.pop('cmap', None) vmin = kwargs.pop('vmin', None) vmax = kwargs.pop('vmax', None) - shading = kwargs.pop('shading', 'faceted') + shading = kwargs.pop('shading', 'flat') + edgecolors = kwargs.pop('edgecolors', 'None') if len(args)==1: C = args[0] @@ -4703,13 +4719,13 @@ coords[:, 0] = X coords[:, 1] = Y - if shading == 'faceted': + if shading == 'faceted' or edgecolors != 'None': showedges = 1 else: showedges = 0 collection = mcoll.QuadMesh( - Nx - 1, Ny - 1, coords, showedges, **kwargs) + Nx - 1, Ny - 1, coords, showedges) # kwargs are not used collection.set_alpha(alpha) collection.set_array(C) if norm is not None: assert(isinstance(norm, mcolors.Normalize)) Modified: trunk/matplotlib/lib/matplotlib/collections.py =================================================================== --- trunk/matplotlib/lib/matplotlib/collections.py 2007年07月29日 08:03:12 UTC (rev 3627) +++ trunk/matplotlib/lib/matplotlib/collections.py 2007年07月30日 02:04:46 UTC (rev 3628) @@ -21,16 +21,12 @@ class Collection(artist.Artist): """ - All properties in a collection must be sequences. The + All properties in a collection must be sequences or scalars; + if scalars, they will be converted to sequences. The property of the ith element of the collection is the prop[i % len(props)]. - This implies that the properties cycle if the len of props is less - than the number of elements of the collection. A length 1 - property is shared by all the elements of the collection - - All color args to a collection are sequences of rgba tuples """ def __init__(self): @@ -133,8 +129,8 @@ linewidths = (0,) else: self._edgecolors = _colors.colorConverter.to_rgba_list(edgecolors) - self._linewidths = linewidths - self._antialiaseds = antialiaseds + self._linewidths = self._get_value(linewidths) + self._antialiaseds = self._get_value(antialiaseds) #self._offsets = offsets self._offsets = offsets self._transOffset = transOffset @@ -221,6 +217,8 @@ ACCEPTS: float or sequence of floats """ self._linewidths = self._get_value(lw) + def set_linewidths(self, lw): + self.set_linewidth(lw) def set_color(self, c): """ @@ -242,16 +240,23 @@ ACCEPTS: matplotlib color arg or sequence of rgba tuples """ self._facecolors = _colors.colorConverter.to_rgba_list(c) + def set_facecolors(self, c): + self.set_facecolor(c) def set_edgecolor(self, c): """ - Set the facecolor(s) of the collection. c can be a matplotlib color + Set the edgecolor(s) of the collection. c can be a matplotlib color arg (all patches have same color), or a a sequence or rgba tuples; if it is a sequence the patches will cycle through the sequence ACCEPTS: matplotlib color arg or sequence of rgba tuples """ - self._edgecolors = _colors.colorConverter.to_rgba_list(c) + if c == 'None': + self._linewidths = (0.0,) + else: + self._edgecolors = _colors.colorConverter.to_rgba_list(c) + def set_edgecolors(self, c): + self.set_edgecolor(c) def set_alpha(self, alpha): """ @@ -568,7 +573,8 @@ class LineCollection(Collection, cm.ScalarMappable): """ - All parameters must be sequences. The property of the ith line + All parameters must be sequences or scalars; if scalars, they will + be converted to sequences. The property of the ith line segment is the prop[i % len(props)], ie the properties cycle if the len of props is less than the number of sements """ @@ -637,8 +643,8 @@ antialiaseds = (mpl.rcParams['lines.antialiased'], ) self._colors = _colors.colorConverter.to_rgba_list(colors) - self._aa = antialiaseds - self._lw = linewidths + self._aa = self._get_value(antialiaseds) + self._lw = self._get_value(linewidths) self.set_linestyle(linestyle) self._uniform_offsets = None if offsets is not None: This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
Revision: 3627 http://matplotlib.svn.sourceforge.net/matplotlib/?rev=3627&view=rev Author: fer_perez Date: 2007年07月29日 01:03:12 -0700 (2007年7月29日) Log Message: ----------- Small optimization. Modified Paths: -------------- trunk/py4science/examples/schrodinger/schrod_fdtd.py Modified: trunk/py4science/examples/schrodinger/schrod_fdtd.py =================================================================== --- trunk/py4science/examples/schrodinger/schrod_fdtd.py 2007年07月29日 06:50:34 UTC (rev 3626) +++ trunk/py4science/examples/schrodinger/schrod_fdtd.py 2007年07月29日 08:03:12 UTC (rev 3627) @@ -237,22 +237,26 @@ IDX2 = range(2,N) # psi [ k + 1 ] IDX3 = range(0,N-2) # psi [ k - 1 ] -for t in range(0,T+1): +for t in range(T+1): + # Precompute a couple of indexing constants, this speeds up the computation + psi_rPR = psi_r[PR] + psi_iPR = psi_i[PR] + # Apply the update equations. psi_i[FU,IDX1] = psi_i[PA,IDX1] + \ - c1*(psi_r[PR,IDX2] - 2*psi_r[PR,IDX1] + - psi_r[PR,IDX3]) - psi_i[FU] = psi_i[FU] - c2V*psi_r[PR] + c1*(psi_rPR[IDX2] - 2*psi_rPR[IDX1] + + psi_rPR[IDX3]) + psi_i[FU] -= c2V*psi_r[PR] psi_r[FU,IDX1] = psi_r[PA,IDX1] - \ - c1*(psi_i[PR,IDX2] - 2*psi_i[PR,IDX1] + - psi_i[PR,IDX3]) - psi_r[FU] = psi_r[FU] + c2V*psi_i[PR] + c1*(psi_iPR[IDX2] - 2*psi_iPR[IDX1] + + psi_iPR[IDX3]) + psi_r[FU] += c2V*psi_i[PR] # Increment the time steps. PR -> PA and FU -> PR - psi_r[PA] = psi_r[PR] + psi_r[PA] = psi_rPR psi_r[PR] = psi_r[FU] - psi_i[PA] = psi_i[PR] + psi_i[PA] = psi_iPR psi_i[PR] = psi_i[FU] # Only plot after a few iterations to make the simulation run faster. This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
Revision: 3626 http://matplotlib.svn.sourceforge.net/matplotlib/?rev=3626&view=rev Author: fer_perez Date: 2007年07月28日 23:50:34 -0700 (2007年7月28日) Log Message: ----------- Add energy display in the same units as the potential Modified Paths: -------------- trunk/py4science/examples/schrodinger/schrod_fdtd.py Modified: trunk/py4science/examples/schrodinger/schrod_fdtd.py =================================================================== --- trunk/py4science/examples/schrodinger/schrod_fdtd.py 2007年07月28日 21:31:18 UTC (rev 3625) +++ trunk/py4science/examples/schrodinger/schrod_fdtd.py 2007年07月29日 06:50:34 UTC (rev 3626) @@ -88,7 +88,7 @@ N = 1200 # Number of spatial points. T = 5*N # Number of time steps. 5*N is a nice value for terminating # before anything reaches the boundaries. -Tp = 40 # Number of time steps to increment before updating the plot. +Tp = 50 # Number of time steps to increment before updating the plot. dx = 1.0e0 # Spatial resolution m = 1.0e0 # Particle mass hbar = 1.0e0 # Plank's constant @@ -98,7 +98,7 @@ # and thickness (for barriers), you'll see the various transmission/reflection # regimes of quantum mechanical tunneling. V0 = 1.0e-2 # Potential amplitude (used for steps and barriers) -THCK = 10 # "Thickness" of the potential barrier (if appropriate +THCK = 15 # "Thickness" of the potential barrier (if appropriate # V-function is chosen) # Uncomment the potential type you want to use here: @@ -108,12 +108,12 @@ # Potential step. The height (V0) of the potential chosen above will determine # the amount of reflection/transmission you'll observe -#POTENTIAL = 'step' +POTENTIAL = 'step' # Potential barrier. Note that BOTH the potential height (V0) and thickness # of the barrier (THCK) affect the amount of tunneling vs reflection you'll # observe. -POTENTIAL = 'barrier' +#POTENTIAL = 'barrier' # Initial wave function constants sigma = 40.0 # Standard deviation on the Gaussian envelope (remember Heisenberg @@ -121,6 +121,11 @@ x0 = round(N/2) - 5*sigma # Time shift k0 = np.pi/20 # Wavenumber (note that energy is a function of k) +# Energy for a localized gaussian wavepacket interacting with a localized +# potential (so the interaction term can be neglected by computing the energy +# integral over a region where V=0) +E = (hbar**2/2.0/m)*(k0**2+0.5/sigma**2) + #============================================================================= # Code begins # @@ -140,7 +145,7 @@ # More simulation parameters. The maximum stable time step is a function of # the potential, V. -Vmax = max(V) # Maximum potential of the domain. +Vmax = V.max() # Maximum potential of the domain. dt = hbar/(2*hbar**2/(m*dx**2)+Vmax) # Critical time step. c1 = hbar*dt/(m*dx**2) # Constant coefficient 1. c2 = 2*dt/hbar # Constant coefficient 2. @@ -148,6 +153,7 @@ # Print summary info print 'One-dimensional Schrodinger equation - time evolution' +print 'Wavepacket energy: ',E print 'Potential type: ',POTENTIAL print 'Potential height V0: ',V0 print 'Barrier thickness: ',THCK @@ -190,30 +196,40 @@ # Initialize the figure and axes. pylab.figure() +xmin = X.min() +xmax = X.max() ymax = 1.5*(psi_r[PR]).max() -pylab.axis([X.min(),X.max(),-ymax,ymax]) +pylab.axis([xmin,xmax,-ymax,ymax]) # Initialize the plots with their own line objects. The figures plot MUCH # faster if you simply update the lines as opposed to redrawing the entire # figure. For reference, include the potential function as well. -lineR, = pylab.plot(X,psi_r[PR],'b',alpha=0.7) # "Real" line -lineI, = pylab.plot(X,psi_i[PR],'r',alpha=0.7) # "Imag" line. -lineP, = pylab.plot(X,psi_p,'k') # "Probability" line +lineR, = pylab.plot(X,psi_r[PR],'b',alpha=0.7,label='Real') +lineI, = pylab.plot(X,psi_i[PR],'r',alpha=0.7,label='Imag') +lineP, = pylab.plot(X,6*psi_p,'k',label='Prob') pylab.title('Potential height: %.2e' % V0) -pylab.legend(('Real','Imag','Prob')) # For non-zero potentials, plot them and shade the classically forbidden region -# in light red -if V.max() !=0 : - V_plot = V/V.max()*ymax/2 +# in light red, as well as drawing a green line at the wavepacket's total +# energy, in the same units the potential is being plotted. +if Vmax !=0 : + Efac = ymax/2.0/Vmax + V_plot = V*Efac pylab.plot(X,V_plot,':k',zorder=0) # Potential line. # reverse x and y2 so the polygon fills in order y1 = free(N) # lower boundary for polygon drawing x = np.concatenate( (X,X[::-1]) ) y = np.concatenate( (y1,V_plot[::-1]) ) pylab.fill(x, y, facecolor='y', alpha=0.2,zorder=0) + # Plot the wavefunction energy, in the same scale as the potential + pylab.axhline(E*Efac,color='g',label='Energy',zorder=1) +pylab.legend(loc='lower right') pylab.draw() +# I think there's a problem with pylab, because it resets the xlim after +# plotting the E line. Fix it back manually. +pylab.xlim(xmin,xmax) + # Direct index assignment is MUCH faster than using a spatial FOR loop, so # these constants are used in the update equations. Remember that Python uses # zero-based indexing. This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
Revision: 3625 http://matplotlib.svn.sourceforge.net/matplotlib/?rev=3625&view=rev Author: fer_perez Date: 2007年07月28日 14:31:18 -0700 (2007年7月28日) Log Message: ----------- Add Schrodinger equation example, contributed by James Nagel <na...@me...> Added Paths: ----------- trunk/py4science/examples/schrodinger/ trunk/py4science/examples/schrodinger/Schrodinger_FDTD.pdf trunk/py4science/examples/schrodinger/schrod_fdtd.py Added: trunk/py4science/examples/schrodinger/Schrodinger_FDTD.pdf =================================================================== (Binary files differ) Property changes on: trunk/py4science/examples/schrodinger/Schrodinger_FDTD.pdf ___________________________________________________________________ Name: svn:mime-type + application/octet-stream Added: trunk/py4science/examples/schrodinger/schrod_fdtd.py =================================================================== --- trunk/py4science/examples/schrodinger/schrod_fdtd.py (rev 0) +++ trunk/py4science/examples/schrodinger/schrod_fdtd.py 2007年07月28日 21:31:18 UTC (rev 3625) @@ -0,0 +1,258 @@ +#!/usr/bin/env python +#============================================================================= +# +# Quantum Mechanical Simulation using Finite-Difference +# Time-Domain (FDTD) Method +# +# This script simulates a probability wave in the presence of multiple +# potentials. The simulation is c arried out by using the FDTD algorithm +# applied to the Schrodinger equation. The program is intended to act as +# a demonstration of the FDTD algorithm and can be used as an educational +# aid for quantum mechanics and numerical methods. The simulation +# parameters are defined in the code constants and can be freely +# manipulated to see different behaviors. +# +# NOTES +# +# The probability density plots are amplified by a factor for visual +# purposes. The psi_p quanity contains the actual probability density +# without any rescaling. +# +# BEWARE: The time step, dt, has strict requirements or else the +# simulation becomes unstable. +# +# The code has three built-in potential functions for demonstration. +# +# 1) Constant potential: Demonstrates a free particle with dispersion. +# +# 2) Step potential: Demonstrates transmission and reflection. +# +# 3) Potential barrier: Demonstrates tunneling. +# +# By tweaking the height of the potential (V0 below) as well as the +# barrier thickness (THCK below), you can see different behaviors: full +# reflection with no noticeable transmission, transmission and +# reflection, or mostly transmission with tunneling. +# +# This script requires pylab and numpy to be installed with +# Python or else it will not run. +# +#============================================================================ +# Author: James Nagel <na...@me...> +# 5/25/07 +# +# Updates by Fernando Perez <Fer...@co...>, 7/28/07 +#============================================================================ + +# Numerical and plotting libraries +import numpy as np +import pylab + +# Set pylab to interactive mode so plots update when run outside ipython +pylab.ion() + +#============================================================================= + +# Utility functions + +# Defines a quick Gaussian pulse function to act as an envelope to the wave +# function. +def Gaussian(x,t,sigma): + """ A Gaussian curve. + x = Variable + t = time shift + sigma = standard deviation """ + return np.exp(-(x-t)**2/(2*sigma**2)) + +def free(npts): + "Free particle." + return np.zeros(npts) + +def step(npts,v0): + "Potential step" + v = free(npts) + v[npts/2:] = v0 + return v + +def barrier(npts,v0,thickness): + "Barrier potential" + v = free(npts) + v[npts/2:npts/2+thickness] = v0 + return v + +#============================================================================= +# +# Simulation Constants. Be sure to include decimal points on appropriate +# variables so they become floats instead of integers. +# +N = 1200 # Number of spatial points. +T = 5*N # Number of time steps. 5*N is a nice value for terminating + # before anything reaches the boundaries. +Tp = 40 # Number of time steps to increment before updating the plot. +dx = 1.0e0 # Spatial resolution +m = 1.0e0 # Particle mass +hbar = 1.0e0 # Plank's constant +X = dx*np.linspace(0,N,N) # Spatial axis. + +# Potential parameters. By playing with the type of potential and the height +# and thickness (for barriers), you'll see the various transmission/reflection +# regimes of quantum mechanical tunneling. +V0 = 1.0e-2 # Potential amplitude (used for steps and barriers) +THCK = 10 # "Thickness" of the potential barrier (if appropriate + # V-function is chosen) + +# Uncomment the potential type you want to use here: + +# Zero potential, packet propagates freely. +#POTENTIAL = 'free' + +# Potential step. The height (V0) of the potential chosen above will determine +# the amount of reflection/transmission you'll observe +#POTENTIAL = 'step' + +# Potential barrier. Note that BOTH the potential height (V0) and thickness +# of the barrier (THCK) affect the amount of tunneling vs reflection you'll +# observe. +POTENTIAL = 'barrier' + +# Initial wave function constants +sigma = 40.0 # Standard deviation on the Gaussian envelope (remember Heisenberg + # uncertainty). +x0 = round(N/2) - 5*sigma # Time shift +k0 = np.pi/20 # Wavenumber (note that energy is a function of k) + +#============================================================================= +# Code begins +# +# You shouldn't need to change anything below unless you want to actually play +# with the numerical algorithm or modify the plotting. +# +# Fill in the appropriate potential function (is there a Python equivalent to +# the SWITCH statement?). +if POTENTIAL=='free': + V = free(N) +elif POTENTIAL=='step': + V = step(N,V0) +elif POTENTIAL=='barrier': + V = barrier(N,V0,THCK) +else: + raise ValueError("Unrecognized potential type: %s" % POTENTIAL) + +# More simulation parameters. The maximum stable time step is a function of +# the potential, V. +Vmax = max(V) # Maximum potential of the domain. +dt = hbar/(2*hbar**2/(m*dx**2)+Vmax) # Critical time step. +c1 = hbar*dt/(m*dx**2) # Constant coefficient 1. +c2 = 2*dt/hbar # Constant coefficient 2. +c2V = c2*V # pre-compute outside of update loop + +# Print summary info +print 'One-dimensional Schrodinger equation - time evolution' +print 'Potential type: ',POTENTIAL +print 'Potential height V0: ',V0 +print 'Barrier thickness: ',THCK + +# Wave functions. Three states represent past, present, and future. +psi_r = np.zeros((3,N)) # Real +psi_i = np.zeros((3,N)) # Imaginary +psi_p = np.zeros(N,) # Observable probability (magnitude-squared + # of the complex wave function). + +# Temporal indexing constants, used for accessing rows of the wavefunctions. +PA = 0 # Past +PR = 1 # Present +FU = 2 # Future + +# Initialize wave function. A present-only state will "split" with half the +# wave function propagating to the left and the other half to the right. +# Including a "past" state will cause it to propagate one way. +xn = range(1,N/2) +x = X[xn]/dx # Normalized position coordinate +gg = Gaussian(x,x0,sigma) +cx = np.cos(k0*x) +sx = np.sin(k0*x) +psi_r[PR,xn] = cx*gg +psi_i[PR,xn] = sx*gg +psi_r[PA,xn] = cx*gg +psi_i[PA,xn] = sx*gg + +# Initial normalization of wavefunctions +# Compute the observable probability. +psi_p = psi_r[PR]**2 + psi_i[PR]**2 + +# Normalize the wave functions so that the total probability in the simulation +# is equal to 1. +P = dx * psi_p.sum() # Total probability. +nrm = np.sqrt(P) +psi_r /= nrm +psi_i /= nrm +psi_p /= P + +# Initialize the figure and axes. +pylab.figure() +ymax = 1.5*(psi_r[PR]).max() +pylab.axis([X.min(),X.max(),-ymax,ymax]) + +# Initialize the plots with their own line objects. The figures plot MUCH +# faster if you simply update the lines as opposed to redrawing the entire +# figure. For reference, include the potential function as well. +lineR, = pylab.plot(X,psi_r[PR],'b',alpha=0.7) # "Real" line +lineI, = pylab.plot(X,psi_i[PR],'r',alpha=0.7) # "Imag" line. +lineP, = pylab.plot(X,psi_p,'k') # "Probability" line +pylab.title('Potential height: %.2e' % V0) +pylab.legend(('Real','Imag','Prob')) + +# For non-zero potentials, plot them and shade the classically forbidden region +# in light red +if V.max() !=0 : + V_plot = V/V.max()*ymax/2 + pylab.plot(X,V_plot,':k',zorder=0) # Potential line. + # reverse x and y2 so the polygon fills in order + y1 = free(N) # lower boundary for polygon drawing + x = np.concatenate( (X,X[::-1]) ) + y = np.concatenate( (y1,V_plot[::-1]) ) + pylab.fill(x, y, facecolor='y', alpha=0.2,zorder=0) +pylab.draw() + +# Direct index assignment is MUCH faster than using a spatial FOR loop, so +# these constants are used in the update equations. Remember that Python uses +# zero-based indexing. +IDX1 = range(1,N-1) # psi [ k ] +IDX2 = range(2,N) # psi [ k + 1 ] +IDX3 = range(0,N-2) # psi [ k - 1 ] + +for t in range(0,T+1): + # Apply the update equations. + psi_i[FU,IDX1] = psi_i[PA,IDX1] + \ + c1*(psi_r[PR,IDX2] - 2*psi_r[PR,IDX1] + + psi_r[PR,IDX3]) + psi_i[FU] = psi_i[FU] - c2V*psi_r[PR] + + psi_r[FU,IDX1] = psi_r[PA,IDX1] - \ + c1*(psi_i[PR,IDX2] - 2*psi_i[PR,IDX1] + + psi_i[PR,IDX3]) + psi_r[FU] = psi_r[FU] + c2V*psi_i[PR] + + # Increment the time steps. PR -> PA and FU -> PR + psi_r[PA] = psi_r[PR] + psi_r[PR] = psi_r[FU] + psi_i[PA] = psi_i[PR] + psi_i[PR] = psi_i[FU] + + # Only plot after a few iterations to make the simulation run faster. + if t % Tp == 0: + # Compute observable probability for the plot. + psi_p = psi_r[PR]**2 + psi_i[PR]**2 + + # Update the plots. + lineR.set_ydata(psi_r[PR]) + lineI.set_ydata(psi_i[PR]) + # Note: we plot the probability density amplified by a factor so it's a + # bit easier to see. + lineP.set_ydata(6*psi_p) + + pylab.draw() + +# So the windows don't auto-close at the end if run outside ipython +pylab.ioff() +pylab.show() Property changes on: trunk/py4science/examples/schrodinger/schrod_fdtd.py ___________________________________________________________________ Name: svn:executable + * This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
Revision: 3624 http://matplotlib.svn.sourceforge.net/matplotlib/?rev=3624&view=rev Author: efiring Date: 2007年07月27日 16:34:29 -0700 (2007年7月27日) Log Message: ----------- tweaked cbook.dedent, inspired by Fernando's version Modified Paths: -------------- trunk/matplotlib/lib/matplotlib/cbook.py Modified: trunk/matplotlib/lib/matplotlib/cbook.py =================================================================== --- trunk/matplotlib/lib/matplotlib/cbook.py 2007年07月27日 15:45:26 UTC (rev 3623) +++ trunk/matplotlib/lib/matplotlib/cbook.py 2007年07月27日 23:34:29 UTC (rev 3624) @@ -543,6 +543,8 @@ first line. It differs from textwrap.dedent in its deletion of leading blank lines and its use of the first non-blank line to determine the indentation. + + It is also faster in most cases. """ if not s: # includes case of s is None return '' @@ -552,6 +554,9 @@ ii += 1 lines = lines[ii:] nshift = len(lines[0]) - len(lines[0].lstrip()) + # Don't use first line in case of """blah... + if ii == 0 and len(lines) > 1: + nshift = len(lines[1]) - len(lines[1].lstrip()) for i, line in enumerate(lines): nwhite = len(line) - len(line.lstrip()) lines[i] = line[min(nshift, nwhite):] This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
Revision: 3623 http://matplotlib.svn.sourceforge.net/matplotlib/?rev=3623&view=rev Author: dsdale Date: 2007年07月27日 08:45:26 -0700 (2007年7月27日) Log Message: ----------- added config module, for testing a traited config system Modified Paths: -------------- trunk/matplotlib/lib/matplotlib/mpl-data/matplotlibrc Added Paths: ----------- trunk/matplotlib/lib/matplotlib/config/ trunk/matplotlib/lib/matplotlib/config/__init__.py trunk/matplotlib/lib/matplotlib/config/api.py trunk/matplotlib/lib/matplotlib/config/checkdep.py trunk/matplotlib/lib/matplotlib/config/configobj.py trunk/matplotlib/lib/matplotlib/config/configtest.py trunk/matplotlib/lib/matplotlib/config/cutils.py trunk/matplotlib/lib/matplotlib/config/matplotlib.conf.default trunk/matplotlib/lib/matplotlib/config/mplconfig.py trunk/matplotlib/lib/matplotlib/config/mpltraits.py trunk/matplotlib/lib/matplotlib/config/rcparams.py trunk/matplotlib/lib/matplotlib/config/rcsetup.py trunk/matplotlib/lib/matplotlib/config/tconfig.py trunk/matplotlib/lib/matplotlib/config/verbose.py trunk/matplotlib/lib/matplotlib/mpl-data/matplotlib.conf Added: trunk/matplotlib/lib/matplotlib/config/__init__.py =================================================================== --- trunk/matplotlib/lib/matplotlib/config/__init__.py (rev 0) +++ trunk/matplotlib/lib/matplotlib/config/__init__.py 2007年07月27日 15:45:26 UTC (rev 3623) @@ -0,0 +1 @@ +# Please keep this file empty \ No newline at end of file Property changes on: trunk/matplotlib/lib/matplotlib/config/__init__.py ___________________________________________________________________ Name: svn:eol-style + native Added: trunk/matplotlib/lib/matplotlib/config/api.py =================================================================== --- trunk/matplotlib/lib/matplotlib/config/api.py (rev 0) +++ trunk/matplotlib/lib/matplotlib/config/api.py 2007年07月27日 15:45:26 UTC (rev 3623) @@ -0,0 +1,12 @@ +""" +""" + +USE_NEW_CONFIG = True + +from rcparams import rc +from cutils import get_config_file + +if USE_NEW_CONFIG: + from mplconfig import rcParams, mplConfig, save_config +else: + from rcparams import rcParams Property changes on: trunk/matplotlib/lib/matplotlib/config/api.py ___________________________________________________________________ Name: svn:eol-style + native Added: trunk/matplotlib/lib/matplotlib/config/checkdep.py =================================================================== --- trunk/matplotlib/lib/matplotlib/config/checkdep.py (rev 0) +++ trunk/matplotlib/lib/matplotlib/config/checkdep.py 2007年07月27日 15:45:26 UTC (rev 3623) @@ -0,0 +1,133 @@ +import os, re, sys +import distutils.version as version + +def dvipng(): + try: + stdin, stdout = os.popen4('dvipng -version') + line = stdout.readlines()[1] + v = line.split()[-1] + float(v) + return v + except (IndexError, ValueError): + return None + +def ghostscript(): + try: + if sys.platform == 'win32': + command = 'gswin32c -v' + else: + command = 'gs -v' + stdin, stdout = os.popen4(command) + line = stdout.readlines()[0] + v = line.split()[2] + vtest = '.'.join(v.split('.')[:2]) # deal with version numbers like '7.07.1' + float(vtest) + return vtest + except (IndexError, ValueError): + return None + +def tex(): + try: + stdin, stdout = os.popen4('tex -version') + line = stdout.readlines()[0] + pattern = '3\.1\d+' + match = re.search(pattern, line) + v = match.group(0) + float(v) + return v + except (IndexError, ValueError): + return None + +def pdftops(): + try: + stdin, stdout = os.popen4('pdftops -v') + for line in stdout.readlines(): + if 'version' in line: + v = line.split()[-1] + float(v) + return v + except (IndexError, ValueError): + return None + +def compare_versions(a, b): + "return True if a is greater than or equal to b" + if a: + a = version.LooseVersion(a) + b = version.LooseVersion(b) + if a>=b: return True + else: return False + else: return False + +def ps_distiller(s): + if not s: + return False + + flag = True + gs_req = '7.07' + gs_sugg = '7.07' + gs_v = ghostscript() + if compare_versions(gs_v, gs_sugg): pass + elif compare_versions(gs_v, gs_req): + verbose.report(('ghostscript-%s found. ghostscript-%s or later ' + 'is recommended to use the ps.usedistiller option.') %\ + (gs_v, gs_sugg)) + else: + flag = False + warnings.warn(('matplotlibrc ps.usedistiller option can not be used ' + 'unless ghostscript-%s or later is installed on your ' + 'system.') % gs_req) + + if s == 'xpdf': + pdftops_req = '3.0' + pdftops_v = pdftops() + if compare_versions(pdftops_v, pdftops_req): pass + else: + flag = False + warnings.warn(('matplotlibrc ps.usedistiller can not be set to ' + 'xpdf unless xpdf-%s or later is installed on your ' + 'system.') % pdftops_req) + + if flag: + return s + else: + return False + +def usetex(s): + if not s: + return False + + tex_req = '3.1415' + gs_req = '7.07' + gs_sugg = '7.07' + dvipng_req = '1.5' + flag = True + + tex_v = tex() + if compare_versions(tex_v, tex_req): pass + else: + flag = False + warnings.warn(('matplotlibrc text.usetex option can not be used ' + 'unless TeX-%s or later is ' + 'installed on your system') % tex_req) + + dvipng_v = dvipng() + if compare_versions(dvipng_v, dvipng_req): pass + else: + flag = False + warnings.warn( 'matplotlibrc text.usetex can not be used with *Agg ' + 'backend unless dvipng-1.5 or later is ' + 'installed on your system') + + gs_v = ghostscript() + if compare_versions(gs_v, gs_sugg): pass + elif compare_versions(gs_v, gs_req): + verbose.report(('ghostscript-%s found. ghostscript-%s or later is ' + 'recommended for use with the text.usetex ' + 'option.') % (gs_v, gs_sugg)) + else: + flag = False + warnings.warn(('matplotlibrc text.usetex can not be used ' + 'unless ghostscript-%s or later is ' + 'installed on your system') % gs_req) + + return flag \ No newline at end of file Property changes on: trunk/matplotlib/lib/matplotlib/config/checkdep.py ___________________________________________________________________ Name: svn:eol-style + native Added: trunk/matplotlib/lib/matplotlib/config/configobj.py =================================================================== --- trunk/matplotlib/lib/matplotlib/config/configobj.py (rev 0) +++ trunk/matplotlib/lib/matplotlib/config/configobj.py 2007年07月27日 15:45:26 UTC (rev 3623) @@ -0,0 +1,2279 @@ +# configobj.py +# A config file reader/writer that supports nested sections in config files. +# Copyright (C) 2005-2006 Michael Foord, Nicola Larosa +# E-mail: fuzzyman AT voidspace DOT org DOT uk +# nico AT tekNico DOT net + +# ConfigObj 4 +# http://www.voidspace.org.uk/python/configobj.html + +# Released subject to the BSD License +# Please see http://www.voidspace.org.uk/python/license.shtml + +# Scripts maintained at http://www.voidspace.org.uk/python/index.shtml +# For information about bugfixes, updates and support, please join the +# ConfigObj mailing list: +# http://lists.sourceforge.net/lists/listinfo/configobj-develop +# Comments, suggestions and bug reports welcome. + +from __future__ import generators + +import sys +INTP_VER = sys.version_info[:2] +if INTP_VER < (2, 2): + raise RuntimeError("Python v.2.2 or later needed") + +import os, re +compiler = None +try: + import compiler +except ImportError: + # for IronPython + pass +from types import StringTypes +from warnings import warn +try: + from codecs import BOM_UTF8, BOM_UTF16, BOM_UTF16_BE, BOM_UTF16_LE +except ImportError: + # Python 2.2 does not have these + # UTF-8 + BOM_UTF8 = '\xef\xbb\xbf' + # UTF-16, little endian + BOM_UTF16_LE = '\xff\xfe' + # UTF-16, big endian + BOM_UTF16_BE = '\xfe\xff' + if sys.byteorder == 'little': + # UTF-16, native endianness + BOM_UTF16 = BOM_UTF16_LE + else: + # UTF-16, native endianness + BOM_UTF16 = BOM_UTF16_BE + +# A dictionary mapping BOM to +# the encoding to decode with, and what to set the +# encoding attribute to. +BOMS = { + BOM_UTF8: ('utf_8', None), + BOM_UTF16_BE: ('utf16_be', 'utf_16'), + BOM_UTF16_LE: ('utf16_le', 'utf_16'), + BOM_UTF16: ('utf_16', 'utf_16'), + } +# All legal variants of the BOM codecs. +# TODO: the list of aliases is not meant to be exhaustive, is there a +# better way ? +BOM_LIST = { + 'utf_16': 'utf_16', + 'u16': 'utf_16', + 'utf16': 'utf_16', + 'utf-16': 'utf_16', + 'utf16_be': 'utf16_be', + 'utf_16_be': 'utf16_be', + 'utf-16be': 'utf16_be', + 'utf16_le': 'utf16_le', + 'utf_16_le': 'utf16_le', + 'utf-16le': 'utf16_le', + 'utf_8': 'utf_8', + 'u8': 'utf_8', + 'utf': 'utf_8', + 'utf8': 'utf_8', + 'utf-8': 'utf_8', + } + +# Map of encodings to the BOM to write. +BOM_SET = { + 'utf_8': BOM_UTF8, + 'utf_16': BOM_UTF16, + 'utf16_be': BOM_UTF16_BE, + 'utf16_le': BOM_UTF16_LE, + None: BOM_UTF8 + } + +try: + from validate import VdtMissingValue +except ImportError: + VdtMissingValue = None + +try: + enumerate +except NameError: + def enumerate(obj): + """enumerate for Python 2.2.""" + i = -1 + for item in obj: + i += 1 + yield i, item + +try: + True, False +except NameError: + True, False = 1, 0 + + +__version__ = '4.4.0' + +__revision__ = '$Id: configobj.py 156 2006年01月31日 14:57:08Z fuzzyman $' + +__docformat__ = "restructuredtext en" + +__all__ = ( + '__version__', + 'DEFAULT_INDENT_TYPE', + 'DEFAULT_INTERPOLATION', + 'ConfigObjError', + 'NestingError', + 'ParseError', + 'DuplicateError', + 'ConfigspecError', + 'ConfigObj', + 'SimpleVal', + 'InterpolationError', + 'InterpolationLoopError', + 'MissingInterpolationOption', + 'RepeatSectionError', + 'UnreprError', + 'UnknownType', + '__docformat__', + 'flatten_errors', +) + +DEFAULT_INTERPOLATION = 'configparser' +DEFAULT_INDENT_TYPE = ' ' +MAX_INTERPOL_DEPTH = 10 + +OPTION_DEFAULTS = { + 'interpolation': True, + 'raise_errors': False, + 'list_values': True, + 'create_empty': False, + 'file_error': False, + 'configspec': None, + 'stringify': True, + # option may be set to one of ('', ' ', '\t') + 'indent_type': None, + 'encoding': None, + 'default_encoding': None, + 'unrepr': False, + 'write_empty_values': False, +} + + +def getObj(s): + s = "a=" + s + if compiler is None: + raise ImportError('compiler module not available') + p = compiler.parse(s) + return p.getChildren()[1].getChildren()[0].getChildren()[1] + +class UnknownType(Exception): + pass + +class Builder: + + def build(self, o): + m = getattr(self, 'build_' + o.__class__.__name__, None) + if m is None: + raise UnknownType(o.__class__.__name__) + return m(o) + + def build_List(self, o): + return map(self.build, o.getChildren()) + + def build_Const(self, o): + return o.value + + def build_Dict(self, o): + d = {} + i = iter(map(self.build, o.getChildren())) + for el in i: + d[el] = i.next() + return d + + def build_Tuple(self, o): + return tuple(self.build_List(o)) + + def build_Name(self, o): + if o.name == 'None': + return None + if o.name == 'True': + return True + if o.name == 'False': + return False + + # An undefinted Name + raise UnknownType('Undefined Name') + + def build_Add(self, o): + real, imag = map(self.build_Const, o.getChildren()) + try: + real = float(real) + except TypeError: + raise UnknownType('Add') + if not isinstance(imag, complex) or imag.real != 0.0: + raise UnknownType('Add') + return real+imag + + def build_Getattr(self, o): + parent = self.build(o.expr) + return getattr(parent, o.attrname) + + def build_UnarySub(self, o): + return -self.build_Const(o.getChildren()[0]) + + def build_UnaryAdd(self, o): + return self.build_Const(o.getChildren()[0]) + +def unrepr(s): + if not s: + return s + return Builder().build(getObj(s)) + +def _splitlines(instring): + """Split a string on lines, without losing line endings or truncating.""" + + +class ConfigObjError(SyntaxError): + """ + This is the base class for all errors that ConfigObj raises. + It is a subclass of SyntaxError. + """ + def __init__(self, message='', line_number=None, line=''): + self.line = line + self.line_number = line_number + self.message = message + SyntaxError.__init__(self, message) + +class NestingError(ConfigObjError): + """ + This error indicates a level of nesting that doesn't match. + """ + +class ParseError(ConfigObjError): + """ + This error indicates that a line is badly written. + It is neither a valid ``key = value`` line, + nor a valid section marker line. + """ + +class DuplicateError(ConfigObjError): + """ + The keyword or section specified already exists. + """ + +class ConfigspecError(ConfigObjError): + """ + An error occured whilst parsing a configspec. + """ + +class InterpolationError(ConfigObjError): + """Base class for the two interpolation errors.""" + +class InterpolationLoopError(InterpolationError): + """Maximum interpolation depth exceeded in string interpolation.""" + + def __init__(self, option): + InterpolationError.__init__( + self, + 'interpolation loop detected in value "%s".' % option) + +class RepeatSectionError(ConfigObjError): + """ + This error indicates additional sections in a section with a + ``__many__`` (repeated) section. + """ + +class MissingInterpolationOption(InterpolationError): + """A value specified for interpolation was missing.""" + + def __init__(self, option): + InterpolationError.__init__( + self, + 'missing option "%s" in interpolation.' % option) + +class UnreprError(ConfigObjError): + """An error parsing in unrepr mode.""" + + +class InterpolationEngine(object): + """ + A helper class to help perform string interpolation. + + This class is an abstract base class; its descendants perform + the actual work. + """ + + # compiled regexp to use in self.interpolate() + _KEYCRE = re.compile(r"%\(([^)]*)\)s") + + def __init__(self, section): + # the Section instance that "owns" this engine + self.section = section + + def interpolate(self, key, value): + def recursive_interpolate(key, value, section, backtrail): + """The function that does the actual work. + + ``value``: the string we're trying to interpolate. + ``section``: the section in which that string was found + ``backtrail``: a dict to keep track of where we've been, + to detect and prevent infinite recursion loops + + This is similar to a depth-first-search algorithm. + """ + # Have we been here already? + if backtrail.has_key((key, section.name)): + # Yes - infinite loop detected + raise InterpolationLoopError(key) + # Place a marker on our backtrail so we won't come back here again + backtrail[(key, section.name)] = 1 + + # Now start the actual work + match = self._KEYCRE.search(value) + while match: + # The actual parsing of the match is implementation-dependent, + # so delegate to our helper function + k, v, s = self._parse_match(match) + if k is None: + # That's the signal that no further interpolation is needed + replacement = v + else: + # Further interpolation may be needed to obtain final value + replacement = recursive_interpolate(k, v, s, backtrail) + # Replace the matched string with its final value + start, end = match.span() + value = ''.join((value[:start], replacement, value[end:])) + new_search_start = start + len(replacement) + # Pick up the next interpolation key, if any, for next time + # through the while loop + match = self._KEYCRE.search(value, new_search_start) + + # Now safe to come back here again; remove marker from backtrail + del backtrail[(key, section.name)] + + return value + + # Back in interpolate(), all we have to do is kick off the recursive + # function with appropriate starting values + value = recursive_interpolate(key, value, self.section, {}) + return value + + def _fetch(self, key): + """Helper function to fetch values from owning section. + + Returns a 2-tuple: the value, and the section where it was found. + """ + # switch off interpolation before we try and fetch anything ! + save_interp = self.section.main.interpolation + self.section.main.interpolation = False + + # Start at section that "owns" this InterpolationEngine + current_section = self.section + while True: + # try the current section first + val = current_section.get(key) + if val is not None: + break + # try "DEFAULT" next + val = current_section.get('DEFAULT', {}).get(key) + if val is not None: + break + # move up to parent and try again + # top-level's parent is itself + if current_section.parent is current_section: + # reached top level, time to give up + break + current_section = current_section.parent + + # restore interpolation to previous value before returning + self.section.main.interpolation = save_interp + if val is None: + raise MissingInterpolationOption(key) + return val, current_section + + def _parse_match(self, match): + """Implementation-dependent helper function. + + Will be passed a match object corresponding to the interpolation + key we just found (e.g., "%(foo)s" or "$foo"). Should look up that + key in the appropriate config file section (using the ``_fetch()`` + helper function) and return a 3-tuple: (key, value, section) + + ``key`` is the name of the key we're looking for + ``value`` is the value found for that key + ``section`` is a reference to the section where it was found + + ``key`` and ``section`` should be None if no further + interpolation should be performed on the resulting value + (e.g., if we interpolated "$$" and returned "$"). + """ + raise NotImplementedError + + +class ConfigParserInterpolation(InterpolationEngine): + """Behaves like ConfigParser.""" + _KEYCRE = re.compile(r"%\(([^)]*)\)s") + + def _parse_match(self, match): + key = match.group(1) + value, section = self._fetch(key) + return key, value, section + + +class TemplateInterpolation(InterpolationEngine): + """Behaves like string.Template.""" + _delimiter = '$' + _KEYCRE = re.compile(r""" + \$(?: + (?P<escaped>\$) | # Two $ signs + (?P<named>[_a-z][_a-z0-9]*) | # $name format + {(?P<braced>[^}]*)} # ${name} format + ) + """, re.IGNORECASE | re.VERBOSE) + + def _parse_match(self, match): + # Valid name (in or out of braces): fetch value from section + key = match.group('named') or match.group('braced') + if key is not None: + value, section = self._fetch(key) + return key, value, section + # Escaped delimiter (e.g., $$): return single delimiter + if match.group('escaped') is not None: + # Return None for key and section to indicate it's time to stop + return None, self._delimiter, None + # Anything else: ignore completely, just return it unchanged + return None, match.group(), None + +interpolation_engines = { + 'configparser': ConfigParserInterpolation, + 'template': TemplateInterpolation, +} + +class Section(dict): + """ + A dictionary-like object that represents a section in a config file. + + It does string interpolation if the 'interpolation' attribute + of the 'main' object is set to True. + + Interpolation is tried first from this object, then from the 'DEFAULT' + section of this object, next from the parent and its 'DEFAULT' section, + and so on until the main object is reached. + + A Section will behave like an ordered dictionary - following the + order of the ``scalars`` and ``sections`` attributes. + You can use this to change the order of members. + + Iteration follows the order: scalars, then sections. + """ + + def __init__(self, parent, depth, main, indict=None, name=None): + """ + * parent is the section above + * depth is the depth level of this section + * main is the main ConfigObj + * indict is a dictionary to initialise the section with + """ + if indict is None: + indict = {} + dict.__init__(self) + # used for nesting level *and* interpolation + self.parent = parent + # used for the interpolation attribute + self.main = main + # level of nesting depth of this Section + self.depth = depth + # the sequence of scalar values in this Section + self.scalars = [] + # the sequence of sections in this Section + self.sections = [] + # purely for information + self.name = name + # for comments :-) + self.comments = {} + self.inline_comments = {} + # for the configspec + self.configspec = {} + self._order = [] + self._configspec_comments = {} + self._configspec_inline_comments = {} + self._cs_section_comments = {} + self._cs_section_inline_comments = {} + # for defaults + self.defaults = [] + # + # we do this explicitly so that __setitem__ is used properly + # (rather than just passing to ``dict.__init__``) + for entry in indict: + self[entry] = indict[entry] + + def _interpolate(self, key, value): + try: + # do we already have an interpolation engine? + engine = self._interpolation_engine + except AttributeError: + # not yet: first time running _interpolate(), so pick the engine + name = self.main.interpolation + if name == True: # note that "if name:" would be incorrect here + # backwards-compatibility: interpolation=True means use default + name = DEFAULT_INTERPOLATION + name = name.lower() # so that "Template", "template", etc. all work + class_ = interpolation_engines.get(name, None) + if class_ is None: + # invalid value for self.main.interpolation + self.main.interpolation = False + return value + else: + # save reference to engine so we don't have to do this again + engine = self._interpolation_engine = class_(self) + # let the engine do the actual work + return engine.interpolate(key, value) + + def __getitem__(self, key): + """Fetch the item and do string interpolation.""" + val = dict.__getitem__(self, key) + if self.main.interpolation and isinstance(val, StringTypes): + return self._interpolate(key, val) + return val + + def __setitem__(self, key, value, unrepr=False): + """ + Correctly set a value. + + Making dictionary values Section instances. + (We have to special case 'Section' instances - which are also dicts) + + Keys must be strings. + Values need only be strings (or lists of strings) if + ``main.stringify`` is set. + + `unrepr`` must be set when setting a value to a dictionary, without + creating a new sub-section. + """ + if not isinstance(key, StringTypes): + raise ValueError, 'The key "%s" is not a string.' % key + # add the comment + if not self.comments.has_key(key): + self.comments[key] = [] + self.inline_comments[key] = '' + # remove the entry from defaults + if key in self.defaults: + self.defaults.remove(key) + # + if isinstance(value, Section): + if not self.has_key(key): + self.sections.append(key) + dict.__setitem__(self, key, value) + elif isinstance(value, dict) and not unrepr: + # First create the new depth level, + # then create the section + if not self.has_key(key): + self.sections.append(key) + new_depth = self.depth + 1 + dict.__setitem__( + self, + key, + Section( + self, + new_depth, + self.main, + indict=value, + name=key)) + else: + if not self.has_key(key): + self.scalars.append(key) + if not self.main.stringify: + if isinstance(value, StringTypes): + pass + elif isinstance(value, (list, tuple)): + for entry in value: + if not isinstance(entry, StringTypes): + raise TypeError, ( + 'Value is not a string "%s".' % entry) + else: + raise TypeError, 'Value is not a string "%s".' % value + dict.__setitem__(self, key, value) + + def __delitem__(self, key): + """Remove items from the sequence when deleting.""" + dict. __delitem__(self, key) + if key in self.scalars: + self.scalars.remove(key) + else: + self.sections.remove(key) + del self.comments[key] + del self.inline_comments[key] + + def get(self, key, default=None): + """A version of ``get`` that doesn't bypass string interpolation.""" + try: + return self[key] + except KeyError: + return default + + def update(self, indict): + """ + A version of update that uses our ``__setitem__``. + """ + for entry in indict: + self[entry] = indict[entry] + + def pop(self, key, *args): + """ """ + val = dict.pop(self, key, *args) + if key in self.scalars: + del self.comments[key] + del self.inline_comments[key] + self.scalars.remove(key) + elif key in self.sections: + del self.comments[key] + del self.inline_comments[key] + self.sections.remove(key) + if self.main.interpolation and isinstance(val, StringTypes): + return self._interpolate(key, val) + return val + + def popitem(self): + """Pops the first (key,val)""" + sequence = (self.scalars + self.sections) + if not sequence: + raise KeyError, ": 'popitem(): dictionary is empty'" + key = sequence[0] + val = self[key] + del self[key] + return key, val + + def clear(self): + """ + A version of clear that also affects scalars/sections + Also clears comments and configspec. + + Leaves other attributes alone : + depth/main/parent are not affected + """ + dict.clear(self) + self.scalars = [] + self.sections = [] + self.comments = {} + self.inline_comments = {} + self.configspec = {} + + def setdefault(self, key, default=None): + """A version of setdefault that sets sequence if appropriate.""" + try: + return self[key] + except KeyError: + self[key] = default + return self[key] + + def items(self): + """ """ + return zip((self.scalars + self.sections), self.values()) + + def keys(self): + """ """ + return (self.scalars + self.sections) + + def values(self): + """ """ + return [self[key] for key in (self.scalars + self.sections)] + + def iteritems(self): + """ """ + return iter(self.items()) + + def iterkeys(self): + """ """ + return iter((self.scalars + self.sections)) + + __iter__ = iterkeys + + def itervalues(self): + """ """ + return iter(self.values()) + + def __repr__(self): + return '{%s}' % ', '.join([('%s: %s' % (repr(key), repr(self[key]))) + for key in (self.scalars + self.sections)]) + + __str__ = __repr__ + + # Extra methods - not in a normal dictionary + + def dict(self): + """ + Return a deepcopy of self as a dictionary. + + All members that are ``Section`` instances are recursively turned to + ordinary dictionaries - by calling their ``dict`` method. + + >>> n = a.dict() + >>> n == a + 1 + >>> n is a + 0 + """ + newdict = {} + for entry in self: + this_entry = self[entry] + if isinstance(this_entry, Section): + this_entry = this_entry.dict() + elif isinstance(this_entry, list): + # create a copy rather than a reference + this_entry = list(this_entry) + elif isinstance(this_entry, tuple): + # create a copy rather than a reference + this_entry = tuple(this_entry) + newdict[entry] = this_entry + return newdict + + def merge(self, indict): + """ + A recursive update - useful for merging config files. + + >>> a = '''[section1] + ... option1 = True + ... [[subsection]] + ... more_options = False + ... # end of file'''.splitlines() + >>> b = '''# File is user.ini + ... [section1] + ... option1 = False + ... # end of file'''.splitlines() + >>> c1 = ConfigObj(b) + >>> c2 = ConfigObj(a) + >>> c2.merge(c1) + >>> c2 + {'section1': {'option1': 'False', 'subsection': {'more_options': 'False'}}} + """ + for key, val in indict.items(): + if (key in self and isinstance(self[key], dict) and + isinstance(val, dict)): + self[key].merge(val) + else: + self[key] = val + + def rename(self, oldkey, newkey): + """ + Change a keyname to another, without changing position in sequence. + + Implemented so that transformations can be made on keys, + as well as on values. (used by encode and decode) + + Also renames comments. + """ + if oldkey in self.scalars: + the_list = self.scalars + elif oldkey in self.sections: + the_list = self.sections + else: + raise KeyError, 'Key "%s" not found.' % oldkey + pos = the_list.index(oldkey) + # + val = self[oldkey] + dict.__delitem__(self, oldkey) + dict.__setitem__(self, newkey, val) + the_list.remove(oldkey) + the_list.insert(pos, newkey) + comm = self.comments[oldkey] + inline_comment = self.inline_comments[oldkey] + del self.comments[oldkey] + del self.inline_comments[oldkey] + self.comments[newkey] = comm + self.inline_comments[newkey] = inline_comment + + def walk(self, function, raise_errors=True, + call_on_sections=False, **keywargs): + """ + Walk every member and call a function on the keyword and value. + + Return a dictionary of the return values + + If the function raises an exception, raise the errror + unless ``raise_errors=False``, in which case set the return value to + ``False``. + + Any unrecognised keyword arguments you pass to walk, will be pased on + to the function you pass in. + + Note: if ``call_on_sections`` is ``True`` then - on encountering a + subsection, *first* the function is called for the *whole* subsection, + and then recurses into it's members. This means your function must be + able to handle strings, dictionaries and lists. This allows you + to change the key of subsections as well as for ordinary members. The + return value when called on the whole subsection has to be discarded. + + See the encode and decode methods for examples, including functions. + + .. caution:: + + You can use ``walk`` to transform the names of members of a section + but you mustn't add or delete members. + + >>> config = '''[XXXXsection] + ... XXXXkey = XXXXvalue'''.splitlines() + >>> cfg = ConfigObj(config) + >>> cfg + {'XXXXsection': {'XXXXkey': 'XXXXvalue'}} + >>> def transform(section, key): + ... val = section[key] + ... newkey = key.replace('XXXX', 'CLIENT1') + ... section.rename(key, newkey) + ... if isinstance(val, (tuple, list, dict)): + ... pass + ... else: + ... val = val.replace('XXXX', 'CLIENT1') + ... section[newkey] = val + >>> cfg.walk(transform, call_on_sections=True) + {'CLIENT1section': {'CLIENT1key': None}} + >>> cfg + {'CLIENT1section': {'CLIENT1key': 'CLIENT1value'}} + """ + out = {} + # scalars first + for i in range(len(self.scalars)): + entry = self.scalars[i] + try: + val = function(self, entry, **keywargs) + # bound again in case name has changed + entry = self.scalars[i] + out[entry] = val + except Exception: + if raise_errors: + raise + else: + entry = self.scalars[i] + out[entry] = False + # then sections + for i in range(len(self.sections)): + entry = self.sections[i] + if call_on_sections: + try: + function(self, entry, **keywargs) + except Exception: + if raise_errors: + raise + else: + entry = self.sections[i] + out[entry] = False + # bound again in case name has changed + entry = self.sections[i] + # previous result is discarded + out[entry] = self[entry].walk( + function, + raise_errors=raise_errors, + call_on_sections=call_on_sections, + **keywargs) + return out + + def decode(self, encoding): + """ + Decode all strings and values to unicode, using the specified encoding. + + Works with subsections and list values. + + Uses the ``walk`` method. + + Testing ``encode`` and ``decode``. + >>> m = ConfigObj(a) + >>> m.decode('ascii') + >>> def testuni(val): + ... for entry in val: + ... if not isinstance(entry, unicode): + ... print >> sys.stderr, type(entry) + ... raise AssertionError, 'decode failed.' + ... if isinstance(val[entry], dict): + ... testuni(val[entry]) + ... elif not isinstance(val[entry], unicode): + ... raise AssertionError, 'decode failed.' + >>> testuni(m) + >>> m.encode('ascii') + >>> a == m + 1 + """ + warn('use of ``decode`` is deprecated.', DeprecationWarning) + def decode(section, key, encoding=encoding, warn=True): + """ """ + val = section[key] + if isinstance(val, (list, tuple)): + newval = [] + for entry in val: + newval.append(entry.decode(encoding)) + elif isinstance(val, dict): + newval = val + else: + newval = val.decode(encoding) + newkey = key.decode(encoding) + section.rename(key, newkey) + section[newkey] = newval + # using ``call_on_sections`` allows us to modify section names + self.walk(decode, call_on_sections=True) + + def encode(self, encoding): + """ + Encode all strings and values from unicode, + using the specified encoding. + + Works with subsections and list values. + Uses the ``walk`` method. + """ + warn('use of ``encode`` is deprecated.', DeprecationWarning) + def encode(section, key, encoding=encoding): + """ """ + val = section[key] + if isinstance(val, (list, tuple)): + newval = [] + for entry in val: + newval.append(entry.encode(encoding)) + elif isinstance(val, dict): + newval = val + else: + newval = val.encode(encoding) + newkey = key.encode(encoding) + section.rename(key, newkey) + section[newkey] = newval + self.walk(encode, call_on_sections=True) + + def istrue(self, key): + """A deprecated version of ``as_bool``.""" + warn('use of ``istrue`` is deprecated. Use ``as_bool`` method ' + 'instead.', DeprecationWarning) + return self.as_bool(key) + + def as_bool(self, key): + """ + Accepts a key as input. The corresponding value must be a string or + the objects (``True`` or 1) or (``False`` or 0). We allow 0 and 1 to + retain compatibility with Python 2.2. + + If the string is one of ``True``, ``On``, ``Yes``, or ``1`` it returns + ``True``. + + If the string is one of ``False``, ``Off``, ``No``, or ``0`` it returns + ``False``. + + ``as_bool`` is not case sensitive. + + Any other input will raise a ``ValueError``. + + >>> a = ConfigObj() + >>> a['a'] = 'fish' + >>> a.as_bool('a') + Traceback (most recent call last): + ValueError: Value "fish" is neither True nor False + >>> a['b'] = 'True' + >>> a.as_bool('b') + 1 + >>> a['b'] = 'off' + >>> a.as_bool('b') + 0 + """ + val = self[key] + if val == True: + return True + elif val == False: + return False + else: + try: + if not isinstance(val, StringTypes): + raise KeyError + else: + return self.main._bools[val.lower()] + except KeyError: + raise ValueError('Value "%s" is neither True nor False' % val) + + def as_int(self, key): + """ + A convenience method which coerces the specified value to an integer. + + If the value is an invalid literal for ``int``, a ``ValueError`` will + be raised. + + >>> a = ConfigObj() + >>> a['a'] = 'fish' + >>> a.as_int('a') + Traceback (most recent call last): + ValueError: invalid literal for int(): fish + >>> a['b'] = '1' + >>> a.as_int('b') + 1 + >>> a['b'] = '3.2' + >>> a.as_int('b') + Traceback (most recent call last): + ValueError: invalid literal for int(): 3.2 + """ + return int(self[key]) + + def as_float(self, key): + """ + A convenience method which coerces the specified value to a float. + + If the value is an invalid literal for ``float``, a ``ValueError`` will + be raised. + + >>> a = ConfigObj() + >>> a['a'] = 'fish' + >>> a.as_float('a') + Traceback (most recent call last): + ValueError: invalid literal for float(): fish + >>> a['b'] = '1' + >>> a.as_float('b') + 1.0 + >>> a['b'] = '3.2' + >>> a.as_float('b') + 3.2000000000000002 + """ + return float(self[key]) + + +class ConfigObj(Section): + """An object to read, create, and write config files.""" + + _keyword = re.compile(r'''^ # line start + (\s*) # indentation + ( # keyword + (?:".*?")| # double quotes + (?:'.*?')| # single quotes + (?:[^'"=].*?) # no quotes + ) + \s*=\s* # divider + (.*) # value (including list values and comments) + $ # line end + ''', + re.VERBOSE) + + _sectionmarker = re.compile(r'''^ + (\s*) # 1: indentation + ((?:\[\s*)+) # 2: section marker open + ( # 3: section name open + (?:"\s*\S.*?\s*")| # at least one non-space with double quotes + (?:'\s*\S.*?\s*')| # at least one non-space with single quotes + (?:[^'"\s].*?) # at least one non-space unquoted + ) # section name close + ((?:\s*\])+) # 4: section marker close + \s*(\#.*)? # 5: optional comment + $''', + re.VERBOSE) + + # this regexp pulls list values out as a single string + # or single values and comments + # FIXME: this regex adds a '' to the end of comma terminated lists + # workaround in ``_handle_value`` + _valueexp = re.compile(r'''^ + (?: + (?: + ( + (?: + (?: + (?:".*?")| # double quotes + (?:'.*?')| # single quotes + (?:[^'",\#][^,\#]*?) # unquoted + ) + \s*,\s* # comma + )* # match all list items ending in a comma (if any) + ) + ( + (?:".*?")| # double quotes + (?:'.*?')| # single quotes + (?:[^'",\#\s][^,]*?)| # unquoted + (?:(?<!,)) # Empty value + )? # last item in a list - or string value + )| + (,) # alternatively a single comma - empty list + ) + \s*(\#.*)? # optional comment + $''', + re.VERBOSE) + + # use findall to get the members of a list value + _listvalueexp = re.compile(r''' + ( + (?:".*?")| # double quotes + (?:'.*?')| # single quotes + (?:[^'",\#].*?) # unquoted + ) + \s*,\s* # comma + ''', + re.VERBOSE) + + # this regexp is used for the value + # when lists are switched off + _nolistvalue = re.compile(r'''^ + ( + (?:".*?")| # double quotes + (?:'.*?')| # single quotes + (?:[^'"\#].*?)| # unquoted + (?:) # Empty value + ) + \s*(\#.*)? # optional comment + $''', + re.VERBOSE) + + # regexes for finding triple quoted values on one line + _single_line_single = re.compile(r"^'''(.*?)'''\s*(#.*)?$") + _single_line_double = re.compile(r'^"""(.*?)"""\s*(#.*)?$') + _multi_line_single = re.compile(r"^(.*?)'''\s*(#.*)?$") + _multi_line_double = re.compile(r'^(.*?)"""\s*(#.*)?$') + + _triple_quote = { + "'''": (_single_line_single, _multi_line_single), + '"""': (_single_line_double, _multi_line_double), + } + + # Used by the ``istrue`` Section method + _bools = { + 'yes': True, 'no': False, + 'on': True, 'off': False, + '1': True, '0': False, + 'true': True, 'false': False, + } + + def __init__(self, infile=None, options=None, **kwargs): + """ + Parse or create a config file object. + + ``ConfigObj(infile=None, options=None, **kwargs)`` + """ + if infile is None: + infile = [] + if options is None: + options = {} + else: + options = dict(options) + # keyword arguments take precedence over an options dictionary + options.update(kwargs) + # init the superclass + Section.__init__(self, self, 0, self) + # + defaults = OPTION_DEFAULTS.copy() + for entry in options.keys(): + if entry not in defaults.keys(): + raise TypeError, 'Unrecognised option "%s".' % entry + # TODO: check the values too. + # + # Add any explicit options to the defaults + defaults.update(options) + # + # initialise a few variables + self.filename = None + self._errors = [] + self.raise_errors = defaults['raise_errors'] + self.interpolation = defaults['interpolation'] + self.list_values = defaults['list_values'] + self.create_empty = defaults['create_empty'] + self.file_error = defaults['file_error'] + self.stringify = defaults['stringify'] + self.indent_type = defaults['indent_type'] + self.encoding = defaults['encoding'] + self.default_encoding = defaults['default_encoding'] + self.BOM = False + self.newlines = None + self.write_empty_values = defaults['write_empty_values'] + self.unrepr = defaults['unrepr'] + # + self.initial_comment = [] + self.final_comment = [] + # + self._terminated = False + # + if isinstance(infile, StringTypes): + self.filename = infile + if os.path.isfile(infile): + infile = open(infile).read() or [] + elif self.file_error: + # raise an error if the file doesn't exist + raise IOError, 'Config file not found: "%s".' % self.filename + else: + # file doesn't already exist + if self.create_empty: + # this is a good test that the filename specified + # isn't impossible - like on a non existent device + h = open(infile, 'w') + h.write('') + h.close() + infile = [] + elif isinstance(infile, (list, tuple)): + infile = list(infile) + elif isinstance(infile, dict): + # initialise self + # the Section class handles creating subsections + if isinstance(infile, ConfigObj): + # get a copy of our ConfigObj + infile = infile.dict() + for entry in infile: + self[entry] = infile[entry] + del self._errors + if defaults['configspec'] is not None: + self._handle_configspec(defaults['configspec']) + else: + self.configspec = None + return + elif hasattr(infile, 'read'): + # This supports file like objects + infile = infile.read() or [] + # needs splitting into lines - but needs doing *after* decoding + # in case it's not an 8 bit encoding + else: + raise TypeError, ('infile must be a filename,' + ' file like object, or list of lines.') + # + if infile: + # don't do it for the empty ConfigObj + infile = self._handle_bom(infile) + # infile is now *always* a list + # + # Set the newlines attribute (first line ending it finds) + # and strip trailing '\n' or '\r' from lines + for line in infile: + if (not line) or (line[-1] not in ('\r', '\n', '\r\n')): + continue + for end in ('\r\n', '\n', '\r'): + if line.endswith(end): + self.newlines = end + break + break + if infile[-1] and infile[-1] in ('\r', '\n', '\r\n'): + self._terminated = True + infile = [line.rstrip('\r\n') for line in infile] + # + self._parse(infile) + # if we had any errors, now is the time to raise them + if self._errors: + info = "at line %s." % self._errors[0].line_number + if len(self._errors) > 1: + msg = ("Parsing failed with several errors.\nFirst error %s" % + info) + error = ConfigObjError(msg) + else: + error = self._errors[0] + # set the errors attribute; it's a list of tuples: + # (error_type, message, line_number) + error.errors = self._errors + # set the config attribute + error.config = self + raise error + # delete private attributes + del self._errors + # + if defaults['configspec'] is None: + self.configspec = None + else: + self._handle_configspec(defaults['configspec']) + + def __repr__(self): + return 'ConfigObj({%s})' % ', '.join( + [('%s: %s' % (repr(key), repr(self[key]))) for key in + (self.scalars + self.sections)]) + + def _handle_bom(self, infile): + """ + Handle any BOM, and decode if necessary. + + If an encoding is specified, that *must* be used - but the BOM should + still be removed (and the BOM attribute set). + + (If the encoding is wrongly specified, then a BOM for an alternative + encoding won't be discovered or removed.) + + If an encoding is not specified, UTF8 or UTF16 BOM will be detected and + removed. The BOM attribute will be set. UTF16 will be decoded to + unicode. + + NOTE: This method must not be called with an empty ``infile``. + + Specifying the *wrong* encoding is likely to cause a + ``UnicodeDecodeError``. + + ``infile`` must always be returned as a list of lines, but may be + passed in as a single string. + """ + if ((self.encoding is not None) and + (self.encoding.lower() not in BOM_LIST)): + # No need to check for a BOM + # the encoding specified doesn't have one + # just decode + return self._decode(infile, self.encoding) + # + if isinstance(infile, (list, tuple)): + line = infile[0] + else: + line = infile + if self.encoding is not None: + # encoding explicitly supplied + # And it could have an associated BOM + # TODO: if encoding is just UTF16 - we ought to check for both + # TODO: big endian and little endian versions. + enc = BOM_LIST[self.encoding.lower()] + if enc == 'utf_16': + # For UTF16 we try big endian and little endian + for BOM, (encoding, final_encoding) in BOMS.items(): + if not final_encoding: + # skip UTF8 + continue + if infile.startswith(BOM): + ### BOM discovered + ##self.BOM = True + # Don't need to remove BOM + return self._decode(infile, encoding) + # + # If we get this far, will *probably* raise a DecodeError + # As it doesn't appear to start with a BOM + return self._decode(infile, self.encoding) + # + # Must be UTF8 + BOM = BOM_SET[enc] + if not line.startswith(BOM): + return self._decode(infile, self.encoding) + # + newline = line[len(BOM):] + # + # BOM removed + if isinstance(infile, (list, tuple)): + infile[0] = newline + else: + infile = newline + self.BOM = True + return self._decode(infile, self.encoding) + # + # No encoding specified - so we need to check for UTF8/UTF16 + for BOM, (encoding, final_encoding) in BOMS.items(): + if not line.startswith(BOM): + continue + else: + # BOM discovered + self.encoding = final_encoding + if not final_encoding: + self.BOM = True + # UTF8 + # remove BOM + newline = line[len(BOM):] + if isinstance(infile, (list, tuple)): + infile[0] = newline + else: + infile = newline + # UTF8 - don't decode + if isinstance(infile, StringTypes): + return infile.splitlines(True) + else: + return infile + # UTF16 - have to decode + return self._decode(infile, encoding) + # + # No BOM discovered and no encoding specified, just return + if isinstance(infile, StringTypes): + # infile read from a file will be a single string + return infile.splitlines(True) + else: + return infile + + def _a_to_u(self, aString): + """Decode ASCII strings to unicode if a self.encoding is specified.""" + if self.encoding: + return aString.decode('ascii') + else: + return aString + + def _decode(self, infile, encoding): + """ + Decode infile to unicode. Using the specified encoding. + + if is a string, it also needs converting to a list. + """ + if isinstance(infile, StringTypes): + # can't be unicode + # NOTE: Could raise a ``UnicodeDecodeError`` + return infile.decode(encoding).splitlines(True) + for i, line in enumerate(infile): + if not isinstance(line, unicode): + # NOTE: The isinstance test here handles mixed lists of unicode/string + # NOTE: But the decode will break on any non-string values + # NOTE: Or could raise a ``UnicodeDecodeError`` + infile[i] = line.decode(encoding) + return infile + + def _decode_element(self, line): + """Decode element to unicode if necessary.""" + if not self.encoding: + return line + if isinstance(line, str) and self.default_encoding: + return line.decode(self.default_encoding) + return line + + def _str(self, value): + """ + Used by ``stringify`` within validate, to turn non-string values + into strings. + """ + if not isinstance(value, StringTypes): + return str(value) + else: + return value + + def _parse(self, infile): + """Actually parse the config file.""" + temp_list_values = self.list_values + if self.unrepr: + self.list_values = False + comment_list = [] + done_start = False + this_section = self + maxline = len(infile) - 1 + cur_index = -1 + reset_comment = False + while cur_index < maxline: + if reset_comment: + comment_list = [] + cur_index += 1 + line = infile[cur_index] + sline = line.strip() + # do we have anything on the line ? + if not sline or sline.startswith('#'): + reset_comment = False + comment_list.append(line) + continue + if not done_start: + # preserve initial comment + self.initial_comment = comment_list + comment_list = [] + done_start = True + reset_comment = True + # first we check if it's a section marker + mat = self._sectionmarker.match(line) + if mat is not None: + # is a section line + (indent, sect_open, sect_name, sect_close, comment) = ( + mat.groups()) + if indent and (self.indent_type is None): + self.indent_type = indent + cur_depth = sect_open.count('[') + if cur_depth != sect_close.count(']'): + self._handle_error( + "Cannot compute the section depth at line %s.", + NestingError, infile, cur_index) + continue + # + if cur_depth < this_section.depth: + # the new section is dropping back to a previous level + try: + parent = self._match_depth( + this_section, + cur_depth).parent + except SyntaxError: + self._handle_error( + "Cannot compute nesting level at line %s.", + NestingError, infile, cur_index) + continue + elif cur_depth == this_section.depth: + # the new section is a sibling of the current section + parent = this_section.parent + elif cur_depth == this_section.depth + 1: + # the new section is a child the current section + parent = this_section + else: + self._handle_error( + "Section too nested at line %s.", + NestingError, infile, cur_index) + # + sect_name = self._unquote(sect_name) + if parent.has_key(sect_name): + self._handle_error( + 'Duplicate section name at line %s.', + DuplicateError, infile, cur_index) + continue + # create the new section + this_section = Section( + parent, + cur_depth, + self, + name=sect_name) + parent[sect_name] = this_section + parent.inline_comments[sect_name] = comment + parent.comments[sect_name] = comment_list + continue + # + # it's not a section... [truncated message content]
Revision: 3622 http://matplotlib.svn.sourceforge.net/matplotlib/?rev=3622&view=rev Author: jouni Date: 2007年07月26日 14:13:58 -0700 (2007年7月26日) Log Message: ----------- Numpy has isfinite, unlike the old numerix Modified Paths: -------------- trunk/matplotlib/lib/matplotlib/backends/backend_pdf.py Modified: trunk/matplotlib/lib/matplotlib/backends/backend_pdf.py =================================================================== --- trunk/matplotlib/lib/matplotlib/backends/backend_pdf.py 2007年07月26日 19:44:35 UTC (rev 3621) +++ trunk/matplotlib/lib/matplotlib/backends/backend_pdf.py 2007年07月26日 21:13:58 UTC (rev 3622) @@ -112,7 +112,7 @@ # need to use %f with some precision. Perhaps the precision # should adapt to the magnitude of the number? elif isinstance(obj, float): - if npy.isnan(obj) or obj in (-npy.inf, npy.inf): + if not npy.isfinite(obj): raise ValueError, "Can only output finite numbers in PDF" r = "%.10f" % obj return r.rstrip('0').rstrip('.') This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.