SourceForge logo
SourceForge logo
Menu

matplotlib-checkins — Commit notification. DO NOT POST to this list, just subscribe to it.

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

Showing results of 5455

<< < 1 .. 216 217 218 219 > >> (Page 218 of 219)
From: <ds...@us...> - 2007年07月18日 16:53:13
Revision: 3562
 http://matplotlib.svn.sourceforge.net/matplotlib/?rev=3562&view=rev
Author: dsdale
Date: 2007年07月18日 09:53:11 -0700 (2007年7月18日)
Log Message:
-----------
make texmanager respect changes to rcParams after initial import
Modified Paths:
--------------
 trunk/matplotlib/CHANGELOG
 trunk/matplotlib/lib/matplotlib/texmanager.py
Modified: trunk/matplotlib/CHANGELOG
===================================================================
--- trunk/matplotlib/CHANGELOG	2007年07月18日 16:45:55 UTC (rev 3561)
+++ trunk/matplotlib/CHANGELOG	2007年07月18日 16:53:11 UTC (rev 3562)
@@ -1,3 +1,8 @@
+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
 
 2007年07月17日 bugfix segfault in transforms module. Thanks Ben North for
Modified: trunk/matplotlib/lib/matplotlib/texmanager.py
===================================================================
--- trunk/matplotlib/lib/matplotlib/texmanager.py	2007年07月18日 16:45:55 UTC (rev 3561)
+++ trunk/matplotlib/lib/matplotlib/texmanager.py	2007年07月18日 16:53:11 UTC (rev 3562)
@@ -33,26 +33,23 @@
 
 """
 
-import glob, md5, os, shutil, sys, warnings
-from tempfile import gettempdir
-from matplotlib import get_configdir, get_home, get_data_path, \
- rcParams, verbose
+import copy, glob, md5, os, shutil, sys, warnings
+import numpy as npy
+import matplotlib as mpl
+from matplotlib import rcParams
 from matplotlib._image import readpng
-from matplotlib.numerix import ravel, where, array, \
- zeros, Float, absolute, nonzero, sqrt
 
-debug = False
+DEBUG = False
 
 if sys.platform.startswith('win'): cmd_split = '&'
 else: cmd_split = ';'
 
-
 def get_dvipng_version():
 stdin, stdout = os.popen4('dvipng -version')
 for line in stdout:
 if line.startswith('dvipng '):
 version = line.split()[-1]
- verbose.report('Found dvipng version %s'% version,
+ mpl.verbose.report('Found dvipng version %s'% version,
 'helpful')
 return version
 raise RuntimeError('Could not obtain dvipng version')
@@ -64,14 +61,13 @@
 working dir
 """
 
- oldpath = get_home()
- if oldpath is None: oldpath = get_data_path()
+ oldpath = mpl.get_home()
+ if oldpath is None: oldpath = mpl.get_data_path()
 oldcache = os.path.join(oldpath, '.tex.cache')
 
- configdir = get_configdir()
+ configdir = mpl.get_configdir()
 texcache = os.path.join(configdir, 'tex.cache')
 
-
 if os.path.exists(oldcache):
 print >> sys.stderr, """\
 WARNING: found a TeX cache dir in the deprecated location "%s".
@@ -82,6 +78,7 @@
 
 dvipngVersion = get_dvipng_version()
 
+ # mappable cache of 
 arrayd = {}
 postscriptd = {}
 pscnt = 0
@@ -91,12 +88,15 @@
 monospace = ('cmtt', '')
 cursive = ('pzc', r'\usepackage{chancery}')
 font_family = 'serif'
+ font_families = ('serif', 'sans-serif', 'cursive', 'monospace')
 
- font_info = {'new century schoolbook': ('pnc', r'\renewcommand{\rmdefault}{pnc}'),
+ font_info = {'new century schoolbook': ('pnc', 
+ r'\renewcommand{\rmdefault}{pnc}'),
 'bookman': ('pbk', r'\renewcommand{\rmdefault}{pbk}'),
 'times': ('ptm', r'\usepackage{mathptmx}'),
 'palatino': ('ppl', r'\usepackage{mathpazo}'),
 'zapf chancery': ('pzc', r'\usepackage{chancery}'),
+ 'cursive': ('pzc', r'\usepackage{chancery}'),
 'charter': ('pch', r'\usepackage{charter}'),
 'serif': ('cmr', ''),
 'sans-serif': ('cmss', ''),
@@ -107,49 +107,37 @@
 'computer modern roman': ('cmr', ''),
 'computer modern sans serif': ('cmss', ''),
 'computer modern typewriter': ('cmtt', '')}
+ 
+ _rc_cache = None
+ _rc_cache_keys = ('text.latex.preamble', )\
+ + tuple('font.'+n for n in ('family', ) + font_families)
 
 def __init__(self):
 
 if not os.path.isdir(self.texcache):
 os.mkdir(self.texcache)
- if rcParams['font.family'].lower() in ('serif', 'sans-serif', 'cursive', 'monospace'):
- self.font_family = rcParams['font.family'].lower()
+ ff = rcParams['font.family'].lower()
+ if ff in self.font_families:
+ self.font_family = ff
 else:
 warnings.warn('The %s font family is not compatible with LaTeX. serif will be used by default.' % ff)
 self.font_family = 'serif'
- self._fontconfig = self.font_family
- for font in rcParams['font.serif']:
- try:
- self.serif = self.font_info[font.lower()]
- except KeyError:
- continue
- else:
- break
- self._fontconfig += self.serif[0]
- for font in rcParams['font.sans-serif']:
- try:
- self.sans_serif = self.font_info[font.lower()]
- except KeyError:
- continue
- else:
- break
- self._fontconfig += self.sans_serif[0]
- for font in rcParams['font.monospace']:
- try:
- self.monospace = self.font_info[font.lower()]
- except KeyError:
- continue
- else:
- break
- self._fontconfig += self.monospace[0]
- for font in rcParams['font.cursive']:
- try:
- self.cursive = self.font_info[font.lower()]
- except KeyError:
- continue
- else:
- break
- self._fontconfig += self.cursive[0]
+ 
+ fontconfig = [self.font_family]
+ for font_family, font_family_attr in \
+ ((ff, ff.replace('-', '_')) for ff in self.font_families):
+ for font in rcParams['font.'+font_family]:
+ if DEBUG: print 'family: %s, font: %s, info: %s'%(font_family, 
+ font, self.font_info[font.lower()])
+ if font.lower() in self.font_info:
+ setattr(self, font_family_attr, 
+ self.font_info[font.lower()])
+ break
+ else:
+ warnings.warn('No LaTeX-compatible font found for the %s font family in rcParams. Using default.' % ff)
+ setattr(self, font_family_attr, font_family)
+ fontconfig.append(getattr(self, font_family_attr)[0])
+ self._fontconfig = ''.join(fontconfig)
 
 # The following packages and commands need to be included in the latex
 # file's preamble:
@@ -158,17 +146,33 @@
 while r'\usepackage{type1cm}' in cmd:
 cmd.remove(r'\usepackage{type1cm}')
 cmd = '\n'.join(cmd)
- self._font_preamble = '\n'.join([r'\usepackage{type1cm}',
- cmd,
- r'\usepackage{textcomp}'])
+ self._font_preamble = '\n'.join([r'\usepackage{type1cm}', cmd,
+ r'\usepackage{textcomp}'])
 
 def get_basefile(self, tex, fontsize, dpi=None):
- s = tex + self._fontconfig + ('%f'%fontsize) + self.get_custom_preamble()
- if dpi: s += ('%s'%dpi)
- bytes = unicode(s).encode('utf-8') # make sure hash is consistent for all strings, regardless of encoding
+ s = ''.join([tex, self.get_font_config(), '%f'%fontsize,
+ self.get_custom_preamble(), str(dpi or '')])
+ # make sure hash is consistent for all strings, regardless of encoding:
+ bytes = unicode(s).encode('utf-8')
 return os.path.join(self.texcache, md5.md5(bytes).hexdigest())
 
 def get_font_config(self):
+ "Reinitializes self if rcParams self depends on have changed."
+ if self._rc_cache is None:
+ self._rc_cache = dict((k,None) for k in self._rc_cache_keys)
+ changed = [par for par in self._rc_cache_keys if rcParams[par] != \
+ self._rc_cache[par]]
+ if changed:
+ if DEBUG: print 'DEBUG following keys changed:', changed
+ for k in changed:
+ if DEBUG: 
+ print 'DEBUG %-20s: %-10s -> %-10s' % \
+ (k, self._rc_cache[k], rcParams[k])
+ # deepcopy may not be necessary, but feels more future-proof
+ self._rc_cache[k] = copy.deepcopy(rcParams[k])
+ if DEBUG: print 'DEBUG RE-INIT\nold fontconfig:', self._fontconfig
+ self.__init__()
+ if DEBUG: print 'DEBUG fontconfig:', self._fontconfig
 return self._fontconfig
 
 def get_font_preamble(self):
@@ -222,34 +226,33 @@
 try:
 fh.write(s)
 except UnicodeEncodeError, err:
- verbose.report("You are using unicode and latex, but have "
- "not enabled the matplotlib 'text.latex.unicode' "
- "rcParam.", 'helpful')
+ mpl.verbose.report("You are using unicode and latex, but have "
+ "not enabled the matplotlib 'text.latex.unicode' "
+ "rcParam.", 'helpful')
 raise
 
 fh.close()
 
 return texfile
 
- def make_dvi(self, tex, fontsize, force=0):
- if debug: force = True
+ def make_dvi(self, tex, fontsize):
 
 basefile = self.get_basefile(tex, fontsize)
 dvifile = '%s.dvi'% basefile
 
- if force or not os.path.exists(dvifile):
+ if DEBUG or not os.path.exists(dvifile):
 texfile = self.make_tex(tex, fontsize)
 outfile = basefile+'.output'
 command = self.get_shell_cmd('cd "%s"'% self.texcache,
 'latex -interaction=nonstopmode %s > "%s"'\
 %(os.path.split(texfile)[-1], outfile))
- verbose.report(command, 'debug')
+ mpl.verbose.report(command, 'debug')
 exit_status = os.system(command)
 fh = file(outfile)
 if exit_status:
 raise RuntimeError(('LaTeX was not able to process the following \
 string:\n%s\nHere is the full report generated by LaTeX: \n\n'% repr(tex)) + fh.read())
- else: verbose.report(fh.read(), 'debug')
+ else: mpl.verbose.report(fh.read(), 'debug')
 fh.close()
 for fname in glob.glob(basefile+'*'):
 if fname.endswith('dvi'): pass
@@ -258,54 +261,51 @@
 
 return dvifile
 
- def make_png(self, tex, fontsize, dpi, force=0):
- if debug: force = True
-
+ def make_png(self, tex, fontsize, dpi):
 basefile = self.get_basefile(tex, fontsize, dpi)
 pngfile = '%s.png'% basefile
 
 # see get_rgba for a discussion of the background
- if force or not os.path.exists(pngfile):
+ if DEBUG or not os.path.exists(pngfile):
 dvifile = self.make_dvi(tex, fontsize)
 outfile = basefile+'.output'
 command = self.get_shell_cmd('cd "%s"' % self.texcache,
 'dvipng -bg Transparent -D %s -T tight -o \
 "%s" "%s" > "%s"'%(dpi, os.path.split(pngfile)[-1],
 os.path.split(dvifile)[-1], outfile))
- verbose.report(command, 'debug')
+ mpl.verbose.report(command, 'debug')
 exit_status = os.system(command)
 fh = file(outfile)
 if exit_status:
 raise RuntimeError('dvipng was not able to \
 process the flowing file:\n%s\nHere is the full report generated by dvipng: \
 \n\n'% dvifile + fh.read())
- else: verbose.report(fh.read(), 'debug')
+ else: mpl.verbose.report(fh.read(), 'debug')
 fh.close()
 os.remove(outfile)
 
 return pngfile
 
- def make_ps(self, tex, fontsize, force=0):
- if debug: force = True
+ def make_ps(self, tex, fontsize):
 
 basefile = self.get_basefile(tex, fontsize)
 psfile = '%s.epsf'% basefile
 
- if force or not os.path.exists(psfile):
+ if DEBUG or not os.path.exists(psfile):
 dvifile = self.make_dvi(tex, fontsize)
 outfile = basefile+'.output'
 command = self.get_shell_cmd('cd "%s"'% self.texcache,
 'dvips -q -E -o "%s" "%s" > "%s"'\
 %(os.path.split(psfile)[-1],
 os.path.split(dvifile)[-1], outfile))
- verbose.report(command, 'debug')
+ mpl.verbose.report(command, 'debug')
 exit_status = os.system(command)
 fh = file(outfile)
 if exit_status:
 raise RuntimeError('dvipng was not able to \
 process the flowing file:\n%s\nHere is the full report generated by dvipng: \
 \n\n'% dvifile + fh.read())
- else: verbose.report(fh.read(), 'debug')
+ else: mpl.verbose.report(fh.read(), 'debug')
 fh.close()
 os.remove(outfile)
 
@@ -346,21 +346,20 @@
 if not fontsize: fontsize = rcParams['font.size']
 if not dpi: dpi = rcParams['savefig.dpi']
 r,g,b = rgb
- key = tex, fontsize, dpi, tuple(rgb)
+ key = tex, self.get_font_config(), fontsize, dpi, tuple(rgb)
 Z = self.arrayd.get(key)
 
 if Z is None:
- # force=True to skip cacheing while debugging
- pngfile = self.make_png(tex, fontsize, dpi, force=False)
+ pngfile = self.make_png(tex, fontsize, dpi)
 X = readpng(os.path.join(self.texcache, pngfile))
 
 if (self.dvipngVersion < '1.6') or rcParams['text.dvipnghack']:
 # hack the alpha channel as described in comment above
- alpha = sqrt(1-X[:,:,0])
+ alpha = npy.sqrt(1-X[:,:,0])
 else:
 alpha = X[:,:,-1]
 
- Z = zeros(X.shape, Float)
+ Z = npy.zeros(X.shape, npy.float)
 Z[:,:,0] = r
 Z[:,:,1] = g
 Z[:,:,2] = b
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
Revision: 3561
 http://matplotlib.svn.sourceforge.net/matplotlib/?rev=3561&view=rev
Author: mdboom
Date: 2007年07月18日 09:45:55 -0700 (2007年7月18日)
Log Message:
-----------
Make Cairo and Gdk backends work with new mathtext refactoring.
Modified Paths:
--------------
 branches/mathtext_mgd/lib/matplotlib/backends/backend_cairo.py
 branches/mathtext_mgd/lib/matplotlib/backends/backend_gdk.py
Modified: branches/mathtext_mgd/lib/matplotlib/backends/backend_cairo.py
===================================================================
--- branches/mathtext_mgd/lib/matplotlib/backends/backend_cairo.py	2007年07月18日 15:57:40 UTC (rev 3560)
+++ branches/mathtext_mgd/lib/matplotlib/backends/backend_cairo.py	2007年07月18日 16:45:55 UTC (rev 3561)
@@ -314,9 +314,8 @@
 # "_draw_mathtext()")
 # return
 
- size = prop.get_size_in_points()
- width, height, fonts = math_parse_s_ft2font(
- s, self.dpi.get(), size)
+ width, height, fonts, used_characters = math_parse_s_ft2font(
+ s, self.dpi.get(), prop)
 
 if angle==90:
 width, height = height, width
@@ -372,8 +371,8 @@
 def get_text_width_height(self, s, prop, ismath):
 if _debug: print '%s.%s()' % (self.__class__.__name__, _fn_name())
 if ismath:
- width, height, fonts = math_parse_s_ft2font(
- s, self.dpi.get(), prop.get_size_in_points())
+ width, height, fonts, used_characters = math_parse_s_ft2font(
+ s, self.dpi.get(), prop)
 return width, height
 
 ctx = self.text_ctx
Modified: branches/mathtext_mgd/lib/matplotlib/backends/backend_gdk.py
===================================================================
--- branches/mathtext_mgd/lib/matplotlib/backends/backend_gdk.py	2007年07月18日 15:57:40 UTC (rev 3560)
+++ branches/mathtext_mgd/lib/matplotlib/backends/backend_gdk.py	2007年07月18日 16:45:55 UTC (rev 3561)
@@ -204,9 +204,8 @@
 
 
 def _draw_mathtext(self, gc, x, y, s, prop, angle):
- size = prop.get_size_in_points()
- width, height, fonts = math_parse_s_ft2font(
- s, self.dpi.get(), size)
+ width, height, fonts, used_characters = math_parse_s_ft2font(
+ s, self.dpi.get(), prop)
 
 if angle==90:
 width, height = height, width
@@ -348,8 +347,8 @@
 
 def get_text_width_height(self, s, prop, ismath):
 if ismath:
- width, height, fonts = math_parse_s_ft2font(
- s, self.dpi.get(), prop.get_size_in_points())
+ width, height, fonts, used_characters = math_parse_s_ft2font(
+ s, self.dpi.get(), prop)
 return width, height
 
 layout, inkRect, logicalRect = self._get_pango_layout(s, prop)
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
Revision: 3560
 http://matplotlib.svn.sourceforge.net/matplotlib/?rev=3560&view=rev
Author: mdboom
Date: 2007年07月18日 08:57:40 -0700 (2007年7月18日)
Log Message:
-----------
Support dotless i and j
Modified Paths:
--------------
 branches/mathtext_mgd/lib/matplotlib/_mathtext_data.py
Modified: branches/mathtext_mgd/lib/matplotlib/_mathtext_data.py
===================================================================
--- branches/mathtext_mgd/lib/matplotlib/_mathtext_data.py	2007年07月18日 15:41:59 UTC (rev 3559)
+++ branches/mathtext_mgd/lib/matplotlib/_mathtext_data.py	2007年07月18日 15:57:40 UTC (rev 3560)
@@ -112,6 +112,8 @@
 r'\phi' : ('cmmi10', 42),
 r'\chi' : ('cmmi10', 17),
 r'\psi' : ('cmmi10', 31),
+ r'\i' : ('cmmi10', 8),
+ r'\j' : ('cmmi10', 65),
 
 r'(' : ('cmr10', 119),
 r'\leftparen' : ('cmr10', 119),
@@ -748,8 +750,7 @@
 r'\Diamond' : ('psyr', 224),
 r'\langle' : ('psyr', 225),
 r'\Sigma' : ('psyr', 229),
- r'\sum' : ('psyr', 229),
-
+ r'\sum' : ('psyr', 229)
 }
 
 # Automatically generated.
@@ -2571,7 +2572,8 @@
 'divideontimes': 8903,
 'lbrack': 91,
 'textquotedblright': 8221,
-'Colon': 8759}
+'Colon': 8759,
+'i': 305}
 
 uni2tex = dict([(v,k) for k,v in tex2uni.items()])
 
@@ -3049,7 +3051,8 @@
 'divideontimes': 'uni22C7',
 'lbrack': 'bracketleft',
 'textquotedblright': 'quotedblright',
-'Colon': 'uni2237'}
+'Colon': 'uni2237',
+'i': 'uni0131'}
 
 type12tex = dict([(v,k) for k,v in tex2type1.items()])
 
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
Revision: 3558
 http://matplotlib.svn.sourceforge.net/matplotlib/?rev=3558&view=rev
Author: mdboom
Date: 2007年07月18日 08:27:58 -0700 (2007年7月18日)
Log Message:
-----------
Got SVG and PS (afm-only) support working. Still kind of tempermental.
Modified Paths:
--------------
 branches/mathtext_mgd/lib/matplotlib/backends/backend_pdf.py
 branches/mathtext_mgd/lib/matplotlib/backends/backend_ps.py
 branches/mathtext_mgd/lib/matplotlib/backends/backend_svg.py
 branches/mathtext_mgd/lib/matplotlib/mathtext.py
Modified: branches/mathtext_mgd/lib/matplotlib/backends/backend_pdf.py
===================================================================
--- branches/mathtext_mgd/lib/matplotlib/backends/backend_pdf.py	2007年07月18日 13:16:35 UTC (rev 3557)
+++ branches/mathtext_mgd/lib/matplotlib/backends/backend_pdf.py	2007年07月18日 15:27:58 UTC (rev 3558)
@@ -15,7 +15,7 @@
 from cStringIO import StringIO
 from datetime import datetime
 from math import ceil, cos, floor, pi, sin
-import sets
+from sets import Set
 
 from matplotlib import __version__, rcParams, agg, get_data_path
 from matplotlib._pylab_helpers import Gcf
@@ -457,9 +457,8 @@
 else:
 realpath, stat_key = get_realpath_and_stat(filename)
 chars = self.used_characters.get(stat_key)
- if chars is not None:
- fontdictObject = self.embedTTF(
- *self.used_characters[stat_key])
+ if chars is not None and len(chars[1]):
+ fontdictObject = self.embedTTF(realpath, chars[1])
 fonts[Fx] = fontdictObject
 #print >>sys.stderr, filename
 self.writeObject(self.fontObject, fonts)
@@ -932,14 +931,13 @@
 fname = font.fname
 realpath, stat_key = get_realpath_and_stat(fname)
 used_characters = self.used_characters.setdefault(
- stat_key, (realpath, sets.Set()))
+ stat_key, (realpath, Set()))
 used_characters[1].update(s)
- print [(os.path.basename(x), y) for x, y in self.used_characters.values()]
 
 def merge_used_characters(self, other):
 for stat_key, (realpath, set) in other.items():
 used_characters = self.used_characters.setdefault(
- stat_key, (realpath, sets.Set()))
+ stat_key, (realpath, Set()))
 used_characters[1].update(set)
 
 def draw_arc(self, gcEdge, rgbFace, x, y, width, height,
@@ -1103,8 +1101,6 @@
 prev_font = None, None
 oldx, oldy = 0, 0
 for ox, oy, fontname, fontsize, glyph in pswriter:
- #print ox, oy, glyph
- #fontname = fontname.lower()
 a = angle / 180.0 * pi
 newx = x + cos(a)*ox - sin(a)*oy
 newy = y + sin(a)*ox + cos(a)*oy
Modified: branches/mathtext_mgd/lib/matplotlib/backends/backend_ps.py
===================================================================
--- branches/mathtext_mgd/lib/matplotlib/backends/backend_ps.py	2007年07月18日 13:16:35 UTC (rev 3557)
+++ branches/mathtext_mgd/lib/matplotlib/backends/backend_ps.py	2007年07月18日 15:27:58 UTC (rev 3558)
@@ -30,7 +30,7 @@
 fromstring, nonzero, ones, put, take, where, isnan
 import binascii
 import re
-import sets
+from sets import Set
 
 if sys.platform.startswith('win'): cmd_split = '&'
 else: cmd_split = ';'
@@ -151,13 +151,13 @@
 each font."""
 realpath, stat_key = get_realpath_and_stat(font.fname)
 used_characters = self.used_characters.setdefault(
- stat_key, (realpath, sets.Set()))
+ stat_key, (realpath, Set()))
 used_characters[1].update(s)
 
 def merge_used_characters(self, other):
 for stat_key, (realpath, set) in other.items():
 used_characters = self.used_characters.setdefault(
- stat_key, (realpath, sets.Set()))
+ stat_key, (realpath, Set()))
 used_characters[1].update(set)
 
 def set_color(self, r, g, b, store=1):
@@ -1037,13 +1037,14 @@
 print >>fh, l.strip()
 if not rcParams['ps.useafm']:
 for font_filename, chars in renderer.used_characters.values():
- font = FT2Font(font_filename)
- cmap = font.get_charmap()
- glyph_ids = []
- for c in chars:
- gind = cmap.get(ord(c)) or 0
- glyph_ids.append(gind)
- convert_ttf_to_ps(font_filename, fh, rcParams['ps.fonttype'], glyph_ids)
+ if len(chars):
+ font = FT2Font(font_filename)
+ cmap = font.get_charmap()
+ glyph_ids = []
+ for c in chars:
+ gind = cmap.get(ord(c)) or 0
+ glyph_ids.append(gind)
+ convert_ttf_to_ps(font_filename, fh, rcParams['ps.fonttype'], glyph_ids)
 print >>fh, "end"
 print >>fh, "%%EndProlog"
 
Modified: branches/mathtext_mgd/lib/matplotlib/backends/backend_svg.py
===================================================================
--- branches/mathtext_mgd/lib/matplotlib/backends/backend_svg.py	2007年07月18日 13:16:35 UTC (rev 3557)
+++ branches/mathtext_mgd/lib/matplotlib/backends/backend_svg.py	2007年07月18日 15:27:58 UTC (rev 3558)
@@ -291,9 +291,12 @@
 self._svgwriter.write (svg)
 
 def _add_char_def(self, prop, char):
- newprop = prop.copy()
- newprop.set_size(self.FONT_SCALE)
- font = self._get_font(newprop)
+ if isinstance(prop, FontProperties):
+ newprop = prop.copy()
+ font = self._get_font(newprop)
+ else:
+ font = prop
+ font.set_size(self.FONT_SCALE, 72)
 ps_name = font.get_sfnt()[(1,0,0,6)]
 char_id = urllib.quote('%s-%d' % (ps_name, ord(char)))
 if char_id in self._char_defs:
@@ -332,8 +335,8 @@
 """
 Draw math text using matplotlib.mathtext
 """
- fontsize = prop.get_size_in_points()
- width, height, svg_elements = math_parse_s_ft2font_svg(s, 72, fontsize)
+ width, height, svg_elements, used_characters = \
+ math_parse_s_ft2font_svg(s, 72, prop)
 svg_glyphs = svg_elements.svg_glyphs
 svg_lines = svg_elements.svg_lines
 color = rgb2hex(gc.get_rgb())
@@ -349,9 +352,8 @@
 svg.append('translate(%f,%f)' % (x, y))
 svg.append('">\n')
 
- for fontname, fontsize, thetext, new_x, new_y_mtc, metrics in svg_glyphs:
- prop = FontProperties(family=fontname, size=fontsize)
- charid = self._add_char_def(prop, thetext)
+ for font, fontsize, thetext, new_x, new_y_mtc, metrics in svg_glyphs:
+ charid = self._add_char_def(font, thetext)
 
 svg.append('<use xlink:href="#%s" transform="translate(%s, %s) scale(%s)"/>\n' % 
 (charid, new_x, -new_y_mtc, fontsize / self.FONT_SCALE))
@@ -417,8 +419,8 @@
 
 def get_text_width_height(self, s, prop, ismath):
 if ismath:
- width, height, trash = math_parse_s_ft2font_svg(
- s, 72, prop.get_size_in_points())
+ width, height, trash, used_characters = \
+ math_parse_s_ft2font_svg(s, 72, prop)
 return width, height
 font = self._get_font(prop)
 font.set_text(s, 0.0)
Modified: branches/mathtext_mgd/lib/matplotlib/mathtext.py
===================================================================
--- branches/mathtext_mgd/lib/matplotlib/mathtext.py	2007年07月18日 13:16:35 UTC (rev 3557)
+++ branches/mathtext_mgd/lib/matplotlib/mathtext.py	2007年07月18日 15:27:58 UTC (rev 3558)
@@ -229,7 +229,7 @@
 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.
@@ -269,7 +269,10 @@
 def render(self, ox, oy, facename, sym, fontsize, dpi):
 pass
 
-
+ def get_used_characters(self):
+ return {}
+ 
+ 
 class DummyFonts(Fonts):
 'dummy class for debugging parser'
 def get_metrics(self, font, sym, fontsize, dpi):
@@ -566,7 +569,7 @@
 'ex' : 'Cmex10'
 }
 
- class FontCache:
+ class CachedFont:
 def __init__(self, font):
 self.font = font
 self.charmap = font.get_charmap()
@@ -577,15 +580,9 @@
 self.glyphd = {}
 self.fonts = {}
 self.used_characters = {}
- 
- # MGDTODO: Separate this out into an SVG class
-# if useSVG:
-# self.svg_glyphs = [] # a list of "glyphs" we need to render this thing in SVG
-# else: pass
-# self.usingSVG = useSVG
 
 def _get_font(self, font):
- """Looks up a FontCache with its charmap and inverse charmap.
+ """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):
@@ -596,14 +593,14 @@
 else:
 basename = font.postscript_name
 
- font_cache = self.fonts.get(basename)
- if font_cache is None:
+ 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'))
+ font = FT2Font(os.path.join(self.basepath, basename.lower() + ".ttf"))
 basename = font.postscript_name
- font_cache = self.FontCache(font)
- self.fonts[basename] = font_cache
- return basename, font_cache
+ cached_font = self.CachedFont(font)
+ self.fonts[basename] = cached_font
+ return basename, cached_font
 
 def get_fonts(self):
 return [x.font for x in self.fonts.values()]
@@ -613,7 +610,7 @@
 self._get_info(font, sym, fontsize, dpi)
 return metrics
 
- def _get_offset(self, basename, font_cache, glyph, fontsize, dpi):
+ 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
 return 0.
@@ -632,18 +629,18 @@
 
 if font in self.fontmap and latex_to_bakoma.has_key(sym):
 basename, num = latex_to_bakoma[sym]
- basename, font_cache = self._get_font(basename.capitalize())
- symbol_name = font_cache.font.get_glyph_name(num)
- num = font_cache.glyphmap[num]
+ 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, font_cache = self._get_font(font)
+ basename, cached_font = self._get_font(font)
 num = ord(sym)
- symbol_name = font_cache.font.get_glyph_name(font_cache.charmap[num])
+ symbol_name = cached_font.font.get_glyph_name(cached_font.charmap[num])
 else:
 num = 0
 raise ValueError('unrecognized symbol "%s"' % sym)
 
- font = font_cache.font
+ font = cached_font.font
 font.set_size(fontsize, dpi)
 glyph = font.load_char(num)
 
@@ -653,7 +650,7 @@
 used_characters[1].update(unichr(num))
 
 xmin, ymin, xmax, ymax = [val/64.0 for val in glyph.bbox]
