Skip to content
Merged
Prev Previous commit
Next Next commit
Tidied boilerplate a little. Seems more python3 compatible (although …
…untested).
  • Loading branch information
pelson committed Jun 8, 2012
commit d7b2999353c654fcd863e9793c9b917e84b099a0
96 changes: 45 additions & 51 deletions boilerplate.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,14 +19,11 @@
import os
import inspect
import random
import re
import sys
import types

# import the local copy of matplotlib, not the installed one
#sys.path.insert(0, './lib')
from matplotlib.axes import Axes
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Notice that this line probably puts the scuppers on including the boilerplate script in setup.py (at least before building the c code) in the future.

from matplotlib.cbook import dedent


# this is the magic line that must exist in pyplot, after which the boilerplate content will be
Expand All @@ -37,13 +34,12 @@
'matplotlib', 'pyplot.py')


AUTOGEN_MSG = """
# This function was autogenerated by boilerplate.py. Do not edit as
# changes will be lost"""

def boilerplate_gen():
"""Generator of lines for the automated part of pyplot."""

_fmtplot = """
# This function was autogenerated by boilerplate.py. Do not edit as
# changes will be lost
PLOT_TEMPLATE = AUTOGEN_MSG + """
@autogen_docstring(Axes.%(func)s)
def %(func)s(%(argspec)s):
%(ax)s = gca()
Expand All @@ -59,17 +55,38 @@ def %(func)s(%(argspec)s):
%(ax)s.hold(%(washold)s)
%(mappable)s
return %(ret)s
"""
_fmtmisc = """
# This function was autogenerated by boilerplate.py. Do not edit as
# changes will be lost
"""


# Used for misc functions such as cla/legend etc.
MISC_FN_TEMPLATE = AUTOGEN_MSG + """
@docstring.copy_dedent(Axes.%(func)s)
def %(func)s(%(argspec)s):
%(ret)s = gca().%(func)s(%(call)s)
draw_if_interactive()
return %(ret)s
"""
"""


# Used for colormap functions
CMAP_TEMPLATE = AUTOGEN_MSG + """
def {name}():
'''
set the default colormap to {name} and apply to current image if any.
See help(colormaps) for more information
'''
rc('image', cmap='{name}')
im = gci()

if im is not None:
im.set_cmap(cm.{name})
draw_if_interactive()

"""


def boilerplate_gen():
"""Generator of lines for the automated part of pyplot."""

# these methods are all simple wrappers of Axes methods by the same
# name.
Expand Down Expand Up @@ -168,17 +185,12 @@ def format_value(value):
return '=mlab.' + value.func_name
if value.func_name == 'mean':
return '=np.' + value.func_name
raise ValueError, ('default value %s unknown to boilerplate.formatvalue'
% value)
raise ValueError(('default value %s unknown to boilerplate.' + \
'formatvalue') % value)
return '='+repr(value)

def remove_final_whitespace(string):
"""
Return a copy of *string* with final whitespace removed from each line.
"""
return '\n'.join(x.rstrip() for x in string.split('\n'))

for fmt,cmdlist in (_fmtplot,_plotcommands),(_fmtmisc,_misccommands):
for fmt, cmdlist in [(PLOT_TEMPLATE, _plotcommands),
(MISC_FN_TEMPLATE, _misccommands)]:
for func in cmdlist:
# For some commands, an additional line is needed to set the
# color map
Expand All @@ -201,13 +213,13 @@ def remove_final_whitespace(string):
call.append('**'+varkw)
call = ', '.join(call)

# Add a hold keyword argument if needed (fmt is _fmtplot) and
# Add a hold keyword argument if needed (fmt is PLOT_TEMPLATE) and
# possible (if *args is used, we can't just add a hold
# argument in front of it since it would gobble one of the
# arguments the user means to pass via *args)
if varargs:
sethold = "hold = %(varkw)s.pop('hold', None)" % locals()
elif fmt is _fmtplot:
elif fmt is PLOT_TEMPLATE:
args.append('hold')
defaults = defaults + (None,)
sethold = ''
Expand All @@ -219,7 +231,7 @@ def remove_final_whitespace(string):

# A gensym-like facility in case some function takes an
# argument named washold, ax, or ret
washold,ret,ax = 'washold', 'ret', 'ax'
washold, ret, ax = 'washold', 'ret', 'ax'
bad = set(args) | set((varargs, varkw))
while washold in bad or ret in bad or ax in bad:
washold = 'washold' + str(random.randrange(10**12))
Expand All @@ -230,29 +242,11 @@ def remove_final_whitespace(string):
# bail out if they are used as argument names
for reserved in ('gca', 'gci', 'draw_if_interactive'):
if reserved in bad:
raise ValueError, \
'Axes method %s has kwarg named %s' % (func, reserved)

yield remove_final_whitespace(fmt%locals())

# define the colormap functions
_fmtcmap = """
# This function was autogenerated by boilerplate.py. Do not edit as
# changes will be lost
def %(name)s():
'''
set the default colormap to %(name)s and apply to current image if any.
See help(colormaps) for more information
'''
rc('image', cmap='%(name)s')
im = gci()

if im is not None:
im.set_cmap(cm.%(name)s)
draw_if_interactive()

"""
msg = 'Axes method %s has kwarg named %s' % (func, reserved)
raise ValueError(msg)

yield fmt % locals()

cmaps = (
'autumn',
'bone',
Expand All @@ -272,22 +266,22 @@ def %(name)s():
)
# add all the colormaps (autumn, hsv, ....)
for name in cmaps:
yield _fmtcmap%locals()
yield CMAP_TEMPLATE.format(name=name)


def build_pyplot():
pyplot_path = os.path.join(os.path.dirname(__file__), 'lib',
'matplotlib', 'pyplot.py')

pyplot_orig = file(pyplot_path, 'r').readlines()
pyplot_orig = open(pyplot_path, 'r').readlines()


try:
pyplot_orig = pyplot_orig[:pyplot_orig.index(PYPLOT_MAGIC_HEADER)+1]
except IndexError:
raise ValueError('The pyplot.py file *must* have the exact line: %s' % PYPLOT_MAGIC_HEADER)

pyplot = file(pyplot_path, 'w')
pyplot = open(pyplot_path, 'w')
pyplot.writelines(pyplot_orig)
pyplot.write('\n')

Expand Down
Loading