8000 matplotlib/boilerplate.py at master · msarahan/matplotlib · GitHub
[go: up one dir, main page]

Skip to content
{"payload":{"allShortcutsEnabled":false,"fileTree":{"":{"items":[{"name":"LICENSE","path":"LICENSE","contentType":"directory"},{"name":"doc","path":"doc","contentType":"directory"},{"name":"examples","path":"examples","contentType":"directory"},{"name":"extern","path":"extern","contentType":"directory"},{"name":"lib","path":"lib","contentType":"directory"},{"name":"release","path":"release","contentType":"directory"},{"name":"src","path":"src","contentType":"directory"},{"name":"tools","path":"tools","contentType":"directory"},{"name":"unit","path":"unit","contentType":"directory"},{"name":".gitattributes","path":".gitattributes","contentType":"file"},{"name":".gitignore","path":".gitignore","contentType":"file"},{"name":".mailmap","path":".mailmap","contentType":"file"},{"name":".travis.yml","path":".travis.yml","contentType":"file"},{"name":"CHANGELOG","path":"CHANGELOG","contentType":"file"},{"name":"CONTRIBUTING.md","path":"CONTRIBUTING.md","contentType":"file"},{"name":"INSTALL","path":"INSTALL","contentType":"file"},{"name":"MANIFEST.in","path":"MANIFEST.in","contentType":"file"},{"name":"Makefile","path":"Makefile","contentType":"file"},{"name":"README.osx","path":"README.osx","contentType":"file"},{"name":"README.rst","path":"README.rst","contentType":"file"},{"name":"boilerplate.py","path":"boilerplate.py","contentType":"file"},{"name":"distribute_setup.py","path":"distribute_setup.py","contentType":"file"},{"name":"license.py","path":"license.py","contentType":"file"},{"name":"matplotlibrc.template","path":"matplotlibrc.template","contentType":"file"},{"name":"setup.cfg.template","path":"setup.cfg.template","contentType":"file"},{"name":"setup.py","path":"setup.py","contentType":"file"},{"name":"setupext.py","path":"setupext.py","contentType":"file"},{"name":"test_only.py","path":"test_only.py","contentType":"file"},{"name":"tests.py","path":"tests.py","contentType":"file"},{"name":"tox.ini","path":"tox.ini","contentType":"file"}],"totalCount":30}},"fileTreeProcessingTime":2.458637,"foldersToFetch":[],"incompleteFileTree":false,"repo":{"id":23260989,"defaultBranch":"master","name":"matplotlib","ownerLogin":"msarahan","currentUserCanPush":false,"isFork":true,"isEmpty":false,"createdAt":"2014-08-23T16:48:35.000Z","ownerAvatar":"https://avatars.githubusercontent.com/u/38393?v=4","public":true,"private":false,"isOrgOwned":false},"codeLineWrapEnabled":false,"symbolsExpanded":false,"treeExpanded":true,"refInfo":{"name":"master","listCacheKey":"v0:1467920943.0","canEdit":false,"refType":"branch","currentOid":"1963e9c2ec22fd796e2952af10c9885d98884c72"},"path":"boilerplate.py","currentUser":null,"blob":{"rawLines":["\"\"\"","Script to autogenerate pyplot wrappers.","","When this script is run, the current contents of pyplot are","split into generatable and non-generatable content (via the magic header",":attr:`PYPLOT_MAGIC_HEADER`) and the generatable content is overwritten.","Hence, the non-generatable content should be edited in the pyplot.py file","itself, whereas the generatable content must be edited via templates in","this file.","","\"\"\"","# We did try to do the wrapping the smart way,","# with callable functions and new.function, but could never get the","# docstrings right for python2.2. See","# http://groups.google.com/group/comp.lang.python/browse_frm/thread/dcd63ec13096a0f6/1b14640f3a4ad3dc?#1b14640f3a4ad3dc","# For some later history, see","# http://thread.gmane.org/gmane.comp.python.matplotlib.devel/7068","","from __future__ import (absolute_import, division, print_function,"," unicode_literals)","","import six","","import os","import inspect","import random","import types","","import textwrap","","# this line imports the installed copy of matplotlib, and not the local copy","from matplotlib.axes import Axes","","","# this is the magic line that must exist in pyplot, after which the boilerplate content will be","# appended","PYPLOT_MAGIC_HEADER = '################# REMAINING CONTENT GENERATED BY boilerplate.py ##############\\n'","","PYPLOT_PATH = os.path.join(os.path.dirname(__file__), 'lib',"," 'matplotlib', 'pyplot.py')","","","AUTOGEN_MSG = \"\"\"","# 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()"," # allow callers to override the hold state by passing hold=True|False"," %(washold)s = %(ax)s.ishold()","%(sethold)s"," if hold is not None:"," %(ax)s.hold(hold)"," try:"," %(ret)s = %(ax)s.%(func)s(%(call)s)"," draw_if_interactive()"," finally:"," %(ax)s.hold(%(washold)s)","%(mappable)s"," return %(ret)s","\"\"\"","","","# 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."," _plotcommands = ("," 'acorr',"," 'angle_spectrum',"," 'arrow',"," 'axhline',"," 'axhspan',"," 'axvline',"," 'axvspan',"," 'bar',"," 'barh',"," 'broken_barh',"," 'boxplot',"," 'cohere',"," 'clabel',"," 'contour',"," 'contourf',"," 'csd',"," 'errorbar',"," 'eventplot',"," 'fill',"," 'fill_between',"," 'fill_betweenx',"," 'hexbin',"," 'hist',"," 'hist2d',"," 'hlines',"," 'imshow',"," 'loglog',"," 'magnitude_spectrum',"," 'pcolor',"," 'pcolormesh',"," 'phase_spectrum',"," 'pie',"," 'plot',"," 'plot_date',"," 'psd',"," 'quiver',"," 'quiverkey',"," 'scatter',"," 'semilogx',"," 'semilogy',"," 'specgram',"," #'spy',"," 'stackplot',"," 'stem',"," 'step',"," 'streamplot',"," 'tricontour',"," 'tricontourf',"," 'tripcolor',"," 'triplot',"," 'violinplot',"," 'vlines',"," 'xcorr',"," 'barbs',"," )",""," _misccommands = ("," 'cla',"," 'grid',"," 'legend',"," 'table',"," 'text',"," 'annotate',"," 'ticklabel_format',"," 'locator_params',"," 'tick_params',"," 'margins',"," 'autoscale',"," )",""," cmappable = {"," 'contour' : 'if %(ret)s._A is not None: sci(%(ret)s)',"," 'contourf': 'if %(ret)s._A is not None: sci(%(ret)s)',"," 'hexbin' : 'sci(%(ret)s)',"," 'scatter' : 'sci(%(ret)s)',"," 'pcolor' : 'sci(%(ret)s)',"," 'pcolormesh': 'sci(%(ret)s)',"," 'hist2d' : 'sci(%(ret)s[-1])',"," 'imshow' : 'sci(%(ret)s)',"," #'spy' : 'sci(%(ret)s)', ### may return image or Line2D"," 'quiver' : 'sci(%(ret)s)',"," 'specgram' : 'sci(%(ret)s[-1])',"," 'streamplot' : 'sci(%(ret)s.lines)',"," 'tricontour' : 'if %(ret)s._A is not None: sci(%(ret)s)',"," 'tricontourf': 'if %(ret)s._A is not None: sci(%(ret)s)',"," 'tripcolor' : 'sci(%(ret)s)',",""," }",""," def format_value(value):"," \"\"\""," Format function default values as needed for inspect.formatargspec."," The interesting part is a hard-coded list of functions used"," as defaults in pyplot methods."," \"\"\""," if isinstance(value, types.FunctionType):"," if value.__name__ in ('detrend_none', 'window_hanning'):"," return '=mlab.' + value.__name__"," if value.__name__ == 'mean':"," return '=np.' + value.__name__"," raise ValueError(('default value %s unknown to boilerplate.' + \\"," 'formatvalue') % value)"," return '='+repr(value)",""," text_wrapper = textwrap.TextWrapper(break_long_words=False)",""," 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"," if func in cmappable:"," mappable = ' ' + cmappable[func] % locals()"," else:"," mappable = ''",""," # Get argspec of wrapped function"," args, varargs, varkw, defaults = inspect.getargspec(getattr(Axes, func))"," args.pop(0) # remove 'self' argument"," if defaults is None:"," defaults = ()"," else:"," def_edited = []"," for val in defaults:"," if isinstance(val, unicode):"," val = val.encode('ascii', 'ignore')"," def_edited.append(val)"," defaults = tuple(def_edited)",""," # How to call the wrapped function"," call = []"," for i, arg in enumerate(args):"," if len(defaults) \u003c len(args) - i:"," call.append('%s' % arg)"," else:"," call.append('%s=%s' % (arg, arg))",""," if varargs is not None:"," call.append('*'+varargs)"," if varkw is not None:"," call.append('**'+varkw)"," call = ', '.join(call)",""," text_wrapper.width = 80 - 19 - len(func)"," join_with = '\\n' + ' ' * (18 + len(func))"," call = join_with.join(text_wrapper.wrap(call))",""," # 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 PLOT_TEMPLATE:"," args.append('hold')"," defaults = defaults + (None,)"," sethold = ''",""," # Now we can build the argspec for defining the wrapper"," argspec = inspect.formatargspec(args, varargs, varkw, defaults,"," formatvalue=format_value)"," argspec = argspec[1:-1] # remove parens",""," text_wrapper.width = 80 - 5 - len(func)"," join_with = '\\n' + ' ' * (5 + len(func))"," argspec = join_with.join(text_wrapper.wrap(argspec))",""," # A gensym-like facility in case some function takes an"," # argument named washold, ax, or ret"," 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))"," ret = 'ret' + str(random.randrange(10**12))"," ax = 'ax' + str(random.randrange(10**12))",""," # Since we can't avoid using some function names,"," # bail out if they are used as argument names"," for reserved in ('gca', 'gci', 'draw_if_interactive'):"," if reserved in bad:"," msg = 'Axes method %s has kwarg named %s' % (func, reserved)"," raise ValueError(msg)",""," yield fmt % locals()",""," cmaps = ("," 'autumn',"," 'bone',"," 'cool',"," 'copper',"," 'flag',"," 'gray' ,"," 'hot',"," 'hsv',"," 'jet' ,"," 'pink',"," 'prism',"," 'spring',"," 'summer',"," 'winter',"," 'spectral'"," )"," # add all the colormaps (autumn, hsv, ....)"," for name in cmaps:"," yield CMAP_TEMPLATE.format(name=name)",""," yield ''"," yield '_setup_pyplot_info_docstrings()'","","def build_pyplot():"," pyplot_path = os.path.join(os.path.dirname(__file__), 'lib',"," 'matplotlib', 'pyplot.py')",""," 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 = open(pyplot_path, 'w')"," pyplot.writelines(pyplot_orig)"," pyplot.write('\\n')",""," pyplot.writelines(boilerplate_gen())"," pyplot.write('\\n')","","","if __name__ == '__main__':"," # Write the matplotlib.pyplot file"," build_pyplot()"],"stylingDirectives":null,"colorizedLines":null,"csv":null,"csvError":null,"dependabotInfo":{"showConfigurationBanner":false,"configFilePath":null,"networkDependabotPath":"/msarahan/matplotlib/network/updates","dismissConfigurationNoticePath":"/settings/dismiss-notice/dependabot_configuration_notice","configurationNoticeDismissed":null},"displayName":"boilerplate.py","displayUrl":"https://github.com/msarahan/matplotlib/blob/master/boilerplate.py?raw=true","headerInfo":{"blobSize":"9.77 KB","deleteTooltip":"You must be signed in to make or propose changes","editTooltip":"You must be signed in to make or propose changes","ghDesktopPath":"https://desktop.github.com","isGitLfs":false,"onBranch":true,"shortPath":"1791c80","siteNavLoginPath":"/login?return_to=https%3A%2F%2Fgithub.com%2Fmsarahan%2Fmatplotlib%2Fblob%2Fmaster%2Fboilerplate.py","isCSV":false,"isRichtext":false,"toc":null,"lineInfo":{"truncatedLoc":"330","truncatedSloc":"282"},"mode":"file"},"image":false,"isCodeownersFile":null,"isPlain":false,"isValidLegacyIssueTemplate":false,"issueTemplate":null,"discussionTemplate":null,"language":"Python","languageID":303,"large":false,"planSupportInfo":{"repoIsFork":null,"repoOwnedByCurrentUser":null,"requestFullPath":"/msarahan/matplotlib/blob/master/boilerplate.py","showFreeOrgGatedFeatureMessage":null,"showPlanSupportBanner":null,"upgradeDataAttributes":null,"upgradePath":null},"publishBannersInfo":{"dismissActionNoticePath":"/settings/dismiss-notice/publish_action_from_dockerfile","releasePath":"/msarahan/matplotlib/releases/new?marketplace=true","showPublishActionBanner":false},"rawBlobUrl":"https://github.com/msarahan/matplotlib/raw/refs/heads/master/boilerplate.py","renderImageOrRaw":false,"richText":null,"renderedFileInfo":null,"shortPath":null,"symbolsEnabled":true,"tabSize":8,"topBannersInfo":{"overridingGlobalFundingFile":false,"globalPreferredFundingPath":null,"showInvalidCitationWarning":false,"citationHelpUrl":"https://docs.github.com/github/creating-cloning-and-archiving-repositories/creating-a-repository-on-github/about-citation-files","actionsOnboardingTip":null},"truncated":false,"viewable":true,"workflowRedirectUrl":null,"symbols":{"timed_out":false,"not_analyzed":false,"symbols":[{"name":"PYPLOT_MAGIC_HEADER","kind":"constant","ident_start":1195,"ident_end":1214,"extent_start":1195,"extent_end":1299,"fully_qualified_name":"PYPLOT_MAGIC_HEADER","ident_utf16":{"start":{"line_number":36,"utf16_col":0},"end":{"line_number":36,"utf16_col":19}},"extent_utf16":{"start":{"line_number":36,"utf16_col":0},"end":{"line_number":36,"utf16_col":104}}},{"name":"PYPLOT_PATH","kind":"constant","ident_start":1301,"ident_end":1312,"extent_start":1301,"extent_end":1419,"fully_qualified_name":"PYPLOT_PATH","ident_utf16":{"start":{"line_number":38,"utf16_col":0},"end":{"line_number":38,"utf16_col":11}},"extent_utf16":{"start":{"line_number":38,"utf16_col":0},"end":{"line_number":39,"utf16_col":57}}},{"name":"AUTOGEN_MSG","kind":"constant","ident_start":1422,"ident_end":1433,"extent_start":1422,"extent_end":1534,"fully_qualified_name":"AUTOGEN_MSG","ident_utf16":{"start":{"line_number":42,"utf16_col":0},"end":{"line_number":42,"utf16_col":11}},"extent_utf16":{"start":{"line_number":42,"utf16_col":0},"end":{"line_number":44,"utf16_col":25}}},{"name":"PLOT_TEMPLATE","kind":"constant","ident_start":1537,"ident_end":1550,"extent_start":1537,"extent_end":1987,"fully_qualified_name":"PLOT_TEMPLATE","ident_utf16":{"start":{"line_number":47,"utf16_col":0},"end":{"line_number":47,"utf16_col":13}},"extent_utf16":{"start":{"line_number":47,"utf16_col":0},"end":{"line_number":63,"utf16_col":3}}},{"name":"MISC_FN_TEMPLATE","kind":"constant","ident_start":2040,"ident_end":2056,"extent_start":2040,"extent_end":2229,"fully_qualified_name":"MISC_FN_TEMPLATE","ident_utf16":{"start":{"line_number":67,"utf16_col":0},"end":{"line_number":67,"utf16_col":16}},"extent_utf16":{"start":{"line_number":67,"utf16_col":0},"end":{"line_number":73,"utf16_col":3}}},{"name":"CMAP_TEMPLATE","kind":"constant","ident_start":2261,"ident_end":2274,"extent_start":2261,"extent_end":2575,"fully_qualified_name":"CMAP_TEMPLATE","ident_utf16":{"start":{"line_number":76,"utf16_col":0},"end":{"line_number":76,"utf16_col":13}},"extent_utf16":{"start":{"line_number":76,"utf16_col":0},"end":{"line_number":89,"utf16_col":3}}},{"name":"boilerplate_gen","kind":"function","ident_start":2582,"ident_end":2597,"extent_start":2578,"extent_end":9352,"fully_qualified_name":"boilerplate_gen","ident_utf16":{"start":{"line_number":92,"utf16_col":4},"end":{"line_number":92,"utf16_col":19}},"extent_utf16":{"start":{"line_number":92,"utf16_col":0},"end":{"line_number":305,"utf16_col":43}}},{"name":"format_value","kind":"function","ident_start":4821,"ident_end":4833,"extent_start":4817,"extent_end":5465,"fully_qualified_name":"format_value","ident_utf16":{"start":{"line_number":187,"utf16_col":8},"end":{"line_number":187,"utf16_col":20}},"extent_utf16":{"start":{"line_number":187,"utf16_col":4},"end":{"line_number":200,"utf16_col":30}}},{"name":"build_pyplot","kind":"function","ident_start":9358,"ident_end":9370,"extent_start":9354,"extent_end":9921,"fully_qualified_name":"build_pyplot","ident_utf16":{"start":{"line_number":307,"utf16_col":4},"end":{"line_number":307,"utf16_col":16}},"extent_utf16":{"start":{"line_number":307,"utf16_col":0},"end":{"line_number":324,"utf16_col":22}}}]}},"copilotInfo":null,"copilotAccessAllowed":false,"modelsAccessAllowed":false,"modelsRepoIntegrationEnabled":false,"csrf_tokens":{"/msarahan/matplotlib/branches":{"post":"NJFuQRA65WWuEBLwq51iOAS44zdXZkrk2yQfWay9ebAB9wY71zw4VDNi7dU8g8TvxdBPyjOCMGcEj54cNpb_CA"},"/repos/preferences":{"post":"fPUnmfsPSpid_szQSbGNUPS1DPy0RRs91bqKMnJEcmkJnlG6aLT05dG7rYtT_IA08U_BIdCn2L32eX9FGOR18g"}}},"title":"matplotlib/boilerplate.py at master · msarahan/matplotlib","appPayload":{"helpUrl":"https://docs.github.com","findFileWorkerPath":"/assets-cdn/worker/find-file-worker-7d7eb7c71814.js","findInFileWorkerPath":"/assets-cdn/worker/find-in-file-worker-1ae9fa256942.js","githubDevUrl":null,"enabled_features":{"code_nav_ui_events":false,"react_blob_overlay":false,"accessible_code_button":true,"github_models_repo_integration":false}}}
0