- offset = self._get_offset(basename, font_cache, glyph, fontsize, dpi)
+ offset = self._get_offset(basename, cached_font, glyph, fontsize, dpi)
 metrics = Bunch(
 advance = glyph.linearHoriAdvance/65536.0,
 height = glyph.height/64.0,
@@ -671,8 +668,8 @@
 'Dimension the drawing canvas; may be a noop'
 self.width = int(w)
 self.height = int(h)
- for font_cache in self.fonts.values():
- font_cache.font.set_bitmap_size(int(w), 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 = \
@@ -680,22 +677,7 @@
 
 font.draw_glyph_to_bitmap(
 int(ox), int(self.height - oy - metrics.ymax), glyph)
-# else:
-# oy += offset - 512/2048.*10.
-# basename = self.fontmap[font]
-# if latex_to_bakoma.has_key(sym):
-# basename, num = latex_to_bakoma[sym]
-# num = self.glyphmaps[basename][num]
-# elif len(sym) == 1:
-# num = ord(sym)
-# else:
-# num = 0
-# print >>sys.stderr, 'unrecognized symbol "%s"' % sym
-# thetext = unichr(num)
-# thetext.encode('utf-8')
-# self.svg_glyphs.append((basename, fontsize, thetext, ox, oy, metrics))
 
-
 def _old_get_kern(self, font, symleft, symright, fontsize, dpi):
 """
 Get the kerning distance for font between symleft and symright.
@@ -715,14 +697,16 @@
 #print basename, symleft, symright, key, kern
 return kern
 
-
+ def get_used_characters(self):
+ return self.used_characters
+ 
 class BakomaPSFonts(BakomaFonts):
 """
 Use the Bakoma postscript fonts for rendering to backend_ps
 """
 
- def _get_offset(self, basename, font_cache, glyph, fontsize, dpi):
- head = font_cache.font.get_sfnt_table("head")
+ def _get_offset(self, basename, cached_font, glyph, fontsize, dpi):
+ head = cached_font.font.get_sfnt_table("head")
 if basename.lower() == 'cmex10':
 return -(head['yMin']+512)/head['unitsPerEm']*10.
 return 0.
@@ -759,7 +743,21 @@
 
 self.pswriter.append((ox, oy, filename, fontsize, num))
 
+class BakomaSVGFonts(BakomaFonts):
+ """Hack of BakomaFonts for SVG support."""
+ def __init__(self):
+ BakomaFonts.__init__(self)
+ self.svg_glyphs = []
+ 
+ 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 += offset - 512/2048.*10.
+ thetext = unichr(num)
+ thetext.encode('utf-8')
+ self.svg_glyphs.append((font, fontsize, thetext, ox, oy, metrics))
+
 class StandardPSFonts(Fonts):
 """
 Use the standard postscript fonts for rendering to backend_ps
@@ -768,21 +766,51 @@
 # allocate a new set of fonts
 basepath = os.path.join( get_data_path(), 'fonts', 'afm' )
 
- fontmap = { 'cal' : 'pzcmi8a',
- 'rm' : 'pncr8a',
- 'tt' : 'pcrr8a',
- 'it' : 'pncri8a',
+ fontmap = { 'cal' : 'pzcmi8a', # Zapf Chancery
+ 'rm' : 'pncr8a', # New Century Schoolbook
+ 'tt' : 'pcrr8a', # Courier 
+ 'it' : 'pncri8a', # New Century Schoolbook Italic
+ 'sf' : 'phvr8a', # Helvetica
+ 'bf' : 'pncb8a', # New Century Schoolbook Bold
+ None : 'psyr' # Symbol
 }
 
 def __init__(self):
 self.glyphd = {}
- self.fonts = dict(
- [ (name, AFM(file(os.path.join(self.basepath, name) + '.afm')))
- for name in self.fnames])
+ self.fonts = {}
 
+ def _get_font(self, font):
+ if isinstance(font, str):
+ if font not in self.fontmap.values():
+ basename = self.fontmap[font]
+ else:
+ basename = font
+ else:
+ basename = font.get_fontname()
+
+ cached_font = self.fonts.get(basename)
+ if cached_font is None:
+ if isinstance(font, str):
+ fname = os.path.join(self.basepath, basename + ".afm")
+ cached_font = AFM(file(fname, 'r'))
+ cached_font.fname = fname
+ basename = cached_font.get_fontname()
+ else:
+ cached_font = font
+ self.fonts[basename] = cached_font
+ return basename, cached_font
+
+ def get_fonts(self):
+ return [x.font for x in self.fonts.values()]
+ 
 def _get_info (self, font, sym, fontsize, dpi):
 'load the cmfont, metrics and glyph with caching'
- key = font, sym, fontsize, dpi
+ if hasattr(font, 'get_fontname'):
+ fontname = font.get_fontname()
+ else:
+ fontname = font
+
+ key = fontname, sym, fontsize, dpi
 tup = self.glyphd.get(key)
 
 if tup is not None:
@@ -790,41 +818,40 @@
 
 if sym in "0123456789()" and font == 'it':
 font = 'rm'
- basename = self.fontmap[font]
 
 if latex_to_standard.has_key(sym):
- basename, num = latex_to_standard[sym]
- char = chr(num)
+ font, num = latex_to_standard[sym]
+ glyph = chr(num)
 elif len(sym) == 1:
- char = sym
+ glyph = sym
+ num = ord(glyph)
 else:
 raise ValueError('unrecognized symbol "%s"' % (sym))
-
+ basename, font = self._get_font(font) 
+ 
 try:
- sym = self.fonts[basename].get_name_char(char)
+ symbol_name = font.get_name_char(glyph)
 except KeyError:
 raise ValueError('unrecognized symbol "%s"' % (sym))
 
 offset = 0
- cmfont = self.fonts[basename]
- fontname = cmfont.get_fontname()
 
 scale = 0.001 * fontsize
 
 xmin, ymin, xmax, ymax = [val * scale
- for val in cmfont.get_bbox_char(char)]
+ for val in font.get_bbox_char(glyph)]
 metrics = Bunch(
 advance = (xmax-xmin),
- width = cmfont.get_width_char(char) * scale,
- height = cmfont.get_width_char(char) * scale,
+ width = font.get_width_char(glyph) * scale,
+ height = font.get_width_char(glyph) * scale,
 xmin = xmin,
 xmax = xmax,
 ymin = ymin+offset,
 ymax = ymax+offset
 )
 
- self.glyphd[key] = fontname, basename, metrics, sym, offset, char
- return fontname, basename, metrics, '/'+sym, offset, char
+ self.glyphd[key] = basename, font, metrics, symbol_name, num, glyph, offset
+ return self.glyphd[key]
 
 def set_canvas_size(self, w, h, pswriter):
 'Dimension the drawing canvas; may be a noop'
@@ -832,32 +859,33 @@
 self.height = h
 self.pswriter = pswriter
 
-
 def render(self, ox, oy, font, sym, fontsize, dpi):
- fontname, basename, metrics, glyphname, offset, char = \
+ basename, font, metrics, symbol_name, num, glyph, offset = \
 self._get_info(font, sym, fontsize, dpi)
- ps = """/%(fontname)s findfont
+ ps = """/%(basename)s findfont
 %(fontsize)s scalefont
 setfont
 %(ox)f %(oy)f moveto
-/%(glyphname)s glyphshow
+/%(symbol_name)s glyphshow
 """ % locals()
 self.pswriter.write(ps)
 
 
 def get_metrics(self, font, sym, fontsize, dpi):
- fontname, basename, metrics, sym, offset, char = \
+ basename, font, metrics, symbol_name, num, glyph, offset = \
 self._get_info(font, sym, fontsize, dpi)
 return metrics
 
 def get_kern(self, font, symleft, symright, fontsize, dpi):
- fontname, basename, metrics, sym, offset, char1 = \
+ basename, font1, metrics, symbol_name, num, glyph1, offset = \
 self._get_info(font, symleft, fontsize, dpi)
- fontname, basename, metrics, sym, offset, char2 = \
+ basename, font2, metrics, symbol_name, num, glyph2, offset = \
 self._get_info(font, symright, fontsize, dpi)
- cmfont = self.fonts[basename]
- return cmfont.get_kern_dist(char1, char2) * 0.001 * fontsize
-
+ if font1.get_fontname() == font2.get_fontname():
+ basename, font = self._get_font(font)
+ return font.get_kern_dist(glyph1, glyph2) * 0.001 * fontsize
+ return 0
+ 
 class Element:
 fontsize = 12
 dpi = 72
@@ -1667,34 +1695,37 @@
 w, h, fontlike, used_characters = self.cache[cacheKey]
 return w, h, fontlike, used_characters
 
+ use_afm = False
 if self.output == 'SVG':
- self.font_object = BakomaFonts(useSVG=True)
+ self.font_object = BakomaSVGFonts()
 #self.font_object = MyUnicodeFonts(output='SVG')
- Element.fonts = self.font_object
 elif self.output == 'Agg':
 self.font_object = BakomaFonts()
 #self.font_object = MyUnicodeFonts()
- Element.fonts = self.font_object
 elif self.output == 'PS':
 if rcParams['ps.useafm']:
 self.font_object = StandardPSFonts()
- Element.fonts = self.font_object
+ use_afm = True
 else:
 self.font_object = BakomaPSFonts()
 #self.font_object = MyUnicodeFonts(output='PS')
- Element.fonts = self.font_object
 elif self.output == 'PDF':
 self.font_object = BakomaPDFFonts()
- Element.fonts = self.font_object
-
+ Element.fonts = self.font_object
+ 
 fontsize = prop.get_size_in_points()
 
 handler.clear()
 expression.parseString( s )
+
+ if use_afm:
+ fname = fontManager.findfont(prop, fontext='afm')
+ default_font = AFM(file(fname, 'r'))
+ default_font.fname = fname
+ else:
+ fname = fontManager.findfont(prop)
+ default_font = FT2Font(fname)
 
- fname = fontManager.findfont(prop)
- default_font = FT2Font(str(fname))
- 
 handler.expr.determine_font([default_font])
 handler.expr.set_size_info(fontsize, dpi)
 
@@ -1729,11 +1760,14 @@
 # The empty list at the end is for lines
 svg_elements = Bunch(svg_glyphs=self.font_object.svg_glyphs,
 svg_lines=[])
- self.cache[cacheKey] = w, h, svg_elements, Element.fonts.used_characters
+ self.cache[cacheKey] = \
+ w, h, svg_elements, Element.fonts.get_used_characters()
 elif self.output == 'Agg':
- self.cache[cacheKey] = w, h, self.font_object.get_fonts(), Element.fonts.used_characters
+ self.cache[cacheKey] = \
+ w, h, self.font_object.get_fonts(), Element.fonts.get_used_characters()
 elif self.output in ('PS', 'PDF'):
- self.cache[cacheKey] = w, h, pswriter, Element.fonts.used_characters
+ self.cache[cacheKey] = \
+ w, h, pswriter, Element.fonts.get_used_characters()
 return self.cache[cacheKey]
 
 if rcParams["mathtext.mathtext2"]:
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
Revision: 3557
 http://matplotlib.svn.sourceforge.net/matplotlib/?rev=3557&view=rev
Author: mdboom
Date: 2007年07月18日 06:16:35 -0700 (2007年7月18日)
Log Message:
-----------
Got mixed text/math working for Agg, Ps (non-afm) and Pdf (non-afm).
All other backends can be considered horribly broken on this branch.
Modified Paths:
--------------
 branches/mathtext_mgd/lib/matplotlib/backends/backend_agg.py
 branches/mathtext_mgd/lib/matplotlib/backends/backend_pdf.py
 branches/mathtext_mgd/lib/matplotlib/backends/backend_ps.py
 branches/mathtext_mgd/lib/matplotlib/mathtext.py
 branches/mathtext_mgd/lib/matplotlib/text.py
Modified: branches/mathtext_mgd/lib/matplotlib/backends/backend_agg.py
===================================================================
--- branches/mathtext_mgd/lib/matplotlib/backends/backend_agg.py	2007年07月18日 07:38:05 UTC (rev 3556)
+++ branches/mathtext_mgd/lib/matplotlib/backends/backend_agg.py	2007年07月18日 13:16:35 UTC (rev 3557)
@@ -180,10 +180,9 @@
 """
 if __debug__: verbose.report('RendererAgg.draw_mathtext',
 'debug-annoying')
- size = prop.get_size_in_points()
- width, height, fonts = math_parse_s_ft2font(
- s, self.dpi.get(), size, angle)
-
+ width, height, fonts, used_characters = math_parse_s_ft2font(
+ s, self.dpi.get(), prop, angle)
+ 
 if angle == 90:
 width, height = height, width
 for font in fonts:
@@ -232,7 +231,6 @@
 # texmanager more efficient. It is not meant to be used
 # outside the backend
 """
-
 if ismath=='TeX':
 # todo: handle props
 size = prop.get_size_in_points()
@@ -242,8 +240,8 @@
 return n,m
 
 if ismath:
- width, height, fonts = math_parse_s_ft2font(
- s, self.dpi.get(), prop.get_size_in_points())
+ width, height, fonts, used_characters = math_parse_s_ft2font(
+ s, self.dpi.get(), prop)
 return width, height
 font = self._get_agg_font(prop)
 font.set_text(s, 0.0) # the width and height of unrotated string
Modified: branches/mathtext_mgd/lib/matplotlib/backends/backend_pdf.py
===================================================================
--- branches/mathtext_mgd/lib/matplotlib/backends/backend_pdf.py	2007年07月18日 07:38:05 UTC (rev 3556)
+++ branches/mathtext_mgd/lib/matplotlib/backends/backend_pdf.py	2007年07月18日 13:16:35 UTC (rev 3557)
@@ -456,8 +456,10 @@
 fontdictObject = self._write_afm_font(filename)
 else:
 realpath, stat_key = get_realpath_and_stat(filename)
- fontdictObject = self.embedTTF(
- *self.used_characters[stat_key])
+ chars = self.used_characters.get(stat_key)
+ if chars is not None:
+ fontdictObject = self.embedTTF(
+ *self.used_characters[stat_key])
 fonts[Fx] = fontdictObject
 #print >>sys.stderr, filename
 self.writeObject(self.fontObject, fonts)
@@ -932,7 +934,14 @@
 used_characters = self.used_characters.setdefault(
 stat_key, (realpath, sets.Set()))
 used_characters[1].update(s)
+ print [(os.path.basename(x), y) for x, y in self.used_characters.values()]
 
+ def merge_used_characters(self, other):
+ for stat_key, (realpath, set) in other.items():
+ used_characters = self.used_characters.setdefault(
+ stat_key, (realpath, sets.Set()))
+ used_characters[1].update(set)
+ 
 def draw_arc(self, gcEdge, rgbFace, x, y, width, height,
 angle1, angle2, rotation):
 """
@@ -1085,8 +1094,9 @@
 
 def draw_mathtext(self, gc, x, y, s, prop, angle):
 # TODO: fix positioning and encoding
- fontsize = prop.get_size_in_points()
- width, height, pswriter = math_parse_s_pdf(s, 72, fontsize, 0, self.track_characters)
+ width, height, pswriter, used_characters = \
+ math_parse_s_pdf(s, 72, prop, 0)
+ self.merge_used_characters(used_characters)
 
 self.check_gc(gc, gc._rgb)
 self.file.output(Op.begin_text)
@@ -1094,7 +1104,7 @@
 oldx, oldy = 0, 0
 for ox, oy, fontname, fontsize, glyph in pswriter:
 #print ox, oy, glyph
- fontname = fontname.lower()
+ #fontname = fontname.lower()
 a = angle / 180.0 * pi
 newx = x + cos(a)*ox - sin(a)*oy
 newy = y + sin(a)*ox + cos(a)*oy
@@ -1199,9 +1209,7 @@
 s = s.encode('cp1252', 'replace')
 
 if ismath:
- fontsize = prop.get_size_in_points()
- w, h, pswriter = math_parse_s_pdf(
- s, 72, fontsize, 0, self.track_characters)
+ w, h, pswriter, used_characters = math_parse_s_pdf(s, 72, prop, 0)
 
 elif rcParams['pdf.use14corefonts']:
 font = self._get_font_afm(prop)
Modified: branches/mathtext_mgd/lib/matplotlib/backends/backend_ps.py
===================================================================
--- branches/mathtext_mgd/lib/matplotlib/backends/backend_ps.py	2007年07月18日 07:38:05 UTC (rev 3556)
+++ branches/mathtext_mgd/lib/matplotlib/backends/backend_ps.py	2007年07月18日 13:16:35 UTC (rev 3557)
@@ -154,6 +154,12 @@
 stat_key, (realpath, sets.Set()))
 used_characters[1].update(s)
 
+ def merge_used_characters(self, other):
+ for stat_key, (realpath, set) in other.items():
+ used_characters = self.used_characters.setdefault(
+ stat_key, (realpath, sets.Set()))
+ used_characters[1].update(set)
+ 
 def set_color(self, r, g, b, store=1):
 if (r,g,b) != self.color:
 if r==g and r==b:
@@ -272,8 +278,8 @@
 return w, h
 
 if ismath:
- width, height, pswriter = math_parse_s_ps(
- s, 72, prop.get_size_in_points(), 0, self.track_characters)
+ width, height, pswriter, used_characters = math_parse_s_ps(
+ s, 72, prop, 0)
 return width, height
 
 if rcParams['ps.useafm']:
@@ -808,8 +814,9 @@
 if debugPS:
 self._pswriter.write("% mathtext\n")
 
- fontsize = prop.get_size_in_points()
- width, height, pswriter = math_parse_s_ps(s, 72, fontsize, angle, self.track_characters)
+ width, height, pswriter, used_characters = \
+ math_parse_s_ps(s, 72, prop, angle)
+ self.merge_used_characters(used_characters)
 self.set_color(*gc.get_rgb())
 thetext = pswriter.getvalue()
 ps = """gsave
Modified: branches/mathtext_mgd/lib/matplotlib/mathtext.py
===================================================================
--- branches/mathtext_mgd/lib/matplotlib/mathtext.py	2007年07月18日 07:38:05 UTC (rev 3556)
+++ branches/mathtext_mgd/lib/matplotlib/mathtext.py	2007年07月18日 13:16:35 UTC (rev 3557)
@@ -119,9 +119,13 @@
 
 KNOWN ISSUES:
 
- - nesting fonts changes in sub/superscript groups not parsing
 - I would also like to add a few more layout commands, like \frac.
 
+STATUS:
+ The *Unicode* classes were incomplete when I found them, and have
+ not been refactored to support intermingling of regular text and
+ math text yet. They are most likely broken. -- Michael Droettboom, July 2007
+ 
 Author : John Hunter <jdh...@ac...>
 Copyright : John Hunter (2004,2005)
 License : matplotlib license (PSF compatible)
@@ -130,6 +134,7 @@
 from __future__ import division
 import os, sys
 from cStringIO import StringIO
+from sets import Set
 
 from matplotlib import verbose
 from matplotlib.pyparsing import Literal, Word, OneOrMore, ZeroOrMore, \
@@ -138,7 +143,7 @@
 operatorPrecedence, opAssoc, ParseResults, Or, Suppress, oneOf
 
 from matplotlib.afm import AFM
-from matplotlib.cbook import enumerate, iterable, Bunch
+from matplotlib.cbook import enumerate, iterable, Bunch, get_realpath_and_stat
 from matplotlib.ft2font import FT2Font
 from matplotlib.font_manager import fontManager, FontProperties
 from matplotlib._mathtext_data import latex_to_bakoma, cmkern, \
@@ -544,80 +549,111 @@
 
 # Old classes
 
-class BakomaTrueTypeFonts(Fonts):
+class BakomaFonts(Fonts):
 """
 Use the Bakoma true type fonts for rendering
 """
- fnames = ('cmmi10', 'cmsy10', 'cmex10',
- 'cmtt10', 'cmr10', 'cmb10', 'cmss10')
 # 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',
+ fontmap = { 'cal' : 'Cmsy10',
+ 'rm' : 'Cmr10',
+ 'tt' : 'Cmtt10',
+ 'it' : 'Cmmi10',
+ 'bf' : 'Cmb10',
+ 'sf' : 'Cmss10',
+ None : 'Cmmi10',
+ 'ex' : 'Cmex10'
 }
 
- def __init__(self, useSVG=False):
- self.glyphd = {}
- self.fonts = dict(
- [ (name, FT2Font(os.path.join(self.basepath, name) + '.ttf'))
- for name in self.fnames])
+ class FontCache:
+ 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 = {}
+ 
+ # MGDTODO: Separate this out into an SVG class
+# if useSVG:
+# self.svg_glyphs = [] # a list of "glyphs" we need to render this thing in SVG
+# else: pass
+# self.usingSVG = useSVG
 
- self.charmaps = dict(
- [ (name, self.fonts[name].get_charmap()) for name in self.fnames])
- # glyphmaps is a dict names to a dict of glyphindex -> charcode
- self.glyphmaps = {}
- for name in self.fnames:
- cmap = self.charmaps[name]
- self.glyphmaps[name] = dict([(glyphind, ccode) for ccode, glyphind in cmap.items()])
+ def _get_font(self, font):
+ """Looks up a FontCache 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
+ else:
+ basename = font.postscript_name
 
- for font in self.fonts.values():
- font.clear()
- if useSVG:
- self.svg_glyphs=[] # a list of "glyphs" we need to render this thing in SVG
- else: pass
- self.usingSVG = useSVG
+ font_cache = self.fonts.get(basename)
+ if font_cache is None:
+ if isinstance(font, str):
+ font = FT2Font(os.path.join(self.basepath, basename.lower() + '.ttf'))
+ basename = font.postscript_name
+ font_cache = self.FontCache(font)
+ self.fonts[basename] = font_cache
+ return basename, font_cache
 
+ def get_fonts(self):
+ return [x.font for x in self.fonts.values()]
+ 
 def get_metrics(self, font, sym, fontsize, dpi):
- cmfont, metrics, glyph, offset = \
+ basename, font, metrics, symbol_name, num, glyph, offset = \
 self._get_info(font, sym, fontsize, dpi)
 return metrics
 
+ def _get_offset(self, basename, font_cache, glyph, fontsize, dpi):
+ if basename.lower() == 'cmex10':
+ return glyph.height/64.0/2 + 256.0/64.0*dpi/72.0
+ return 0.
+ 
 def _get_info (self, font, sym, fontsize, dpi):
 'load the cmfont, metrics and glyph with caching'
- key = font, sym, fontsize, dpi
+ if hasattr(font, 'postscript_name'):
+ fontname = font.postscript_name
+ else:
+ fontname = font
+ 
+ key = fontname, sym, fontsize, dpi
 tup = self.glyphd.get(key)
 
 if tup is not None: return tup
-
- basename = self.fontmap[font]
-
- if latex_to_bakoma.has_key(sym):
+ 
+ if font in self.fontmap and latex_to_bakoma.has_key(sym):
 basename, num = latex_to_bakoma[sym]
- num = self.glyphmaps[basename][num]
+ basename, font_cache = self._get_font(basename.capitalize())
+ symbol_name = font_cache.font.get_glyph_name(num)
+ num = font_cache.glyphmap[num]
 elif len(sym) == 1:
+ basename, font_cache = self._get_font(font)
 num = ord(sym)
+ symbol_name = font_cache.font.get_glyph_name(font_cache.charmap[num])
 else:
 num = 0
 raise ValueError('unrecognized symbol "%s"' % sym)
 
- #print sym, basename, num
- cmfont = self.fonts[basename]
- cmfont.set_size(fontsize, dpi)
- head = cmfont.get_sfnt_table('head')
- glyph = cmfont.load_char(num)
+ font = font_cache.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]
- if basename == 'cmex10':
- offset = glyph.height/64.0/2 + 256.0/64.0*dpi/72.0
- #offset = -(head['yMin']+512)/head['unitsPerEm']*10.
- else:
- offset = 0.
+ offset = self._get_offset(basename, font_cache, glyph, fontsize, dpi)
 metrics = Bunch(
 advance = glyph.linearHoriAdvance/65536.0,
 height = glyph.height/64.0,
@@ -627,38 +663,37 @@
 ymin = ymin+offset,
 ymax = ymax+offset,
 )
-
- self.glyphd[key] = cmfont, metrics, glyph, offset
+ 
+ self.glyphd[key] = basename, font, metrics, symbol_name, num, glyph, offset
 return self.glyphd[key]
 
 def set_canvas_size(self, w, h):
 'Dimension the drawing canvas; may be a noop'
 self.width = int(w)
 self.height = int(h)
- for font in self.fonts.values():
- font.set_bitmap_size(int(w), int(h))
+ for font_cache in self.fonts.values():
+ font_cache.font.set_bitmap_size(int(w), int(h))
 
 def render(self, ox, oy, font, sym, fontsize, dpi):
- cmfont, metrics, glyph, offset = \
+ basename, font, metrics, symbol_name, num, glyph, offset = \
 self._get_info(font, sym, fontsize, dpi)
 
- if not self.usingSVG:
- cmfont.draw_glyph_to_bitmap(
- int(ox), int(self.height - oy - metrics.ymax), glyph)
- else:
- oy += offset - 512/2048.*10.
- basename = self.fontmap[font]
- if latex_to_bakoma.has_key(sym):
- basename, num = latex_to_bakoma[sym]
- num = self.glyphmaps[basename][num]
- elif len(sym) == 1:
- num = ord(sym)
- else:
- num = 0
- print >>sys.stderr, 'unrecognized symbol "%s"' % sym
- thetext = unichr(num)
- thetext.encode('utf-8')
- self.svg_glyphs.append((basename, fontsize, thetext, ox, oy, metrics))
+ font.draw_glyph_to_bitmap(
+ int(ox), int(self.height - oy - metrics.ymax), glyph)
+# else:
+# oy += offset - 512/2048.*10.
+# basename = self.fontmap[font]
+# if latex_to_bakoma.has_key(sym):
+# basename, num = latex_to_bakoma[sym]
+# num = self.glyphmaps[basename][num]
+# elif len(sym) == 1:
+# num = ord(sym)
+# else:
+# num = 0
+# print >>sys.stderr, 'unrecognized symbol "%s"' % sym
+# thetext = unichr(num)
+# thetext.encode('utf-8')
+# self.svg_glyphs.append((basename, fontsize, thetext, ox, oy, metrics))
 
 
 def _old_get_kern(self, font, symleft, symright, fontsize, dpi):
@@ -680,153 +715,46 @@
 #print basename, symleft, symright, key, kern
 return kern
 
- def _get_num(self, font, sym):
- 'get charcode for sym'
- basename = self.fontmap[font]
- if latex_to_bakoma.has_key(sym):
- basename, num = latex_to_bakoma[sym]
- num = self.glyphmaps[basename][num]
- elif len(sym) == 1:
- num = ord(sym)
- else:
- num = 0
- return num
 
-
-class BakomaPSFonts(Fonts):
+class BakomaPSFonts(BakomaFonts):
 """
 Use the Bakoma postscript fonts for rendering to backend_ps
 """
- facenames = ('cmmi10', 'cmsy10', 'cmex10',
- 'cmtt10', 'cmr10', 'cmb10', 'cmss10')
- # 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',
- }
-
- def __init__(self, character_tracker=None):
- self.glyphd = {}
- self.fonts = dict(
- [ (name, FT2Font(os.path.join(self.basepath, name) + '.ttf'))
- for name in self.facenames])
-
- self.glyphmaps = {}
- for facename in self.facenames:
- charmap = self.fonts[facename].get_charmap()
- self.glyphmaps[facename] = dict([(glyphind, charcode)
- for charcode, glyphind in charmap.items()])
- for font in self.fonts.values():
- font.clear()
- self.character_tracker = character_tracker
-
- def _get_info (self, font, sym, fontsize, dpi):
- 'load the cmfont, metrics and glyph with caching'
- key = font, sym, fontsize, dpi
- tup = self.glyphd.get(key)
-
- if tup is not None:
- return tup
-
- basename = self.fontmap[font]
-
- if latex_to_bakoma.has_key(sym):
- basename, num = latex_to_bakoma[sym]
- sym = self.fonts[basename].get_glyph_name(num)
- num = self.glyphmaps[basename][num]
- elif len(sym) == 1:
- num = ord(sym)
- else:
- num = 0
- #sym = '.notdef'
- raise ValueError('unrecognized symbol "%s, %d"' % (sym, num))
-
- cmfont = self.fonts[basename]
- cmfont.set_size(fontsize, dpi)
- head = cmfont.get_sfnt_table('head')
- glyph = cmfont.load_char(num)
-
- if self.character_tracker:
- self.character_tracker(cmfont, unichr(num))
-
- xmin, ymin, xmax, ymax = [val/64.0 for val in glyph.bbox]
- if basename == 'cmex10':
- offset = -(head['yMin']+512)/head['unitsPerEm']*10.
- else:
- offset = 0.
- metrics = Bunch(
- advance = glyph.linearHoriAdvance/65536.0,
- height = glyph.height/64.0,
- width = glyph.width/64.0,
- xmin = xmin,
- xmax = xmax,
- ymin = ymin+offset,
- ymax = ymax+offset
- )
-
- self.glyphd[key] = basename, metrics, sym, offset
- return basename, metrics, '/'+sym, offset
-
+ def _get_offset(self, basename, font_cache, glyph, fontsize, dpi):
+ head = font_cache.font.get_sfnt_table("head")
+ if basename.lower() == 'cmex10':
+ return -(head['yMin']+512)/head['unitsPerEm']*10.
+ return 0.
+ 
 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):
- fontname, metrics, glyphname, offset = \
+ basename, font, metrics, symbol_name, num, glyph, offset = \
 self._get_info(font, sym, fontsize, dpi)
- fontname = fontname.capitalize()
- if fontname == 'Cmex10':
+ if basename.lower() == 'cmex10':
 oy += offset - 512/2048.*10.
 
- ps = """/%(fontname)s findfont
+ ps = """/%(basename)s findfont
 %(fontsize)s scalefont
 setfont
 %(ox)f %(oy)f moveto
-/%(glyphname)s glyphshow
+/%(symbol_name)s glyphshow
 """ % locals()
 self.pswriter.write(ps)
 
-
- def get_metrics(self, font, sym, fontsize, dpi):
- basename, metrics, sym, offset = \
- self._get_info(font, sym, fontsize, dpi)
- return metrics
-
 class BakomaPDFFonts(BakomaPSFonts):
 """Hack of BakomaPSFonts for PDF support."""
 
- def _get_filename_and_num (self, font, sym, fontsize, dpi):
- 'should be part of _get_info'
- basename = self.fontmap[font]
-
- if latex_to_bakoma.has_key(sym):
- basename, num = latex_to_bakoma[sym]
- sym = self.fonts[basename].get_glyph_name(num)
- num = self.glyphmaps[basename][num]
- elif len(sym) == 1:
- num = ord(sym)
- else:
- num = 0
- raise ValueError('unrecognized symbol "%s"' % (sym,))
-
- return os.path.join(self.basepath, basename) + '.ttf', num
-
 def render(self, ox, oy, font, sym, fontsize, dpi):
- fontname, metrics, glyphname, offset = \
+ basename, font, metrics, symbol_name, num, glyph, offset = \
 self._get_info(font, sym, fontsize, dpi)
- filename, num = self._get_filename_and_num(font, sym, fontsize, dpi)
- if self.character_tracker:
- self.character_tracker(filename, unichr(num))
- if fontname.lower() == 'cmex10':
+ filename = font.fname
+ if basename.lower() == 'cmex10':
 oy += offset - 512/2048.*10.
 
 self.pswriter.append((ox, oy, filename, fontsize, num))
@@ -1256,32 +1184,25 @@
 
 def set_font(self, font):
 return
- 
- # MGDTODO: The code below is probably now broken
- #print 'set fonts'
-# for i in range(len(self.elements)-1):
-# if not isinstance(self.elements[i], SymbolElement): continue
-# if not isinstance(self.elements[i+1], SymbolElement): continue
-# symleft = self.elements[i].sym
-# symright = self.elements[i+1].sym
-# self.elements[i].kern = None
-# #self.elements[i].kern = Element.fonts.get_kern(font, symleft, symright, self.fontsize, self.dpi)
 
-
 def set_size_info(self, fontsize, dpi):
- self.elements[0].set_size_info(self._scale*fontsize, dpi)
+ if len(self.elements):
+ self.elements[0].set_size_info(self._scale*fontsize, dpi)
 Element.set_size_info(self, fontsize, dpi)
 #print 'set size'
 
 
 def set_origin(self, ox, oy):
- self.elements[0].set_origin(ox, oy)
+ if len(self.elements):
+ self.elements[0].set_origin(ox, oy)
 Element.set_origin(self, ox, oy)
 
 
 def advance(self):
 'get the horiz advance'
- return self.elements[-1].xmax() - self.elements[0].ox
+ if len(self.elements):
+ return self.elements[-1].xmax() - self.elements[0].ox
+ return 0
 
 
 def height(self):
@@ -1298,7 +1219,8 @@
 
 def render(self):
 'render to the fonts canvas'
- self.elements[0].render()
+ if len(self.elements):
+ self.elements[0].render()
 Element.render(self)
 
 def xmin(self):
@@ -1320,6 +1242,18 @@
 def __repr__(self):
 return 'Group: [ %s ]' % ' '.join([str(e) for e in self.elements])
 
+class MathGroupElement(GroupElement):
+ def determine_font(self, font_stack):
+ font_stack.append('it')
+ for element in self.elements:
+ element.determine_font(font_stack)
+ font_stack.pop()
+
+class NonMathGroupElement(GroupElement):
+ def determine_font(self, font_stack):
+ for element in self.elements:
+ element.determine_font(font_stack)
+ 
 class ExpressionElement(GroupElement):
 """
 The entire mathtext expression
@@ -1328,8 +1262,7 @@
 def __repr__(self):
 return 'Expression: [ %s ]' % ' '.join([str(e) for e in self.elements])
 
- def determine_font(self):
- font_stack = ['it']
+ def determine_font(self, font_stack):
 GroupElement.determine_font(self, font_stack)
 
 class Handler:
@@ -1337,12 +1270,24 @@
 
 def clear(self):
 self.symbols = []
- self.subscript_stack = []
 
 def expression(self, s, loc, toks):
+ #~ print "expr", toks
 self.expr = ExpressionElement(toks)
 return [self.expr]
 
+ def math(self, s, loc, toks):
+ #~ print "math", toks
+ math = MathGroupElement(toks)
+ return [math]
+
+ def non_math(self, s, loc, toks):
+ #~ print "non_math", toks
+ symbols = [SymbolElement(c) for c in toks[0]]
+ self.symbols.extend(symbols)
+ non_math = NonMathGroupElement(symbols)
+ return [non_math]
+ 
 def space(self, s, loc, toks):
 assert(len(toks)==1)
 
@@ -1510,8 +1455,8 @@
 latexfont = Forward().setParseAction(handler.latexfont).setName("latexfont")
 subsuper = Forward().setParseAction(handler.subsuperscript).setName("subsuper")
 placeable = Forward().setName("placeable")
+expression = Forward().setParseAction(handler.expression).setName("expression")
 
-
 lbrace = Literal('{').suppress()
 rbrace = Literal('}').suppress()
 lbrack = Literal('[')
@@ -1599,6 +1544,7 @@
 r"[:,.;!]",
 r"[!@%&]",
 r"[[\]()]",
+ r"\\\$"
 ])
 + ")"
 ).setParseAction(handler.symbol).leaveWhitespace()
@@ -1670,15 +1616,30 @@
 | (( subscript | superscript) + placeable)
 )
 
-expression = OneOrMore(
+math = OneOrMore(
 space
 | font
 | latexfont
 | subsuper
- ).setParseAction(handler.expression).setName("expression")
+ ).setParseAction(handler.math).setName("math")
 
- 
+math_delim =(~bslash
+ + Literal('$'))
 
+non_math = Regex(r"(?:[^$]|(?:\\\$))*"
+ ).setParseAction(handler.non_math).setName("non_math").leaveWhitespace()
+
+expression <<(
+ non_math
+ + ZeroOrMore(
+ Suppress(math_delim)
+ + math
+ + Suppress(math_delim)
+ + non_math
+ )
+ )
+ 
+
 ####
 
 
@@ -1700,18 +1661,18 @@
 self.output = output
 self.cache = {}
 
- def __call__(self, s, dpi, fontsize, angle=0, character_tracker=None):
- cacheKey = (s, dpi, fontsize, angle)
- s = s[1:-1] # strip the $ from front and back
+ def __call__(self, s, dpi, prop, angle=0):
+ cacheKey = (s, dpi, hash(prop), angle)
 if self.cache.has_key(cacheKey):
- w, h, fontlike = self.cache[cacheKey]
- return w, h, fontlike
+ w, h, fontlike, used_characters = self.cache[cacheKey]
+ return w, h, fontlike, used_characters
+
 if self.output == 'SVG':
- self.font_object = BakomaTrueTypeFonts(useSVG=True)
+ self.font_object = BakomaFonts(useSVG=True)
 #self.font_object = MyUnicodeFonts(output='SVG')
 Element.fonts = self.font_object
 elif self.output == 'Agg':
- self.font_object = BakomaTrueTypeFonts()
+ self.font_object = BakomaFonts()
 #self.font_object = MyUnicodeFonts()
 Element.fonts = self.font_object
 elif self.output == 'PS':
@@ -1719,17 +1680,22 @@
 self.font_object = StandardPSFonts()
 Element.fonts = self.font_object
 else:
- self.font_object = BakomaPSFonts(character_tracker)
+ self.font_object = BakomaPSFonts()
 #self.font_object = MyUnicodeFonts(output='PS')
 Element.fonts = self.font_object
 elif self.output == 'PDF':
- self.font_object = BakomaPDFFonts(character_tracker)
+ self.font_object = BakomaPDFFonts()
 Element.fonts = self.font_object
+
+ fontsize = prop.get_size_in_points()
 
 handler.clear()
 expression.parseString( s )
-
- handler.expr.determine_font()
+ 
+ fname = fontManager.findfont(prop)
+ default_font = FT2Font(str(fname))
+ 
+ handler.expr.determine_font([default_font])
 handler.expr.set_size_info(fontsize, dpi)
 
 # set the origin once to allow w, h compution
@@ -1738,7 +1704,7 @@
 xmax = max([e.xmax() for e in handler.symbols])
 ymin = min([e.ymin() for e in handler.symbols])
 ymax = max([e.ymax() for e in handler.symbols])
-
+ 
 # now set the true origin - doesn't affect with and height
 w, h = xmax-xmin, ymax-ymin
 # a small pad for the canvas size
@@ -1758,20 +1724,18 @@
 
 handler.expr.render()
 handler.clear()
-
+ 
 if self.output == 'SVG':
 # The empty list at the end is for lines
 svg_elements = Bunch(svg_glyphs=self.font_object.svg_glyphs,
 svg_lines=[])
- self.cache[cacheKey] = w, h, svg_elements
- return w, h, svg_elements
+ self.cache[cacheKey] = w, h, svg_elements, Element.fonts.used_characters
 elif self.output == 'Agg':
- self.cache[cacheKey] = w, h, self.font_object.fonts.values()
- return w, h, self.font_object.fonts.values()
+ self.cache[cacheKey] = w, h, self.font_object.get_fonts(), Element.fonts.used_characters
 elif self.output in ('PS', 'PDF'):
- self.cache[cacheKey] = w, h, pswriter
- return w, h, pswriter
-
+ self.cache[cacheKey] = w, h, pswriter, Element.fonts.used_characters
+ return self.cache[cacheKey]
+ 
 if rcParams["mathtext.mathtext2"]:
 from matplotlib.mathtext2 import math_parse_s_ft2font
 from matplotlib.mathtext2 import math_parse_s_ft2font_svg
Modified: branches/mathtext_mgd/lib/matplotlib/text.py
===================================================================
--- branches/mathtext_mgd/lib/matplotlib/text.py	2007年07月18日 07:38:05 UTC (rev 3556)
+++ branches/mathtext_mgd/lib/matplotlib/text.py	2007年07月18日 13:16:35 UTC (rev 3557)
@@ -238,7 +238,7 @@
 lines = [self._text]
 else:
 lines = self._text.split('\n')
-
+ 
 whs = []
 # Find full vertical extent of font,
 # including ascenders and descenders:
@@ -753,8 +753,8 @@
 if rcParams['text.usetex']: return 'TeX'
 if not matplotlib._havemath: return False
 if len(self._text)<2: return False
- return ( self._text.startswith('$') and
- self._text.endswith('$') )
+ dollar_signs = self._text.count('$') - self._text.count('\\$')
+ return dollar_signs > 0 and dollar_signs % 2 == 0
 
 def set_fontproperties(self, fp):
 """
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
Revision: 3556
 http://matplotlib.svn.sourceforge.net/matplotlib/?rev=3556&view=rev
Author: efiring
Date: 2007年07月18日 00:38:05 -0700 (2007年7月18日)
Log Message:
-----------
Standardized imports in ticker.py
Modified Paths:
--------------
 trunk/matplotlib/lib/matplotlib/ticker.py
Modified: trunk/matplotlib/lib/matplotlib/ticker.py
===================================================================
--- trunk/matplotlib/lib/matplotlib/ticker.py	2007年07月17日 22:33:42 UTC (rev 3555)
+++ trunk/matplotlib/lib/matplotlib/ticker.py	2007年07月18日 07:38:05 UTC (rev 3556)
@@ -111,14 +111,17 @@
 
 from __future__ import division
 import sys, os, re, time, math, warnings
-from mlab import linspace
+import numpy as npy
+import matplotlib as mpl
 from matplotlib import verbose, rcParams
-from numpy import absolute, arange, array, asarray, floor, log, logical_and, nonzero, ones, take, zeros
-from matplotlib.numerix.mlab import amin, amax, std, mean
-from matplotlib.mlab import frange
-from cbook import strip_math
-from transforms import nonsingular, Value, Interval
+from matplotlib import cbook
+from matplotlib import mlab
+from matplotlib import transforms as mtrans
 
+
+
+
+
 class TickHelper:
 
 viewInterval = None
@@ -147,8 +150,8 @@
 cases where the Intervals do not need to be updated
 automatically.
 '''
- self.dataInterval = Interval(Value(vmin), Value(vmax))
- self.viewInterval = Interval(Value(vmin), Value(vmax))
+ self.dataInterval = mtrans.Interval(mtrans.Value(vmin), mtrans.Value(vmax))
+ self.viewInterval = mtrans.Interval(mtrans.Value(vmin), mtrans.Value(vmax))
 
 class Formatter(TickHelper):
 """
@@ -330,7 +333,7 @@
 sciNotStr = r'{\times}'+self.format_data(10**self.orderOfMagnitude)
 else:
 sciNotStr = u'\xd7'+'1e%d'% self.orderOfMagnitude
- if self._useMathText or self._usetex: 
+ if self._useMathText or self._usetex:
 return ''.join(('$',sciNotStr,offsetStr,'$'))
 else: return ''.join((sciNotStr,offsetStr))
 else: return ''
@@ -352,16 +355,16 @@
 if locs is None or not len(locs) or range == 0:
 self.offset = 0
 return
- ave_loc = mean(locs)
+ ave_loc = npy.mean(locs)
 if ave_loc: # dont want to take log10(0)
- ave_oom = math.floor(math.log10(mean(absolute(locs))))
+ ave_oom = math.floor(math.log10(npy.mean(npy.absolute(locs))))
 range_oom = math.floor(math.log10(range))
 
- if absolute(ave_oom-range_oom) >= 3: # four sig-figs
+ if npy.absolute(ave_oom-range_oom) >= 3: # four sig-figs
 if ave_loc < 0:
- self.offset = math.ceil(amax(locs)/10**range_oom)*10**range_oom
+ self.offset = math.ceil(npy.max(locs)/10**range_oom)*10**range_oom
 else:
- self.offset = math.floor(amin(locs)/10**(range_oom))*10**(range_oom)
+ self.offset = math.floor(npy.min(locs)/10**(range_oom))*10**(range_oom)
 else: self.offset = 0
 
 def _set_orderOfMagnitude(self,range):
@@ -370,7 +373,7 @@
 if not self._scientific:
 self.orderOfMagnitude = 0
 return
- locs = absolute(self.locs)
+ locs = npy.absolute(self.locs)
 if self.offset: oom = math.floor(math.log10(range))
 else:
 if locs[0] > locs[-1]: val = locs[0]
@@ -388,7 +391,7 @@
 # set the format string to format all the ticklabels
 # The floating point black magic (adding 1e-15 and formatting
 # to 8 digits) may warrant review and cleanup.
- locs = (array(self.locs)-self.offset) / 10**self.orderOfMagnitude+1e-15
+ locs = (npy.asarray(self.locs)-self.offset) / 10**self.orderOfMagnitude+1e-15
 sigfigs = [len(str('%1.8f'% loc).split('.')[1].rstrip('0')) \
 for loc in locs]
 sigfigs.sort()
@@ -397,7 +400,7 @@
 
 def pprint_val(self, x):
 xp = (x-self.offset)/10**self.orderOfMagnitude
- if absolute(xp) < 1e-8: xp = 0
+ if npy.absolute(xp) < 1e-8: xp = 0
 return self.format % xp
 
 def _formatSciNotation(self, s):
@@ -464,7 +467,7 @@
 
 def format_data(self,value):
 self.labelOnlyBase = False
- value = strip_math(self.__call__(value))
+ value = cbook.strip_math(self.__call__(value))
 self.labelOnlyBase = True
 return value
 
@@ -570,7 +573,7 @@
 def autoscale(self):
 'autoscale the view limits'
 self.verify_intervals()
- return nonsingular(*self.dataInterval.get_bounds())
+ return mtrans.nonsingular(*self.dataInterval.get_bounds())
 
 def pan(self, numsteps):
 'Pan numticks (can be positive or negative)'
@@ -611,7 +614,7 @@
 def __call__(self):
 'Return the locations of the ticks'
 dmin, dmax = self.dataInterval.get_bounds()
- return arange(dmin + self.offset, dmax+1, self._base)
+ return npy.arange(dmin + self.offset, dmax+1, self._base)
 
 
 class FixedLocator(Locator):
@@ -684,7 +687,7 @@
 
 
 if self.numticks==0: return []
- ticklocs = linspace(vmin, vmax, self.numticks)
+ ticklocs = npy.linspace(vmin, vmax, self.numticks)
 
 return ticklocs
 
@@ -712,7 +715,7 @@
 vmin = math.floor(scale*vmin)/scale
 vmax = math.ceil(scale*vmax)/scale
 
- return nonsingular(vmin, vmax)
+ return mtrans.nonsingular(vmin, vmax)
 
 
 def closeto(x,y):
@@ -776,9 +779,8 @@
 if vmax<vmin:
 vmin, vmax = vmax, vmin
 vmin = self._base.ge(vmin)
-
- locs = frange(vmin, vmax+0.001*self._base.get_base(), self._base.get_base())
-
+ base = self._base.get_base()
+ locs = mlab.frange(vmin, vmax+0.001*base, base)
 return locs
 
 def autoscale(self):
@@ -796,7 +798,7 @@
 vmin -=1
 vmax +=1
 
- return nonsingular(vmin, vmax)
+ return mtrans.nonsingular(vmin, vmax)
 
 def scale_range(vmin, vmax, n = 1, threshold=100):
 dv = abs(vmax - vmin)
@@ -858,20 +860,20 @@
 if self._trim:
 extra_bins = int(divmod((best_vmax - vmax), step)[0])
 nbins -= extra_bins
- return (arange(nbins+1) * step + best_vmin + offset)
+ return (npy.arange(nbins+1) * step + best_vmin + offset)
 
 
 def __call__(self):
 self.verify_intervals()
 vmin, vmax = self.viewInterval.get_bounds()
- vmin, vmax = nonsingular(vmin, vmax, expander = 0.05)
+ vmin, vmax = mtrans.nonsingular(vmin, vmax, expander = 0.05)
 return self.bin_boundaries(vmin, vmax)
 
 def autoscale(self):
 self.verify_intervals()
 dmin, dmax = self.dataInterval.get_bounds()
- dmin, dmax = nonsingular(dmin, dmax, expander = 0.05)
- return take(self.bin_boundaries(dmin, dmax), [0,-1])
+ dmin, dmax = mtrans.nonsingular(dmin, dmax, expander = 0.05)
+ return npy.take(self.bin_boundaries(dmin, dmax), [0,-1])
 
 
 def decade_down(x, base=10):
@@ -915,7 +917,7 @@
 if subs is None:
 self._subs = None # autosub
 else:
- self._subs = array(subs)+0.0
+ self._subs = npy.asarray(subs)+0.0
 
 def _set_numticks(self):
 self.numticks = 15 # todo; be smart here; this is just for dev
@@ -936,9 +938,9 @@
 numdec = math.floor(vmax)-math.ceil(vmin)
 
 if self._subs is None: # autosub
- if numdec>10: subs = array([1.0])
- elif numdec>6: subs = arange(2.0, b, 2.0)
- else: subs = arange(2.0, b)
+ if numdec>10: subs = npy.array([1.0])
+ elif numdec>6: subs = npy.arange(2.0, b, 2.0)
+ else: subs = npy.arange(2.0, b)
 else:
 subs = self._subs
 
@@ -946,10 +948,11 @@
 while numdec/stride+1 > self.numticks:
 stride += 1
 
- for decadeStart in b**arange(math.floor(vmin),math.ceil(vmax)+stride, stride):
+ for decadeStart in b**npy.arange(math.floor(vmin),
+ math.ceil(vmax)+stride, stride):
 ticklocs.extend( subs*decadeStart )
 
- return array(ticklocs)
+ return npy.array(ticklocs)
 
 def autoscale(self):
 'Try to choose the view limits intelligently'
@@ -970,7 +973,7 @@
 if vmin==vmax:
 vmin = decade_down(vmin,self._base)
 vmax = decade_up(vmax,self._base)
- return nonsingular(vmin, vmax)
+ return mtrans.nonsingular(vmin, vmax)
 
 class AutoLocator(MaxNLocator):
 def __init__(self):
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
Revision: 3555
 http://matplotlib.svn.sourceforge.net/matplotlib/?rev=3555&view=rev
Author: efiring
Date: 2007年07月17日 15:33:42 -0700 (2007年7月17日)
Log Message:
-----------
Bugfix in changed import strategy
Modified Paths:
--------------
 trunk/matplotlib/lib/matplotlib/axes.py
Modified: trunk/matplotlib/lib/matplotlib/axes.py
===================================================================
--- trunk/matplotlib/lib/matplotlib/axes.py	2007年07月17日 22:15:44 UTC (rev 3554)
+++ trunk/matplotlib/lib/matplotlib/axes.py	2007年07月17日 22:33:42 UTC (rev 3555)
@@ -9,19 +9,19 @@
 rcParams = matplotlib.rcParams
 
 from matplotlib import artist as martist
-from matplotlib import agg 
+from matplotlib import agg
 from matplotlib import axis as maxis
-from matplotlib import cbook 
+from matplotlib import cbook
 from matplotlib import collections as mcoll
 from matplotlib import colors as mcolors
 from matplotlib import contour as mcontour
 from matplotlib import dates as mdates
-from matplotlib import font_manager 
+from matplotlib import font_manager
 from matplotlib import image as mimage
 from matplotlib import legend as mlegend
 from matplotlib import lines as mlines
-from matplotlib import mlab 
-from matplotlib import cm 
+from matplotlib import mlab
+from matplotlib import cm
 from matplotlib import patches as mpatches
 from matplotlib import quiver as mquiver
 from matplotlib import table as mtable
@@ -56,8 +56,6 @@
 return args
 mask = reduce(ma.mask_or, masks)
 margs = []
- is_string_like = mpl_cbook.is_string_like
- iterable = mpl_cbook.iterable
 for x in args:
 if (not is_string_like(x)
 and iterable(x)
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
From: <jd...@us...> - 2007年07月17日 22:15:45
Revision: 3554
 http://matplotlib.svn.sourceforge.net/matplotlib/?rev=3554&view=rev
Author: jdh2358
Date: 2007年07月17日 15:15:44 -0700 (2007年7月17日)
Log Message:
-----------
recleanup of axes imports
Modified Paths:
--------------
 trunk/matplotlib/README
 trunk/matplotlib/examples/agg_test.py
 trunk/matplotlib/lib/matplotlib/__init__.py
 trunk/matplotlib/lib/matplotlib/axes.py
 trunk/matplotlib/setup.py
Modified: trunk/matplotlib/README
===================================================================
--- trunk/matplotlib/README	2007年07月17日 16:37:14 UTC (rev 3553)
+++ trunk/matplotlib/README	2007年07月17日 22:15:44 UTC (rev 3554)
@@ -54,8 +54,8 @@
 
 AUTHOR
 
- John D. Hunter <jdh...@ac...>
- Copyright (c) 2002-2004 John D. Hunter; All Rights Reserved.
+ John D. Hunter <jd...@gm...>
+ Copyright (c) 2002-2007 John D. Hunter; All Rights Reserved.
 
 Jeremy O'Donoghue wrote the wx backend
 
Modified: trunk/matplotlib/examples/agg_test.py
===================================================================
--- trunk/matplotlib/examples/agg_test.py	2007年07月17日 16:37:14 UTC (rev 3553)
+++ trunk/matplotlib/examples/agg_test.py	2007年07月17日 22:15:44 UTC (rev 3554)
@@ -106,39 +106,42 @@
 renderer.color_rgba8( white )
 agg.render_scanlines_rgba(rasterizer, scanline, renderer);
 
-## Copy a rectangle from the buffer the rectangle defined by
-## x0,y0->x1,y1 and paste it at xdest, ydest
-x0, y0 = 10, 50
-x1, y1 = 110, 190
-xdest, ydest = 350, 200
+if 0:
+ ## Copy a rectangle from the buffer the rectangle defined by
+ ## x0,y0->x1,y1 and paste it at xdest, ydest
+ x0, y0 = 10, 50
+ x1, y1 = 110, 190
+ xdest, ydest = 350, 200
 
 
-widthr, heightr = x1-x0, y1-y0
-strider = widthr*4
-copybuffer = agg.buffer(widthr, heightr, strider)
 
-rbufcopy = agg.rendering_buffer()
-rbufcopy.attachb(copybuffer)
-pfcopy = agg.pixel_format_rgba(rbufcopy)
-rbasecopy = agg.renderer_base_rgba(pfcopy)
+ widthr, heightr = x1-x0, y1-y0
+ strider = widthr*4
+ copybuffer = agg.buffer(widthr, heightr, strider)
 
-rect = agg.rect(x0, y0, x1, y1)
-print rect.is_valid()
-rectp = agg.rectPtr(rect)
-#print dir(rbasecopy)
 
-# agg is funny about the arguments to copy from; the last 2 args are
-# dx, dy. If the src and dest buffers are the same size and you omit
-# the dx and dy args, the position of the copy in the dest buffer is
-# the same as in the src. Since our dest buffer is smaller than our
-# src buffer, we have to offset the location by -x0, -y0
-rbasecopy.copy_from(rbuf, rect, -x0, -y0);
+ rbufcopy = agg.rendering_buffer()
+ rbufcopy.attachb(copybuffer)
+ pfcopy = agg.pixel_format_rgba(rbufcopy)
+ rbasecopy = agg.renderer_base_rgba(pfcopy)
 
-# paste the rectangle at a new location xdest, ydest
-rbase.copy_from(rbufcopy, None, xdest, ydest);
+ rect = agg.rect(x0, y0, x1, y1)
+ print rect.is_valid()
+ rectp = agg.rectPtr(rect)
+ #print dir(rbasecopy)
 
+ # agg is funny about the arguments to copy from; the last 2 args are
+ # dx, dy. If the src and dest buffers are the same size and you omit
+ # the dx and dy args, the position of the copy in the dest buffer is
+ # the same as in the src. Since our dest buffer is smaller than our
+ # src buffer, we have to offset the location by -x0, -y0
+ rbasecopy.copy_from(rbuf, rect, -x0, -y0);
 
+ # paste the rectangle at a new location xdest, ydest
+ rbase.copy_from(rbufcopy, None, xdest, ydest);
 
+
+
 ## Display it with PIL
 s = buffer.to_string()
 print len(s)
Modified: trunk/matplotlib/lib/matplotlib/__init__.py
===================================================================
--- trunk/matplotlib/lib/matplotlib/__init__.py	2007年07月17日 16:37:14 UTC (rev 3553)
+++ trunk/matplotlib/lib/matplotlib/__init__.py	2007年07月17日 22:15:44 UTC (rev 3554)
@@ -801,8 +801,6 @@
 """
 pass
 
-
-
 class Namespace:
 """
 A class which takes a list of modules and creates an object with
@@ -832,3 +830,4 @@
 mod = getattr(basemod, name)
 setattr(self, name, mod)
 
+
Modified: trunk/matplotlib/lib/matplotlib/axes.py
===================================================================
--- trunk/matplotlib/lib/matplotlib/axes.py	2007年07月17日 16:37:14 UTC (rev 3553)
+++ trunk/matplotlib/lib/matplotlib/axes.py	2007年07月17日 22:15:44 UTC (rev 3554)
@@ -8,11 +8,32 @@
 import matplotlib
 rcParams = matplotlib.rcParams
 
-# import a bunch of matplotlib modules into a single namespace
-mpl = matplotlib.Importer("""artist, agg, axis, cbook, collections, colors,
- contour, dates, font_manager, image, legend, lines, mlab, cm,
- patches, quiver, table, text, ticker, transforms""")
+from matplotlib import artist as martist
+from matplotlib import agg 
+from matplotlib import axis as maxis
+from matplotlib import cbook 
+from matplotlib import collections as mcoll
+from matplotlib import colors as mcolors
+from matplotlib import contour as mcontour
+from matplotlib import dates as mdates
+from matplotlib import font_manager 
+from matplotlib import image as mimage
+from matplotlib import legend as mlegend
+from matplotlib import lines as mlines
+from matplotlib import mlab 
+from matplotlib import cm 
+from matplotlib import patches as mpatches
+from matplotlib import quiver as mquiver
+from matplotlib import table as mtable
+from matplotlib import text as mtext
+from matplotlib import ticker as mticker
+from matplotlib import transforms as mtrans
 
+iterable = cbook.iterable
+is_string_like = cbook.is_string_like
+
+
+
 def delete_masked_points(*args):
 """
 Find all masked points in a set of arguments, and return
@@ -35,9 +56,11 @@
 return args
 mask = reduce(ma.mask_or, masks)
 margs = []
+ is_string_like = mpl_cbook.is_string_like
+ iterable = mpl_cbook.iterable
 for x in args:
- if (not mpl.cbook.is_string_like(x)
- and mpl.cbook.iterable(x)
+ if (not is_string_like(x)
+ and iterable(x)
 and len(x) == len(mask)):
 if (hasattr(x, 'get_compressed_copy')):
 compressed_x = x.get_compressed_copy(mask)
@@ -69,7 +92,7 @@
 
 # Is fmt just a colorspec?
 try:
- color = mpl.colors.colorConverter.to_rgb(fmt)
+ color = mcolors.colorConverter.to_rgb(fmt)
 return linestyle, marker, color # Yes.
 except ValueError:
 pass # No, not just a color.
@@ -89,17 +112,17 @@
 chars = [c for c in fmt]
 
 for c in chars:
- if mpl.lines.lineStyles.has_key(c):
+ if mlines.lineStyles.has_key(c):
 if linestyle is not None:
 raise ValueError(
 'Illegal format string "%s"; two linestyle symbols' % fmt)
 linestyle = c
- elif mpl.lines.lineMarkers.has_key(c):
+ elif mlines.lineMarkers.has_key(c):
 if marker is not None:
 raise ValueError(
 'Illegal format string "%s"; two marker symbols' % fmt)
 marker = c
- elif mpl.colors.colorConverter.colors.has_key(c):
+ elif mcolors.colorConverter.colors.has_key(c):
 if color is not None:
 raise ValueError(
 'Illegal format string "%s"; two color symbols' % fmt)
@@ -240,7 +263,7 @@
 if multicol:
 for j in range(y.shape[1]):
 color = self._get_next_cycle_color()
- seg = mpl.lines.Line2D(x, y[:,j],
+ seg = mlines.Line2D(x, y[:,j],
 color = color,
 axes=self.axes,
 )
@@ -248,7 +271,7 @@
 ret.append(seg)
 else:
 color = self._get_next_cycle_color()
- seg = mpl.lines.Line2D(x, y,
+ seg = mlines.Line2D(x, y,
 color = color,
 axes=self.axes,
 )
@@ -259,7 +282,7 @@
 
 def _plot_2_args(self, tup2, **kwargs):
 ret = []
- if mpl.cbook.is_string_like(tup2[1]):
+ if is_string_like(tup2[1]):
 
 assert self.command == 'plot', 'fill needs at least 2 non-string arguments'
 y, fmt = tup2
@@ -271,7 +294,7 @@
 _color = color
 if _color is None:
 _color = self._get_next_cycle_color()
- seg = mpl.lines.Line2D(x, y,
+ seg = mlines.Line2D(x, y,
 color=_color,
 linestyle=linestyle, marker=marker,
 axes=self.axes,
@@ -293,7 +316,7 @@
 
 def makeline(x, y):
 color = self._get_next_cycle_color()
- seg = mpl.lines.Line2D(x, y,
+ seg = mlines.Line2D(x, y,
 color=color,
 axes=self.axes,
 )
@@ -302,7 +325,7 @@
 
 def makefill(x, y):
 facecolor = self._get_next_cycle_color()
- seg = mpl.patches.Polygon(zip(x, y),
+ seg = mpatches.Polygon(zip(x, y),
 facecolor = facecolor,
 fill=True,
 )
@@ -333,7 +356,7 @@
 _color = color
 if _color is None:
 _color = self._get_next_cycle_color()
- seg = mpl.lines.Line2D(x, y,
+ seg = mlines.Line2D(x, y,
 color=_color,
 linestyle=linestyle, marker=marker,
 axes=self.axes,
@@ -343,7 +366,7 @@
 
 def makefill(x, y):
 facecolor = color
- seg = mpl.patches.Polygon(zip(x, y),
+ seg = mpatches.Polygon(zip(x, y),
 facecolor = facecolor,
 fill=True,
 )
@@ -377,13 +400,13 @@
 remaining = []
 continue
 if len(remaining)==3:
- if not mpl.cbook.is_string_like(remaining[2]):
+ if not is_string_like(remaining[2]):
 raise ValueError, 'third arg must be a format string'
 for seg in self._plot_3_args(remaining, **kwargs):
 yield seg
 remaining=[]
 continue
- if mpl.cbook.is_string_like(remaining[2]):
+ if is_string_like(remaining[2]):
 for seg in self._plot_3_args(remaining[:3], **kwargs):
 yield seg
 remaining=remaining[3:]
@@ -392,15 +415,15 @@
 yield seg
 remaining=remaining[2:]
 
-ValueType=type(mpl.transforms.zero())
+ValueType=type(mtrans.zero())
 def makeValue(v):
 if type(v) == ValueType:
 return v
 else:
- return mpl.transforms.Value(v)
+ return mtrans.Value(v)
 
 
-class Axes(mpl.artist.Artist):
+class Axes(martist.Artist):
 """
 The Axes contains most of the figure elements: Axis, Tick, Line2D,
 Text, Polygon etc, and sets the coordinate system
@@ -413,8 +436,8 @@
 
 """
 
- scaled = {mpl.transforms.IDENTITY : 'linear',
- mpl.transforms.LOG10 : 'log',
+ scaled = {mtrans.IDENTITY : 'linear',
+ mtrans.LOG10 : 'log',
 }
 
 def __str__(self):
@@ -463,7 +486,7 @@
 yticks: sequence of floats
 
 """
- mpl.artist.Artist.__init__(self)
+ martist.Artist.__init__(self)
 self._position = map(makeValue, rect)
 self._originalPosition = rect
 self.set_axes(self)
@@ -506,7 +529,7 @@
 self.set_navigate(True)
 self.set_navigate_mode(None)
 
- if len(kwargs): mpl.artist.setp(self, **kwargs)
+ if len(kwargs): martist.setp(self, **kwargs)
 
 if self.xaxis is not None:
 self._xcid = self.xaxis.callbacks.connect('units finalize', self.relim)
@@ -521,8 +544,8 @@
 
 def _init_axis(self):
 "move this out of __init__ because non-separable axes don't use it"
- self.xaxis = mpl.axis.XAxis(self)
- self.yaxis = mpl.axis.YAxis(self)
+ self.xaxis = maxis.XAxis(self)
+ self.yaxis = maxis.YAxis(self)
 
 
 def sharex_foreign(self, axforeign):
@@ -594,7 +617,7 @@
 
 ACCEPTS: a Figure instance
 """
- mpl.artist.Artist.set_figure(self, fig)
+ martist.Artist.set_figure(self, fig)
 
 l, b, w, h = self._position
 xmin = fig.bbox.ll().x()
@@ -609,8 +632,8 @@
 self.top = (b+h)*figh
 
 
- Bbox = mpl.transforms.Bbox
- Point = mpl.transforms.Point
+ Bbox = mtrans.Bbox
+ Point = mtrans.Point
 self.bbox = Bbox(
 Point(self.left, self.bottom),
 Point(self.right, self.top ),
@@ -625,10 +648,10 @@
 """
 
 
- one = mpl.transforms.one
- zero = mpl.transforms.zero
- Point = mpl.transforms.Point
- Bbox = mpl.transforms.Bbox
+ one = mtrans.one
+ zero = mtrans.zero
+ Point = mtrans.Point
+ Bbox = mtrans.Bbox
 if self._sharex is not None:
 left=self._sharex.viewLim.ll().x()
 right=self._sharex.viewLim.ur().x()
@@ -645,12 +668,12 @@
 
 
 self.viewLim = Bbox(Point(left, bottom), Point(right, top))
- self.dataLim = mpl.transforms.unit_bbox()
+ self.dataLim = mtrans.unit_bbox()
 
- self.transData = mpl.transforms.get_bbox_transform(
+ self.transData = mtrans.get_bbox_transform(
 self.viewLim, self.bbox)
- self.transAxes = mpl.transforms.get_bbox_transform(
- mpl.transforms.unit_bbox(), self.bbox)
+ self.transAxes = mtrans.get_bbox_transform(
+ mtrans.unit_bbox(), self.bbox)
 
 if self._sharex:
 self.transData.set_funcx(self._sharex.transData.get_funcx())
@@ -701,7 +724,7 @@
 self.yaxis.cla()
 
 self.dataLim.ignore(1)
- self.callbacks = mpl.cbook.CallbackRegistry(('xlim_changed', 'ylim_changed'))
+ self.callbacks = cbook.CallbackRegistry(('xlim_changed', 'ylim_changed'))
 
 if self._sharex is not None:
 self.xaxis.major = self._sharex.xaxis.major
@@ -726,8 +749,8 @@
 self._autoscaleon = True
 
 self.grid(self._gridOn)
- props = mpl.font_manager.FontProperties(size=rcParams['axes.titlesize'])
- self.title = mpl.text.Text(
+ props = font_manager.FontProperties(size=rcParams['axes.titlesize'])
+ self.title = mtext.Text(
 x=0.5, y=1.02, text='',
 fontproperties=props,
 verticalalignment='bottom',
@@ -738,7 +761,7 @@
 
 self._set_artist_props(self.title)
 
- self.axesPatch = mpl.patches.Rectangle(
+ self.axesPatch = mpatches.Rectangle(
 xy=(0,0), width=1, height=1,
 facecolor=self._axisbg,
 edgecolor=rcParams['axes.edgecolor'],
@@ -746,7 +769,7 @@
 self.axesPatch.set_figure(self.figure)
 self.axesPatch.set_transform(self.transAxes)
 self.axesPatch.set_linewidth(rcParams['axes.linewidth'])
- self.axesFrame = mpl.lines.Line2D((0,1,1,0,0), (0,0,1,1,0),
+ self.axesFrame = mlines.Line2D((0,1,1,0,0), (0,0,1,1,0),
 linewidth=rcParams['axes.linewidth'],
 color=rcParams['axes.edgecolor'],
 figure=self.figure)
@@ -840,7 +863,7 @@
 """
 ACCEPTS: ['C', 'SW', 'S', 'SE', 'E', 'NE', 'N', 'NW', 'W']
 """
- if anchor in mpl.transforms.PBox.coefs.keys() or len(anchor) == 2:
+ if anchor in mtrans.PBox.coefs.keys() or len(anchor) == 2:
 self._anchor = anchor
 else:
 raise ValueError('argument must be among %s' %
@@ -880,7 +903,7 @@
 if data_ratio is None:
 data_ratio = ysize/xsize
 box_aspect = A * data_ratio
- pb = mpl.transforms.PBox(self._originalPosition)
+ pb = mtrans.PBox(self._originalPosition)
 pb1 = pb.shrink_to_aspect(box_aspect, fig_aspect)
 self.set_position(pb1.anchor(self._anchor), 'active')
 return
@@ -953,7 +976,7 @@
 kwargs are passed on to set_xlim and set_ylim -- see their
 docstrings for details
 '''
- if len(v)==1 and mpl.cbook.is_string_like(v[0]):
+ if len(v)==1 and is_string_like(v[0]):
 s = v[0].lower()
 if s=='on': self.set_axis_on()
 elif s=='off': self.set_axis_off()
@@ -1020,11 +1043,11 @@
 
 def get_images(self):
 'return a list of Axes images contained by the Axes'
- return mpl.cbook.silent_list('AxesImage', self.images)
+ return cbook.silent_list('AxesImage', self.images)
 
 def get_lines(self):
 'Return a list of lines contained by the Axes'
- return mpl.cbook.silent_list('Line2D', self.lines)
+ return cbook.silent_list('Line2D', self.lines)
 
 def get_xaxis(self):
 'Return the XAxis instance'
@@ -1032,12 +1055,12 @@
 
 def get_xgridlines(self):
 'Get the x grid lines as a list of Line2D instances'
- return mpl.cbook.silent_list('Line2D xgridline', self.xaxis.get_gridlines())
+ return cbook.silent_list('Line2D xgridline', self.xaxis.get_gridlines())
 
 
 def get_xticklines(self):
 'Get the xtick lines as a list of Line2D instances'
- return mpl.cbook.silent_list('Text xtickline', self.xaxis.get_ticklines())
+ return cbook.silent_list('Text xtickline', self.xaxis.get_ticklines())
 
 
 def get_yaxis(self):
@@ -1046,11 +1069,11 @@
 
 def get_ygridlines(self):
 'Get the y grid lines as a list of Line2D instances'
- return mpl.cbook.silent_list('Line2D ygridline', self.yaxis.get_gridlines())
+ return cbook.silent_list('Line2D ygridline', self.yaxis.get_gridlines())
 
 def get_yticklines(self):
 'Get the ytick lines as a list of Line2D instances'
- return mpl.cbook.silent_list('Line2D ytickline', self.yaxis.get_ticklines())
+ return cbook.silent_list('Line2D ytickline', self.yaxis.get_ticklines())
 
 #### Adding and tracking artists
 
@@ -1265,7 +1288,7 @@
 im.draw(renderer)
 else:
 # make a composite image blending alpha
- # list of (mpl.image.Image, ox, oy)
+ # list of (mimage.Image, ox, oy)
 
 
 mag = renderer.get_image_magnification()
@@ -1273,7 +1296,7 @@
 for im in self.images if im.get_visible()]
 
 
- im = mpl.image.from_images(self.bbox.height()*mag,
+ im = mimage.from_images(self.bbox.height()*mag,
 self.bbox.width()*mag,
 ims)
 im.is_grayscale = False
@@ -1398,7 +1421,7 @@
 if len(kwargs): b = True
 self.xaxis.grid(b, **kwargs)
 self.yaxis.grid(b, **kwargs)
- grid.__doc__ = mpl.cbook.dedent(grid.__doc__) % mpl.artist.kwdocd
+ grid.__doc__ = cbook.dedent(grid.__doc__) % martist.kwdocd
 
 def ticklabel_format(self, **kwargs):
 """
@@ -1499,7 +1522,7 @@
 ACCEPTS: len(2) sequence of floats
 """
 
- if xmax is None and mpl.cbook.iterable(xmin):
+ if xmax is None and iterable(xmin):
 xmin,xmax = xmin
 
 
@@ -1513,11 +1536,11 @@
 if xmin is None: xmin = old_xmin
 if xmax is None: xmax = old_xmax
 
- if (self.transData.get_funcx().get_type()==mpl.transforms.LOG10
+ if (self.transData.get_funcx().get_type()==mtrans.LOG10
 and min(xmin, xmax)<=0):
 raise ValueError('Cannot set nonpositive limits with log transform')
 
- xmin, xmax = mpl.transforms.nonsingular(xmin, xmax, increasing=False)
+ xmin, xmax = mtrans.nonsingular(xmin, xmax, increasing=False)
 self.viewLim.intervalx().set_bounds(xmin, xmax)
 if emit: self.callbacks.process('xlim_changed', self)
 
@@ -1549,19 +1572,19 @@
 #if subsx is None: subsx = range(2, basex)
 assert(value.lower() in ('log', 'linear', ))
 if value == 'log':
- self.xaxis.set_major_locator(mpl.ticker.LogLocator(basex))
- self.xaxis.set_major_formatter(mpl.ticker.LogFormatterMathtext(basex))
- self.xaxis.set_minor_locator(mpl.ticker.LogLocator(basex,subsx))
- self.transData.get_funcx().set_type(mpl.transforms.LOG10)
+ self.xaxis.set_major_locator(mticker.LogLocator(basex))
+ self.xaxis.set_major_formatter(mticker.LogFormatterMathtext(basex))
+ self.xaxis.set_minor_locator(mticker.LogLocator(basex,subsx))
+ self.transData.get_funcx().set_type(mtrans.LOG10)
 minx, maxx = self.get_xlim()
 if min(minx, maxx)<=0:
 self.autoscale_view()
 elif value == 'linear':
- self.xaxis.set_major_locator(mpl.ticker.AutoLocator())
- self.xaxis.set_major_formatter(mpl.ticker.ScalarFormatter())
- self.xaxis.set_minor_locator(mpl.ticker.NullLocator())
- self.xaxis.set_minor_formatter(mpl.ticker.NullFormatter())
- self.transData.get_funcx().set_type( mpl.transforms.IDENTITY )
+ self.xaxis.set_major_locator(mticker.AutoLocator())
+ self.xaxis.set_major_formatter(mticker.ScalarFormatter())
+ self.xaxis.set_minor_locator(mticker.NullLocator())
+ self.xaxis.set_minor_formatter(mticker.NullFormatter())
+ self.transData.get_funcx().set_type( mtrans.IDENTITY )
 
 def get_xticks(self):
 'Return the x ticks as a list of locations'
@@ -1577,7 +1600,7 @@
 
 def get_xticklabels(self):
 'Get the xtick labels as a list of Text instances'
- return mpl.cbook.silent_list('Text xticklabel', self.xaxis.get_ticklabels())
+ return cbook.silent_list('Text xticklabel', self.xaxis.get_ticklabels())
 
 def set_xticklabels(self, labels, fontdict=None, **kwargs):
 """
@@ -1592,7 +1615,7 @@
 ACCEPTS: sequence of strings
 """
 return self.xaxis.set_ticklabels(labels, fontdict, **kwargs)
- set_xticklabels.__doc__ = mpl.cbook.dedent(set_xticklabels.__doc__) % mpl.artist.kwdocd
+ set_xticklabels.__doc__ = cbook.dedent(set_xticklabels.__doc__) % martist.kwdocd
 
 def get_ylim(self):
 'Get the y axis range [ymin, ymax]'
@@ -1621,7 +1644,7 @@
 """
 
 
- if ymax is None and mpl.cbook.iterable(ymin):
+ if ymax is None and iterable(ymin):
 ymin,ymax = ymin
 
 if ymin is not None:
@@ -1634,11 +1657,11 @@
 if ymin is None: ymin = old_ymin
 if ymax is None: ymax = old_ymax
 
- if (self.transData.get_funcy().get_type()==mpl.transforms.LOG10
+ if (self.transData.get_funcy().get_type()==mtrans.LOG10
 and min(ymin, ymax)<=0):
 raise ValueError('Cannot set nonpositive limits with log transform')
 
- ymin, ymax = mpl.transforms.nonsingular(ymin, ymax, increasing=False)
+ ymin, ymax = mtrans.nonsingular(ymin, ymax, increasing=False)
 self.viewLim.intervaly().set_bounds(ymin, ymax)
 if emit: self.callbacks.process('ylim_changed', self)
 
@@ -1671,20 +1694,20 @@
 assert(value.lower() in ('log', 'linear', ))
 
 if value == 'log':
- self.yaxis.set_major_locator(mpl.ticker.LogLocator(basey))
- self.yaxis.set_major_formatter(mpl.ticker.LogFormatterMathtext(basey))
- self.yaxis.set_minor_locator(mpl.ticker.LogLocator(basey,subsy))
- self.transData.get_funcy().set_type(mpl.transforms.LOG10)
+ self.yaxis.set_major_locator(mticker.LogLocator(basey))
+ self.yaxis.set_major_formatter(mticker.LogFormatterMathtext(basey))
+ self.yaxis.set_minor_locator(mticker.LogLocator(basey,subsy))
+ self.transData.get_funcy().set_type(mtrans.LOG10)
 miny, maxy = self.get_ylim()
 if min(miny, maxy)<=0:
 self.autoscale_view()
 
 elif value == 'linear':
- self.yaxis.set_major_locator(mpl.ticker.AutoLocator())
- self.yaxis.set_major_formatter(mpl.ticker.ScalarFormatter())
- self.yaxis.set_minor_locator(mpl.ticker.NullLocator())
- self.yaxis.set_minor_formatter(mpl.ticker.NullFormatter())
- self.transData.get_funcy().set_type( mpl.transforms.IDENTITY )
+ self.yaxis.set_major_locator(mticker.AutoLocator())
+ self.yaxis.set_major_formatter(mticker.ScalarFormatter())
+ self.yaxis.set_minor_locator(mticker.NullLocator())
+ self.yaxis.set_minor_formatter(mticker.NullFormatter())
+ self.transData.get_funcy().set_type( mtrans.IDENTITY )
 
 def get_yticks(self):
 'Return the y ticks as a list of locations'
@@ -1700,7 +1723,7 @@
 
 def get_yticklabels(self):
 'Get the ytick labels as a list of Text instances'
- return mpl.cbook.silent_list('Text yticklabel', self.yaxis.get_ticklabels())
+ return cbook.silent_list('Text yticklabel', self.yaxis.get_ticklabels())
 
 def set_yticklabels(self, labels, fontdict=None, **kwargs):
 """
@@ -1715,13 +1738,13 @@
 ACCEPTS: sequence of strings
 """
 return self.yaxis.set_ticklabels(labels, fontdict, **kwargs)
- set_yticklabels.__doc__ = mpl.cbook.dedent(set_yticklabels.__doc__) % mpl.artist.kwdocd
+ set_yticklabels.__doc__ = cbook.dedent(set_yticklabels.__doc__) % martist.kwdocd
 
 def toggle_log_lineary(self):
 'toggle between log and linear on the y axis'
 funcy = self.transData.get_funcy().get_type()
- if funcy==mpl.transforms.LOG10: self.set_yscale('linear')
- elif funcy==mpl.transforms.IDENTITY: self.set_yscale('log')
+ if funcy==mtrans.LOG10: self.set_yscale('linear')
+ elif funcy==mtrans.IDENTITY: self.set_yscale('log')
 
 def xaxis_date(self, tz=None):
 """Sets up x-axis ticks and labels that treat the x data as dates.
@@ -1730,13 +1753,13 @@
 """
 
 locator = self.xaxis.get_major_locator()
- if not isinstance(locator, mpl.dates.DateLocator):
- locator = mpl.dates.AutoDateLocator(tz)
+ if not isinstance(locator, mdates.DateLocator):
+ locator = mdates.AutoDateLocator(tz)
 self.xaxis.set_major_locator(locator)
 
 formatter = self.xaxis.get_major_formatter()
- if not isinstance(formatter, mpl.dates.DateFormatter):
- formatter = mpl.dates.AutoDateFormatter(locator)
+ if not isinstance(formatter, mdates.DateFormatter):
+ formatter = mdates.AutoDateFormatter(locator)
 self.xaxis.set_major_formatter(formatter)
 
 def yaxis_date(self, tz=None):
@@ -1746,13 +1769,13 @@
 """
 
 locator = self.yaxis.get_major_locator()
- if not isinstance(locator, mpl.dates.DateLocator):
- locator = mpl.dates.AutoDateLocator(tz)
+ if not isinstance(locator, mdates.DateLocator):
+ locator = mdates.AutoDateLocator(tz)
 self.yaxis.set_major_locator(locator)
 
 formatter = self.xaxis.get_major_formatter()
- if not isinstance(formatter, mpl.dates.DateFormatter):
- formatter = mpl.dates.AutoDateFormatter(locator)
+ if not isinstance(formatter, mdates.DateFormatter):
+ formatter = mdates.AutoDateFormatter(locator)
 self.yaxis.set_major_formatter(formatter)
 
 def format_xdata(self, x):
@@ -1836,7 +1859,7 @@
 lw, c = args
 else:
 raise ValueError('args must be a (linewidth, color) tuple')
- c =mpl.colors.colorConverter.to_rgba(c)
+ c =mcolors.colorConverter.to_rgba(c)
 self._cursorProps = lw, c
 
 
@@ -1924,7 +1947,7 @@
 if len(args)>1:
 raise DeprecationWarning(
 'New pick API implemented -- see API_CHANGES in the src distribution')
- mpl.artist.Artist.pick(self,args[0])
+ martist.Artist.pick(self,args[0])
 
 def __pick(self, x, y, trans=None, among=None):
 """
@@ -1969,7 +1992,7 @@
 verts = a.get_verts()
 tverts = a.get_transform().seq_xy_tups(verts)
 xt, yt = zip(*tverts)
- elif isinstance(a, mpl.lines.Line2D):
+ elif isinstance(a, mlines.Line2D):
 xdata = a.get_xdata(orig=False)
 ydata = a.get_ydata(orig=False)
 xt, yt = a.get_transform().numerix_x_y(xdata, ydata)
@@ -1979,7 +2002,7 @@
 artists = self.lines + self.patches + self.texts
 if callable(among):
 artists = filter(test, artists)
- elif mpl.cbook.iterable(among):
+ elif iterable(among):
 amongd = dict([(k,1) for k in among])
 artists = [a for a in artists if a in amongd]
 elif among is None:
@@ -2018,7 +2041,7 @@
 if fontdict is not None: self.title.update(fontdict)
 self.title.update(kwargs)
 return self.title
- set_title.__doc__ = mpl.cbook.dedent(set_title.__doc__) % mpl.artist.kwdocd
+ set_title.__doc__ = cbook.dedent(set_title.__doc__) % martist.kwdocd
 
 def set_xlabel(self, xlabel, fontdict=None, **kwargs):
 """
@@ -2037,7 +2060,7 @@
 if fontdict is not None: label.update(fontdict)
 label.update(kwargs)
 return label
- set_xlabel.__doc__ = mpl.cbook.dedent(set_xlabel.__doc__) % mpl.artist.kwdocd
+ set_xlabel.__doc__ = cbook.dedent(set_xlabel.__doc__) % martist.kwdocd
 
 def set_ylabel(self, ylabel, fontdict=None, **kwargs):
 """
@@ -2057,7 +2080,7 @@
 if fontdict is not None: label.update(fontdict)
 label.update(kwargs)
 return label
- set_ylabel.__doc__ = mpl.cbook.dedent(set_ylabel.__doc__) % mpl.artist.kwdocd
+ set_ylabel.__doc__ = cbook.dedent(set_ylabel.__doc__) % martist.kwdocd
 
 def text(self, x, y, s, fontdict=None,
 withdash=False, **kwargs):
@@ -2114,11 +2137,11 @@
 # the withdash kwarg and simply delegate whether there's
 # a dash to TextWithDash and dashlength.
 if withdash:
- t = mpl.text.TextWithDash(
+ t = mtext.TextWithDash(
 x=x, y=y, text=s,
 )
 else:
- t = mpl.text.Text(
+ t = mtext.Text(
 x=x, y=y, text=s,
 )
 self._set_artist_props(t)
@@ -2132,7 +2155,7 @@
 #if t.get_clip_on(): t.set_clip_box(self.bbox)
 if kwargs.has_key('clip_on'): t.set_clip_box(self.bbox)
 return t
- text.__doc__ = mpl.cbook.dedent(text.__doc__) % mpl.artist.kwdocd
+ text.__doc__ = cbook.dedent(text.__doc__) % martist.kwdocd
 
 def annotate(self, *args, **kwargs):
 """
@@ -2145,13 +2168,13 @@
 
 %(Annotation)s
 """
- a = mpl.text.Annotation(*args, **kwargs)
- a.set_transform(mpl.transforms.identity_transform())
+ a = mtext.Annotation(*args, **kwargs)
+ a.set_transform(mtrans.identity_transform())
 self._set_artist_props(a)
 if kwargs.has_key('clip_on'): a.set_clip_box(self.bbox)
 self.texts.append(a)
 return a
- annotate.__doc__ = mpl.cbook.dedent(annotate.__doc__) % mpl.artist.kwdocd
+ annotate.__doc__ = cbook.dedent(annotate.__doc__) % martist.kwdocd
 
 #### Lines and spans
 
@@ -2185,11 +2208,11 @@
 %(Line2D)s
 """
 
- trans = mpl.transforms.blend_xy_sep_transform( self.transAxes, self.transData)
+ trans = mtrans.blend_xy_sep_transform( self.transAxes, self.transData)
 l, = self.plot([xmin,xmax], [y,y], transform=trans, scalex=False, **kwargs)
 return l
 
- axhline.__doc__ = mpl.cbook.dedent(axhline.__doc__) % mpl.artist.kwdocd
+ axhline.__doc__ = cbook.dedent(axhline.__doc__) % martist.kwdocd
 
 def axvline(self, x=0, ymin=0, ymax=1, **kwargs):
 """
@@ -2221,11 +2244,11 @@
 %(Line2D)s
 """
 
- trans = mpl.transforms.blend_xy_sep_transform( self.transData, self.transAxes )
+ trans = mtrans.blend_xy_sep_transform( self.transData, self.transAxes )
 l, = self.plot([x,x], [ymin,ymax] , transform=trans, scaley=False, **kwargs)
 return l
 
- axvline.__doc__ = mpl.cbook.dedent(axvline.__doc__) % mpl.artist.kwdocd
+ axvline.__doc__ = cbook.dedent(axvline.__doc__) % martist.kwdocd
 
 def axhspan(self, ymin, ymax, xmin=0, xmax=1, **kwargs):
 """
@@ -2260,13 +2283,13 @@
 %(Polygon)s
 """
 # convert y axis units
- trans = mpl.transforms.blend_xy_sep_transform( self.transAxes, self.transData)
+ trans = mtrans.blend_xy_sep_transform( self.transAxes, self.transData)
 verts = (xmin, ymin), (xmin, ymax), (xmax, ymax), (xmax, ymin)
- p = mpl.patches.Polygon(verts, **kwargs)
+ p = mpatches.Polygon(verts, **kwargs)
 p.set_transform(trans)
 self.add_patch(p)
 return p
- axhspan.__doc__ = mpl.cbook.dedent(axhspan.__doc__) % mpl.artist.kwdocd
+ axhspan.__doc__ = cbook.dedent(axhspan.__doc__) % martist.kwdocd
 
 def axvspan(self, xmin, xmax, ymin=0, ymax=1, **kwargs):
 """
@@ -2300,13 +2323,13 @@
 %(Polygon)s
 """
 # convert x axis units
- trans = mpl.transforms.blend_xy_sep_transform(self.transData, self.transAxes)
+ trans = mtrans.blend_xy_sep_transform(self.transData, self.transAxes)
 verts = [(xmin, ymin), (xmin, ymax), (xmax, ymax), (xmax, ymin)]
- p = mpl.patches.Polygon(verts, **kwargs)
+ p = mpatches.Polygon(verts, **kwargs)
 p.set_transform(trans)
 self.add_patch(p)
 return p
- axvspan.__doc__ = mpl.cbook.dedent(axvspan.__doc__) % mpl.artist.kwdocd
+ axvspan.__doc__ = cbook.dedent(axvspan.__doc__) % martist.kwdocd
 
 
 def hlines(self, y, xmin, xmax, colors='k', linestyle='solid',
@@ -2331,10 +2354,16 @@
 raise DeprecationWarning(
 'hlines now uses a collections.LineCollection and not a list of Line2D to draw; see API_CHANGES')
 
- if not mpl.cbook.iterable(y): y = [y]
- if not mpl.cbook.iterable(xmin): xmin = [xmin]
- if not mpl.cbook.iterable(xmax): xmax = [xmax]
+ if not iterable(y): y = [y]
+ if not iterable(xmin): xmin = [xmin]
+ if not iterable(xmax): xmax = [xmax]
 y = npy.asarray(y)
+
+ if len(xmin)==1:
+ xmin = xmin*ones(y.shape, y.dtype)
+ if len(ymax)==1:
+ xmax = xmax*ones(y.shape, y.dtype)
+
 xmin = npy.asarray(xmin)
 xmax = npy.asarray(xmax)
 
@@ -2349,7 +2378,7 @@
 
 verts = [ ((thisxmin, thisy), (thisxmax, thisy))
 for thisxmin, thisxmax, thisy in zip(xmin, xmax, y)]
- coll = mpl.collections.LineCollection(verts, colors=colors,
+ coll = mcoll.LineCollection(verts, colors=colors,
 linestyle=linestyle, label=label)
 self.add_collection(coll)
 
@@ -2369,7 +2398,7 @@
 
 
 return coll
- hlines.__doc__ = mpl.cbook.dedent(hlines.__doc__)
+ hlines.__doc__ = cbook.dedent(hlines.__doc__)
 
 def vlines(self, x, ymin, ymax, colors='k', linestyle='solid',
 label='', **kwargs):
@@ -2400,9 +2429,9 @@
 self._process_unit_info(xdata=x, ydata=ymin, kwargs=kwargs)
 
 
- if not mpl.cbook.iterable(x): x = [x]
- if not mpl.cbook.iterable(ymin): ymin = [ymin]
- if not mpl.cbook.iterable(ymax): ymax = [ymax]
+ if not iterable(x): x = [x]
+ if not iterable(ymin): ymin = [ymin]
+ if not iterable(ymax): ymax = [ymax]
 x = npy.asarray(x)
 ymin = npy.asarray(ymin)
 ymax = npy.asarray(ymax)
@@ -2424,7 +2453,7 @@
 verts = [ ((thisx, thisymin), (thisx, thisymax))
 for thisx, (thisymin, thisymax) in zip(x,Y)]
 #print 'creating line collection'
- coll = mpl.collections.LineCollection(verts, colors=colors,
+ coll = mcoll.LineCollection(verts, colors=colors,
 linestyle=linestyle, label=label)
 self.add_collection(coll)
 coll.update(kwargs)
@@ -2432,7 +2461,7 @@
 minx = x.min()
 maxx = x.max()
 miny = min(ymin.min(), ymax.min())
- maxy = max(ymax.max(), ymax.max())
+ maxy = max(ymin.max(), ymax.max())
 minx, maxx = self.convert_xunits((minx, maxx))
 miny, maxy = self.convert_yunits((miny, maxy))
 corners = (minx, miny), (maxx, maxy)
@@ -2440,7 +2469,7 @@
 self.autoscale_view()
 
 return coll
- vlines.__doc__ = mpl.cbook.dedent(vlines.__doc__) % mpl.artist.kwdocd
+ vlines.__doc__ = cbook.dedent(vlines.__doc__) % martist.kwdocd
 
 #### Basic plotting
 def plot(self, *args, **kwargs):
@@ -2555,7 +2584,7 @@
 self.autoscale_view(scalex=scalex, scaley=scaley)
 return lines
 
- plot.__doc__ = mpl.cbook.dedent(plot.__doc__) % mpl.artist.kwdocd
+ plot.__doc__ = cbook.dedent(plot.__doc__) % martist.kwdocd
 
 def plot_date(self, x, y, fmt='bo', tz=None, xdate=True, ydate=False,
 **kwargs):
@@ -2604,7 +2633,7 @@
 self.autoscale_view()
 
 return ret
- plot_date.__doc__ = mpl.cbook.dedent(plot_date.__doc__) % mpl.artist.kwdocd
+ plot_date.__doc__ = cbook.dedent(plot_date.__doc__) % martist.kwdocd
 
 
 def loglog(self, *args, **kwargs):
@@ -2652,7 +2681,7 @@
 self._hold = b # restore the hold
 
 return l
- loglog.__doc__ = mpl.cbook.dedent(loglog.__doc__) % mpl.artist.kwdocd
+ loglog.__doc__ = cbook.dedent(loglog.__doc__) % martist.kwdocd
 
 def semilogx(self, *args, **kwargs):
 """
@@ -2685,7 +2714,7 @@
 l = self.plot(*args, **kwargs)
 self._hold = b # restore the hold
 return l
- semilogx.__doc__ = mpl.cbook.dedent(semilogx.__doc__) % mpl.artist.kwdocd
+ semilogx.__doc__ = cbook.dedent(semilogx.__doc__) % martist.kwdocd
 
 def semilogy(self, *args, **kwargs):
 """
@@ -2719,7 +2748,7 @@
 self._hold = b # restore the hold
 
 return l
- semilogy.__doc__ = mpl.cbook.dedent(semilogy.__doc__) % mpl.artist.kwdocd
+ semilogy.__doc__ = cbook.dedent(semilogy.__doc__) % martist.kwdocd
 
 def acorr(self, x, **kwargs):
 """
@@ -2754,9 +2783,9 @@
 See the respective function for documentation on valid kwargs
 """
 return self.xcorr(x, x, **kwargs)
- acorr.__doc__ = mpl.cbook.dedent(acorr.__doc__) % mpl.artist.kwdocd
+ acorr.__doc__ = cbook.dedent(acorr.__doc__) % martist.kwdocd
 
- def xcorr(self, x, y, normed=False, detrend=mpl.mlab.detrend_none, usevlines=False,
+ def xcorr(self, x, y, normed=False, detrend=mlab.detrend_none, usevlines=False,
 maxlags=None, **kwargs):
 """
 XCORR(x, y, normed=False, detrend=mlab.detrend_none, usevlines=False, **kwargs):
@@ -2821,7 +2850,7 @@
 a, = self.plot(lags, c, **kwargs)
 b = None
 return lags, c, a, b
- xcorr.__doc__ = mpl.cbook.dedent(xcorr.__doc__) % mpl.artist.kwdocd
+ xcorr.__doc__ = cbook.dedent(xcorr.__doc__) % martist.kwdocd
 
 def legend(self, *args, **kwargs):
 """
@@ -2893,9 +2922,9 @@
 handles = self.lines[:]
 handles.extend(self.patches)
 handles.extend([c for c in self.collections
- if isinstance(c, mpl.collections.LineCollection)])
+ if isinstance(c, mcoll.LineCollection)])
 handles.extend([c for c in self.collections
- if isinstance(c, mpl.collections.RegularPolyCollection)])
+ if isinstance(c, mcoll.RegularPolyCollection)])
 return handles
 
 if len(args)==0:
@@ -2916,7 +2945,7 @@
 handles = [h for h, label in zip(get_handles(), labels)]
 
 elif len(args)==2:
- if mpl.cbook.is_string_like(args[1]) or isinstance(args[1], int):
+ if is_string_like(args[1]) or isinstance(args[1], int):
 # LABELS, LOC
 labels, loc = args
 handles = [h for h, label in zip(get_handles(), labels)]
@@ -2933,8 +2962,8 @@
 raise TypeError('Invalid arguments to legend')
 
 
- handles = mpl.cbook.flatten(handles)
- self.legend_ = mpl.legend.Legend(self, handles, labels, **kwargs)
+ handles = cbook.flatten(handles)
+ self.legend_ = mlegend.Legend(self, handles, labels, **kwargs)
 return self.legend_
 
 
@@ -3011,7 +3040,7 @@
 if not self._hold: self.cla()
 
 def make_iterable(x):
- if not mpl.cbook.iterable(x):
+ if not iterable(x):
 return [x]
 else:
 return x
@@ -3071,24 +3100,24 @@
 
 # if color looks like a color string, an RGB tuple or a
 # scalar, then repeat it by nbars
- if (mpl.cbook.is_string_like(color) or
- (mpl.cbook.iterable(color) and len(color)==3 and nbars!=3) or
- not mpl.cbook.iterable(color)):
+ if (is_string_like(color) or
+ (iterable(color) and len(color)==3 and nbars!=3) or
+ not iterable(color)):
 color = [color]*nbars
 
 # if edgecolor looks like a color string, an RGB tuple or a
 # scalar, then repeat it by nbars
- if (mpl.cbook.is_string_like(edgecolor) or
- (mpl.cbook.iterable(edgecolor) and len(edgecolor)==3 and nbars!=3) or
- not mpl.cbook.iterable(edgecolor)):
+ if (is_string_like(edgecolor) or
+ (iterable(edgecolor) and len(edgecolor)==3 and nbars!=3) or
+ not iterable(edgecolor)):
 edgecolor = [edgecolor]*nbars
 
 if yerr is not None:
- if not mpl.cbook.iterable(yerr):
+ if not iterable(yerr):
 yerr = [yerr]*nbars
 
 if xerr is not None:
- if not mpl.cbook.iterable(xerr):
+ if not iterable(xerr):
 xerr = [xerr]*nbars
 
 assert len(left)==nbars, "argument 'left' must be %d or scalar" % nbars
@@ -3139,7 +3168,7 @@
 if w<0:
 l += w
 w = abs(w)
- r = mpl.patches.Rectangle(
+ r = mpatches.Rectangle(
 xy=(l, b), width=w, height=h,
 facecolor=c,
 edgecolor=e,
@@ -3184,7 +3213,7 @@
 self.dataLim.intervaly().set_bounds(ymin, ymax)
 self.autoscale_view()
 return patches
- bar.__doc__ = mpl.cbook.dedent(bar.__doc__) % mpl.artist.kwdocd
+ bar.__doc__ = cbook.dedent(bar.__doc__) % martist.kwdocd
 
 def barh(self, bottom, width, height=0.8, left=None, **kwargs):
 """
@@ -3246,7 +3275,7 @@
 orientation='horizontal', **kwargs)
 return patches
 
- barh.__doc__ = mpl.cbook.dedent(barh.__doc__) % mpl.artist.kwdocd
+ barh.__doc__ = cbook.dedent(barh.__doc__) % martist.kwdocd
 
 def broken_barh(self, xranges, yrange, **kwargs):
 """
@@ -3264,13 +3293,13 @@
 facecolors='black', 'red', 'green'
 
 """
- col = mpl.collections.BrokenBarHCollection(xranges, yrange, **kwargs)
+ col = mcoll.BrokenBarHCollection(xranges, yrange, **kwargs)
 self.add_collection(col, autolim=True)
 self.autoscale_view()
 
 return col
 
- broken_barh.__doc__ = mpl.cbook.dedent(broken_barh.__doc__) % mpl.artist.kwdocd
+ broken_barh.__doc__ = cbook.dedent(broken_barh.__doc__) % martist.kwdocd
 
 def stem(self, x, y, linefmt='b-', markerfmt='bo', basefmt='r-'):
 """
@@ -3350,7 +3379,7 @@
 Return value:
 
 If autopct is None, return a list of (patches, texts), where patches
- is a sequence of mpl.patches.Wedge instances and texts is a
+ is a sequence of mpatches.Wedge instances and texts is a
 list of the label Text instnaces
 
 If autopct is not None, return (patches, texts, autotexts), where
@@ -3385,7 +3414,7 @@
 x += expl*math.cos(thetam)
 y += expl*math.sin(thetam)
 
- w = mpl.patches.Wedge((x,y), radius, 360.*theta1, 360.*theta2,
+ w = mpatches.Wedge((x,y), radius, 360.*theta1, 360.*theta2,
 facecolor=colors[i%len(colors)])
 slices.append(w)
 self.add_patch(w)
@@ -3395,7 +3424,7 @@
 # make sure to add a shadow after the call to
 # add_patch so the figure and transform props will be
 # set
- shad = mpl.patches.Shadow(w, -0.02, -0.02,
+ shad = mpatches.Shadow(w, -0.02, -0.02,
 #props={'facecolor':w.get_facecolor()}
 )
 shad.set_zorder(0.9*w.get_zorder())
@@ -3415,7 +3444,7 @@
 if autopct is not None:
 xt = x + pctdistance*radius*math.cos(thetam)
 yt = y + pctdistance*radius*math.sin(thetam)
- if mpl.cbook.is_string_like(autopct):
+ if is_string_like(autopct):
 s = autopct%(100.*frac)
 elif callable(autopct):
 s = autopct(100.*frac)
@@ -3501,18 +3530,18 @@
 if not self._hold: self.cla()
 
 # make sure all the args are iterable arrays
- if not mpl.cbook.iterable(x): x = npy.asarray([x])
+ if not iterable(x): x = npy.asarray([x])
 else: x = npy.asarray(x)
 
- if not mpl.cbook.iterable(y): y = npy.asarray([y])
+ if not iterable(y): y = npy.asarray([y])
 else: y = npy.asarray(y)
 
 if xerr is not None:
- if not mpl.cbook.iterable(xerr): xerr = npy.asarray([xerr])
+ if not iterable(xerr): xerr = npy.asarray([xerr])
 else: xerr = npy.asarray(xerr)
 
 if yerr is not None:
- if not mpl.cbook.iterable(yerr): yerr = npy.asarray([yerr])
+ if not iterable(yerr): yerr = npy.asarray([yerr])
 else: yerr = npy.asarray(yerr)
 
 l0 = None
@@ -3581,7 +3610,7 @@
 
 self.autoscale_view()
 return (l0, caplines, barcols)
- errorbar.__doc__ = mpl.cbook.dedent(errorbar.__doc__) % mpl.artist.kwdocd
+ errorbar.__doc__ = cbook.dedent(errorbar.__doc__) % martist.kwdocd
 
 def boxplot(self, x, notch=0, sym='b+', vert=1, whis=1.5,
 positions=None, widths=None):
@@ -3663,7 +3692,7 @@
 d = npy.ravel(x[i])
 row = len(d)
 # get median and quartiles
- q1, med, q3 = mpl.mlab.prctile(d,[25,50,75])
+ q1, med, q3 = mlab.prctile(d,[25,50,75])
 # get high extreme
 iq = q3 - q1
 hi_val = q3 + whis*iq
@@ -3870,16 +3899,16 @@
 # The inherent ambiguity is resolved in favor of color
 # mapping, not interpretation as rgb or rgba.
 
- if not mpl.cbook.is_string_like(c):
+ if not is_string_like(c):
 sh = npy.shape(c)
 if len(sh) == 1 and sh[0] == len(x):
 colors = None # use cmap, norm after collection is created
 else:
- colors = mpl.colors.colorConverter.to_rgba_list(c, alpha)
+ colors = mcolors.colorConverter.to_rgba_list(c, alpha)
 else:
- colors = mpl.colors.colorConverter.to_rgba_list(c, alpha)
+ colors = mcolors.colorConverter.to_rgba_list(c, alpha)
 
- if not mpl.cbook.iterable(s):
+ if not iterable(s):
 scales = (s,)
 else:
 scales = s
@@ -3895,14 +3924,14 @@
 marker = (verts, 0)
 verts = None
 
- if mpl.cbook.is_string_like(marker):
+ if is_string_like(marker):
 # the standard way to define symbols using a string character
 sym = syms.get(marker)
 if sym is None and verts is None:
 raise ValueError('Unknown marker symbol to scatter')
 numsides, rotation = syms[marker]
 
- elif mpl.cbook.iterable(marker):
+ elif iterable(marker):
 # accept marker to be:
 # (numsides, style, [angle])
 # or
@@ -3911,7 +3940,7 @@
 if len(marker)<2 or len(marker)>3:
 raise ValueError('Cannot create markersymbol from marker')
 
- if mpl.cbook.is_numlike(marker[0]):
+ if cbook.is_numlike(marker[0]):
 # (numsides, style, [angle])
 
 if len(marker)==2:
@@ -3931,7 +3960,7 @@
 if sym is not None:
 if not starlike:
 
- collection = mpl.collections.RegularPolyCollection(
+ collection = mcoll.RegularPolyCollection(
 self.figure.dpi,
 numsides, rotation, scales,
 facecolors = colors,
@@ -3941,7 +3970,7 @@
 transOffset = self.transData,
 )
 else:
- collection = mpl.collections.StarPolygonCollection(
+ collection = mcoll.StarPolygonCollection(
 self.figure.dpi,
 numsides, rotation, scales,
 facecolors = colors,
@@ -3962,7 +3991,7 @@
 else:
 # todo -- make this nx friendly
 verts = [verts*s for s in scales]
- collection = mpl.collections.PolyCollection(
+ collection = mcoll.PolyCollection(
 verts,
 facecolors = colors,
 edgecolors = edgecolors,
@@ -3970,13 +3999,13 @@
 offsets = zip(x,y),
 transOffset = self.transData,
 )
- collection.set_transform(mpl.transforms.identity_transform())
+ collection.set_transform(mtrans.identity_transform())
 collection.set_alpha(alpha)
 collection.update(kwargs)
 
 if colors is None:
- if norm is not None: assert(isinstance(norm, mpl.colors.Normalize))
- if cmap is not None: assert(isinstance(cmap, mpl.colors.Colormap))
+ if norm is not None: assert(isinstance(norm, mcolors.Normalize))
+ if cmap is not None: assert(isinstance(cmap, mcolors.Colormap))
 collection.set_array(npy.asarray(c))
 collection.set_cmap(cmap)
 collection.set_norm(norm)
@@ -4010,7 +4039,7 @@
 self.add_collection(collection)
 return collection
 
- scatter.__doc__ = mpl.cbook.dedent(scatter.__doc__) % mpl.artist.kwdocd
+ scatter.__doc__ = cbook.dedent(scatter.__doc__) % martist.kwdocd
 
 def scatter_classic(self, x, y, s=None, c='b'):
 """
@@ -4047,35 +4076,35 @@
 Optional kwargs control the arrow properties:
 %(Arrow)s
 """
- a = mpl.patches.FancyArrow(x, y, dx, dy, **kwargs)
+ a = mpatches.FancyArrow(x, y, dx, dy, **kwargs)
 self.add_artist(a)
 return a
- arrow.__doc__ = mpl.cbook.dedent(arrow.__doc__) % mpl.artist.kwdocd
+ arrow.__doc__ = cbook.dedent(arrow.__doc__) % martist.kwdocd
 
 def quiverkey(self, *args, **kw):
- qk = mpl.quiver.QuiverKey(*args, **kw)
+ qk = mquiver.QuiverKey(*args, **kw)
 self.add_artist(qk)
 return qk
- quiverkey.__doc__ = mpl.quiver.QuiverKey.quiverkey_doc
+ quiverkey.__doc__ = mquiver.QuiverKey.quiverkey_doc
 
 def quiver2(self, *args, **kw):
- q = mpl.quiver.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__ = mpl.quiver.Quiver.quiver_doc
+ quiver2.__doc__ = mquiver.Quiver.quiver_doc
 
 def quiver(self, *args, **kw):
- if (len(args) == 3 or len(args) == 5) and not mpl.cbook.iterable(args[-1]):
+ 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 mpl.colors.is_color_like(c):
+ 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__ = mpl.quiver.Quiver.quiver_doc
+ quiver.__doc__ = mquiver.Quiver.quiver_doc
 
 def quiver_classic(self, U, V, *args, **kwargs ):
 """
@@ -4119,12 +4148,12 @@
 # ( U, V )
 U = npy.asarray(U)
 V = npy.asarray(V)
- X,Y = mpl.mlab.meshgrid( npy.arange(U.shape[1]), npy.arange(U.shape[0]) )
+ 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 = mpl.mlab.meshgrid( npy.arange(U.shape[1]), npy.arange(U.shape[0]) )
+ 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:
@@ -4186,10 +4215,10 @@
 C = clr
 
 I = U.shape[0]
- arrows = [mpl.patches.FancyArrow(X[i],Y[i],U[i],V[i],0.1*S ).get_verts()
+ arrows = [mpatches.FancyArrow(X[i],Y[i],U[i],V[i],0.1*S ).get_verts()
 for i in xrange(I)]
 
- collection = mpl.collections.PolyCollection(
+ collection = mcoll.PolyCollection(
 arrows,
 edgecolors = 'None',
 antialiaseds = (1,),
@@ -4255,7 +4284,7 @@
 patches.append( poly )
 self.autoscale_view()
 return patches
- fill.__doc__ = mpl.cbook.dedent(fill.__doc__) % mpl.artist.kwdocd
+ fill.__doc__ = cbook.dedent(fill.__doc__) % martist.kwdocd
 #### plotting z(x,y): imshow, pcolor and relatives, contour
 
 
@@ -4299,7 +4328,7 @@
 The value for each component of MxNx3 and MxNx4 float arrays should be
 in the range 0.0 to 1.0; MxN float arrays may be normalised.
 
- A mpl.image.AxesImage instance is returned
+ A image.AxesImage instance is returned
 
 The following kwargs are allowed:
 
@@ -4320,7 +4349,7 @@
 image.interpolation. See also th the filternorm and
 filterrad parameters
 
- * norm is a mpl.colors.Normalize instance; default is
+ * norm is a mcolors.Normalize instance; default is
 normalization(). This scales luminance -> 0-1 (only used for an
 MxN float array).
 
@@ -4354,16 +4383,16 @@
 parameter, ie when interpolation is one of: 'sinc',
 'lanczos' or 'blackman'
 
- Additional kwargs are mpl.artist properties
+ Additional kwargs are martist properties
 """
 
 if not self._hold: self.cla()
 
- if norm is not None: assert(isinstance(norm, mpl.colors.Normalize))
- if cmap is not None: assert(isinstance(cmap, mpl.colors.Colormap))
+ if norm is not None: assert(isinstance(norm, mcolors.Normalize))
+ if cmap is not None: assert(isinstance(cmap, mcolors.Colormap))
 if aspect is None: aspect = rcParams['image.aspect']
 self.set_aspect(aspect)
- im = mpl.image.AxesImage(self, cmap, norm, interpolation, origin, extent,
+ im = mimage.AxesImage(self, cmap, norm, interpolation, origin, extent,
 filternorm=filternorm,
 filterrad=filterrad, **kwargs)
 
@@ -4423,9 +4452,9 @@
 Optional keyword args are shown with their defaults below (you must
 use kwargs for these):
 
- * cmap = mpl.cm.jet : a cm Colormap instance from mpl.cm
+ * cmap = cm.jet : a cm Colormap instance from cm
 
- * norm = Normalize() : mpl.colors.Normalize instance
+ * norm = Normalize() : mcolors.Normalize instance
 is used to scale luminance data to 0,1.
 
 * vmin=None and vmax=None : vmin and vmax are used in conjunction
@@ -4438,7 +4467,7 @@
 
 * alpha=1.0 : the alpha blending value
 
- Return value is a mpl.collections.PatchCollection
+ Return value is a mcoll.PatchCollection
 object
 
 Grid Orientation
@@ -4497,7 +4526,7 @@
 if len(args)==1:
 C = args[0]
 numRows, numCols = C.shape
- X, Y = mpl.mlab.meshgrid(npy.arange(numCols+1), npy.arange(numRows+1) )
+ X, Y = mlab.meshgrid(npy.arange(numCols+1), npy.arange(numRows+1) )
 elif len(args)==3:
 X, Y, C = args
 numRows, numCols = C.shape
@@ -4553,7 +4582,7 @@
 else:
 edgecolors = 'None'
 
- collection = mpl.collections.PolyCollection(
+ collection = mcoll.PolyCollection(
 verts,
 edgecolors = edgecolors,
 antialiaseds = (0,),
@@ -4563,8 +4592,8 @@
 
 collection.set_alpha(alpha)
 collection.set_array(C)
- if norm is not None: assert(isinstance(norm, mpl.colors.Normalize))
- if cmap is not None: assert(isinstance(cmap, mpl.colors.Colormap))
+ if norm is not None: assert(isinstance(norm, mcolors.Normalize))
+ if cmap is not None: assert(isinstance(cmap, mcolors.Colormap))
 collection.set_cmap(cmap)
 collection.set_norm(norm)
 if vmin is not None or vmax is not None:
@@ -4585,7 +4614,7 @@
 self.autoscale_view()
 self.add_collection(collection)
 return collection
- pcolor.__doc__ = mpl.cbook.dedent(pcolor.__doc__) % mpl.artist.kwdocd
+ pcolor.__doc__ = cbook.dedent(pcolor.__doc__) % martist.kwdocd
 
 def pcolormesh(self, *args, **kwargs):
 """
@@ -4646,7 +4675,7 @@
 if len(args)==1:
 C = args[0]
 numRows, numCols = C.shape
- X, Y = mpl.mlab.meshgrid(npy.arange(numCols+1), npy.arange(numRows+1) )
+ X, Y = mlab.meshgrid(npy.arange(numCols+1), npy.arange(numRows+1) )
 elif len(args)==3:
 X, Y, C = args
 numRows, numCols = C.shape
@@ -4674,12 +4703,12 @@
 else:
 showedges = 0
 
- collection = mpl.collections.QuadMesh(
+ collection = mcoll.QuadMesh(
 Nx - 1, Ny - 1, coords, showedges, **kwargs)
 collection.set_alpha(alpha)
 collection.set_array(C)
- if norm is not None: assert(isinstance(norm, mpl.colors.Normalize))
- if cmap is not None: assert(isinstance(cmap, mpl.colors.Colormap))
+ if norm is not None: assert(isinstance(norm, mcolors.Normalize))
+ if cmap is not None: assert(isinstance(cmap, mcolors.Colormap))
 collection.set_cmap(cmap)
 collection.set_norm(norm)
 if vmin is not None or vmax is not None:
@@ -4699,21 +4728,21 @@
 self.autoscale_view()
 self.add_collection(collection)
 return collection
- pcolormesh.__doc__ = mpl.cbook.dedent(pcolormesh.__doc__) % mpl.artist.kwdocd
+ pcolormesh.__doc__ = cbook.dedent(pcolormesh.__doc__) % martist.kwdocd
 
 def contour(self, *args, **kwargs):
 kwargs['filled'] = False
- return mpl.contour.ContourSet(self, *args, **kwargs)
- contour.__doc__ = mpl.contour.ContourSet.contour_doc
+ return mcontour.ContourSet(self, *args, **kwargs)
+ contour.__doc__ = mcontour.ContourSet.contour_doc
 
 def contourf(self, *args, **kwargs):
 kwargs['filled'] = True
- return mpl.contour.ContourSet(self, *args, **kwargs)
- contourf.__doc__ = mpl.contour.ContourSet.contour_doc
+ return mcontour.ContourSet(self, *args, **kwargs)
+ contourf.__doc__ = mcontour.ContourSet.contour_doc
 
 def clabel(self, CS, *args, **kwargs):
 return CS.clabel(*args, **kwargs)
- clabel.__doc__ = mpl.contour.ContourSet.clabel.__doc__
+ ...
 
[truncated message content]
Revision: 3553
 http://matplotlib.svn.sourceforge.net/matplotlib/?rev=3553&view=rev
Author: dsdale
Date: 2007年07月17日 09:37:14 -0700 (2007年7月17日)
Log Message:
-----------
add some comments to new RcParams class
Modified Paths:
--------------
 trunk/matplotlib/lib/matplotlib/__init__.py
Modified: trunk/matplotlib/lib/matplotlib/__init__.py
===================================================================
--- trunk/matplotlib/lib/matplotlib/__init__.py	2007年07月17日 15:35:41 UTC (rev 3552)
+++ trunk/matplotlib/lib/matplotlib/__init__.py	2007年07月17日 16:37:14 UTC (rev 3553)
@@ -531,13 +531,14 @@
 class RcParams(dict):
 
 """A dictionary object including validation
+ 
+ validating functions are defined and associated with rc parameters in
+ rcsetup.py
 """
 
 validate = dict([ (key, converter) for key, (default, converter) in \
 defaultParams.iteritems() ])
 
- fail_on_error = False
- 
 def __setitem__(self, key, val):
 try:
 if key in _deprecated_map.keys():
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
From: <ds...@us...> - 2007年07月17日 15:35:52
Revision: 3552
 http://matplotlib.svn.sourceforge.net/matplotlib/?rev=3552&view=rev
Author: dsdale
Date: 2007年07月17日 08:35:41 -0700 (2007年7月17日)
Log Message:
-----------
validate rcParams
Modified Paths:
--------------
 trunk/matplotlib/CHANGELOG
 trunk/matplotlib/lib/matplotlib/__init__.py
 trunk/matplotlib/lib/matplotlib/rcsetup.py
Modified: trunk/matplotlib/CHANGELOG
===================================================================
--- trunk/matplotlib/CHANGELOG	2007年07月17日 13:40:56 UTC (rev 3551)
+++ trunk/matplotlib/CHANGELOG	2007年07月17日 15:35:41 UTC (rev 3552)
@@ -1,3 +1,5 @@
+2007年07月17日 added validation to setting and changing rcParams - DSD
+
 2007年07月17日 bugfix segfault in transforms module. Thanks Ben North for
 the patch. - ADS
 
Modified: trunk/matplotlib/lib/matplotlib/__init__.py
===================================================================
--- trunk/matplotlib/lib/matplotlib/__init__.py	2007年07月17日 13:40:56 UTC (rev 3551)
+++ trunk/matplotlib/lib/matplotlib/__init__.py	2007年07月17日 15:35:41 UTC (rev 3552)
@@ -518,34 +518,6 @@
 return fname
 
 
-def validate_key(key, val, line, cnt, fname, fail_on_error):
- if key in _deprecated_map.keys():
- alt = _deprecated_map[key]
- warnings.warn('%s is deprecated in matplotlibrc - use %s instead.' % (key, alt))
- key = alt
-
- if not defaultParams.has_key(key):
- print >> sys.stderr, """\
-Bad key "%s" on line %d in
-%s.
-You probably need to get an updated matplotlibrc file from
-http://matplotlib.sf.net/matplotlibrc or from the matplotlib source
-distribution""" % (key, cnt, fname)
- return None
-
- default, converter = defaultParams[key]
-
- if fail_on_error:
- return converter(val) # try to convert to proper type or raise
- else:
- try: cval = converter(val) # try to convert to proper type or raise
- except Exception, msg:
- warnings.warn('Bad val "%s" on line #%d\n\t"%s"\n\tin file "%s"\n\t%s' % (
- val, cnt, line, fname, msg))
- return None
- else:
- return cval
-
 _deprecated_map = {
 'text.fontstyle': 'font.style',
 'text.fontangle': 'font.style',
@@ -555,6 +527,31 @@
 'tick.size' : 'tick.major.size',
 }
 
+
+class RcParams(dict):
+ 
+ """A dictionary object including validation
+ """
+ 
+ validate = dict([ (key, converter) for key, (default, converter) in \
+ defaultParams.iteritems() ])
+ 
+ fail_on_error = False
+ 
+ def __setitem__(self, key, val):
+ try:
+ if key in _deprecated_map.keys():
+ alt = _deprecated_map[key]
+ warnings.warn('%s is deprecated in matplotlibrc. Use %s \
+instead.'% (key, alt))
+ key = alt
+ cval = self.validate[key](val)
+ dict.__setitem__(self, key, cval)
+ except KeyError:
+ raise KeyError('%s is not a valid rc parameter.\
+See rcParams.keys() for a list of valid parameters.'%key)
+
+
 def rc_params(fail_on_error=False):
 'Return the default params updated from the values in the rc file'
 
@@ -573,7 +570,8 @@
 if not strippedline: continue
 tup = strippedline.split(':',1)
 if len(tup) !=2:
- warnings.warn('Illegal line #%d\n\t%s\n\tin file "%s"' % (cnt, line, fname))
+ warnings.warn('Illegal line #%d\n\t%s\n\tin file "%s"'%\
+ (cnt, line, fname))
 continue
 key, val = tup
 key = key.strip()
@@ -582,35 +580,53 @@
 warnings.warn('Duplicate key in file "%s", line #%d'%(fname,cnt))
 rc_temp[key] = (val, line, cnt)
 
- ret = dict([ (key,default) for key, (default, converter) in defaultParams.iteritems() ])
+ ret = RcParams([ (key, default) for key, (default, converter) in \
+ defaultParams.iteritems() ])
 
 for key in ('verbose.level', 'verbose.fileo'):
 if key in rc_temp:
 val, line, cnt = rc_temp.pop(key)
- cval = validate_key(key, val, line, cnt, fname, fail_on_error)
- if cval is not None:
- ret[key] = cval
+ if fail_on_error:
+ ret[key] = val # try to convert to proper type or raise
+ else:
+ try: ret[key] = val # try to convert to proper type or skip
+ except Exception, msg:
+ warnings.warn('Bad val "%s" on line #%d\n\t"%s"\n\tin file \
+"%s"\n\t%s' % (val, cnt, line, fname, msg))
 
 verbose.set_level(ret['verbose.level'])
 verbose.set_fileo(ret['verbose.fileo'])
 
 for key, (val, line, cnt) in rc_temp.iteritems():
- cval = validate_key(key, val, line, cnt, fname, fail_on_error)
- if cval is not None:
- ret[key] = cval
+ if defaultParams.has_key(key):
+ if fail_on_error:
+ ret[key] = val # try to convert to proper type or raise
+ else:
+ try: ret[key] = val # try to convert to proper type or skip
+ except Exception, msg:
+ warnings.warn('Bad val "%s" on line #%d\n\t"%s"\n\tin file \
+"%s"\n\t%s' % (val, cnt, line, fname, msg))
+ else:
+ print >> sys.stderr, """
+Bad key "%s" on line %d in
+%s.
+You probably need to get an updated matplotlibrc file from
+http://matplotlib.sf.net/matplotlibrc or from the matplotlib source
+distribution""" % (key, cnt, fname)
 
 if ret['datapath'] is None:
 ret['datapath'] = get_data_path()
 
 verbose.report('loaded rc file %s'%fname)
-
+ 
 return ret
 
 
 # this is the instance used by the matplotlib classes
 rcParams = rc_params()
 
-rcParamsDefault = dict(rcParams.items()) # a copy
+rcParamsDefault = RcParams([ (key, default) for key, (default, converter) in \
+ defaultParams.iteritems() ])
 
 rcParams['ps.usedistiller'] = checkdep_ps_distiller(rcParams['ps.usedistiller'])
 rcParams['text.usetex'] = checkdep_usetex(rcParams['text.usetex'])
Modified: trunk/matplotlib/lib/matplotlib/rcsetup.py
===================================================================
--- trunk/matplotlib/lib/matplotlib/rcsetup.py	2007年07月17日 13:40:56 UTC (rev 3551)
+++ trunk/matplotlib/lib/matplotlib/rcsetup.py	2007年07月17日 15:35:41 UTC (rev 3552)
@@ -36,8 +36,8 @@
 'Convert b to a boolean or raise'
 if type(b) is str:
 b = b.lower()
- if b in ('t', 'y', 'yes', 'true', '1', 1, True): return True
- elif b in ('f', 'n', 'no', 'false', '0', 0, False): return False
+ if b in ('t', 'y', 'yes', 'on', 'true', '1', 1, True): return True
+ elif b in ('f', 'n', 'no', 'off', 'false', '0', 0, False): return False
 else:
 raise ValueError('Could not convert "%s" to boolean' % b)
 
@@ -142,12 +142,15 @@
 
 if len(s)==6 and s.isalnum(): # looks like hex
 return '#' + s
+ 
+ if len(s)==7 and s.startswith('#') and s[1:].isalnum():
+ return s
 
 if s.isalpha():
 #assuming a color name, hold on
 return s
 
- raise ValueError('"s" does not look like color arg')
+ raise ValueError('%s does not look like color arg'%s)
 
 def validate_stringlist(s):
 'return a list'
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
Revision: 3551
 http://matplotlib.svn.sourceforge.net/matplotlib/?rev=3551&view=rev
Author: dsdale
Date: 2007年07月17日 06:40:56 -0700 (2007年7月17日)
Log Message:
-----------
ticker.py import numpy rather than numerix
Modified Paths:
--------------
 trunk/matplotlib/lib/matplotlib/ticker.py
Modified: trunk/matplotlib/lib/matplotlib/ticker.py
===================================================================
--- trunk/matplotlib/lib/matplotlib/ticker.py	2007年07月17日 12:55:05 UTC (rev 3550)
+++ trunk/matplotlib/lib/matplotlib/ticker.py	2007年07月17日 13:40:56 UTC (rev 3551)
@@ -113,8 +113,7 @@
 import sys, os, re, time, math, warnings
 from mlab import linspace
 from matplotlib import verbose, rcParams
-from numerix import absolute, arange, array, asarray, Float, floor, log, \
- logical_and, nonzero, ones, take, zeros
+from numpy import absolute, arange, array, asarray, floor, log, logical_and, nonzero, ones, take, zeros
 from matplotlib.numerix.mlab import amin, amax, std, mean
 from matplotlib.mlab import frange
 from cbook import strip_math
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
Revision: 3550
 http://matplotlib.svn.sourceforge.net/matplotlib/?rev=3550&view=rev
Author: mdboom
Date: 2007年07月17日 05:55:05 -0700 (2007年7月17日)
Log Message:
-----------
Fix charOverChars (\angstrom)
Modified Paths:
--------------
 branches/mathtext_mgd/lib/matplotlib/mathtext.py
Modified: branches/mathtext_mgd/lib/matplotlib/mathtext.py
===================================================================
--- branches/mathtext_mgd/lib/matplotlib/mathtext.py	2007年07月17日 12:40:56 UTC (rev 3549)
+++ branches/mathtext_mgd/lib/matplotlib/mathtext.py	2007年07月17日 12:55:05 UTC (rev 3550)
@@ -971,11 +971,11 @@
 raise NotImplementedError('derived must override')
 
 def determine_font(self, font_stack):
- 'a first pass to determine the font of this element (one of tt, it, rm , cal)'
+ 'a first pass to determine the font of this element (one of tt, it, rm , cal, bf, sf)'
 raise NotImplementedError('derived must override')
 
 def set_font(self, font):
- 'set the font (one of tt, it, rm , cal)'
+ 'set the font (one of tt, it, rm, cal, bf, sf)'
 raise NotImplementedError('derived must override')
 
 def render(self):
@@ -1143,6 +1143,8 @@
 pass
 
 class SymbolElement(Element):
+ hardcoded_font = False
+
 def __init__(self, sym):
 Element.__init__(self)
 self.sym = sym
@@ -1150,17 +1152,20 @@
 self.widthm = 1 # the width of an m; will be resized below
 
 def determine_font(self, font_stack):
- 'set the font (one of tt, it, rm, cal)'
+ 'set the font (one of tt, it, rm, cal, bf, sf)'
 self.set_font(font_stack[-1])
 for neighbor_type in ('above', 'below', 'subscript', 'superscript'):
 neighbor = self.neighbors.get(neighbor_type)
 if neighbor is not None:
 neighbor.determine_font(font_stack)
 
- def set_font(self, font):
- # space doesn't care about font, only size
- assert not hasattr(self, 'font')
- self.font = font
+ def set_font(self, font, hardcoded=False):
+ if hardcoded:
+ self.hardcoded_font = True
+ self.font = font
+ if not self.hardcoded_font:
+ assert not hasattr(self, 'font')
+ self.font = font
 
 def set_origin(self, ox, oy):
 Element.set_origin(self, ox, oy)
@@ -1355,26 +1360,25 @@
 #print "symbol", toks
 
 s = toks[0]
- # MGDTODO: This clause is probably broken due to font changes
-# if charOverChars.has_key(s):
-# under, over, pad = charOverChars[s]
-# font, tok, scale = under
-# sym = SymbolElement(tok)
-# if font is not None:
-# sym.set_font(font)
-# sym.set_scale(scale)
-# sym.set_pady(pad)
+ if charOverChars.has_key(s):
+ under, over, pad = charOverChars[s]
+ font, tok, scale = under
+ sym = SymbolElement(tok)
+ if font is not None:
+ sym.set_font(font, hardcoded=True)
+ sym.set_scale(scale)
+ sym.set_pady(pad)
 
-# font, tok, scale = over
-# sym2 = SymbolElement(tok)
-# if font is not None:
-# sym2.set_font(font)
-# sym2.set_scale(scale)
+ font, tok, scale = over
+ sym2 = SymbolElement(tok)
+ if font is not None:
+ sym2.set_font(font, hardcoded=True)
+ sym2.set_scale(scale)
 
-# sym.neighbors['above'] = sym2
-# self.symbols.append(sym2)
-# else:
- sym = SymbolElement(toks[0])
+ sym.neighbors['above'] = sym2
+ self.symbols.append(sym2)
+ else:
+ sym = SymbolElement(toks[0])
 self.symbols.append(sym)
 
 return [sym]
@@ -1673,8 +1677,8 @@
 | subsuper
 ).setParseAction(handler.expression).setName("expression")
 
+ 
 
-
 ####
 
 
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
Revision: 3549
 http://matplotlib.svn.sourceforge.net/matplotlib/?rev=3549&view=rev
Author: mdboom
Date: 2007年07月17日 05:40:56 -0700 (2007年7月17日)
Log Message:
-----------
Add support for bf (bold) and sf (sans serif) math fonts.
Modified Paths:
--------------
 branches/mathtext_mgd/lib/matplotlib/mathtext.py
Added Paths:
-----------
 branches/mathtext_mgd/lib/matplotlib/mpl-data/fonts/ttf/cmb10.ttf
 branches/mathtext_mgd/lib/matplotlib/mpl-data/fonts/ttf/cmss10.ttf
Modified: branches/mathtext_mgd/lib/matplotlib/mathtext.py
===================================================================
--- branches/mathtext_mgd/lib/matplotlib/mathtext.py	2007年07月17日 12:21:59 UTC (rev 3548)
+++ branches/mathtext_mgd/lib/matplotlib/mathtext.py	2007年07月17日 12:40:56 UTC (rev 3549)
@@ -475,6 +475,8 @@
 'rm' : 'cmr10.ttf',
 'tt' : 'cmtt10.ttf',
 'it' : 'cmmi10.ttf',
+ 'bf' : 'cmb10.ttf',
+ 'sf' : 'cmss10.ttf',
 None : 'cmmi10.ttf',
 }
 
@@ -547,7 +549,7 @@
 Use the Bakoma true type fonts for rendering
 """
 fnames = ('cmmi10', 'cmsy10', 'cmex10',
- 'cmtt10', 'cmr10')
+ 'cmtt10', 'cmr10', 'cmb10', 'cmss10')
 # allocate a new set of fonts
 basepath = os.path.join( get_data_path(), 'fonts', 'ttf' )
 
@@ -555,6 +557,8 @@
 'rm' : 'cmr10',
 'tt' : 'cmtt10',
 'it' : 'cmmi10',
+ 'bf' : 'cmb10',
+ 'sf' : 'cmss10',
 None : 'cmmi10',
 }
 
@@ -694,7 +698,7 @@
 Use the Bakoma postscript fonts for rendering to backend_ps
 """
 facenames = ('cmmi10', 'cmsy10', 'cmex10',
- 'cmtt10', 'cmr10')
+ 'cmtt10', 'cmr10', 'cmb10', 'cmss10')
 # allocate a new set of fonts
 basepath = os.path.join( get_data_path(), 'fonts', 'ttf' )
 
@@ -702,6 +706,8 @@
 'rm' : 'cmr10',
 'tt' : 'cmtt10',
 'it' : 'cmmi10',
+ 'bf' : 'cmb10',
+ 'sf' : 'cmss10',
 None : 'cmmi10',
 }
 
@@ -1566,9 +1572,8 @@
 | times
 | div)
 
-fontname = oneOf("rm cal it tt")
- # mathbf and mathsf not supported yet
-latex2efont = oneOf("mathrm mathcal mathit mathtt")
+fontname = oneOf("rm cal it tt sf bf")
+latex2efont = oneOf("mathrm mathcal mathit mathtt mathsf mathbf")
 
 texsym = Combine(bslash + Word(alphanums) + NotAny("{"))
 
@@ -1668,6 +1673,8 @@
 | subsuper
 ).setParseAction(handler.expression).setName("expression")
 
+
+
 ####
 
 
Added: branches/mathtext_mgd/lib/matplotlib/mpl-data/fonts/ttf/cmb10.ttf
===================================================================
(Binary files differ)
Property changes on: branches/mathtext_mgd/lib/matplotlib/mpl-data/fonts/ttf/cmb10.ttf
___________________________________________________________________
Name: svn:mime-type
 + application/octet-stream
Added: branches/mathtext_mgd/lib/matplotlib/mpl-data/fonts/ttf/cmss10.ttf
===================================================================
(Binary files differ)
Property changes on: branches/mathtext_mgd/lib/matplotlib/mpl-data/fonts/ttf/cmss10.ttf
___________________________________________________________________
Name: svn:mime-type
 + application/octet-stream
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
Revision: 3548
 http://matplotlib.svn.sourceforge.net/matplotlib/?rev=3548&view=rev
Author: mdboom
Date: 2007年07月17日 05:21:59 -0700 (2007年7月17日)
Log Message:
-----------
Add support for Latex2e-style math fonts (\mathrm, \mathit etc.)
Add support for function name shortcuts (\sin, \cos etc.)
Raise an exception when encountering double subscript or superscripts
(e.g. x_i_j)
Modified Paths:
--------------
 branches/mathtext_mgd/lib/matplotlib/mathtext.py
Modified: branches/mathtext_mgd/lib/matplotlib/mathtext.py
===================================================================
--- branches/mathtext_mgd/lib/matplotlib/mathtext.py	2007年07月17日 10:09:27 UTC (rev 3547)
+++ branches/mathtext_mgd/lib/matplotlib/mathtext.py	2007年07月17日 12:21:59 UTC (rev 3548)
@@ -135,7 +135,7 @@
 from matplotlib.pyparsing import Literal, Word, OneOrMore, ZeroOrMore, \
 Combine, Group, Optional, Forward, NotAny, alphas, nums, alphanums, \
 StringStart, StringEnd, ParseException, FollowedBy, Regex, \
- operatorPrecedence, opAssoc, ParseResults, Or, Suppress
+ operatorPrecedence, opAssoc, ParseResults, Or, Suppress, oneOf
 
 from matplotlib.afm import AFM
 from matplotlib.cbook import enumerate, iterable, Bunch
@@ -1230,6 +1230,8 @@
 """
 def __init__(self, elements):
 Element.__init__(self)
+ if not isinstance(elements, list):
+ elements = elements.asList()
 self.elements = elements
 for i in range(len(elements)-1):
 self.elements[i].neighbors['right'] = self.elements[i+1]
@@ -1414,6 +1416,15 @@
 self.symbols.append(above)
 return [sym]
 
+ def function(self, s, loc, toks):
+ #~ print "function", toks
+ symbols = [FontElement("rm")]
+ for c in toks[0]:
+ sym = SymbolElement(c)
+ symbols.append(sym)
+ self.symbols.append(sym)
+ return [GroupElement(symbols)]
+ 
 def group(self, s, loc, toks):
 assert(len(toks)==1)
 #print 'grp', toks
@@ -1427,6 +1438,16 @@
 font = FontElement(name)
 return [font]
 
+ def latexfont(self, s, loc, toks):
+ assert(len(toks)==1)
+ name, grp = toks[0]
+ if len(grp.elements):
+ font = FontElement(name[4:])
+ font.neighbors['right'] = grp.elements[0]
+ grp.elements.insert(0, font)
+ return [grp]
+ return []
+ 
 _subsuperscript_names = {
 'normal': ['subscript', 'superscript'],
 'overUnder': ['below', 'above']
@@ -1463,6 +1484,10 @@
 if compound[other_index] in next.neighbors:
 prev.neighbors[names[other_index]] = next.neighbors[compound[other_index]]
 del next.neighbors[compound[other_index]]
+ elif compound[index] in next.neighbors:
+ raise ValueError(
+ "Double %ss" %
+ self._subsuperscript_names['normal'][index])
 return [prev]
 
 def is_overunder(self, prev):
@@ -1472,6 +1497,7 @@
 
 # All forward declarations are here
 font = Forward().setParseAction(handler.font).setName("font")
+latexfont = Forward().setParseAction(handler.latexfont).setName("latexfont")
 subsuper = Forward().setParseAction(handler.subsuperscript).setName("subsuper")
 placeable = Forward().setName("placeable")
 
@@ -1522,12 +1548,13 @@
 overUnder =(over
 | under)
 
-accent =(Literal('hat') | Literal('check') | Literal('dot') | 
- Literal('breve') | Literal('acute') | Literal('ddot') | 
- Literal('grave') | Literal('tilde') | Literal('bar') | 
- Literal('vec') | Literal('"') | Literal("`") | Literal("'") |
- Literal('~') | Literal('.') | Literal('^'))
+accent = oneOf("hat check dot breve acute ddot grave tilde bar vec "
+ "\" ` ' ~ . ^")
 
+function = oneOf("arccos csc ker min arcsin deg lg Pr arctan det lim sec "
+ "arg dim liminf sin cos exp limsup sinh cosh gcd ln sup "
+ "cot hom log tan coth inf max tanh")
+
 number = Combine(Word(nums) + Optional(Literal('.')) + Optional( Word(nums) ))
 
 plus = Literal('+')
@@ -1539,14 +1566,9 @@
 | times
 | div)
 
-roman = Literal('rm')
-cal = Literal('cal')
-italics = Literal('it')
-typewriter = Literal('tt')
-fontname =(roman 
- | cal 
- | italics
- | typewriter)
+fontname = oneOf("rm cal it tt")
+ # mathbf and mathsf not supported yet
+latex2efont = oneOf("mathrm mathcal mathit mathtt")
 
 texsym = Combine(bslash + Word(alphanums) + NotAny("{"))
 
@@ -1588,16 +1610,28 @@
 + Optional(rbrace)
 ).setParseAction(handler.accent).setName("accent")
 
+function =(Suppress(bslash)
+ + function).setParseAction(handler.function).setName("function")
+
 group = Group(
 lbrace
 + OneOrMore(
 space
 | font
+ | latexfont
 | subsuper
 )
 + rbrace
 ).setParseAction(handler.group).setName("group")
 
+font <<(Suppress(bslash)
+ + fontname)
+
+latexfont << Group(
+ Suppress(bslash)
+ + latex2efont
+ + group)
+
 composite = Group(
 Combine(
 bslash
@@ -1607,10 +1641,8 @@
 + group
 ).setParseAction(handler.composite).setName("composite")
 
-font <<(Suppress(bslash)
- + fontname)
-
 placeable <<(accent
+ ^ function 
 ^ symbol
 ^ group
 ^ composite
@@ -1632,6 +1664,7 @@
 expression = OneOrMore(
 space
 | font
+ | latexfont
 | subsuper
 ).setParseAction(handler.expression).setName("expression")
 
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
From: <as...@us...> - 2007年07月17日 10:09:29
Revision: 3547
 http://matplotlib.svn.sourceforge.net/matplotlib/?rev=3547&view=rev
Author: astraw
Date: 2007年07月17日 03:09:27 -0700 (2007年7月17日)
Log Message:
-----------
bugfix segfault in transforms module. Thanks Ben North for the patch
Modified Paths:
--------------
 trunk/matplotlib/CHANGELOG
 trunk/matplotlib/src/_transforms.cpp
Modified: trunk/matplotlib/CHANGELOG
===================================================================
--- trunk/matplotlib/CHANGELOG	2007年07月16日 22:19:24 UTC (rev 3546)
+++ trunk/matplotlib/CHANGELOG	2007年07月17日 10:09:27 UTC (rev 3547)
@@ -1,3 +1,6 @@
+2007年07月17日 bugfix segfault in transforms module. Thanks Ben North for
+ the patch. - ADS
+
 2007年07月16日 clean up some code in ticker.ScalarFormatter, use unicode to
 render multiplication sign in offset ticklabel - DSD
 
Modified: trunk/matplotlib/src/_transforms.cpp
===================================================================
--- trunk/matplotlib/src/_transforms.cpp	2007年07月16日 22:19:24 UTC (rev 3546)
+++ trunk/matplotlib/src/_transforms.cpp	2007年07月17日 10:09:27 UTC (rev 3547)
@@ -33,7 +33,7 @@
 int
 LazyValue::compare(const Py::Object &other) {
 if (!check(other))
- throw Py::TypeError("Can on compare LazyValues with LazyValues");
+ throw Py::TypeError("Can only compare LazyValues with LazyValues");
 LazyValue* pother = static_cast<LazyValue*>(other.ptr());
 double valself = val();
 double valother = pother->val();
@@ -2079,12 +2079,13 @@
 
 args.verify_length(6);
 
- LazyValue::check(args[0]);
- LazyValue::check(args[1]);
- LazyValue::check(args[2]);
- LazyValue::check(args[3]);
- LazyValue::check(args[4]);
- LazyValue::check(args[5]);
+ if (!LazyValue::check(args[0])
+ || !LazyValue::check(args[1])
+ || !LazyValue::check(args[2])
+ || !LazyValue::check(args[3])
+ || !LazyValue::check(args[4])
+ || !LazyValue::check(args[5]))
+ throw Py::TypeError("Affine(a, b, c, d, tx, ty) expected 6 LazyValue args");
 
 LazyValue* a = static_cast<LazyValue*>(args[0].ptr());
 LazyValue* b = static_cast<LazyValue*>(args[1].ptr());
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
Revision: 3546
 http://matplotlib.svn.sourceforge.net/matplotlib/?rev=3546&view=rev
Author: jrevans
Date: 2007年07月16日 15:19:24 -0700 (2007年7月16日)
Log Message:
-----------
Changed what appeared to be a typo where x-axis values were being converted using the y-axis unit converters.
Modified Paths:
--------------
 trunk/matplotlib/lib/matplotlib/axes.py
Modified: trunk/matplotlib/lib/matplotlib/axes.py
===================================================================
--- trunk/matplotlib/lib/matplotlib/axes.py	2007年07月16日 19:40:34 UTC (rev 3545)
+++ trunk/matplotlib/lib/matplotlib/axes.py	2007年07月16日 22:19:24 UTC (rev 3546)
@@ -1507,7 +1507,7 @@
 if xmin is not None:
 xmin = self.convert_xunits(xmin)
 if xmax is not None:
- xmax = self.convert_yunits(xmax)
+ xmax = self.convert_xunits(xmax)
 
 old_xmin,old_xmax = self.get_xlim()
 if xmin is None: xmin = old_xmin
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
From: <ds...@us...> - 2007年07月16日 19:40:35
Revision: 3545
 http://matplotlib.svn.sourceforge.net/matplotlib/?rev=3545&view=rev
Author: dsdale
Date: 2007年07月16日 12:40:34 -0700 (2007年7月16日)
Log Message:
-----------
cleanup some code in ScalerFormatter, use unicode multiplication sign in 
offset ticklabel
Modified Paths:
--------------
 trunk/matplotlib/CHANGELOG
 trunk/matplotlib/lib/matplotlib/ticker.py
Modified: trunk/matplotlib/CHANGELOG
===================================================================
--- trunk/matplotlib/CHANGELOG	2007年07月16日 18:29:23 UTC (rev 3544)
+++ trunk/matplotlib/CHANGELOG	2007年07月16日 19:40:34 UTC (rev 3545)
@@ -1,3 +1,6 @@
+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 
 notation (10^0 was being rendered as 10 in some cases) - DSD
 
Modified: trunk/matplotlib/lib/matplotlib/ticker.py
===================================================================
--- trunk/matplotlib/lib/matplotlib/ticker.py	2007年07月16日 18:29:23 UTC (rev 3544)
+++ trunk/matplotlib/lib/matplotlib/ticker.py	2007年07月16日 19:40:34 UTC (rev 3545)
@@ -274,7 +274,7 @@
 def __init__(self, useOffset=True, useMathText=False):
 # useOffset allows plotting small data ranges with large offsets:
 # for example: [1+1e-9,1+2e-9,1+3e-9]
- # useMathText will render the offset an scientific notation in mathtext
+ # useMathText will render the offset and scientific notation in mathtext
 self._useOffset = useOffset
 self._usetex = rcParams['text.usetex']
 self._useMathText = useMathText
@@ -292,7 +292,9 @@
 return self.pprint_val(x)
 
 def set_scientific(self, b):
- 'True or False to turn scientific notation on or off; see also set_powerlimits()'
+ '''True or False to turn scientific notation on or off
+ see also set_powerlimits()
+ '''
 self._scientific = bool(b)
 
 def set_powerlimits(self, lims):
@@ -311,11 +313,9 @@
 'return a short formatted string representation of a number'
 return '%1.3g'%value
 
- def format_data(self,value,sign=False,mathtext=False):
+ def format_data(self,value):
 'return a formatted string representation of a number'
- if sign: s = '%+1.10e'% value
- else: s = '%1.10e'% value
- return self._formatSciNotation(s,mathtext=mathtext)
+ return self._formatSciNotation('%1.10e'% value)
 
 def get_offset(self):
 """Return scientific notation, plus offset"""
@@ -324,16 +324,15 @@
 offsetStr = ''
 sciNotStr = ''
 if self.offset:
- if self._usetex or self._useMathText:
- offsetStr = self.format_data(self.offset, sign=True, mathtext=True)
- else:
- offsetStr = self.format_data(self.offset, sign=True, mathtext=False)
+ offsetStr = self.format_data(self.offset)
+ if self.offset > 0: offsetStr = '+' + offsetStr
 if self.orderOfMagnitude:
 if self._usetex or self._useMathText:
- sciNotStr = r'{\times}'+self.format_data(10**self.orderOfMagnitude, mathtext=True)
+ sciNotStr = r'{\times}'+self.format_data(10**self.orderOfMagnitude)
 else:
- sciNotStr = 'x1e%+d'% self.orderOfMagnitude
- if self._useMathText or self._usetex: return ''.join(('$',sciNotStr,offsetStr,'$'))
+ sciNotStr = u'\xd7'+'1e%d'% self.orderOfMagnitude
+ if self._useMathText or self._usetex: 
+ return ''.join(('$',sciNotStr,offsetStr,'$'))
 else: return ''.join((sciNotStr,offsetStr))
 else: return ''
 
@@ -402,14 +401,14 @@
 if absolute(xp) < 1e-8: xp = 0
 return self.format % xp
 
- def _formatSciNotation(self, s, mathtext=False):
+ def _formatSciNotation(self, s):
 # transform 1e+004 into 1e4, for example
 tup = s.split('e')
 try:
 significand = tup[0].rstrip('0').rstrip('.')
 sign = tup[1][0].replace('+', '')
 exponent = tup[1][1:].lstrip('0')
- if mathtext:
+ if self._useMathText or self._usetex:
 if significand == '1':
 # reformat 1x10^y as 10^y
 significand = ''
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
Revision: 3544
 http://matplotlib.svn.sourceforge.net/matplotlib/?rev=3544&view=rev
Author: mdboom
Date: 2007年07月16日 11:29:23 -0700 (2007年7月16日)
Log Message:
-----------
Fix running unicode_demo.py from backend_driver.py. (The -*- coding
line must appear before any non-comment lines).
Modified Paths:
--------------
 trunk/matplotlib/examples/backend_driver.py
Modified: trunk/matplotlib/examples/backend_driver.py
===================================================================
--- trunk/matplotlib/examples/backend_driver.py	2007年07月16日 18:06:54 UTC (rev 3543)
+++ trunk/matplotlib/examples/backend_driver.py	2007年07月16日 18:29:23 UTC (rev 3544)
@@ -38,7 +38,7 @@
 'figtext.py',
 'fill_demo.py',
 'finance_demo.py',
-# 'fonts_demo_kw.py',
+ 'fonts_demo_kw.py',
 'histogram_demo.py',
 'image_demo.py',
 'image_demo2.py',
@@ -125,6 +125,13 @@
 tmpfile_name = '_tmp_%s.py' % basename
 tmpfile = file(tmpfile_name, 'w')
 
+ for line in file(fname):
+ line_lstrip = line.lstrip()
+ if line_lstrip.startswith("#"):
+ tmpfile.write(line)
+ else:
+ break
+
 tmpfile.writelines((
 'from __future__ import division\n',
 'import matplotlib\n',
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
Revision: 3543
 http://matplotlib.svn.sourceforge.net/matplotlib/?rev=3543&view=rev
Author: astraw
Date: 2007年07月16日 11:06:54 -0700 (2007年7月16日)
Log Message:
-----------
don't require setuptools by default.
Modified Paths:
--------------
 trunk/matplotlib/setup.py
Modified: trunk/matplotlib/setup.py
===================================================================
--- trunk/matplotlib/setup.py	2007年07月16日 17:59:17 UTC (rev 3542)
+++ trunk/matplotlib/setup.py	2007年07月16日 18:06:54 UTC (rev 3543)
@@ -72,8 +72,7 @@
 directory.""")
 
 import glob
-#from distutils.core import Extension, setup
-from setuptools import setup
+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, \
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
Revision: 3542
 http://matplotlib.svn.sourceforge.net/matplotlib/?rev=3542&view=rev
Author: mdboom
Date: 2007年07月16日 10:59:17 -0700 (2007年7月16日)
Log Message:
-----------
Deal with font tags (\cal \it \rm etc.) more like TeX
Modified Paths:
--------------
 branches/mathtext_mgd/lib/matplotlib/mathtext.py
Modified: branches/mathtext_mgd/lib/matplotlib/mathtext.py
===================================================================
--- branches/mathtext_mgd/lib/matplotlib/mathtext.py	2007年07月16日 15:42:25 UTC (rev 3541)
+++ branches/mathtext_mgd/lib/matplotlib/mathtext.py	2007年07月16日 17:59:17 UTC (rev 3542)
@@ -135,7 +135,7 @@
 from matplotlib.pyparsing import Literal, Word, OneOrMore, ZeroOrMore, \
 Combine, Group, Optional, Forward, NotAny, alphas, nums, alphanums, \
 StringStart, StringEnd, ParseException, FollowedBy, Regex, \
- operatorPrecedence, opAssoc, ParseResults, Or
+ operatorPrecedence, opAssoc, ParseResults, Or, Suppress
 
 from matplotlib.afm import AFM
 from matplotlib.cbook import enumerate, iterable, Bunch
@@ -927,7 +927,6 @@
 class Element:
 fontsize = 12
 dpi = 72
- font = 'it'
 _padx, _pady = 2, 2 # the x and y padding in points
 _scale = 1.0
 
@@ -965,10 +964,14 @@
 'get the ymax of ink rect'
 raise NotImplementedError('derived must override')
 
+ def determine_font(self, font_stack):
+ 'a first pass to determine the font of this element (one of tt, it, rm , cal)'
+ raise NotImplementedError('derived must override')
+
 def set_font(self, font):
 'set the font (one of tt, it, rm , cal)'
 raise NotImplementedError('derived must override')
-
+ 
 def render(self):
 'render to the fonts canvas'
 for element in self.neighbors.values():
@@ -1044,6 +1047,45 @@
 def __repr__(self):
 return str(self.__class__) + str(self.neighbors)
 
+class FontElement(Element):
+ def __init__(self, name):
+ Element.__init__(self)
+ self.name = name
+
+ def advance(self):
+ 'get the horiz advance'
+ return 0
+ 
+ def height(self):
+ 'get the element height: ymax-ymin'
+ return 0
+ 
+ def width(self):
+ 'get the element width: xmax-xmin'
+ return 0
+ 
+ def xmin(self):
+ 'get the xmin of ink rect'
+ return 0
+ 
+ def xmax(self):
+ 'get the xmax of ink rect'
+ return 0
+ 
+ def ymin(self):
+ 'get the ymin of ink rect'
+ return 0
+ 
+ def ymax(self):
+ 'get the ymax of ink rect'
+ return 0
+ 
+ def determine_font(self, font_stack):
+ font_stack[-1] = self.name
+
+ def set_font(self, font):
+ return
+ 
 class SpaceElement(Element):
 'blank horizontal space'
 def __init__(self, space, height=0):
@@ -1083,10 +1125,17 @@
 'get the max ink in y'
 return self.oy + self.height()
 
- def set_font(self, f):
+ def determine_font(self, font_stack):
 # space doesn't care about font, only size
+ for neighbor_type in ('above', 'below', 'subscript', 'superscript'):
+ neighbor = self.neighbors.get(neighbor_type)
+ if neighbor is not None:
+ neighbor.determine_font(font_stack)
+
+ def set_font(self, font_stack):
+ # space doesn't care about font, only size
 pass
-
+ 
 class SymbolElement(Element):
 def __init__(self, sym):
 Element.__init__(self)
@@ -1094,10 +1143,19 @@
 self.kern = None
 self.widthm = 1 # the width of an m; will be resized below
 
+ def determine_font(self, font_stack):
+ 'set the font (one of tt, it, rm, cal)'
+ self.set_font(font_stack[-1])
+ for neighbor_type in ('above', 'below', 'subscript', 'superscript'):
+ neighbor = self.neighbors.get(neighbor_type)
+ if neighbor is not None:
+ neighbor.determine_font(font_stack)
+ 
 def set_font(self, font):
- 'set the font (one of tt, it, rm , cal)'
+ # space doesn't care about font, only size
+ assert not hasattr(self, 'font')
 self.font = font
-
+ 
 def set_origin(self, ox, oy):
 Element.set_origin(self, ox, oy)
 
@@ -1163,6 +1221,8 @@
 def __repr__(self):
 return self.sym
 
+class AccentElement(SymbolElement):
+ pass
 
 class GroupElement(Element):
 """
@@ -1174,20 +1234,25 @@
 for i in range(len(elements)-1):
 self.elements[i].neighbors['right'] = self.elements[i+1]
 
- def set_font(self, font):
+ def determine_font(self, font_stack):
 'set the font (one of tt, it, rm , cal)'
+ font_stack.append(font_stack[-1])
 for element in self.elements:
- element.set_font(font)
+ element.determine_font(font_stack)
+ font_stack.pop()
 
-
+ def set_font(self, font):
+ return
+ 
+ # MGDTODO: The code below is probably now broken
 #print 'set fonts'
- for i in range(len(self.elements)-1):
- if not isinstance(self.elements[i], SymbolElement): continue
- if not isinstance(self.elements[i+1], SymbolElement): continue
- symleft = self.elements[i].sym
- symright = self.elements[i+1].sym
- self.elements[i].kern = None
- #self.elements[i].kern = Element.fonts.get_kern(font, symleft, symright, self.fontsize, self.dpi)
+# for i in range(len(self.elements)-1):
+# if not isinstance(self.elements[i], SymbolElement): continue
+# if not isinstance(self.elements[i+1], SymbolElement): continue
+# symleft = self.elements[i].sym
+# symright = self.elements[i+1].sym
+# self.elements[i].kern = None
+# #self.elements[i].kern = Element.fonts.get_kern(font, symleft, symright, self.fontsize, self.dpi)
 
 
 def set_size_info(self, fontsize, dpi):
@@ -1250,6 +1315,9 @@
 def __repr__(self):
 return 'Expression: [ %s ]' % ' '.join([str(e) for e in self.elements])
 
+ def determine_font(self):
+ font_stack = ['it']
+ GroupElement.determine_font(self, font_stack)
 
 class Handler:
 symbols = []
@@ -1275,29 +1343,30 @@
 return [element]
 
 def symbol(self, s, loc, toks):
-
 assert(len(toks)==1)
-
+ #print "symbol", toks
+ 
 s = toks[0]
- if charOverChars.has_key(s):
- under, over, pad = charOverChars[s]
- font, tok, scale = under
- sym = SymbolElement(tok)
- if font is not None:
- sym.set_font(font)
- sym.set_scale(scale)
- sym.set_pady(pad)
+ # MGDTODO: This clause is probably broken due to font changes
+# if charOverChars.has_key(s):
+# under, over, pad = charOverChars[s]
+# font, tok, scale = under
+# sym = SymbolElement(tok)
+# if font is not None:
+# sym.set_font(font)
+# sym.set_scale(scale)
+# sym.set_pady(pad)
 
- font, tok, scale = over
- sym2 = SymbolElement(tok)
- if font is not None:
- sym2.set_font(font)
- sym2.set_scale(scale)
+# font, tok, scale = over
+# sym2 = SymbolElement(tok)
+# if font is not None:
+# sym2.set_font(font)
+# sym2.set_scale(scale)
 
- sym.neighbors['above'] = sym2
- self.symbols.append(sym2)
- else:
- sym = SymbolElement(toks[0])
+# sym.neighbors['above'] = sym2
+# self.symbols.append(sym2)
+# else:
+ sym = SymbolElement(toks[0])
 self.symbols.append(sym)
 
 return [sym]
@@ -1339,7 +1408,7 @@
 r'\.' : r'\combiningdotabove',
 r'\^' : r'\circumflexaccent',
 }
- above = SymbolElement(d[accent])
+ above = AccentElement(d[accent])
 sym.neighbors['above'] = above
 sym.set_pady(1)
 self.symbols.append(above)
@@ -1352,12 +1421,11 @@
 return [grp]
 
 def font(self, s, loc, toks):
-
 assert(len(toks)==1)
- name, grp = toks[0]
+ name = toks[0]
 #print 'fontgrp', toks
- grp.set_font(name[1:]) # suppress the slash
- return [grp]
+ font = FontElement(name)
+ return [font]
 
 _subsuperscript_names = {
 'normal': ['subscript', 'superscript'],
@@ -1524,8 +1592,8 @@
 lbrace
 + OneOrMore(
 space
- ^ font
- ^ subsuper
+ | font
+ | subsuper
 )
 + rbrace
 ).setParseAction(handler.group).setName("group")
@@ -1539,11 +1607,8 @@
 + group
 ).setParseAction(handler.composite).setName("composite")
 
-font << Group(
- Combine(
- bslash
- + fontname)
- + group)
+font <<(Suppress(bslash)
+ + fontname)
 
 placeable <<(accent
 ^ symbol
@@ -1566,8 +1631,8 @@
 
 expression = OneOrMore(
 space
- ^ font
- ^ subsuper
+ | font
+ | subsuper
 ).setParseAction(handler.expression).setName("expression")
 
 ####
@@ -1616,10 +1681,11 @@
 elif self.output == 'PDF':
 self.font_object = BakomaPDFFonts(character_tracker)
 Element.fonts = self.font_object
-
+ 
 handler.clear()
 expression.parseString( s )
 
+ handler.expr.determine_font()
 handler.expr.set_size_info(fontsize, dpi)
 
 # set the origin once to allow w, h compution
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
Revision: 3541
 http://matplotlib.svn.sourceforge.net/matplotlib/?rev=3541&view=rev
Author: mdboom
Date: 2007年07月16日 08:42:25 -0700 (2007年7月16日)
Log Message:
-----------
Minor cleanup and simplifications. Handle sub/superscript as a unary operator.
Modified Paths:
--------------
 branches/mathtext_mgd/lib/matplotlib/mathtext.py
Modified: branches/mathtext_mgd/lib/matplotlib/mathtext.py
===================================================================
--- branches/mathtext_mgd/lib/matplotlib/mathtext.py	2007年07月16日 15:08:12 UTC (rev 3540)
+++ branches/mathtext_mgd/lib/matplotlib/mathtext.py	2007年07月16日 15:42:25 UTC (rev 3541)
@@ -1013,7 +1013,6 @@
 self.dpi = dpi
 for loc, element in self.neighbors.items():
 if loc in ('subscript', 'superscript'):
- print type(element), element
 element.set_size_info(0.7*self.fontsize, dpi)
 else:
 element.set_size_info(self.fontsize, dpi)
@@ -1260,7 +1259,6 @@
 self.subscript_stack = []
 
 def expression(self, s, loc, toks):
- print "expression", toks
 self.expr = ExpressionElement(toks)
 return [self.expr]
 
@@ -1281,7 +1279,6 @@
 assert(len(toks)==1)
 
 s = toks[0]
- print 'sym', toks[0]
 if charOverChars.has_key(s):
 under, over, pad = charOverChars[s]
 font, tok, scale = under
@@ -1374,25 +1371,32 @@
 
 def subsuperscript(self, s, loc, toks):
 assert(len(toks)==1)
- print 'subscript', toks
+ #~ print 'subsuperscript', toks
 
- if len(toks[0])==3:
+ if len(toks[0]) == 1:
+ return toks[0].asList()
+ if len(toks[0]) == 3:
 prev, op, next = toks[0]
- index, other_index = self._subsuperscript_indices[op]
- if self.is_overunder(prev):
- names = self._subsuperscript_names['overUnder']
- else:
- names = self._subsuperscript_names['normal']
- 
- prev.neighbors[names[index]] = next
+ elif len(toks[0]) == 2:
+ prev = SpaceElement(0)
+ op, next = toks[0]
+ else:
+ raise ParseException("Unable to parse subscript/superscript construct.")
 
- for compound in self._subsuperscript_names.values():
- if compound[other_index] in next.neighbors:
- prev.neighbors[names[other_index]] = next.neighbors[compound[other_index]]
- del next.neighbors[compound[other_index]]
- return [prev]
- return toks[0].asList()
+ index, other_index = self._subsuperscript_indices[op]
+ if self.is_overunder(prev):
+ names = self._subsuperscript_names['overUnder']
+ else:
+ names = self._subsuperscript_names['normal']
 
+ prev.neighbors[names[index]] = next
+
+ for compound in self._subsuperscript_names.values():
+ if compound[other_index] in next.neighbors:
+ prev.neighbors[names[other_index]] = next.neighbors[compound[other_index]]
+ del next.neighbors[compound[other_index]]
+ return [prev]
+
 def is_overunder(self, prev):
 return isinstance(prev, SymbolElement) and overunder.has_key(prev.sym)
 
@@ -1522,7 +1526,6 @@
 space
 ^ font
 ^ subsuper
- ^ placeable
 )
 + rbrace
 ).setParseAction(handler.group).setName("group")
@@ -1549,20 +1552,22 @@
 )
 
 subsuper << Group(
- placeable
- + ZeroOrMore(
- ( subscript
- | superscript
- )
- + subsuper
+ (
+ placeable
+ + ZeroOrMore(
+ ( subscript
+ | superscript
+ )
+ + subsuper
+ )
 )
+ | (( subscript | superscript) + placeable)
 )
 
 expression = OneOrMore(
 space
 ^ font
 ^ subsuper
- ^ placeable
 ).setParseAction(handler.expression).setName("expression")
 
 ####
@@ -1616,8 +1621,6 @@
 expression.parseString( s )
 
 handler.expr.set_size_info(fontsize, dpi)
- print handler.expr
- print handler.symbols
 
 # set the origin once to allow w, h compution
 handler.expr.set_origin(0, 0)
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
Revision: 3540
 http://matplotlib.svn.sourceforge.net/matplotlib/?rev=3540&view=rev
Author: mdboom
Date: 2007年07月16日 08:08:12 -0700 (2007年7月16日)
Log Message:
-----------
Got nested sub/superscripts working. Improved formatting of grammar
to be more readable to newbies (like me).
Modified Paths:
--------------
 branches/mathtext_mgd/lib/matplotlib/mathtext.py
Modified: branches/mathtext_mgd/lib/matplotlib/mathtext.py
===================================================================
--- branches/mathtext_mgd/lib/matplotlib/mathtext.py	2007年07月16日 14:06:59 UTC (rev 3539)
+++ branches/mathtext_mgd/lib/matplotlib/mathtext.py	2007年07月16日 15:08:12 UTC (rev 3540)
@@ -119,7 +119,6 @@
 
 KNOWN ISSUES:
 
- - nested subscripts, eg, x_i_j not working; but you can do x_{i_j}
 - nesting fonts changes in sub/superscript groups not parsing
 - I would also like to add a few more layout commands, like \frac.
 
@@ -136,7 +135,7 @@
 from matplotlib.pyparsing import Literal, Word, OneOrMore, ZeroOrMore, \
 Combine, Group, Optional, Forward, NotAny, alphas, nums, alphanums, \
 StringStart, StringEnd, ParseException, FollowedBy, Regex, \
- operatorPrecedence, opAssoc, ParseResults
+ operatorPrecedence, opAssoc, ParseResults, Or
 
 from matplotlib.afm import AFM
 from matplotlib.cbook import enumerate, iterable, Bunch
@@ -1014,6 +1013,7 @@
 self.dpi = dpi
 for loc, element in self.neighbors.items():
 if loc in ('subscript', 'superscript'):
+ print type(element), element
 element.set_size_info(0.7*self.fontsize, dpi)
 else:
 element.set_size_info(self.fontsize, dpi)
@@ -1257,8 +1257,10 @@
 
 def clear(self):
 self.symbols = []
+ self.subscript_stack = []
 
 def expression(self, s, loc, toks):
+ print "expression", toks
 self.expr = ExpressionElement(toks)
 return [self.expr]
 
@@ -1279,7 +1281,7 @@
 assert(len(toks)==1)
 
 s = toks[0]
- #~ print 'sym', toks[0]
+ print 'sym', toks[0]
 if charOverChars.has_key(s):
 under, over, pad = charOverChars[s]
 font, tok, scale = under
@@ -1360,172 +1362,209 @@
 grp.set_font(name[1:]) # suppress the slash
 return [grp]
 
- def subscript(self, s, loc, toks):
+ _subsuperscript_names = {
+ 'normal': ['subscript', 'superscript'],
+ 'overUnder': ['below', 'above']
+ }
+
+ _subsuperscript_indices = {
+ '_': (0, 1),
+ '^': (1, 0)
+ }
+ 
+ def subsuperscript(self, s, loc, toks):
 assert(len(toks)==1)
- #print 'subsup', toks
- if len(toks[0])==2:
- under, next = toks[0]
- prev = SpaceElement(0)
- else:
- prev, under, next = toks[0]
+ print 'subscript', toks
 
- if self.is_overunder(prev):
- prev.neighbors['below'] = next
- else:
- prev.neighbors['subscript'] = next
+ if len(toks[0])==3:
+ prev, op, next = toks[0]
+ index, other_index = self._subsuperscript_indices[op]
+ if self.is_overunder(prev):
+ names = self._subsuperscript_names['overUnder']
+ else:
+ names = self._subsuperscript_names['normal']
+ 
+ prev.neighbors[names[index]] = next
 
- return loc, [prev]
+ for compound in self._subsuperscript_names.values():
+ if compound[other_index] in next.neighbors:
+ prev.neighbors[names[other_index]] = next.neighbors[compound[other_index]]
+ del next.neighbors[compound[other_index]]
+ return [prev]
+ return toks[0].asList()
 
 def is_overunder(self, prev):
 return isinstance(prev, SymbolElement) and overunder.has_key(prev.sym)
 
- def superscript(self, s, loc, toks):
- assert(len(toks)==1)
- #print 'subsup', toks
- if len(toks[0])==2:
- under, next = toks[0]
- prev = SpaceElement(0,0.6)
- else:
- prev, under, next = toks[0]
- if self.is_overunder(prev):
- prev.neighbors['above'] = next
- else:
- prev.neighbors['superscript'] = next
-
- return [prev]
-
- def subsuperscript(self, s, loc, toks):
- assert(len(toks)==1)
- #print 'subsup', toks
- prev, undersym, down, oversym, up = toks[0]
-
- if self.is_overunder(prev):
- prev.neighbors['below'] = down
- prev.neighbors['above'] = up
- else:
- prev.neighbors['subscript'] = down
- prev.neighbors['superscript'] = up
-
- return [prev]
-
-
-
 handler = Handler()
 
-lbrace = Literal('{').suppress()
-rbrace = Literal('}').suppress()
-lbrack = Literal('[')
-rbrack = Literal(']')
-lparen = Literal('(')
-rparen = Literal(')')
-grouping = lbrack | rbrack | lparen | rparen
+# All forward declarations are here
+font = Forward().setParseAction(handler.font).setName("font")
+subsuper = Forward().setParseAction(handler.subsuperscript).setName("subsuper")
+placeable = Forward().setName("placeable")
 
-bslash = Literal('\\')
 
+lbrace = Literal('{').suppress()
+rbrace = Literal('}').suppress()
+lbrack = Literal('[')
+rbrack = Literal(']')
+lparen = Literal('(')
+rparen = Literal(')')
+grouping =(lbrack 
+ | rbrack 
+ | lparen 
+ | rparen)
 
-langle = Literal('<')
-rangle = Literal('>')
-equals = Literal('=')
-relation = langle | rangle | equals
+subscript = Literal('_')
+superscript = Literal('^')
 
-colon = Literal(':')
-comma = Literal(',')
-period = Literal('.')
-semicolon = Literal(';')
-exclamation = Literal('!')
+bslash = Literal('\\')
 
-punctuation = colon | comma | period | semicolon
+langle = Literal('<')
+rangle = Literal('>')
+equals = Literal('=')
+relation =(langle
+ | rangle
+ | equals)
 
-at = Literal('@')
-percent = Literal('%')
-ampersand = Literal('&')
-misc = exclamation | at | percent | ampersand
+colon = Literal(':')
+comma = Literal(',')
+period = Literal('.')
+semicolon = Literal(';')
+exclamation = Literal('!')
+punctuation =(colon
+ | comma
+ | period
+ | semicolon)
 
-over = Literal('over')
-under = Literal('under')
-#~ composite = over | under
-overUnder = over | under
+at = Literal('@')
+percent = Literal('%')
+ampersand = Literal('&')
+misc =(exclamation
+ | at
+ | percent
+ | ampersand)
 
-accent = Literal('hat') | Literal('check') | Literal('dot') | \
- Literal('breve') | Literal('acute') | Literal('ddot') | \
- Literal('grave') | Literal('tilde') | Literal('bar') | \
- Literal('vec') | Literal('"') | Literal("`") | Literal("'") |\
- Literal('~') | Literal('.') | Literal('^')
+over = Literal('over')
+under = Literal('under')
+overUnder =(over
+ | under)
 
+accent =(Literal('hat') | Literal('check') | Literal('dot') | 
+ Literal('breve') | Literal('acute') | Literal('ddot') | 
+ Literal('grave') | Literal('tilde') | Literal('bar') | 
+ Literal('vec') | Literal('"') | Literal("`") | Literal("'") |
+ Literal('~') | Literal('.') | Literal('^'))
 
+number = Combine(Word(nums) + Optional(Literal('.')) + Optional( Word(nums) ))
 
+plus = Literal('+')
+minus = Literal('-')
+times = Literal('*')
+div = Literal('/')
+binop =(plus 
+ | minus
+ | times
+ | div)
 
-number = Combine(Word(nums) + Optional(Literal('.')) + Optional( Word(nums) ))
+roman = Literal('rm')
+cal = Literal('cal')
+italics = Literal('it')
+typewriter = Literal('tt')
+fontname =(roman 
+ | cal 
+ | italics
+ | typewriter)
 
-plus = Literal('+')
-minus = Literal('-')
-times = Literal('*')
-div = Literal('/')
-binop = plus | minus | times | div
+texsym = Combine(bslash + Word(alphanums) + NotAny("{"))
 
+char = Word(alphanums + ' ', exact=1).leaveWhitespace()
 
-roman = Literal('rm')
-cal = Literal('cal')
-italics = Literal('it')
-typewriter = Literal('tt')
-fontname = roman | cal | italics | typewriter
+space =(FollowedBy(bslash)
+ + (Literal(r'\ ')
+ | Literal(r'\/')
+ | Group(Literal(r'\hspace{') + number + Literal('}'))
+ )
+ ).setParseAction(handler.space).setName('space')
 
-texsym = Combine(bslash + Word(alphanums) + NotAny("{"))
+symbol = Regex("(" + ")|(".join(
+ [
+ r"\\[a-zA-Z0-9]+(?!{)",
+ r"[a-zA-Z0-9 ]",
+ r"[+\-*/]",
+ r"[<>=]",
+ r"[:,.;!]",
+ r"[!@%&]",
+ r"[[\]()]",
+ ])
+ + ")"
+ ).setParseAction(handler.symbol).leaveWhitespace()
 
-char = Word(alphanums + ' ', exact=1).leaveWhitespace()
+_symbol =(texsym
+ | char
+ | binop
+ | relation
+ | punctuation
+ | misc
+ | grouping
+ ).setParseAction(handler.symbol).leaveWhitespace()
 
-space = FollowedBy(bslash) + (Literal(r'\ ') | Literal(r'\/') | Group(Literal(r'\hspace{') + number + Literal('}'))).setParseAction(handler.space).setName('space')
+accent = Group(
+ Combine(bslash + accent)
+ + Optional(lbrace)
+ + symbol
+ + Optional(rbrace)
+ ).setParseAction(handler.accent).setName("accent")
 
-symbol = Regex("("+")|(".join(
- [
- r"\\[a-zA-Z0-9]+(?!{)",
- r"[a-zA-Z0-9 ]",
- r"[+\-*/]",
- r"[<>=]",
- r"[:,.;!]",
- r"[!@%&]",
- r"[[\]()]",
- ])+")"
- ).setParseAction(handler.symbol).leaveWhitespace()
+group = Group(
+ lbrace
+ + OneOrMore(
+ space
+ ^ font
+ ^ subsuper
+ ^ placeable
+ )
+ + rbrace
+ ).setParseAction(handler.group).setName("group")
 
-#~ symbol = (texsym ^ char ^ binop ^ relation ^ punctuation ^ misc ^ grouping ).setParseAction(handler.symbol).leaveWhitespace()
-_symbol = (texsym | char | binop | relation | punctuation | misc | grouping ).setParseAction(handler.symbol).leaveWhitespace()
+composite = Group(
+ Combine(
+ bslash
+ + overUnder
+ )
+ + group
+ + group
+ ).setParseAction(handler.composite).setName("composite")
 
-subscript = Forward().setParseAction(handler.subscript).setName("subscript")
-superscript = Forward().setParseAction(handler.superscript).setName("superscript")
-subsuperscript = Forward().setParseAction(handler.subsuperscript).setName("subsuperscript")
+font << Group(
+ Combine(
+ bslash
+ + fontname)
+ + group)
 
-font = Forward().setParseAction(handler.font).setName("font")
+placeable <<(accent
+ ^ symbol
+ ^ group
+ ^ composite
+ )
 
+subsuper << Group(
+ placeable
+ + ZeroOrMore(
+ ( subscript
+ | superscript
+ )
+ + subsuper
+ )
+ )
 
-accent = Group( Combine(bslash + accent) + Optional(lbrace) + symbol + Optional(rbrace)).setParseAction(handler.accent).setName("accent")
-group = Group( lbrace + OneOrMore(symbol^subscript^superscript^subsuperscript^space^font^accent) + rbrace).setParseAction(handler.group).setName("group")
-#~ group = Group( lbrace + OneOrMore(subsuperscript | subscript | superscript | symbol | space ) + rbrace).setParseAction(handler.group).setName("group")
+expression = OneOrMore(
+ space
+ ^ font
+ ^ subsuper
+ ^ placeable
+ ).setParseAction(handler.expression).setName("expression")
 
-#composite = Group( Combine(bslash + composite) + lbrace + symbol + rbrace + lbrace + symbol + rbrace).setParseAction(handler.composite).setName("composite")
-#~ composite = Group( Combine(bslash + composite) + group + group).setParseAction(handler.composite).setName("composite")
-composite = Group( Combine(bslash + overUnder) + group + group).setParseAction(handler.composite).setName("composite")
-
-
-
-
-
-
-symgroup = font | group | symbol
-
-subscript << Group( Optional(symgroup) + Literal('_') + symgroup )
-superscript << Group( Optional(symgroup) + Literal('^') + symgroup )
-subsuperscript << Group( symgroup + Literal('_') + symgroup + Literal('^') + symgroup )
-
-font << Group( Combine(bslash + fontname) + group)
-
-
-
-expression = OneOrMore(
- space ^ font ^ accent ^ symbol ^ subscript ^ superscript ^ subsuperscript ^ group ^ composite ).setParseAction(handler.expression).setName("expression")
-#~ expression = OneOrMore(
- #~ group | composite | space | font | subsuperscript | subscript | superscript | symbol ).setParseAction(handler.expression).setName("expression")
-
 ####
 
 
@@ -1577,7 +1616,9 @@
 expression.parseString( s )
 
 handler.expr.set_size_info(fontsize, dpi)
-
+ print handler.expr
+ print handler.symbols
+ 
 # set the origin once to allow w, h compution
 handler.expr.set_origin(0, 0)
 xmin = min([e.xmin() for e in handler.symbols])
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
From: <ds...@us...> - 2007年07月16日 14:07:01
Revision: 3539
 http://matplotlib.svn.sourceforge.net/matplotlib/?rev=3539&view=rev
Author: dsdale
Date: 2007年07月16日 07:06:59 -0700 (2007年7月16日)
Log Message:
-----------
fixed a formatting bug in ticker.ScalarFormatter (10^0 was rendered as 
10 in some cases)
Modified Paths:
--------------
 trunk/matplotlib/CHANGELOG
 trunk/matplotlib/lib/matplotlib/ticker.py
Modified: trunk/matplotlib/CHANGELOG
===================================================================
--- trunk/matplotlib/CHANGELOG	2007年07月16日 13:16:25 UTC (rev 3538)
+++ trunk/matplotlib/CHANGELOG	2007年07月16日 14:06:59 UTC (rev 3539)
@@ -1,3 +1,6 @@
+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
 doubles in (the now misnamed) MPL_isnan.h. - ADS
 
Modified: trunk/matplotlib/lib/matplotlib/ticker.py
===================================================================
--- trunk/matplotlib/lib/matplotlib/ticker.py	2007年07月16日 13:16:25 UTC (rev 3538)
+++ trunk/matplotlib/lib/matplotlib/ticker.py	2007年07月16日 14:06:59 UTC (rev 3539)
@@ -402,27 +402,26 @@
 if absolute(xp) < 1e-8: xp = 0
 return self.format % xp
 
- def _formatSciNotation(self,s, mathtext=False):
+ def _formatSciNotation(self, s, mathtext=False):
 # transform 1e+004 into 1e4, for example
 tup = s.split('e')
 try:
- mantissa = tup[0].rstrip('0').rstrip('.')
+ significand = tup[0].rstrip('0').rstrip('.')
 sign = tup[1][0].replace('+', '')
 exponent = tup[1][1:].lstrip('0')
 if mathtext:
- if self._usetex:
- if mantissa=='1':
- return r'10^{%s%s}'%(sign, exponent)
- else:
- return r'%s{\times}10^{%s%s}'%(mantissa, sign, exponent)
+ if significand == '1':
+ # reformat 1x10^y as 10^y
+ significand = ''
+ if exponent:
+ exponent = '10^{%s%s}'%(sign, exponent)
+ if significand and exponent:
+ return r'%s{\times}%s'%(significand, exponent)
 else:
- if mantissa=='1':
- return r'10^{%s%s}'%(sign, exponent)
- else:
- return r'%s{\times}10^{%s%s}'%(mantissa, sign, exponent)
+ return r'%s%s'%(significand, exponent)
 else:
- return ('%se%s%s' %(mantissa, sign, exponent)).rstrip('e')
- except IndexError,msg:
+ return ('%se%s%s' %(significand, sign, exponent)).rstrip('e')
+ except IndexError, msg:
 return s
 
 
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
From: <md...@us...> - 2007年07月16日 13:17:04
Revision: 3538
 http://matplotlib.svn.sourceforge.net/matplotlib/?rev=3538&view=rev
Author: mdboom
Date: 2007年07月16日 06:16:25 -0700 (2007年7月16日)
Log Message:
-----------
Fix ttconv so it can handle fontmeta with newlines in it
Modified Paths:
--------------
 trunk/matplotlib/ttconv/pprdrv.h
 trunk/matplotlib/ttconv/pprdrv_tt.cpp
 trunk/matplotlib/ttconv/ttutil.cpp
Modified: trunk/matplotlib/ttconv/pprdrv.h
===================================================================
--- trunk/matplotlib/ttconv/pprdrv.h	2007年07月16日 12:02:47 UTC (rev 3537)
+++ trunk/matplotlib/ttconv/pprdrv.h	2007年07月16日 13:16:25 UTC (rev 3538)
@@ -58,6 +58,8 @@
 virtual void add_pair(const char* key, const char* value) = 0;
 };
 
+void replace_newlines_with_spaces(char* a);
+
 /*
 * A simple class for all ttconv exceptions.
 */
Modified: trunk/matplotlib/ttconv/pprdrv_tt.cpp
===================================================================
--- trunk/matplotlib/ttconv/pprdrv_tt.cpp	2007年07月16日 12:02:47 UTC (rev 3537)
+++ trunk/matplotlib/ttconv/pprdrv_tt.cpp	2007年07月16日 13:16:25 UTC (rev 3538)
@@ -210,6 +210,7 @@
 	 font->Copyright = (char*)calloc(sizeof(char),length+1);
 	 strncpy(font->Copyright,(const char*)strings+offset,length);
 	 font->Copyright[length]=(char)NULL;
+	 replace_newlines_with_spaces(font->Copyright);
 	 
 #ifdef DEBUG_TRUETYPE
 	 debug("font->Copyright=\"%s\"",font->Copyright);
@@ -224,6 +225,7 @@
 	 font->FamilyName = (char*)calloc(sizeof(char),length+1);
 	 strncpy(font->FamilyName,(const char*)strings+offset,length);
 	 font->FamilyName[length]=(char)NULL;
+	 replace_newlines_with_spaces(font->FamilyName);
 	 
 #ifdef DEBUG_TRUETYPE
 	 debug("font->FamilyName=\"%s\"",font->FamilyName);
@@ -238,6 +240,7 @@
 	 font->Style = (char*)calloc(sizeof(char),length+1);
 	 strncpy(font->Style,(const char*)strings+offset,length);
 	 font->Style[length]=(char)NULL;
+	 replace_newlines_with_spaces(font->Style);
 	 
 #ifdef DEBUG_TRUETYPE
 	 debug("font->Style=\"%s\"",font->Style);
@@ -252,6 +255,7 @@
 	 font->FullName = (char*)calloc(sizeof(char),length+1);
 	 strncpy(font->FullName,(const char*)strings+offset,length);
 	 font->FullName[length]=(char)NULL;
+	 replace_newlines_with_spaces(font->FullName);
 	 
 #ifdef DEBUG_TRUETYPE
 	 debug("font->FullName=\"%s\"",font->FullName);
@@ -266,7 +270,8 @@
 	 font->Version = (char*)calloc(sizeof(char),length+1);
 	 strncpy(font->Version,(const char*)strings+offset,length);
 	 font->Version[length]=(char)NULL;
-	 
+	 replace_newlines_with_spaces(font->Version);
+
 #ifdef DEBUG_TRUETYPE
 	 debug("font->Version=\"%s\"",font->Version);
 #endif
@@ -280,7 +285,8 @@
 	 font->PostName = (char*)calloc(sizeof(char),length+1);
 	 strncpy(font->PostName,(const char*)strings+offset,length);
 	 font->PostName[length]=(char)NULL;
-	 
+	 replace_newlines_with_spaces(font->PostName);
+
 #ifdef DEBUG_TRUETYPE
 	 debug("font->PostName=\"%s\"",font->PostName);
 #endif
@@ -294,6 +300,7 @@
 	 font->Trademark = (char*)calloc(sizeof(char),length+1);
 	 strncpy(font->Trademark,(const char*)strings+offset,length);
 	 font->Trademark[length]=(char)NULL;
+	 replace_newlines_with_spaces(font->Trademark);
 	 
 #ifdef DEBUG_TRUETYPE
 	 debug("font->Trademark=\"%s\"",font->Trademark);
@@ -343,7 +350,7 @@
 
 /* If there is a Copyright notice, put it here too. */
 if( font->Copyright != (char*)NULL )
-	stream.printf("%%%%Copyright: %s\n",font->Copyright);
+ stream.printf("%%%%Copyright: %s\n",font->Copyright);
 
 /* We created this file. */
 if( font->target_type == PS_TYPE_42 )
Modified: trunk/matplotlib/ttconv/ttutil.cpp
===================================================================
--- trunk/matplotlib/ttconv/ttutil.cpp	2007年07月16日 12:02:47 UTC (rev 3537)
+++ trunk/matplotlib/ttconv/ttutil.cpp	2007年07月16日 13:16:25 UTC (rev 3538)
@@ -62,3 +62,12 @@
 this->write(a);
 this->write("\n");
 }
+
+void replace_newlines_with_spaces(char *a) {
+ char* i = a;
+ while (*i != 0) {
+ if (*i == '\n')
+ *i = ' ';
+ i++;
+ }
+}
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
Revision: 3537
 http://matplotlib.svn.sourceforge.net/matplotlib/?rev=3537&view=rev
Author: mdboom
Date: 2007年07月16日 05:02:47 -0700 (2007年7月16日)
Log Message:
-----------
Updated pyparsing to latest stable version (1.4.6) and updating
mathtext to support it.
Modified Paths:
--------------
 branches/mathtext_mgd/lib/matplotlib/mathtext.py
 branches/mathtext_mgd/lib/matplotlib/pyparsing.py
Modified: branches/mathtext_mgd/lib/matplotlib/mathtext.py
===================================================================
--- branches/mathtext_mgd/lib/matplotlib/mathtext.py	2007年07月16日 08:01:21 UTC (rev 3536)
+++ branches/mathtext_mgd/lib/matplotlib/mathtext.py	2007年07月16日 12:02:47 UTC (rev 3537)
@@ -135,7 +135,8 @@
 from matplotlib import verbose
 from matplotlib.pyparsing import Literal, Word, OneOrMore, ZeroOrMore, \
 Combine, Group, Optional, Forward, NotAny, alphas, nums, alphanums, \
- StringStart, StringEnd, ParseException, FollowedBy, Regex
+ StringStart, StringEnd, ParseException, FollowedBy, Regex, \
+ operatorPrecedence, opAssoc, ParseResults
 
 from matplotlib.afm import AFM
 from matplotlib.cbook import enumerate, iterable, Bunch
@@ -1259,7 +1260,7 @@
 
 def expression(self, s, loc, toks):
 self.expr = ExpressionElement(toks)
- return loc, [self.expr]
+ return [self.expr]
 
 def space(self, s, loc, toks):
 assert(len(toks)==1)
@@ -1271,7 +1272,7 @@
 
 element = SpaceElement(num)
 self.symbols.append(element)
- return loc, [element]
+ return [element]
 
 def symbol(self, s, loc, toks):
 
@@ -1300,7 +1301,7 @@
 sym = SymbolElement(toks[0])
 self.symbols.append(sym)
 
- return loc, [sym]
+ return [sym]
 
 def composite(self, s, loc, toks):
 
@@ -1315,7 +1316,7 @@
 self.symbols.append(sym0)
 self.symbols.append(sym1)
 
- return loc, [sym0]
+ return [sym0]
 
 def accent(self, s, loc, toks):
 
@@ -1343,13 +1344,13 @@
 sym.neighbors['above'] = above
 sym.set_pady(1)
 self.symbols.append(above)
- return loc, [sym]
+ return [sym]
 
 def group(self, s, loc, toks):
 assert(len(toks)==1)
 #print 'grp', toks
 grp = GroupElement(toks[0])
- return loc, [grp]
+ return [grp]
 
 def font(self, s, loc, toks):
 
@@ -1357,7 +1358,7 @@
 name, grp = toks[0]
 #print 'fontgrp', toks
 grp.set_font(name[1:]) # suppress the slash
- return loc, [grp]
+ return [grp]
 
 def subscript(self, s, loc, toks):
 assert(len(toks)==1)
@@ -1391,7 +1392,7 @@
 else:
 prev.neighbors['superscript'] = next
 
- return loc, [prev]
+ return [prev]
 
 def subsuperscript(self, s, loc, toks):
 assert(len(toks)==1)
@@ -1405,7 +1406,7 @@
 prev.neighbors['subscript'] = down
 prev.neighbors['superscript'] = up
 
- return loc, [prev]
+ return [prev]
 
 
 
Modified: branches/mathtext_mgd/lib/matplotlib/pyparsing.py
===================================================================
--- branches/mathtext_mgd/lib/matplotlib/pyparsing.py	2007年07月16日 08:01:21 UTC (rev 3536)
+++ branches/mathtext_mgd/lib/matplotlib/pyparsing.py	2007年07月16日 12:02:47 UTC (rev 3537)
@@ -1,6 +1,6 @@
 # module pyparsing.py
 #
-# Copyright (c) 2003,2004,2005 Paul T. McGuire
+# Copyright (c) 2003-2007 Paul T. McGuire
 #
 # Permission is hereby granted, free of charge, to any person obtaining
 # a copy of this software and associated documentation files (the
@@ -21,27 +21,24 @@
 # TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
 # SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 #
-# Todo:
-# - add pprint() - pretty-print output of defined BNF
-#
 #from __future__ import generators
 
 __doc__ = \
 """
 pyparsing module - Classes and methods to define and execute parsing grammars
 
-The pyparsing module is an alternative approach to creating and executing simple grammars,
+The pyparsing module is an alternative approach to creating and executing simple grammars, 
 vs. the traditional lex/yacc approach, or the use of regular expressions. With pyparsing, you
-don't need to learn a new syntax for defining grammars or matching expressions - the parsing module
+don't need to learn a new syntax for defining grammars or matching expressions - the parsing module 
 provides a library of classes that you use to construct the grammar directly in Python.
 
 Here is a program to parse "Hello, World!" (or any greeting of the form "<salutation>, <addressee>!")::
 
 from pyparsing import Word, alphas
-
+ 
 # define grammar of a greeting
- greet = Word( alphas ) + "," + Word( alphas ) + "!"
-
+ greet = Word( alphas ) + "," + Word( alphas ) + "!" 
+ 
 hello = "Hello, World!"
 print hello, "->", greet.parseString( hello )
 
@@ -49,10 +46,10 @@
 
 Hello, World! -> ['Hello', ',', 'World', '!']
 
-The Python representation of the grammar is quite readable, owing to the self-explanatory
+The Python representation of the grammar is quite readable, owing to the self-explanatory 
 class names, and the use of '+', '|' and '^' operators.
 
-The parsed results returned from parseString() can be accessed as a nested list, a dictionary, or an
+The parsed results returned from parseString() can be accessed as a nested list, a dictionary, or an 
 object with named attributes.
 
 The pyparsing module handles some of the problems that are typically vexing when writing text parsers:
@@ -60,15 +57,18 @@
 - quoted strings
 - embedded comments
 """
-__version__ = "1.3.4alpha1"
-__versionTime__ = "14 December 2005 05:48"
+__version__ = "1.4.6"
+__versionTime__ = "11 April 2007 16:41"
 __author__ = "Paul McGuire <pt...@us...>"
 
 import string
+from weakref import ref as wkref
 import copy,sys
 import warnings
 import re
-#sys.stderr.write( "testing pyparsing module, version %s, %s\n" % (__version__,__versionTime__ ) )
+import sre_constants
+import xml.sax.saxutils
+#~ sys.stderr.write( "testing pyparsing module, version %s, %s\n" % (__version__,__versionTime__ ) )
 
 def _ustr(obj):
 """Drop-in replacement for str(obj) that tries to be Unicode friendly. It first tries
@@ -79,7 +79,7 @@
 # If this works, then _ustr(obj) has the same behaviour as str(obj), so
 # it won't break any existing code.
 return str(obj)
-
+ 
 except UnicodeEncodeError, e:
 # The Python docs (http://docs.python.org/ref/customization.html#l2h-182)
 # state that "The return value must be a string object". However, does a
@@ -96,21 +96,29 @@
 
 def _str2dict(strg):
 return dict( [(c,0) for c in strg] )
+ #~ return set( [c for c in strg] )
 
+class _Constants(object):
+ pass
+ 
 alphas = string.lowercase + string.uppercase
 nums = string.digits
 hexnums = nums + "ABCDEFabcdef"
-alphanums = alphas + nums
+alphanums = alphas + nums 
 
 class ParseBaseException(Exception):
 """base exception class for all parsing runtime exceptions"""
 __slots__ = ( "loc","msg","pstr","parserElement" )
 # Performance tuning: we construct a *lot* of these, so keep this
- # constructor as small and fast as possible
- def __init__( self, pstr, loc, msg, elem=None ):
+ # constructor as small and fast as possible 
+ def __init__( self, pstr, loc=0, msg=None, elem=None ):
 self.loc = loc
- self.msg = msg
- self.pstr = pstr
+ if msg is None:
+ self.msg = pstr
+ self.pstr = ""
+ else:
+ self.msg = msg
+ self.pstr = pstr
 self.parserElement = elem
 
 def __getattr__( self, aname ):
@@ -129,55 +137,78 @@
 raise AttributeError, aname
 
 def __str__( self ):
- return "%s (at char %d), (line:%d, col:%d)" % ( self.msg, self.loc, self.lineno, self.column )
+ return "%s (at char %d), (line:%d, col:%d)" % \
+ ( self.msg, self.loc, self.lineno, self.column )
 def __repr__( self ):
 return _ustr(self)
 def markInputline( self, markerString = ">!<" ):
- """Extracts the exception line from the input string, and marks
+ """Extracts the exception line from the input string, and marks 
 the location of the exception with a special symbol.
 """
 line_str = self.line
 line_column = self.column - 1
 if markerString:
- line_str = "".join( [line_str[:line_column], markerString, line_str[line_column:]])
+ line_str = "".join( [line_str[:line_column],
+ markerString, line_str[line_column:]])
 return line_str.strip()
 
 class ParseException(ParseBaseException):
- """exception thrown when parse expressions don't match class"""
- """supported attributes by name are:
+ """exception thrown when parse expressions don't match class;
+ supported attributes by name are:
 - lineno - returns the line number of the exception text
 - col - returns the column number of the exception text
 - line - returns the line containing the exception text
 """
 pass
-
+ 
 class ParseFatalException(ParseBaseException):
 """user-throwable exception thrown when inconsistent parse content
 is found; stops all parsing immediately"""
 pass
 
+#~ class ReparseException(ParseBaseException):
+ #~ """Experimental class - parse actions can raise this exception to cause
+ #~ pyparsing to reparse the input string:
+ #~ - with a modified input string, and/or
+ #~ - with a modified start location
+ #~ Set the values of the ReparseException in the constructor, and raise the
+ #~ exception in a parse action to cause pyparsing to use the new string/location.
+ #~ Setting the values as None causes no change to be made.
+ #~ """
+ #~ def __init_( self, newstring, restartLoc ):
+ #~ self.newParseText = newstring
+ #~ self.reparseLoc = restartLoc
+
 class RecursiveGrammarException(Exception):
 """exception thrown by validate() if the grammar could be improperly recursive"""
 def __init__( self, parseElementList ):
 self.parseElementTrace = parseElementList
-
+ 
 def __str__( self ):
 return "RecursiveGrammarException: %s" % self.parseElementTrace
 
+class _ParseResultsWithOffset(object):
+ def __init__(self,p1,p2):
+ self.tup = (p1,p2)
+ def __getitem__(self,i):
+ return self.tup[i]
+ def __repr__(self):
+ return repr(self.tup)
+
 class ParseResults(object):
 """Structured parse results, to provide multiple means of access to the parsed data:
 - as a list (len(results))
 - by list index (results[0], results[1], etc.)
 - by attribute (results.<resultsName>)
 """
- __slots__ = ( "__toklist", "__tokdict", "__doinit", "__name", "__parent", "__modal" )
+ __slots__ = ( "__toklist", "__tokdict", "__doinit", "__name", "__parent", "__accumNames", "__weakref__" )
 def __new__(cls, toklist, name=None, asList=True, modal=True ):
 if isinstance(toklist, cls):
 return toklist
 retobj = object.__new__(cls)
 retobj.__doinit = True
 return retobj
-
+ 
 # Performance tuning: we construct a *lot* of these, so keep this
 # constructor as small and fast as possible
 def __init__( self, toklist, name=None, asList=True, modal=True ):
@@ -185,77 +216,87 @@
 self.__doinit = False
 self.__name = None
 self.__parent = None
- self.__modal = modal
+ self.__accumNames = {}
 if isinstance(toklist, list):
 self.__toklist = toklist[:]
 else:
 self.__toklist = [toklist]
 self.__tokdict = dict()
 
+ # this line is related to debugging the asXML bug
+ #~ asList = False
+ 
 if name:
- if not self.__name:
- self.__modal = self.__modal and modal
+ if not modal:
+ self.__accumNames[name] = 0
 if isinstance(name,int):
 name = _ustr(name) # will always return a str, but use _ustr for consistency
 self.__name = name
- if toklist:
- if isinstance(toklist,basestring):
+ if not toklist in (None,'',[]):
+ if isinstance(toklist,basestring): 
 toklist = [ toklist ]
 if asList:
 if isinstance(toklist,ParseResults):
- self[name] = (toklist.copy(),-1)
+ self[name] = _ParseResultsWithOffset(toklist.copy(),-1)
 else:
- self[name] = (ParseResults(toklist[0]),-1)
+ self[name] = _ParseResultsWithOffset(ParseResults(toklist[0]),-1)
 self[name].__name = name
 else:
 try:
 self[name] = toklist[0]
- except TypeError:
+ except (KeyError,TypeError):
 self[name] = toklist
 
 def __getitem__( self, i ):
 if isinstance( i, (int,slice) ):
 return self.__toklist[i]
 else:
- if self.__modal:
+ if i not in self.__accumNames:
 return self.__tokdict[i][-1][0]
 else:
 return ParseResults([ v[0] for v in self.__tokdict[i] ])
 
 def __setitem__( self, k, v ):
- if isinstance(v,tuple):
+ if isinstance(v,_ParseResultsWithOffset):
 self.__tokdict[k] = self.__tokdict.get(k,list()) + [v]
 sub = v[0]
+ elif isinstance(k,int):
+ self.__toklist[k] = v
+ sub = v
 else:
 self.__tokdict[k] = self.__tokdict.get(k,list()) + [(v,0)]
 sub = v
 if isinstance(sub,ParseResults):
- sub.__parent = self
-
+ sub.__parent = wkref(self)
+ 
 def __delitem__( self, i ):
- del self.__toklist[i]
+ if isinstance(i,(int,slice)):
+ del self.__toklist[i]
+ else:
+ del self._tokdict[i]
 
 def __contains__( self, k ):
 return self.__tokdict.has_key(k)
-
+ 
 def __len__( self ): return len( self.__toklist )
+ def __nonzero__( self ): return len( self.__toklist ) > 0
 def __iter__( self ): return iter( self.__toklist )
- def keys( self ):
+ def keys( self ): 
 """Returns all named result keys."""
 return self.__tokdict.keys()
-
- def items( self ):
+ 
+ def items( self ): 
 """Returns all named result keys and values as a list of tuples."""
- return [(k,v[-1][0]) for k,v in self.__tokdict.items()]
-
- def values( self ):
+ return [(k,self[k]) for k in self.__tokdict.keys()]
+ 
+ def values( self ): 
 """Returns all named result values."""
 return [ v[-1][0] for v in self.__tokdict.values() ]
 
 def __getattr__( self, name ):
 if name not in self.__slots__:
 if self.__tokdict.has_key( name ):
- if self.__modal:
+ if name not in self.__accumNames:
 return self.__tokdict[name][-1][0]
 else:
 return ParseResults([ v[0] for v in self.__tokdict[name] ])
@@ -263,19 +304,27 @@
 return ""
 return None
 
+ def __add__( self, other ):
+ ret = self.copy()
+ ret += other
+ return ret
+ 
 def __iadd__( self, other ):
 if other.__tokdict:
 offset = len(self.__toklist)
 addoffset = ( lambda a: (a<0 and offset) or (a+offset) )
- otherdictitems = [(k,(v[0],addoffset(v[1])) ) for (k,vlist) in other.__tokdict.items() for v in vlist]
+ otheritems = other.__tokdict.items()
+ otherdictitems = [(k, _ParseResultsWithOffset(v[0],addoffset(v[1])) )
+ for (k,vlist) in otheritems for v in vlist]
 for k,v in otherdictitems:
 self[k] = v
 if isinstance(v[0],ParseResults):
- v[0].__parent = self
+ v[0].__parent = wkref(self)
 self.__toklist += other.__toklist
+ self.__accumNames.update( other.__accumNames )
 del other
 return self
-
+ 
 def __repr__( self ):
 return "(%s, %s)" % ( repr( self.__toklist ), repr( self.__tokdict ) )
 
@@ -321,45 +370,52 @@
 ret = ParseResults( self.__toklist )
 ret.__tokdict = self.__tokdict.copy()
 ret.__parent = self.__parent
- ret.__modal = self.__modal
+ ret.__accumNames.update( self.__accumNames )
 ret.__name = self.__name
 return ret
-
+ 
 def asXML( self, doctag=None, namedItemsOnly=False, indent="", formatted=True ):
 """Returns the parse results as XML. Tags are created for tokens and lists that have defined results names."""
 nl = "\n"
 out = []
- namedItems = dict( [ (v[1],k) for (k,vlist) in self.__tokdict.items() for v in vlist ] )
+ namedItems = dict( [ (v[1],k) for (k,vlist) in self.__tokdict.items()
+ for v in vlist ] )
 nextLevelIndent = indent + " "
-
+ 
 # collapse out indents if formatting is not desired
 if not formatted:
 indent = ""
 nextLevelIndent = ""
 nl = ""
-
+ 
 selfTag = None
 if doctag is not None:
 selfTag = doctag
 else:
 if self.__name:
 selfTag = self.__name
-
+ 
 if not selfTag:
 if namedItemsOnly:
 return ""
 else:
 selfTag = "ITEM"
-
+ 
 out += [ nl, indent, "<", selfTag, ">" ]
-
+ 
 worklist = self.__toklist
 for i,res in enumerate(worklist):
 if isinstance(res,ParseResults):
 if i in namedItems:
- out += [ res.asXML(namedItems[i], namedItemsOnly and doctag is None, nextLevelIndent,formatted)]
+ out += [ res.asXML(namedItems[i],
+ namedItemsOnly and doctag is None,
+ nextLevelIndent,
+ formatted)]
 else:
- out += [ res.asXML(None, namedItemsOnly and doctag is None, nextLevelIndent,formatted)]
+ out += [ res.asXML(None,
+ namedItemsOnly and doctag is None,
+ nextLevelIndent,
+ formatted)]
 else:
 # individual token, see if there is a name for it
 resTag = None
@@ -370,51 +426,110 @@
 continue
 else:
 resTag = "ITEM"
- out += [ nl, nextLevelIndent, "<", resTag, ">", _ustr(res), "</", resTag, ">" ]
-
+ xmlBodyText = xml.sax.saxutils.escape(_ustr(res))
+ out += [ nl, nextLevelIndent, "<", resTag, ">",
+ xmlBodyText,
+ "</", resTag, ">" ]
+ 
 out += [ nl, indent, "</", selfTag, ">" ]
 return "".join(out)
 
-
 def __lookup(self,sub):
 for k,vlist in self.__tokdict.items():
 for v,loc in vlist:
 if sub is v:
 return k
 return None
-
+ 
 def getName(self):
 """Returns the results name for this token expression."""
 if self.__name:
 return self.__name
 elif self.__parent:
- par = self.__parent
+ par = self.__parent()
 if par:
 return par.__lookup(self)
 else:
 return None
- elif (len(self) == 1 and
+ elif (len(self) == 1 and 
 len(self.__tokdict) == 1 and
 self.__tokdict.values()[0][0][1] in (0,-1)):
 return self.__tokdict.keys()[0]
 else:
 return None
+ 
+ def dump(self,indent='',depth=0):
+ """Diagnostic method for listing out the contents of a ParseResults.
+ Accepts an optional indent argument so that this string can be embedded
+ in a nested display of other data."""
+ out = []
+ out.append( indent+_ustr(self.asList()) )
+ keys = self.items()
+ keys.sort()
+ for k,v in keys:
+ if out:
+ out.append('\n')
+ out.append( "%s%s- %s: " % (indent,(' '*depth), k) )
+ if isinstance(v,ParseResults):
+ if v.keys():
+ #~ out.append('\n')
+ out.append( v.dump(indent,depth+1) )
+ #~ out.append('\n')
+ else:
+ out.append(_ustr(v))
+ else:
+ out.append(_ustr(v))
+ #~ out.append('\n')
+ return "".join(out)
 
+ # add support for pickle protocol
+ def __getstate__(self):
+ return ( self.__toklist,
+ ( self.__tokdict.copy(),
+ self.__parent is not None and self.__parent() or None,
+ self.__accumNames,
+ self.__name ) )
+ 
+ def __setstate__(self,state):
+ self.__toklist = state[0]
+ self.__tokdict, \
+ par, \
+ inAccumNames, \
+ self.__name = state[1]
+ self.__accumNames = {}
+ self.__accumNames.update(inAccumNames)
+ if par is not None:
+ self.__parent = wkref(par)
+ else:
+ self.__parent = None
+
+
 def col (loc,strg):
- """Returns current column within a string, counting newlines as line separators
+ """Returns current column within a string, counting newlines as line separators.
 The first column is number 1.
+
+ Note: the default parsing behavior is to expand tabs in the input string
+ before starting the parsing process. See L{I{ParserElement.parseString}<ParserElement.parseString>} for more information
+ on parsing strings containing <TAB>s, and suggested methods to maintain a
+ consistent view of the parsed string, the parse location, and line and column
+ positions within the parsed string.
 """
- return loc - strg.rfind("\n", 0, loc)
+ return (loc<len(strg) and strg[loc] == '\n') and 1 or loc - strg.rfind("\n", 0, loc)
 
 def lineno(loc,strg):
- """Returns current line number within a string, counting newlines as line separators
+ """Returns current line number within a string, counting newlines as line separators.
 The first line is number 1.
+ 
+ Note: the default parsing behavior is to expand tabs in the input string
+ before starting the parsing process. See L{I{ParserElement.parseString}<ParserElement.parseString>} for more information
+ on parsing strings containing <TAB>s, and suggested methods to maintain a
+ consistent view of the parsed string, the parse location, and line and column
+ positions within the parsed string.
 """
 return strg.count("\n",0,loc) + 1
 
 def line( loc, strg ):
- """Returns the line of text containing loc within a string, counting newlines as line separators
- The first line is number 1.
+ """Returns the line of text containing loc within a string, counting newlines as line separators.
 """
 lastCR = strg.rfind("\n", 0, loc)
 nextCR = strg.find("\n", loc)
@@ -424,13 +539,13 @@
 return strg[lastCR+1:]
 
 def _defaultStartDebugAction( instring, loc, expr ):
- print "Match",expr,"at loc",loc,"(%d,%d)" % ( lineno(loc,instring), col(loc,instring) )
+ print "Match",_ustr(expr),"at loc",loc,"(%d,%d)" % ( lineno(loc,instring), col(loc,instring) )
 
 def _defaultSuccessDebugAction( instring, startloc, endloc, expr, toks ):
- print "Matched",expr,"->",toks.asList()
-
+ print "Matched",_ustr(expr),"->",toks.asList()
+ 
 def _defaultExceptionDebugAction( instring, loc, expr, exc ):
- print "Exception raised:", exc
+ print "Exception raised:", _ustr(exc)
 
 def nullDebugAction(*args):
 """'Do-nothing' debug action, to suppress debugging output during parsing."""
@@ -439,37 +554,44 @@
 class ParserElement(object):
 """Abstract base level parser element class."""
 DEFAULT_WHITE_CHARS = " \n\t\r"
-
+ 
 def setDefaultWhitespaceChars( chars ):
 """Overrides the default whitespace chars
 """
 ParserElement.DEFAULT_WHITE_CHARS = chars
 setDefaultWhitespaceChars = staticmethod(setDefaultWhitespaceChars)
-
+ 
 def __init__( self, savelist=False ):
- self.parseAction = None
+ self.parseAction = list()
+ self.failAction = None
 #~ self.name = "<unknown>" # don't define self.name, let subclasses try/except upcall
 self.strRepr = None
 self.resultsName = None
 self.saveAsList = savelist
 self.skipWhitespace = True
 self.whiteChars = ParserElement.DEFAULT_WHITE_CHARS
- self.mayReturnEmpty = False
+ self.copyDefaultWhiteChars = True
+ self.mayReturnEmpty = False # used when checking for left-recursion
 self.keepTabs = False
- self.ignoreExprs = []
+ self.ignoreExprs = list()
 self.debug = False
 self.streamlined = False
- self.mayIndexError = True
+ self.mayIndexError = True # used to optimize exception handling for subclasses that don't advance parse index
 self.errmsg = ""
- self.modalResults = True
- self.debugActions = ( None, None, None )
+ self.modalResults = True # used to mark results names as modal (report only last) or cumulative (list all)
+ self.debugActions = ( None, None, None ) #custom debug actions
 self.re = None
+ self.callPreparse = True # used to avoid redundant calls to preParse
+ self.callDuringTry = False
 
 def copy( self ):
- """Make a copy of this ParseElement. Useful for defining different parse actions
+ """Make a copy of this ParserElement. Useful for defining different parse actions
 for the same parsing pattern, using copies of the original parse element."""
 cpy = copy.copy( self )
- cpy.whiteChars = ParserElement.DEFAULT_WHITE_CHARS
+ cpy.parseAction = self.parseAction[:]
+ cpy.ignoreExprs = self.ignoreExprs[:]
+ if self.copyDefaultWhiteChars:
+ cpy.whiteChars = ParserElement.DEFAULT_WHITE_CHARS
 return cpy
 
 def setName( self, name ):
@@ -479,9 +601,9 @@
 return self
 
 def setResultsName( self, name, listAllMatches=False ):
- """Define name for referencing matching tokens as a nested attribute
+ """Define name for referencing matching tokens as a nested attribute 
 of the returned parse results.
- NOTE: this returns a *copy* of the original ParseElement object;
+ NOTE: this returns a *copy* of the original ParserElement object;
 this is so that the client can define a basic element, such as an
 integer, and reference it in multiple places with different names.
 """
@@ -490,19 +612,111 @@
 newself.modalResults = not listAllMatches
 return newself
 
- def setParseAction( self, fn ):
+ def normalizeParseActionArgs( f ):
+ """Internal method used to decorate parse actions that take fewer than 3 arguments,
+ so that all parse actions can be called as f(s,l,t)."""
+ STAR_ARGS = 4
+
+ try:
+ restore = None
+ if isinstance(f,type):
+ restore = f
+ f = f.__init__
+ if f.func_code.co_flags & STAR_ARGS:
+ return f
+ numargs = f.func_code.co_argcount
+ if hasattr(f,"im_self"):
+ numargs -= 1
+ if restore:
+ f = restore
+ except AttributeError:
+ try:
+ # not a function, must be a callable object, get info from the
+ # im_func binding of its bound __call__ method
+ if f.__call__.im_func.func_code.co_flags & STAR_ARGS:
+ return f
+ numargs = f.__call__.im_func.func_code.co_argcount
+ if hasattr(f.__call__,"im_self"):
+ numargs -= 1
+ except AttributeError:
+ # not a bound method, get info directly from __call__ method
+ if f.__call__.func_code.co_flags & STAR_ARGS:
+ return f
+ numargs = f.__call__.func_code.co_argcount
+ if hasattr(f.__call__,"im_self"):
+ numargs -= 1
+
+ #~ print "adding function %s with %d args" % (f.func_name,numargs)
+ if numargs == 3:
+ return f
+ else:
+ if numargs == 2:
+ def tmp(s,l,t):
+ return f(l,t)
+ elif numargs == 1:
+ def tmp(s,l,t):
+ return f(t)
+ else: #~ numargs == 0:
+ def tmp(s,l,t):
+ return f()
+ try:
+ tmp.__name__ = f.__name__
+ except AttributeError:
+ # no need for special handling if attribute doesnt exist
+ pass
+ try:
+ tmp.__doc__ = f.__doc__
+ except AttributeError:
+ # no need for special handling if attribute doesnt exist
+ pass
+ try:
+ tmp.__dict__.update(f.__dict__)
+ except AttributeError:
+ # no need for special handling if attribute doesnt exist
+ pass
+ return tmp
+ normalizeParseActionArgs = staticmethod(normalizeParseActionArgs)
+ 
+ def setParseAction( self, *fns, **kwargs ):
 """Define action to perform when successfully matching parse element definition.
- Parse action fn is a callable method with the arguments (s, loc, toks) where:
- - s = the original string being parsed
+ Parse action fn is a callable method with 0-3 arguments, called as fn(s,loc,toks),
+ fn(loc,toks), fn(toks), or just fn(), where:
+ - s = the original string being parsed (see note below)
 - loc = the location of the matching substring
 - toks = a list of the matched tokens, packaged as a ParseResults object
- If the function fn modifies the tokens, it can return them as the return
+ If the functions in fns modify the tokens, they can return them as the return
 value from fn, and the modified list of tokens will replace the original.
 Otherwise, fn does not need to return any value.
- """
- self.parseAction = fn
+ 
+ Note: the default parsing behavior is to expand tabs in the input string
+ before starting the parsing process. See L{I{parseString}<parseString>} for more information
+ on parsing strings containing <TAB>s, and suggested methods to maintain a
+ consistent view of the parsed string, the parse location, and line and column
+ positions within the parsed string.
+ """
+ self.parseAction = map(self.normalizeParseActionArgs, list(fns))
+ self.callDuringTry = ("callDuringTry" in kwargs and kwargs["callDuringTry"])
 return self
 
+ def addParseAction( self, *fns, **kwargs ):
+ """Add parse action to expression's list of parse actions. See L{I{setParseAction}<setParseAction>}."""
+ self.parseAction += map(self.normalizeParseActionArgs, list(fns))
+ self.callDuringTry = self.callDuringTry or ("callDuringTry" in kwargs and kwargs["callDuringTry"])
+ return self
+
+ def setFailAction( self, fn ):
+ """Define action to perform if parsing fails at this expression. 
+ Fail acton fn is a callable function that takes the arguments 
+ fn(s,loc,expr,err) where:
+ - s = string being parsed
+ - loc = location where expression match was attempted and failed
+ - expr = the parse expression that failed
+ - err = the exception thrown
+ The function returns no value. It may throw ParseFatalException
+ if it is desired to stop parsing immediately."""
+ self.failAction = fn
+ return self
+ 
 def skipIgnorables( self, instring, loc ):
 exprsFound = True
 while exprsFound:
@@ -510,7 +724,7 @@
 for e in self.ignoreExprs:
 try:
 while 1:
- loc,dummy = e.parse( instring, loc )
+ loc,dummy = e._parse( instring, loc )
 exprsFound = True
 except ParseException:
 pass
@@ -519,13 +733,13 @@
 def preParse( self, instring, loc ):
 if self.ignoreExprs:
 loc = self.skipIgnorables( instring, loc )
-
+ 
 if self.skipWhitespace:
 wt = self.whiteChars
 instrlen = len(instring)
 while loc < instrlen and instring[loc] in wt:
 loc += 1
-
+ 
 return loc
 
 def parseImpl( self, instring, loc, doActions=True ):
@@ -535,66 +749,70 @@
 return tokenlist
 
 #~ @profile
- def parse( self, instring, loc, doActions=True, callPreParse=True ):
+ def _parseNoCache( self, instring, loc, doActions=True, callPreParse=True ):
 debugging = ( self.debug ) #and doActions )
 
- if debugging:
+ if debugging or self.failAction:
 #~ print "Match",self,"at loc",loc,"(%d,%d)" % ( lineno(loc,instring), col(loc,instring) )
 if (self.debugActions[0] ):
 self.debugActions[0]( instring, loc, self )
- if callPreParse:
- loc = self.preParse( instring, loc )
+ if callPreParse and self.callPreparse:
+ preloc = self.preParse( instring, loc )
+ else:
+ preloc = loc
 tokensStart = loc
 try:
 try:
- loc,tokens = self.parseImpl( instring, loc, doActions )
+ loc,tokens = self.parseImpl( instring, preloc, doActions )
 except IndexError:
- raise ParseException, ( instring, len(instring), self.errmsg, self )
+ raise ParseException( instring, len(instring), self.errmsg, self )
 except ParseException, err:
 #~ print "Exception raised:", err
- if (self.debugActions[2] ):
+ if self.debugActions[2]:
 self.debugActions[2]( instring, tokensStart, self, err )
+ if self.failAction:
+ self.failAction( instring, tokensStart, self, err )
 raise
 else:
 if callPreParse:
- loc = self.preParse( instring, loc )
+ preloc = self.preParse( instring, loc )
+ else:
+ preloc = loc
 tokensStart = loc
 if self.mayIndexError or loc >= len(instring):
 try:
- loc,tokens = self.parseImpl( instring, loc, doActions )
+ loc,tokens = self.parseImpl( instring, preloc, doActions )
 except IndexError:
- raise ParseException, ( instring, len(instring), self.errmsg, self )
+ raise ParseException( instring, len(instring), self.errmsg, self )
 else:
- loc,tokens = self.parseImpl( instring, loc, doActions )
-
+ loc,tokens = self.parseImpl( instring, preloc, doActions )
+ 
 tokens = self.postParse( instring, loc, tokens )
 
 retTokens = ParseResults( tokens, self.resultsName, asList=self.saveAsList, modal=self.modalResults )
- if self.parseAction and doActions:
+ if self.parseAction and (doActions or self.callDuringTry):
 if debugging:
 try:
- tokens = self.parseAction( instring, tokensStart, retTokens )
- if tokens is not None:
- if isinstance(tokens,tuple):
- tokens = tokens[1]
- retTokens = ParseResults( tokens,
- self.resultsName,
- asList=self.saveAsList and isinstance(tokens,(ParseResults,list)),
- modal=self.modalResults )
+ for fn in self.parseAction:
+ tokens = fn( instring, tokensStart, retTokens )
+ if tokens is not None:
+ retTokens = ParseResults( tokens, 
+ self.resultsName, 
+ asList=self.saveAsList and isinstance(tokens,(ParseResults,list)), 
+ modal=self.modalResults )
 except ParseException, err:
 #~ print "Exception raised in user parse action:", err
 if (self.debugActions[2] ):
 self.debugActions[2]( instring, tokensStart, self, err )
 raise
 else:
- tokens = self.parseAction( instring, tokensStart, retTokens )
- if tokens is not None:
- if isinstance(tokens,tuple):
- tokens = tokens[1]
- retTokens = ParseResults( tokens,
- self.resultsName,
- asList=self.saveAsList and isinstance(tokens,(ParseResults,list)),
- modal=self.modalResults )
+ for fn in self.parseAction:
+ tokens = fn( instring, tokensStart, retTokens )
+ if tokens is not None:
+ retTokens = ParseResults( tokens, 
+ self.resultsName, 
+ asList=self.saveAsList and isinstance(tokens,(ParseResults,list)), 
+ modal=self.modalResults )
 
 if debugging:
 #~ print "Matched",self,"->",retTokens.asList()
@@ -604,53 +822,128 @@
 return loc, retTokens
 
 def tryParse( self, instring, loc ):
- return self.parse( instring, loc, doActions=False )[0]
+ return self._parse( instring, loc, doActions=False )[0]
+ 
+ # this method gets repeatedly called during backtracking with the same arguments -
+ # we can cache these arguments and save ourselves the trouble of re-parsing the contained expression
+ def _parseCache( self, instring, loc, doActions=True, callPreParse=True ):
+ #if doActions and self.parseAction:
+ # return self._parseNoCache( instring, loc, doActions, callPreParse )
+ lookup = (self,instring,loc,callPreParse,doActions)
+ if lookup in ParserElement._exprArgCache:
+ value = ParserElement._exprArgCache[ lookup ]
+ if isinstance(value,Exception):
+ if isinstance(value,ParseBaseException):
+ value.loc = loc
+ raise value
+ return value
+ else:
+ try:
+ ParserElement._exprArgCache[ lookup ] = \
+ value = self._parseNoCache( instring, loc, doActions, callPreParse )
+ return value
+ except ParseBaseException, pe:
+ ParserElement._exprArgCache[ lookup ] = pe
+ raise
 
+ _parse = _parseNoCache
+
+ # argument cache for optimizing repeated calls when backtracking through recursive expressions
+ _exprArgCache = {}
+ def resetCache():
+ ParserElement._exprArgCache.clear()
+ resetCache = staticmethod(resetCache)
+ 
+ _packratEnabled = False
+ def enablePackrat():
+ """Enables "packrat" parsing, which adds memoizing to the parsing logic.
+ Repeated parse attempts at the same string location (which happens 
+ often in many complex grammars) can immediately return a cached value, 
+ instead of re-executing parsing/validating code. Memoizing is done of
+ both valid results and parsing exceptions.
+ 
+ This speedup may break existing programs that use parse actions that 
+ have side-effects. For this reason, packrat parsing is disabled when
+ you first import pyparsing. To activate the packrat feature, your
+ program must call the class method ParserElement.enablePackrat(). If
+ your program uses psyco to "compile as you go", you must call 
+ enablePackrat before calling psyco.full(). If you do not do this,
+ Python will crash. For best results, call enablePackrat() immediately
+ after importing pyparsing.
+ """
+ if not ParserElement._packratEnabled:
+ ParserElement._packratEnabled = True
+ ParserElement._parse = ParserElement._parseCache
+ enablePackrat = staticmethod(enablePackrat)
+
 def parseString( self, instring ):
 """Execute the parse expression with the given string.
- This is the main interface to the client code, once the complete
+ This is the main interface to the client code, once the complete 
 expression has been built.
+ 
+ Note: parseString implicitly calls expandtabs() on the input string,
+ in order to report proper column numbers in parse actions. 
+ If the input string contains tabs and
+ the grammar uses parse actions that use the loc argument to index into the 
+ string being parsed, you can ensure you have a consistent view of the input 
+ string by:
+ - calling parseWithTabs on your grammar before calling parseString
+ (see L{I{parseWithTabs}<parseWithTabs>})
+ - define your parse action using the full (s,loc,toks) signature, and 
+ reference the input string using the parse action's s argument
+ - explictly expand the tabs in your input string before calling 
+ parseString 
 """
+ ParserElement.resetCache()
 if not self.streamlined:
 self.streamline()
- self.saveAsList = True
+ #~ self.saveAsList = True
 for e in self.ignoreExprs:
 e.streamline()
 if self.keepTabs:
- loc, tokens = self.parse( instring, 0 )
+ loc, tokens = self._parse( instring, 0 )
 else:
- loc, tokens = self.parse( instring.expandtabs(), 0 )
+ loc, tokens = self._parse( instring.expandtabs(), 0 )
 return tokens
 
- def scanString( self, instring ):
- """Scan the input string for expression matches. Each match will return the matching tokens, start location, and end location."""
+ def scanString( self, instring, maxMatches=sys.maxint ):
+ """Scan the input string for expression matches. Each match will return the 
+ matching tokens, start location, and end location. May be called with optional
+ maxMatches argument, to clip scanning after 'n' matches are found.
+ 
+ Note that the start and end locations are reported relative to the string
+ being parsed. See L{I{parseString}<parseString>} for more information on parsing 
+ strings with embedded tabs."""
 if not self.streamlined:
 self.streamline()
 for e in self.ignoreExprs:
 e.streamline()
-
+ 
 if not self.keepTabs:
- instring = instring.expandtabs()
+ instring = _ustr(instring).expandtabs()
 instrlen = len(instring)
 loc = 0
 preparseFn = self.preParse
- parseFn = self.parse
- while loc < instrlen:
+ parseFn = self._parse
+ ParserElement.resetCache()
+ matches = 0
+ while loc <= instrlen and matches < maxMatches:
 try:
- loc = preparseFn( instring, loc )
- nextLoc,tokens = parseFn( instring, loc, callPreParse=False )
+ preloc = preparseFn( instring, loc )
+ nextLoc,tokens = parseFn( instring, preloc, callPreParse=False )
 except ParseException:
- loc += 1
+ loc = preloc+1
 else:
- yield tokens, loc, nextLoc
+ matches += 1
+ yield tokens, preloc, nextLoc
 loc = nextLoc
-
+ 
 def transformString( self, instring ):
 """Extension to scanString, to modify matching text with modified tokens that may
- be returned from a parse action. To use transformString, define a grammar and
- attach a parse action to it that modifies the returned token list.
- Invoking transformString() on a target string will then scan for matches,
- and replace the matched text patterns according to the logic in the parse
+ be returned from a parse action. To use transformString, define a grammar and 
+ attach a parse action to it that modifies the returned token list. 
+ Invoking transformString() on a target string will then scan for matches, 
+ and replace the matched text patterns according to the logic in the parse 
 action. transformString() returns the resulting transformed string."""
 out = []
 lastE = 0
@@ -668,54 +961,85 @@
 out.append(t)
 lastE = e
 out.append(instring[lastE:])
- return "".join(out)
+ return "".join(map(_ustr,out))
 
+ def searchString( self, instring, maxMatches=sys.maxint ):
+ """Another extension to scanString, simplifying the access to the tokens found
+ to match the given parse expression. May be called with optional
+ maxMatches argument, to clip searching after 'n' matches are found.
+ """
+ return ParseResults([ t for t,s,e in self.scanString( instring, maxMatches ) ])
+ 
 def __add__(self, other ):
 """Implementation of + operator - returns And"""
 if isinstance( other, basestring ):
 other = Literal( other )
+ if not isinstance( other, ParserElement ):
+ warnings.warn("Cannot add element of type %s to ParserElement" % type(other),
+ SyntaxWarning, stacklevel=2)
 return And( [ self, other ] )
 
 def __radd__(self, other ):
 """Implementation of += operator"""
 if isinstance( other, basestring ):
 other = Literal( other )
+ if not isinstance( other, ParserElement ):
+ warnings.warn("Cannot add element of type %s to ParserElement" % type(other),
+ SyntaxWarning, stacklevel=2)
 return other + self
 
 def __or__(self, other ):
 """Implementation of | operator - returns MatchFirst"""
 if isinstance( other, basestring ):
 other = Literal( other )
+ if not isinstance( other, ParserElement ):
+ warnings.warn("Cannot add element of type %s to ParserElement" % type(other),
+ SyntaxWarning, stacklevel=2)
 return MatchFirst( [ self, other ] )
 
 def __ror__(self, other ):
 """Implementation of |= operator"""
 if isinstance( other, basestring ):
 other = Literal( other )
+ if not isinstance( other, ParserElement ):
+ warnings.warn("Cannot add element of type %s to ParserElement" % type(other),
+ SyntaxWarning, stacklevel=2)
 return other | self
 
 def __xor__(self, other ):
 """Implementation of ^ operator - returns Or"""
 if isinstance( other, basestring ):
 other = Literal( other )
+ if not isinstance( other, ParserElement ):
+ warnings.warn("Cannot add element of type %s to ParserElement" % type(other),
+ SyntaxWarning, stacklevel=2)
 return Or( [ self, other ] )
 
 def __rxor__(self, other ):
 """Implementation of ^= operator"""
 if isinstance( other, basestring ):
 other = Literal( other )
+ if not isinstance( other, ParserElement ):
+ warnings.warn("Cannot add element of type %s to ParserElement" % type(other),
+ SyntaxWarning, stacklevel=2)
 return other ^ self
 
 def __and__(self, other ):
 """Implementation of & operator - returns Each"""
 if isinstance( other, basestring ):
 other = Literal( other )
+ if not isinstance( other, ParserElement ):
+ warnings.warn("Cannot add element of type %s to ParserElement" % type(other),
+ SyntaxWarning, stacklevel=2)
 return Each( [ self, other ] )
 
 def __rand__(self, other ):
 """Implementation of right-& operator"""
 if isinstance( other, basestring ):
 other = Literal( other )
+ if not isinstance( other, ParserElement ):
+ warnings.warn("Cannot add element of type %s to ParserElement" % type(other),
+ SyntaxWarning, stacklevel=2)
 return other & self
 
 def __invert__( self ):
@@ -723,13 +1047,13 @@
 return NotAny( self )
 
 def suppress( self ):
- """Suppresses the output of this ParseElement; useful to keep punctuation from
+ """Suppresses the output of this ParserElement; useful to keep punctuation from
 cluttering up returned output.
 """
 return Suppress( self )
 
 def leaveWhitespace( self ):
- """Disables the skipping of whitespace before matching the characters in the
+ """Disables the skipping of whitespace before matching the characters in the 
 ParserElement's defined pattern. This is normally only used internally by
 the pyparsing module, but may be needed in some whitespace-sensitive grammars.
 """
@@ -741,16 +1065,18 @@
 """
 self.skipWhitespace = True
 self.whiteChars = chars
-
+ self.copyDefaultWhiteChars = False
+ return self
+ 
 def parseWithTabs( self ):
 """Overrides default behavior to expand <TAB>s to spaces before parsing the input string.
- Must be called before parseString when the input grammar contains elements that
+ Must be called before parseString when the input grammar contains elements that 
 match <TAB> characters."""
 self.keepTabs = True
 return self
-
+ 
 def ignore( self, other ):
- """Define expression to be ignored (e.g., comments) while doing pattern
+ """Define expression to be ignored (e.g., comments) while doing pattern 
 matching; may be called repeatedly, to define multiple comment or other
 ignorable patterns.
 """
@@ -763,8 +1089,8 @@
 
 def setDebugActions( self, startAction, successAction, exceptionAction ):
 """Enable display of debugging messages while doing pattern matching."""
- self.debugActions = (startAction or _defaultStartDebugAction,
- successAction or _defaultSuccessDebugAction,
+ self.debugActions = (startAction or _defaultStartDebugAction, 
+ successAction or _defaultSuccessDebugAction, 
 exceptionAction or _defaultExceptionDebugAction)
 self.debug = True
 return self
@@ -782,15 +1108,15 @@
 
 def __repr__( self ):
 return _ustr(self)
-
+ 
 def streamline( self ):
 self.streamlined = True
 self.strRepr = None
 return self
-
+ 
 def checkRecursion( self, parseElementList ):
 pass
-
+ 
 def validate( self, validateTrace=[] ):
 """Check defined expressions for valid structure, check for infinite recursive definitions."""
 self.checkRecursion( [] )
@@ -840,7 +1166,7 @@
 self.mayIndexError = False
 self.errmsg = "Unmatchable token"
 self.myException.msg = self.errmsg
-
+ 
 def parseImpl( self, instring, loc, doActions=True ):
 exc = self.myException
 exc.loc = loc
@@ -857,9 +1183,10 @@
 try:
 self.firstMatchChar = matchString[0]
 except IndexError:
- warnings.warn("null string passed to Literal; use Empty() instead",
+ warnings.warn("null string passed to Literal; use Empty() instead", 
 SyntaxWarning, stacklevel=2)
- self.name = '"%s"' % self.match
+ self.__class__ = Empty
+ self.name = '"%s"' % _ustr(self.match)
 self.errmsg = "Expected " + self.name
 self.mayReturnEmpty = False
 self.myException.msg = self.errmsg
@@ -873,14 +1200,14 @@
 if (instring[loc] == self.firstMatchChar and
 (self.matchLen==1 or instring.startswith(self.match,loc)) ):
 return loc+self.matchLen, self.match
- #~ raise ParseException, ( instring, loc, self.errmsg )
+ #~ raise ParseException( instring, loc, self.errmsg )
 exc = self.myException
 exc.loc = loc
 exc.pstr = instring
 raise exc
 
 class Keyword(Token):
- """Token to exactly match a specified string as a keyword, that is, it must be
+ """Token to exactly match a specified string as a keyword, that is, it must be 
 immediately followed by a non-keyword character. Compare with Literal::
 Literal("if") will match the leading 'if' in 'ifAndOnlyIf'.
 Keyword("if") will not; it will only match the leading 'if in 'if x=1', or 'if(y==2)'
@@ -890,7 +1217,7 @@
 matching, default is False.
 """
 DEFAULT_KEYWORD_CHARS = alphanums+"_$"
-
+ 
 def __init__( self, matchString, identChars=DEFAULT_KEYWORD_CHARS, caseless=False ):
 super(Keyword,self).__init__()
 self.match = matchString
@@ -898,7 +1225,7 @@
 try:
 self.firstMatchChar = matchString[0]
 except IndexError:
- warnings.warn("null string passed to Keyword; use Empty() instead",
+ warnings.warn("null string passed to Keyword; use Empty() instead", 
 SyntaxWarning, stacklevel=2)
 self.name = '"%s"' % self.match
 self.errmsg = "Expected " + self.name
@@ -914,29 +1241,31 @@
 def parseImpl( self, instring, loc, doActions=True ):
 if self.caseless:
 if ( (instring[ loc:loc+self.matchLen ].upper() == self.caselessmatch) and
- (loc >= len(instring)-self.matchLen or instring[loc+self.matchLen].upper() not in self.identChars) ):
+ (loc >= len(instring)-self.matchLen or instring[loc+self.matchLen].upper() not in self.identChars) and
+ (loc == 0 or instring[loc-1].upper() not in self.identChars) ):
 return loc+self.matchLen, self.match
 else:
 if (instring[loc] == self.firstMatchChar and
 (self.matchLen==1 or instring.startswith(self.match,loc)) and
- (loc >= len(instring)-self.matchLen or instring[loc+self.matchLen] not in self.identChars) ):
+ (loc >= len(instring)-self.matchLen or instring[loc+self.matchLen] not in self.identChars) and
+ (loc == 0 or instring[loc-1] not in self.identChars) ):
 return loc+self.matchLen, self.match
- #~ raise ParseException, ( instring, loc, self.errmsg )
+ #~ raise ParseException( instring, loc, self.errmsg )
 exc = self.myException
 exc.loc = loc
 exc.pstr = instring
 raise exc
-
+ 
 def copy(self):
 c = super(Keyword,self).copy()
 c.identChars = Keyword.DEFAULT_KEYWORD_CHARS
 return c
-
+ 
 def setDefaultKeywordChars( chars ):
 """Overrides the default Keyword chars
 """
 Keyword.DEFAULT_KEYWORD_CHARS = chars
- setDefaultKeywordChars = staticmethod(setDefaultKeywordChars)
+ setDefaultKeywordChars = staticmethod(setDefaultKeywordChars) 
 
 
 class CaselessLiteral(Literal):
@@ -955,7 +1284,7 @@
 def parseImpl( self, instring, loc, doActions=True ):
 if instring[ loc:loc+self.matchLen ].upper() == self.match:
 return loc+self.matchLen, self.returnString
- #~ raise ParseException, ( instring, loc, self.errmsg )
+ #~ raise ParseException( instring, loc, self.errmsg )
 exc = self.myException
 exc.loc = loc
 exc.pstr = instring
@@ -963,13 +1292,13 @@
 
 class CaselessKeyword(Keyword):
 def __init__( self, matchString, identChars=Keyword.DEFAULT_KEYWORD_CHARS ):
- super(CaselessKeyword,self).__init__( matchString, identCars, caseless=True )
+ super(CaselessKeyword,self).__init__( matchString, identChars, caseless=True )
 
 def parseImpl( self, instring, loc, doActions=True ):
 if ( (instring[ loc:loc+self.matchLen ].upper() == self.caselessmatch) and
 (loc >= len(instring)-self.matchLen or instring[loc+self.matchLen].upper() not in self.identChars) ):
 return loc+self.matchLen, self.match
- #~ raise ParseException, ( instring, loc, self.errmsg )
+ #~ raise ParseException( instring, loc, self.errmsg )
 exc = self.myException
 exc.loc = loc
 exc.pstr = instring
@@ -982,7 +1311,7 @@
 defaults to the initial character set), and an optional minimum,
 maximum, and/or exact length.
 """
- def __init__( self, initChars, bodyChars=None, min=1, max=0, exact=0 ):
+ def __init__( self, initChars, bodyChars=None, min=1, max=0, exact=0, asKeyword=False ):
 super(Word,self).__init__()
 self.initCharsOrig = initChars
 self.initChars = _str2dict(initChars)
@@ -992,7 +1321,7 @@
 else:
 self.bodyCharsOrig = initChars
 self.bodyChars = _str2dict(initChars)
-
+ 
 self.maxSpecified = max > 0
 
 self.minLen = min
@@ -1010,20 +1339,26 @@
 self.errmsg = "Expected " + self.name
 self.myException.msg = self.errmsg
 self.mayIndexError = False
-
+ self.asKeyword = asKeyword
+ 
 if ' ' not in self.initCharsOrig+self.bodyCharsOrig and (min==1 and max==0 and exact==0):
 if self.bodyCharsOrig == self.initCharsOrig:
 self.reString = "[%s]+" % _escapeRegexRangeChars(self.initCharsOrig)
 elif len(self.bodyCharsOrig) == 1:
 self.reString = "%s[%s]*" % \
- (_escapeRegexChars(self.initCharsOrig),
+ (re.escape(self.initCharsOrig),
 _escapeRegexRangeChars(self.bodyCharsOrig),)
 else:
 self.reString = "[%s][%s]*" % \
 (_escapeRegexRangeChars(self.initCharsOrig),
 _escapeRegexRangeChars(self.bodyCharsOrig),)
- self.re = re.compile( self.reString )
-
+ if self.asKeyword:
+ self.reString = r"\b"+self.reString+r"\b"
+ try:
+ self.re = re.compile( self.reString )
+ except:
+ self.re = None
+ 
 def parseImpl( self, instring, loc, d...
 
[truncated message content]

Showing results of 5455

<< < 1 .. 216 217 218 219 > >> (Page 218 of 219)
Want the latest updates on software, tech news, and AI?
Get latest updates about software, tech news, and AI from SourceForge directly in your inbox once a month.
Thanks for helping keep SourceForge clean.
X





Briefly describe the problem (required):
Upload screenshot of ad (required):
Select a file, or drag & drop file here.
Screenshot instructions:

Click URL instructions:
Right-click on the ad, choose "Copy Link", then paste here →
(This may not be possible with some types of ads)

More information about our ad policies

Ad destination/click URL:

AltStyle によって変換されたページ (->オリジナル) /