From b2408c331b6d962e9d3857252cb56ea1f55ada33 Mon Sep 17 00:00:00 2001 From: Cimarron Mittelsteadt Date: Fri, 12 Sep 2014 15:58:25 -0700 Subject: [PATCH 1/2] STY/TST: Fixing up pep8 errors and updating test test_coding_standards to reflect the fixes --- lib/matplotlib/__init__.py | 186 +++-- lib/matplotlib/_pylab_helpers.py | 18 +- lib/matplotlib/afm.py | 11 +- lib/matplotlib/artist.py | 24 +- lib/matplotlib/axis.py | 339 ++++---- lib/matplotlib/bezier.py | 63 +- lib/matplotlib/mlab.py | 757 ++++++++++-------- lib/matplotlib/path.py | 59 +- lib/matplotlib/tests/test_coding_standards.py | 10 +- 9 files changed, 803 insertions(+), 664 deletions(-) diff --git a/lib/matplotlib/__init__.py b/lib/matplotlib/__init__.py index 7d31f01f05f9..a76f47126637 100644 --- a/lib/matplotlib/__init__.py +++ b/lib/matplotlib/__init__.py @@ -106,14 +106,15 @@ import sys import distutils.version -__version__ = '1.5.x' -__version__numpy__ = '1.6' # minimum required numpy version +__version__ = '1.5.x' +__version__numpy__ = '1.6' # minimum required numpy version try: import dateutil except ImportError: raise ImportError("matplotlib requires dateutil") + def compare_versions(a, b): "return True if a is greater than or equal to b" if a: @@ -200,11 +201,6 @@ def _forward_ilshift(self, other): # datetime support _havedate = True -#try: -# import pkg_resources # pkg_resources is part of setuptools -#except ImportError: _have_pkg_resources = False -#else: _have_pkg_resources = True - if not _python24: raise ImportError('matplotlib requires Python 2.4 or later') @@ -244,13 +240,14 @@ def _is_writable_dir(p): return True + class Verbose: """ A class to handle reporting. Set the fileo attribute to any file instance to handle the output. Default is sys.stdout """ levels = ('silent', 'helpful', 'debug', 'debug-annoying') - vald = dict( [(level, i) for i,level in enumerate(levels)]) + vald = dict([(level, i) for i, level in enumerate(levels)]) # parse the verbosity from the command line; flags look like # --verbose-silent or --verbose-helpful @@ -294,7 +291,9 @@ def set_fileo(self, fname): try: fileo = open(fname, 'w') except IOError: - raise ValueError('Verbose object could not open log file "%s" for writing.\nCheck your matplotlibrc verbose.fileo setting'%fname) + raise ValueError('Verbose object could not open log file "{}"' + ' for writing.\nCheck your matplotlibrc ' + 'verbose.fileo setting'.format(fname)) else: self.fileo = fileo @@ -319,12 +318,14 @@ def wrap(self, fmt, func, level='helpful', always=True): call; otherwise only on the first time the function is called """ assert six.callable(func) + def wrapper(*args, **kwargs): ret = func(*args, **kwargs) if (always or not wrapper._spoke): - spoke = self.report(fmt%ret, level) - if not wrapper._spoke: wrapper._spoke = spoke + spoke = self.report(fmt % ret, level) + if not wrapper._spoke: + wrapper._spoke = spoke return ret wrapper._spoke = False wrapper.__doc__ = func.__doc__ @@ -332,16 +333,15 @@ def wrapper(*args, **kwargs): def ge(self, level): 'return true if self.level is >= level' - return self.vald[self.level]>=self.vald[level] + return self.vald[self.level] >= self.vald[level] -verbose=Verbose() - +verbose = Verbose() def checkdep_dvipng(): try: - s = subprocess.Popen(['dvipng','-version'], stdout=subprocess.PIPE, + s = subprocess.Popen(['dvipng', '-version'], stdout=subprocess.PIPE, stderr=subprocess.PIPE) stdout, stderr = s.communicate() line = stdout.decode('ascii').split('\n')[1] @@ -350,6 +350,7 @@ def checkdep_dvipng(): except (IndexError, ValueError, OSError): return None + def checkdep_ghostscript(): if sys.platform == 'win32': gs_execs = ['gswin32c', 'gswin64c', 'gs'] @@ -368,9 +369,10 @@ def checkdep_ghostscript(): pass return None, None + def checkdep_tex(): try: - s = subprocess.Popen(['tex','-version'], stdout=subprocess.PIPE, + s = subprocess.Popen(['tex', '-version'], stdout=subprocess.PIPE, stderr=subprocess.PIPE) stdout, stderr = s.communicate() line = stdout.decode('ascii').split('\n')[0] @@ -381,9 +383,10 @@ def checkdep_tex(): except (IndexError, ValueError, AttributeError, OSError): return None + def checkdep_pdftops(): try: - s = subprocess.Popen(['pdftops','-v'], stdout=subprocess.PIPE, + s = subprocess.Popen(['pdftops', '-v'], stdout=subprocess.PIPE, stderr=subprocess.PIPE) stdout, stderr = s.communicate() lines = stderr.decode('ascii').split('\n') @@ -394,9 +397,10 @@ def checkdep_pdftops(): except (IndexError, ValueError, UnboundLocalError, OSError): return None + def checkdep_inkscape(): try: - s = subprocess.Popen(['inkscape','-V'], stdout=subprocess.PIPE, + s = subprocess.Popen(['inkscape', '-V'], stdout=subprocess.PIPE, stderr=subprocess.PIPE) stdout, stderr = s.communicate() lines = stdout.decode('ascii').split('\n') @@ -408,9 +412,10 @@ def checkdep_inkscape(): except (IndexError, ValueError, UnboundLocalError, OSError): return None + def checkdep_xmllint(): try: - s = subprocess.Popen(['xmllint','--version'], stdout=subprocess.PIPE, + s = subprocess.Popen(['xmllint', '--version'], stdout=subprocess.PIPE, stderr=subprocess.PIPE) stdout, stderr = s.communicate() lines = stderr.decode('ascii').split('\n') @@ -422,6 +427,7 @@ def checkdep_xmllint(): except (IndexError, ValueError, UnboundLocalError, OSError): return None + def checkdep_ps_distiller(s): if not s: return False @@ -430,34 +436,39 @@ def checkdep_ps_distiller(s): gs_req = '7.07' gs_sugg = '7.07' gs_exec, gs_v = checkdep_ghostscript() - if compare_versions(gs_v, gs_sugg): pass + if compare_versions(gs_v, gs_sugg): + pass elif compare_versions(gs_v, gs_req): verbose.report(('ghostscript-%s found. ghostscript-%s or later ' - 'is recommended to use the ps.usedistiller option.') % (gs_v, gs_sugg)) + 'is recommended to use the ps.usedistiller option.') + % (gs_v, gs_sugg)) else: flag = False warnings.warn(('matplotlibrc ps.usedistiller option can not be used ' - 'unless ghostscript-%s or later is installed on your system') % gs_req) + 'unless ghostscript-%s or later is installed on your ' + 'system') % gs_req) if s == 'xpdf': pdftops_req = '3.0' - pdftops_req_alt = '0.9' # poppler version numbers, ugh + pdftops_req_alt = '0.9' # poppler version numbers, ugh pdftops_v = checkdep_pdftops() if compare_versions(pdftops_v, pdftops_req): pass - elif compare_versions(pdftops_v, pdftops_req_alt) and not \ - compare_versions(pdftops_v, '1.0'): + elif (compare_versions(pdftops_v, pdftops_req_alt) and not + compare_versions(pdftops_v, '1.0')): pass else: flag = False warnings.warn(('matplotlibrc ps.usedistiller can not be set to ' - 'xpdf unless xpdf-%s or later is installed on your system') % pdftops_req) + 'xpdf unless xpdf-%s or later is installed on ' + 'your system') % pdftops_req) if flag: return s else: return False + def checkdep_usetex(s): if not s: return False @@ -469,7 +480,8 @@ def checkdep_usetex(s): flag = True tex_v = checkdep_tex() - if compare_versions(tex_v, tex_req): pass + if compare_versions(tex_v, tex_req): + pass else: flag = False warnings.warn(('matplotlibrc text.usetex option can not be used ' @@ -477,15 +489,17 @@ def checkdep_usetex(s): 'installed on your system') % tex_req) dvipng_v = checkdep_dvipng() - if compare_versions(dvipng_v, dvipng_req): pass + if compare_versions(dvipng_v, dvipng_req): + pass else: flag = False - warnings.warn( 'matplotlibrc text.usetex can not be used with *Agg ' - 'backend unless dvipng-1.5 or later is ' - 'installed on your system') + warnings.warn('matplotlibrc text.usetex can not be used with *Agg ' + 'backend unless dvipng-1.5 or later is ' + 'installed on your system') gs_exec, gs_v = checkdep_ghostscript() - if compare_versions(gs_v, gs_sugg): pass + if compare_versions(gs_v, gs_sugg): + pass elif compare_versions(gs_v, gs_req): verbose.report(('ghostscript-%s found. ghostscript-%s or later is ' 'recommended for use with the text.usetex ' @@ -503,7 +517,8 @@ def _get_home(): """Find user's home directory if possible. Otherwise, returns None. - :see: http://mail.python.org/pipermail/python-list/2005-February/325395.html + :see: + http://mail.python.org/pipermail/python-list/2005-February/325395.html """ try: path = os.path.expanduser("~") @@ -544,6 +559,7 @@ def _create_tmp_config_dir(): get_home = verbose.wrap('$HOME=%s', _get_home, always=False) + def _get_xdg_config_dir(): """ Returns the XDG configuration directory, according to the `XDG @@ -650,7 +666,8 @@ def _get_data_path(): if 'MATPLOTLIBDATA' in os.environ: path = os.environ['MATPLOTLIBDATA'] if not os.path.isdir(path): - raise RuntimeError('Path in environment MATPLOTLIBDATA not a directory') + raise RuntimeError('Path in environment MATPLOTLIBDATA not a ' + 'directory') return path path = os.sep.join([os.path.dirname(__file__), 'mpl-data']) @@ -665,7 +682,7 @@ def _get_data_path(): return path # py2exe zips pure python, so still need special check - if getattr(sys,'frozen',None): + if getattr(sys, 'frozen', None): exe_path = os.path.dirname(sys.executable) path = os.path.join(exe_path, 'mpl-data') if os.path.isdir(path): @@ -683,6 +700,7 @@ def _get_data_path(): raise RuntimeError('Could not find the matplotlib data files') + def _get_data_path_cached(): if defaultParams['datapath'][0] is None: defaultParams['datapath'][0] = _get_data_path() @@ -692,12 +710,13 @@ def _get_data_path_cached(): always=False) - def get_example_data(fname): """ - get_example_data is deprecated -- use matplotlib.cbook.get_sample_data instead + get_example_data is deprecated -- use matplotlib.cbook.get_sample_data + instead """ - raise NotImplementedError('get_example_data is deprecated -- use matplotlib.cbook.get_sample_data instead') + raise NotImplementedError('get_example_data is deprecated -- use ' + 'matplotlib.cbook.get_sample_data instead') def get_py2exe_datafiles(): @@ -750,7 +769,7 @@ def matplotlib_fname(): return fname if 'MATPLOTLIBRC' in os.environ: - path = os.environ['MATPLOTLIBRC'] + path = os.environ['MATPLOTLIBRC'] if os.path.exists(path): fname = os.path.join(path, 'matplotlibrc') if os.path.exists(fname): @@ -786,14 +805,15 @@ def matplotlib_fname(): _deprecated_map = { - 'text.fontstyle': ('font.style',lambda x: x), - 'text.fontangle': ('font.style',lambda x: x), - 'text.fontvariant': ('font.variant',lambda x: x), - 'text.fontweight': ('font.weight',lambda x: x), - 'text.fontsize': ('font.size',lambda x: x), - 'tick.size' : ('tick.major.size',lambda x: x), - 'svg.embed_char_paths' : ('svg.fonttype',lambda x: "path" if x else "none"), - 'savefig.extension' : ('savefig.format',lambda x: x), + 'text.fontstyle': ('font.style', lambda x: x), + 'text.fontangle': ('font.style', lambda x: x), + 'text.fontvariant': ('font.variant', lambda x: x), + 'text.fontweight': ('font.weight', lambda x: x), + 'text.fontsize': ('font.size', lambda x: x), + 'tick.size': ('tick.major.size', lambda x: x), + 'svg.embed_char_paths': ('svg.fonttype', + lambda x: "path" if x else "none"), + 'savefig.extension': ('savefig.format', lambda x: x), } _deprecated_ignore_map = { @@ -817,7 +837,7 @@ class RcParams(dict): def __setitem__(self, key, val): try: if key in _deprecated_map: - alt_key, alt_val = _deprecated_map[key] + alt_key, alt_val = _deprecated_map[key] warnings.warn(self.msg_depr % (key, alt_key)) key = alt_key val = alt_val(val) @@ -836,7 +856,7 @@ def __setitem__(self, key, val): def __getitem__(self, key): if key in _deprecated_map: - alt_key, alt_val = _deprecated_map[key] + alt_key, alt_val = _deprecated_map[key] warnings.warn(self.msg_depr % (key, alt_key)) key = alt_key elif key in _deprecated_ignore_map: @@ -898,7 +918,7 @@ def rc_params(fail_on_error=False): if not os.path.exists(fname): # this should never happen, default in mpl-data should always be found message = 'could not find rc file; returning defaults' - ret = RcParams([(key, default) for key, (default, _) in \ + ret = RcParams([(key, default) for key, (default, _) in six.iteritems(defaultParams)]) warnings.warn(message) return ret @@ -946,7 +966,8 @@ def _rc_params_in_file(fname, fail_on_error=False): for line in fd: cnt += 1 strippedline = line.split('#', 1)[0].strip() - if not strippedline: continue + if not strippedline: + continue tup = strippedline.split(':', 1) if len(tup) != 2: error_details = _error_details_fmt % (cnt, line, fname) @@ -956,7 +977,7 @@ def _rc_params_in_file(fname, fail_on_error=False): key = key.strip() val = val.strip() if key in rc_temp: - warnings.warn('Duplicate key in file "%s", line #%d' % \ + warnings.warn('Duplicate key in file "%s", line #%d' % (fname, cnt)) rc_temp[key] = (val, line, cnt) @@ -966,10 +987,10 @@ def _rc_params_in_file(fname, fail_on_error=False): if key in rc_temp: val, line, cnt = rc_temp.pop(key) if fail_on_error: - config[key] = val # try to convert to proper type or raise + config[key] = val # try to convert to proper type or raise else: try: - config[key] = val # try to convert to proper type or skip + config[key] = val # try to convert to proper type or skip except Exception as msg: error_details = _error_details_fmt % (cnt, line, fname) warnings.warn('Bad val "%s" on %s\n\t%s' % @@ -978,17 +999,17 @@ def _rc_params_in_file(fname, fail_on_error=False): for key, (val, line, cnt) in six.iteritems(rc_temp): if key in defaultParams: if fail_on_error: - config[key] = val # try to convert to proper type or raise + config[key] = val # try to convert to proper type or raise else: try: - config[key] = val # try to convert to proper type or skip + config[key] = val # try to convert to proper type or skip except Exception as msg: error_details = _error_details_fmt % (cnt, line, fname) warnings.warn('Bad val "%s" on %s\n\t%s' % (val, error_details, msg)) elif key in _deprecated_ignore_map: warnings.warn('%s is deprecated. Update your matplotlibrc to use ' - '%s instead.'% (key, _deprecated_ignore_map[key])) + '%s instead.' % (key, _deprecated_ignore_map[key])) else: print(""" @@ -1037,9 +1058,9 @@ def rc_params_from_file(fname, fail_on_error=False, use_default_template=True): %s Please do not ask for support with these customizations active. ***************************************************************** -"""% '\n'.join(config['text.latex.preamble']), 'helpful') +""" % '\n'.join(config['text.latex.preamble']), 'helpful') - verbose.report('loaded rc file %s'%fname) + verbose.report('loaded rc file %s' % fname) return config @@ -1063,16 +1084,19 @@ def rc_params_from_file(fname, fail_on_error=False, use_default_template=True): rcParamsOrig = rcParams.copy() -rcParamsDefault = RcParams([(key, default) for key, (default, converter) in \ +rcParamsDefault = RcParams([(key, default) for key, (default, converter) in six.iteritems(defaultParams)]) -rcParams['ps.usedistiller'] = checkdep_ps_distiller(rcParams['ps.usedistiller']) +rcParams['ps.usedistiller'] = checkdep_ps_distiller( + rcParams['ps.usedistiller'] +) rcParams['text.usetex'] = checkdep_usetex(rcParams['text.usetex']) if rcParams['axes.formatter.use_locale']: import locale locale.setlocale(locale.LC_ALL, '') + def rc(group, **kwargs): """ Set the current rc params. Group is the grouping for the rc, e.g., @@ -1124,13 +1148,13 @@ def rc(group, **kwargs): """ aliases = { - 'lw' : 'linewidth', - 'ls' : 'linestyle', - 'c' : 'color', - 'fc' : 'facecolor', - 'ec' : 'edgecolor', - 'mew' : 'markeredgewidth', - 'aa' : 'antialiased', + 'lw': 'linewidth', + 'ls': 'linestyle', + 'c': 'color', + 'fc': 'facecolor', + 'ec': 'edgecolor', + 'mew': 'markeredgewidth', + 'aa': 'antialiased', } if is_string_like(group): @@ -1142,8 +1166,9 @@ def rc(group, **kwargs): try: rcParams[key] = v except KeyError: - raise KeyError('Unrecognized key "%s" for group "%s" and name "%s"' % - (key, g, name)) + raise KeyError(('Unrecognized key "%s" for group "%s" and ' + 'name "%s"') % (key, g, name)) + def rcdefaults(): """ @@ -1216,6 +1241,7 @@ def rc_file_defaults(): or matplotlib.backends is imported for the first time. """ + def use(arg, warn=True, force=False): """ Set the matplotlib backend to one of the known backends. @@ -1270,10 +1296,12 @@ def use(arg, warn=True, force=False): if need_reload: reload(sys.modules['matplotlib.backends']) + def get_backend(): """Return the name of the current backend.""" return rcParams['backend'] + def interactive(b): """ Set interactive mode to boolean b. @@ -1282,6 +1310,7 @@ def interactive(b): """ rcParams['interactive'] = b + def is_interactive(): 'Return true if plot mode is interactive' # ps1 exists if the python interpreter is running in an @@ -1291,6 +1320,7 @@ def is_interactive(): hasattr(sys, 'ps1') or sys.flags.interactive) return b + def tk_window_focus(): """Return true if focus maintenance under TkAgg on win32 is on. This currently works only for python.exe and IPython.exe. @@ -1381,8 +1411,8 @@ def test(verbosity=1): # store the old values before overriding plugins = [] - plugins.append( KnownFailure() ) - plugins.extend( [plugin() for plugin in nose.plugins.builtin.plugins] ) + plugins.append(KnownFailure()) + plugins.extend([plugin() for plugin in nose.plugins.builtin.plugins]) manager = PluginManager(plugins=plugins) config = nose.config.Config(verbosity=verbosity, plugins=manager) @@ -1402,10 +1432,10 @@ def test(verbosity=1): return success -test.__test__ = False # nose: this function is not a test +test.__test__ = False # nose: this function is not a test -verbose.report('matplotlib version %s'%__version__) -verbose.report('verbose.level %s'%verbose.level) -verbose.report('interactive is %s'%is_interactive()) -verbose.report('platform is %s'%sys.platform) -verbose.report('loaded modules: %s'%six.iterkeys(sys.modules), 'debug') +verbose.report('matplotlib version %s' % __version__) +verbose.report('verbose.level %s' % verbose.level) +verbose.report('interactive is %s' % is_interactive()) +verbose.report('platform is %s' % sys.platform) +verbose.report('loaded modules: %s' % six.iterkeys(sys.modules), 'debug') diff --git a/lib/matplotlib/_pylab_helpers.py b/lib/matplotlib/_pylab_helpers.py index f5219208ef27..4ae654e71f49 100644 --- a/lib/matplotlib/_pylab_helpers.py +++ b/lib/matplotlib/_pylab_helpers.py @@ -5,15 +5,15 @@ unicode_literals) import six - -import sys, gc - +import sys +import gc import atexit def error_msg(msg): print(msg, file=sys.stderr) + class Gcf(object): """ Singleton to manage a set of integer-numbered figures. @@ -54,7 +54,8 @@ def destroy(num): In the interactive backends, this is bound to the window "destroy" and "delete" events. """ - if not Gcf.has_fignum(num): return + if not Gcf.has_fignum(num): + return manager = Gcf.figs[num] manager.canvas.mpl_disconnect(manager._cidgcf) @@ -67,7 +68,6 @@ def destroy(num): Gcf._activeQue.append(f) del Gcf.figs[num] - #print len(Gcf.figs.keys()), len(Gcf._activeQue) manager.destroy() gc.collect(1) @@ -118,9 +118,10 @@ def get_active(): """ Return the manager of the active figure, or *None*. """ - if len(Gcf._activeQue)==0: + if len(Gcf._activeQue) == 0: return None - else: return Gcf._activeQue[-1] + else: + return Gcf._activeQue[-1] @staticmethod def set_active(manager): @@ -130,7 +131,8 @@ def set_active(manager): oldQue = Gcf._activeQue[:] Gcf._activeQue = [] for m in oldQue: - if m != manager: Gcf._activeQue.append(m) + if m != manager: + Gcf._activeQue.append(m) Gcf._activeQue.append(manager) Gcf.figs[manager.num] = manager diff --git a/lib/matplotlib/afm.py b/lib/matplotlib/afm.py index e83299922ddb..1dff9403210e 100644 --- a/lib/matplotlib/afm.py +++ b/lib/matplotlib/afm.py @@ -44,7 +44,7 @@ import re from ._mathtext_data import uni2type1 -#Convert string the a python type +# Convert string the a python type # some afm files have floats where we are expecting ints -- there is # probably a better way to handle this (support floats, round rather @@ -155,13 +155,13 @@ def _parse_header(fh): if line.startswith(b'Comment'): continue lst = line.split(b' ', 1) - #print '%-s\t%-d line :: %-s' % ( fh.name, len(lst), line ) + key = lst[0] if len(lst) == 2: val = lst[1] else: val = b'' - #key, val = line.split(' ', 1) + try: d[key] = headerConverters[key](val) except ValueError: @@ -170,7 +170,7 @@ def _parse_header(fh): continue except KeyError: print('Found an unknown keyword in AFM header (was %s)' % key, - file=sys.stderr) + file=sys.stderr) continue if key == b'StartCharMetrics': return d @@ -517,7 +517,8 @@ def get_familyname(self): # FamilyName not specified so we'll make a guess name = self.get_fullname() - extras = br'(?i)([ -](regular|plain|italic|oblique|bold|semibold|light|ultralight|extra|condensed))+$' + extras = (br'(?i)([ -](regular|plain|italic|oblique|bold|semibold|' + br'light|ultralight|extra|condensed))+$') return re.sub(extras, '', name) def get_weight(self): diff --git a/lib/matplotlib/artist.py b/lib/matplotlib/artist.py index d1ef2e59750e..957398b335e1 100644 --- a/lib/matplotlib/artist.py +++ b/lib/matplotlib/artist.py @@ -9,11 +9,11 @@ import matplotlib import matplotlib.cbook as cbook from matplotlib import docstring, rcParams -from .transforms import Bbox, IdentityTransform, TransformedBbox, \ - TransformedPath, Transform +from .transforms import (Bbox, IdentityTransform, TransformedBbox, + TransformedPath, Transform) from .path import Path -## Note, matplotlib artists use the doc strings for set and get +# Note, matplotlib artists use the doc strings for set and get # methods to enable the introspection methods of setp and getp. Every # set_* method should have a docstring containing the line # @@ -158,7 +158,6 @@ def convert_xunits(self, x): """ ax = getattr(self, 'axes', None) if ax is None or ax.xaxis is None: - #print 'artist.convert_xunits no conversion: ax=%s'%ax return x return ax.xaxis.convert_units(x) @@ -584,7 +583,7 @@ def set_clip_path(self, path, transform=None): if transform is None: if isinstance(path, Rectangle): self.clipbox = TransformedBbox(Bbox.unit(), - path.get_transform()) + path.get_transform()) self._clippath = None success = True elif isinstance(path, Patch): @@ -866,8 +865,8 @@ def matchfunc(x): if matchfunc(c): artists.append(c) artists.extend([thisc for thisc in - c.findobj(matchfunc, include_self=False) - if matchfunc(thisc)]) + c.findobj(matchfunc, include_self=False) + if matchfunc(thisc)]) if include_self and matchfunc(self): artists.append(self) @@ -924,7 +923,8 @@ def get_aliases(self): return aliases _get_valid_values_regex = re.compile( - r"\n\s*ACCEPTS:\s*((?:.|\n)*?)(?:$|(?:\n\n))") + r"\n\s*ACCEPTS:\s*((?:.|\n)*?)(?:$|(?:\n\n))" + ) def get_valid_values(self, attr): """ @@ -934,7 +934,8 @@ def get_valid_values(self, attr): for a line that begins with ACCEPTS: e.g., for a line linestyle, return - "[ ``'-'`` | ``'--'`` | ``'-.'`` | ``':'`` | ``'steps'`` | ``'None'`` ]" + "[ ``'-'`` | ``'--'`` | ``'-.'`` | ``':'`` | ``'steps'`` | ``'None'`` + ]" """ name = 'set_%s' % attr @@ -1094,7 +1095,7 @@ def pprint_setters_rest(self, prop=None, leadingspace=2): lines.append('') lines.append(table_formatstr) - lines.append(pad + 'Property'.ljust(col0_len + 3) + \ + lines.append(pad + 'Property'.ljust(col0_len + 3) + 'Description'.ljust(col1_len)) lines.append(table_formatstr) @@ -1121,7 +1122,6 @@ def properties(self): getters = [name for name in dir(o) if name.startswith('get_') and six.callable(getattr(o, name))] - #print getters getters.sort() d = dict() for name in getters: @@ -1323,7 +1323,7 @@ def kwdoc(a): hardcopy = matplotlib.rcParams['docstring.hardcopy'] if hardcopy: return '\n'.join(ArtistInspector(a).pprint_setters_rest( - leadingspace=2)) + leadingspace=2)) else: return '\n'.join(ArtistInspector(a).pprint_setters(leadingspace=2)) diff --git a/lib/matplotlib/axis.py b/lib/matplotlib/axis.py index 6f2b24c1793f..909a5e893097 100644 --- a/lib/matplotlib/axis.py +++ b/lib/matplotlib/axis.py @@ -73,7 +73,8 @@ def __init__(self, axes, loc, label, labelsize=None, labelcolor=None, zorder=None, - gridOn=None, # defaults to axes.grid depending on axes.grid.which + gridOn=None, # defaults to axes.grid depending on + # axes.grid.which tick1On=True, tick2On=True, label1On=True, @@ -88,11 +89,12 @@ def __init__(self, axes, loc, label, artist.Artist.__init__(self) if gridOn is None: - if major and (rcParams['axes.grid.which'] in ('both','major')): + if major and (rcParams['axes.grid.which'] in ('both', 'major')): gridOn = rcParams['axes.grid'] - elif (not major) and (rcParams['axes.grid.which'] in ('both','minor')): + elif (not major) and (rcParams['axes.grid.which'] + in ('both', 'minor')): gridOn = rcParams['axes.grid'] - else : + else: gridOn = False self.set_figure(axes.figure) @@ -174,8 +176,6 @@ def get_children(self): def set_clip_path(self, clippath, transform=None): artist.Artist.set_clip_path(self, clippath, transform) - #self.tick1line.set_clip_path(clippath, transform) - #self.tick2line.set_clip_path(clippath, transform) self.gridline.set_clip_path(clippath, transform) set_clip_path.__doc__ = artist.Artist.set_clip_path.__doc__ @@ -271,7 +271,6 @@ def set_label2(self, s): def _set_artist_props(self, a): a.set_figure(self.figure) - #if isinstance(a, mlines.Line2D): a.set_clip_box(self.axes.bbox) def get_view_interval(self): 'return the view Interval instance for the axis this tick is ticking' @@ -356,7 +355,6 @@ def _get_text1(self): # the y loc is 3 points below the min of y axis # get the affine as an a,b,c,d,tx,ty list # x in data coords, y in axes coords - #t = mtext.Text( trans, vert, horiz = self._get_text1_transform() t = mtext.Text( x=0, y=0, @@ -373,7 +371,6 @@ def _get_text2(self): 'Get the default Text 2 instance' # x in data coords, y in axes coords - #t = mtext.Text( trans, vert, horiz = self._get_text2_transform() t = mtext.Text( x=0, y=1, @@ -389,14 +386,10 @@ def _get_text2(self): def _get_tick1line(self): 'Get the default line2D instance' # x in data coords, y in axes coords - l = mlines.Line2D(xdata=(0,), ydata=(0,), - color=self._color, - linestyle='None', - marker=self._tickmarkers[0], - markersize=self._size, - markeredgewidth=self._width, - zorder=self._zorder, - ) + l = mlines.Line2D(xdata=(0,), ydata=(0,), color=self._color, + linestyle='None', marker=self._tickmarkers[0], + markersize=self._size, + markeredgewidth=self._width, zorder=self._zorder) l.set_transform(self.axes.get_xaxis_transform(which='tick1')) self._set_artist_props(l) return l @@ -405,13 +398,12 @@ def _get_tick2line(self): 'Get the default line2D instance' # x in data coords, y in axes coords l = mlines.Line2D(xdata=(0,), ydata=(1,), - color=self._color, - linestyle='None', - marker=self._tickmarkers[1], - markersize=self._size, - markeredgewidth=self._width, - zorder=self._zorder, - ) + color=self._color, + linestyle='None', + marker=self._tickmarkers[1], + markersize=self._size, + markeredgewidth=self._width, + zorder=self._zorder) l.set_transform(self.axes.get_xaxis_transform(which='tick2')) self._set_artist_props(l) @@ -421,12 +413,11 @@ def _get_gridline(self): 'Get the default line2D instance' # x in data coords, y in axes coords l = mlines.Line2D(xdata=(0.0, 0.0), ydata=(0, 1.0), - color=rcParams['grid.color'], - linestyle=rcParams['grid.linestyle'], - linewidth=rcParams['grid.linewidth'], - alpha=rcParams['grid.alpha'], - markersize=0 - ) + color=rcParams['grid.color'], + linestyle=rcParams['grid.linestyle'], + linewidth=rcParams['grid.linewidth'], + alpha=rcParams['grid.alpha'], + markersize=0) l.set_transform(self.axes.get_xaxis_transform(which='grid')) l.get_path()._interpolation_steps = GRIDLINE_INTERPOLATION_STEPS self._set_artist_props(l) @@ -506,7 +497,6 @@ def _get_text1(self): horizontalalignment=horiz, ) t.set_transform(trans) - #t.set_transform( self.axes.transData ) self._set_artist_props(t) return t @@ -530,13 +520,12 @@ def _get_tick1line(self): # x in axes coords, y in data coords l = mlines.Line2D((0,), (0,), - color=self._color, - marker=self._tickmarkers[0], - linestyle='None', - markersize=self._size, - markeredgewidth=self._width, - zorder=self._zorder, - ) + color=self._color, + marker=self._tickmarkers[0], + linestyle='None', + markersize=self._size, + markeredgewidth=self._width, + zorder=self._zorder) l.set_transform(self.axes.get_yaxis_transform(which='tick1')) self._set_artist_props(l) return l @@ -545,13 +534,12 @@ def _get_tick2line(self): 'Get the default line2D instance' # x in axes coords, y in data coords l = mlines.Line2D((1,), (0,), - color=self._color, - marker=self._tickmarkers[1], - linestyle='None', - markersize=self._size, - markeredgewidth=self._width, - zorder=self._zorder, - ) + color=self._color, + marker=self._tickmarkers[1], + linestyle='None', + markersize=self._size, + markeredgewidth=self._width, + zorder=self._zorder) l.set_transform(self.axes.get_yaxis_transform(which='tick2')) self._set_artist_props(l) return l @@ -560,12 +548,11 @@ def _get_gridline(self): 'Get the default line2D instance' # x in axes coords, y in data coords l = mlines.Line2D(xdata=(0, 1), ydata=(0, 0), - color=rcParams['grid.color'], - linestyle=rcParams['grid.linestyle'], - linewidth=rcParams['grid.linewidth'], - alpha=rcParams['grid.alpha'], - markersize=0 - ) + color=rcParams['grid.color'], + linestyle=rcParams['grid.linestyle'], + linewidth=rcParams['grid.linewidth'], + alpha=rcParams['grid.alpha'], + markersize=0) l.set_transform(self.axes.get_yaxis_transform(which='grid')) l.get_path()._interpolation_steps = GRIDLINE_INTERPOLATION_STEPS @@ -643,12 +630,6 @@ def __init__(self, axes, pickradius=15): self.minor = Ticker() self.callbacks = cbook.CallbackRegistry() - #class dummy: - # locator = None - # formatter = None - #self.major = dummy() - #self.minor = dummy() - self._autolabelpos = True self._smart_bounds = False @@ -745,8 +726,10 @@ def cla(self): self.callbacks = cbook.CallbackRegistry() # whether the grids are on - self._gridOnMajor = rcParams['axes.grid'] and (rcParams['axes.grid.which'] in ('both','major')) - self._gridOnMinor = rcParams['axes.grid'] and (rcParams['axes.grid.which'] in ('both','minor')) + self._gridOnMajor = (rcParams['axes.grid'] and + rcParams['axes.grid.which'] in ('both', 'major')) + self._gridOnMinor = (rcParams['axes.grid'] and + rcParams['axes.grid.which'] in ('both', 'minor')) self.label.set_text('') self._set_artist_props(self.label) @@ -812,10 +795,10 @@ def _bool(arg): # The following lists may be moved to a more # accessible location. kwkeys0 = ['size', 'width', 'color', 'tickdir', 'pad', - 'labelsize', 'labelcolor', 'zorder', 'gridOn', - 'tick1On', 'tick2On', 'label1On', 'label2On'] + 'labelsize', 'labelcolor', 'zorder', 'gridOn', + 'tick1On', 'tick2On', 'label1On', 'label2On'] kwkeys1 = ['length', 'direction', 'left', 'bottom', 'right', 'top', - 'labelleft', 'labelbottom', 'labelright', 'labeltop'] + 'labelleft', 'labelbottom', 'labelright', 'labeltop'] kwkeys = kwkeys0 + kwkeys1 kwtrans = dict() if to_init_kw: @@ -994,9 +977,10 @@ def _update_ticks(self, renderer): tick_tups = [ti for ti in tick_tups if (ti[1] >= ilow) and (ti[1] <= ihigh)] - # so that we don't lose ticks on the end, expand out the interval ever so slightly. The - # "ever so slightly" is defined to be the width of a half of a pixel. We don't want to draw - # a tick that even one pixel outside of the defined axis interval. + # so that we don't lose ticks on the end, expand out the interval ever + # so slightly. The "ever so slightly" is defined to be the width of a + # half of a pixel. We don't want to draw a tick that even one pixel + # outside of the defined axis interval. if interval[0] <= interval[1]: interval_expanded = interval else: @@ -1095,7 +1079,6 @@ def get_tightbbox(self, renderer): bb.extend(ticklabelBoxes) bb.extend(ticklabelBoxes2) - #self.offsetText bb = [b for b in bb if b.width != 0 or b.height != 0] if bb: _bbox = mtransforms.Bbox.union(bb) @@ -1204,11 +1187,11 @@ def get_ticklabels(self, minor=False, which=None): return self.get_minorticklabels() elif which == 'major': return self.get_majorticklabels() - elif which =='both': + elif which == 'both': return self.get_majorticklabels() + self.get_minorticklabels() else: - raise ValueError("`which` must be one of ('minor', 'major', 'both')" + - "not " + str(which)) + raise ValueError("`which` must be one of ('minor', 'major', " + "'both') not " + str(which)) if minor: return self.get_minorticklabels() return self.get_majorticklabels() @@ -1393,7 +1376,6 @@ def update_units(self, data): neednew = self.converter != converter self.converter = converter default = self.converter.default_units(data, self) - #print 'update units: default=%s, units=%s'%(default, self.units) if default is not None and self.units is None: self.set_units(default) @@ -1548,7 +1530,6 @@ def set_ticklabels(self, ticklabels, *args, **kwargs): ACCEPTS: sequence of strings """ - #ticklabels = [str(l) for l in ticklabels] minor = kwargs.pop('minor', False) if minor: self.set_minor_formatter(mticker.FixedFormatter(ticklabels)) @@ -1577,7 +1558,7 @@ def set_ticks(self, ticks, minor=False): ACCEPTS: sequence of floats """ - ### XXX if the user changes units, the information will be lost here + # XXX if the user changes units, the information will be lost here ticks = self.convert_units(ticks) if len(ticks) > 1: xleft, xright = self.get_view_interval() @@ -1650,8 +1631,8 @@ def contains(self, mouseevent): l, b = self.axes.transAxes.transform_point((0, 0)) r, t = self.axes.transAxes.transform_point((1, 1)) inaxis = xaxes >= 0 and xaxes <= 1 and ( - (y < b and y > b - self.pickradius) or - (y > t and y < t + self.pickradius)) + (y < b and y > b - self.pickradius) or + (y > t and y < t + self.pickradius)) return inaxis, {} def _get_tick(self, major): @@ -1665,13 +1646,12 @@ def _get_label(self): # x in axes coords, y in display coords (to be updated at draw # time by _update_label_positions) label = mtext.Text(x=0.5, y=0, - fontproperties=font_manager.FontProperties( + fontproperties=font_manager.FontProperties( size=rcParams['axes.labelsize'], weight=rcParams['axes.labelweight']), - color=rcParams['axes.labelcolor'], - verticalalignment='top', - horizontalalignment='center', - ) + color=rcParams['axes.labelcolor'], + verticalalignment='top', + horizontalalignment='center') label.set_transform(mtransforms.blended_transform_factory( self.axes.transAxes, mtransforms.IdentityTransform())) @@ -1683,44 +1663,50 @@ def _get_label(self): def _get_offset_text(self): # x in axes coords, y in display coords (to be updated at draw time) offsetText = mtext.Text(x=1, y=0, - fontproperties=font_manager.FontProperties( - size=rcParams['xtick.labelsize']), - color=rcParams['xtick.color'], - verticalalignment='top', - horizontalalignment='right', - ) + fontproperties=font_manager.FontProperties( + size=rcParams['xtick.labelsize']), + color=rcParams['xtick.color'], + verticalalignment='top', + horizontalalignment='right') offsetText.set_transform(mtransforms.blended_transform_factory( - self.axes.transAxes, mtransforms.IdentityTransform())) + self.axes.transAxes, mtransforms.IdentityTransform()) + ) self._set_artist_props(offsetText) self.offset_text_position = 'bottom' return offsetText def _get_pixel_distance_along_axis(self, where, perturb): """ - Returns the amount, in data coordinates, that a single pixel corresponds to in the - locality given by "where", which is also given in data coordinates, and is an x coordinate. - "perturb" is the amount to perturb the pixel. Usually +0.5 or -0.5. + Returns the amount, in data coordinates, that a single pixel + corresponds to in the locality given by "where", which is also given + in data coordinates, and is an x coordinate. "perturb" is the amount + to perturb the pixel. Usually +0.5 or -0.5. - Implementing this routine for an axis is optional; if present, it will ensure that no - ticks are lost due to round-off at the extreme ends of an axis. + Implementing this routine for an axis is optional; if present, it will + ensure that no ticks are lost due to round-off at the extreme ends of + an axis. """ - # Note that this routine does not work for a polar axis, because of the 1e-10 below. To - # do things correctly, we need to use rmax instead of 1e-10 for a polar axis. But - # since we do not have that kind of information at this point, we just don't try to - # pad anything for the theta axis of a polar plot. + # Note that this routine does not work for a polar axis, because of + # the 1e-10 below. To do things correctly, we need to use rmax + # instead of 1e-10 for a polar axis. But since we do not have that + # kind of information at this point, we just don't try to pad anything + # for the theta axis of a polar plot. if self.axes.name == 'polar': - return 0.0 + return 0.0 # - # first figure out the pixel location of the "where" point. We use 1e-10 for the - # y point, so that we remain compatible with log axes. - # - trans = self.axes.transData # transformation from data coords to display coords - transinv = trans.inverted() # transformation from display coords to data coords - pix = trans.transform_point((where, 1e-10)) - ptp = transinv.transform_point((pix[0] + perturb, pix[1])) # perturb the pixel. - dx = abs(ptp[0] - where) + # first figure out the pixel location of the "where" point. We use + # 1e-10 for the y point, so that we remain compatible with log axes. + + # transformation from data coords to display coords + trans = self.axes.transData + # transformation from display coords to data coords + transinv = trans.inverted() + pix = trans.transform_point((where, 1e-10)) + # perturb the pixel + ptp = transinv.transform_point((pix[0] + perturb, pix[1])) + dx = abs(ptp[0] - where) return dx @@ -1757,9 +1743,9 @@ def _update_label_position(self, bboxes, bboxes2): else: bbox = mtransforms.Bbox.union(bboxes) bottom = bbox.y0 - self.label.set_position((x, - bottom - \ - self.labelpad * self.figure.dpi / 72.0)) + self.label.set_position( + (x, bottom - self.labelpad * self.figure.dpi / 72.0) + ) else: if not len(bboxes2): @@ -1767,8 +1753,9 @@ def _update_label_position(self, bboxes, bboxes2): else: bbox = mtransforms.Bbox.union(bboxes2) top = bbox.y1 - self.label.set_position((x, - top + self.labelpad * self.figure.dpi / 72.0)) + self.label.set_position( + (x, top + self.labelpad * self.figure.dpi / 72.0) + ) def _update_offset_text_position(self, bboxes, bboxes2): """ @@ -1781,8 +1768,9 @@ def _update_offset_text_position(self, bboxes, bboxes2): else: bbox = mtransforms.Bbox.union(bboxes) bottom = bbox.y0 - self.offsetText.set_position((x, - bottom - self.OFFSETTEXTPAD * self.figure.dpi / 72.0)) + self.offsetText.set_position( + (x, bottom - self.OFFSETTEXTPAD * self.figure.dpi / 72.0) + ) def get_text_heights(self, renderer): """ @@ -1850,24 +1838,24 @@ def get_ticks_position(self): majt = self.majorTicks[0] mT = self.minorTicks[0] - majorTop = (not majt.tick1On) and \ - majt.tick2On and (not majt.label1On) and majt.label2On - minorTop = (not mT.tick1On) and \ - mT.tick2On and (not mT.label1On) and mT.label2On + majorTop = ((not majt.tick1On) and majt.tick2On and + (not majt.label1On) and majt.label2On) + minorTop = ((not mT.tick1On) and mT.tick2On and + (not mT.label1On) and mT.label2On) if majorTop and minorTop: return 'top' - MajorBottom = majt.tick1On and (not majt.tick2On) and \ - majt.label1On and (not majt.label2On) - MinorBottom = mT.tick1On and (not mT.tick2On) and \ - mT.label1On and (not mT.label2On) + MajorBottom = (majt.tick1On and (not majt.tick2On) and + majt.label1On and (not majt.label2On)) + MinorBottom = (mT.tick1On and (not mT.tick2On) and + mT.label1On and (not mT.label2On)) if MajorBottom and MinorBottom: return 'bottom' - majorDefault = majt.tick1On and majt.tick2On and \ - majt.label1On and (not majt.label2On) - minorDefault = mT.tick1On and mT.tick2On and \ - mT.label1On and (not mT.label2On) + majorDefault = (majt.tick1On and majt.tick2On and + majt.label1On and (not majt.label2On)) + minorDefault = (mT.tick1On and mT.tick2On and + mT.label1On and (not mT.label2On)) if majorDefault and minorDefault: return 'default' @@ -1952,8 +1940,8 @@ def contains(self, mouseevent): l, b = self.axes.transAxes.transform_point((0, 0)) r, t = self.axes.transAxes.transform_point((1, 1)) inaxis = yaxes >= 0 and yaxes <= 1 and ( - (x < l and x > l - self.pickradius) or - (x > r and x < r + self.pickradius)) + (x < l and x > l - self.pickradius) or + (x > r and x < r + self.pickradius)) return inaxis, {} def _get_tick(self, major): @@ -1967,16 +1955,15 @@ def _get_label(self): # x in display coords (updated by _update_label_position) # y in axes coords label = mtext.Text(x=0, y=0.5, - # todo: get the label position - fontproperties=font_manager.FontProperties( + # todo: get the label position + fontproperties=font_manager.FontProperties( size=rcParams['axes.labelsize'], weight=rcParams['axes.labelweight']), - color=rcParams['axes.labelcolor'], - verticalalignment='bottom', - horizontalalignment='center', - rotation='vertical', - rotation_mode='anchor', - ) + color=rcParams['axes.labelcolor'], + verticalalignment='bottom', + horizontalalignment='center', + rotation='vertical', + rotation_mode='anchor') label.set_transform(mtransforms.blended_transform_factory( mtransforms.IdentityTransform(), self.axes.transAxes)) @@ -1987,37 +1974,44 @@ def _get_label(self): def _get_offset_text(self): # x in display coords, y in axes coords (to be updated at draw time) offsetText = mtext.Text(x=0, y=0.5, - fontproperties=font_manager.FontProperties( - size=rcParams['ytick.labelsize']), - color=rcParams['ytick.color'], - verticalalignment='baseline', - horizontalalignment='left', - ) + fontproperties=font_manager.FontProperties( + size=rcParams['ytick.labelsize'] + ), + color=rcParams['ytick.color'], + verticalalignment='baseline', + horizontalalignment='left') offsetText.set_transform(mtransforms.blended_transform_factory( - self.axes.transAxes, mtransforms.IdentityTransform())) + self.axes.transAxes, mtransforms.IdentityTransform()) + ) self._set_artist_props(offsetText) self.offset_text_position = 'left' return offsetText def _get_pixel_distance_along_axis(self, where, perturb): """ - Returns the amount, in data coordinates, that a single pixel corresponds to in the - locality given by "where", which is also given in data coordinates, and is an y coordinate. - "perturb" is the amount to perturb the pixel. Usually +0.5 or -0.5. + Returns the amount, in data coordinates, that a single pixel + corresponds to in the locality given by *where*, which is also given + in data coordinates, and is an y coordinate. + + *perturb* is the amount to perturb the pixel. Usually +0.5 or -0.5. - Implementing this routine for an axis is optional; if present, it will ensure that no - ticks are lost due to round-off at the extreme ends of an axis. + Implementing this routine for an axis is optional; if present, it will + ensure that no ticks are lost due to round-off at the extreme ends of + an axis. """ # - # first figure out the pixel location of the "where" point. We use 1e-10 for the - # x point, so that we remain compatible with log axes. - # - trans = self.axes.transData # transformation from data coords to display coords - transinv = trans.inverted() # transformation from display coords to data coords - pix = trans.transform_point((1e-10, where)) - ptp = transinv.transform_point((pix[0], pix[1] + perturb)) # perturb the pixel. - dy = abs(ptp[1] - where) + # first figure out the pixel location of the "where" point. We use + # 1e-10 for the x point, so that we remain compatible with log axes. + + # transformation from data coords to display coords + trans = self.axes.transData + # transformation from display coords to data coords + transinv = trans.inverted() + pix = trans.transform_point((1e-10, where)) + # perturb the pixel + ptp = transinv.transform_point((pix[0], pix[1] + perturb)) + dy = abs(ptp[1] - where) return dy def get_label_position(self): @@ -2056,8 +2050,9 @@ def _update_label_position(self, bboxes, bboxes2): bbox = mtransforms.Bbox.union(bboxes) left = bbox.x0 - self.label.set_position((left - \ - self.labelpad * self.figure.dpi / 72.0, y)) + self.label.set_position( + (left - self.labelpad * self.figure.dpi / 72.0, y) + ) else: if not len(bboxes2): @@ -2066,8 +2061,9 @@ def _update_label_position(self, bboxes, bboxes2): bbox = mtransforms.Bbox.union(bboxes2) right = bbox.x1 - self.label.set_position((right + \ - self.labelpad * self.figure.dpi / 72.0, y)) + self.label.set_position( + (right + self.labelpad * self.figure.dpi / 72.0, y) + ) def _update_offset_text_position(self, bboxes, bboxes2): """ @@ -2076,8 +2072,9 @@ def _update_offset_text_position(self, bboxes, bboxes2): """ x, y = self.offsetText.get_position() top = self.axes.bbox.ymax - self.offsetText.set_position((x, - top + self.OFFSETTEXTPAD * self.figure.dpi / 72.0)) + self.offsetText.set_position( + (x, top + self.OFFSETTEXTPAD * self.figure.dpi / 72.0) + ) def set_offset_position(self, position): assert position == 'left' or position == 'right' @@ -2153,24 +2150,24 @@ def get_ticks_position(self): majt = self.majorTicks[0] mT = self.minorTicks[0] - majorRight = (not majt.tick1On) and majt.tick2On \ - and (not majt.label1On) and majt.label2On - minorRight = (not mT.tick1On) and mT.tick2On and \ - (not mT.label1On) and mT.label2On + majorRight = ((not majt.tick1On) and majt.tick2On + and (not majt.label1On) and majt.label2On) + minorRight = ((not mT.tick1On) and mT.tick2On and + (not mT.label1On) and mT.label2On) if majorRight and minorRight: return 'right' - majorLeft = majt.tick1On and (not majt.tick2On) and \ - majt.label1On and (not majt.label2On) - minorLeft = mT.tick1On and (not mT.tick2On) and \ - mT.label1On and (not mT.label2On) + majorLeft = (majt.tick1On and (not majt.tick2On) and + majt.label1On and (not majt.label2On)) + minorLeft = (mT.tick1On and (not mT.tick2On) and + mT.label1On and (not mT.label2On)) if majorLeft and minorLeft: return 'left' - majorDefault = majt.tick1On and majt.tick2On and \ - majt.label1On and (not majt.label2On) - minorDefault = mT.tick1On and mT.tick2On and \ - mT.label1On and (not mT.label2On) + majorDefault = (majt.tick1On and majt.tick2On and + majt.label1On and (not majt.label2On)) + minorDefault = (mT.tick1On and mT.tick2On and + mT.label1On and (not mT.label2On)) if majorDefault and minorDefault: return 'default' diff --git a/lib/matplotlib/bezier.py b/lib/matplotlib/bezier.py index ce2c9d5052a1..8400edf6ef7e 100644 --- a/lib/matplotlib/bezier.py +++ b/lib/matplotlib/bezier.py @@ -40,7 +40,7 @@ def get_intersection(cx1, cy1, cos_t1, sin_t1, if ad_bc == 0.: raise ValueError("Given lines do not intersect") - #rhs_inverse + # rhs_inverse a_, b_ = d, -b c_, d_ = -c, a a_, b_, c_, d_ = [k / ad_bc for k in [a_, b_, c_, d_]] @@ -70,7 +70,7 @@ def get_normal_points(cx, cy, cos_t, sin_t, length): return x1, y1, x2, y2 -## BEZIER routines +# BEZIER routines # subdividing bezier curve # http://www.cs.mtu.edu/~shene/COURSES/cs3621/NOTES/spline/Bezier/bezier-sub.html @@ -126,7 +126,8 @@ def find_bezier_t_intersecting_with_closedpath(bezier_point_at_t, if not xor(start_inside, end_inside): raise NonIntersectingPathException( - "the segment does not seem to intersect with the path") + "the segment does not seem to intersect with the path" + ) while 1: @@ -233,7 +234,7 @@ def _f(r): t0=rmin, t1=rmax, tolerence=tolerence) -## matplotlib specific +# matplotlib specific def split_path_inout(path, inside, tolerence=0.01, reorder_inout=False): @@ -285,8 +286,6 @@ def split_path_inout(path, inside, tolerence=0.01, reorder_inout=False): verts_left = left[1:] verts_right = right[:] - #i += 1 - if path.codes is None: path_in = Path(concat([path.vertices[:i], verts_left])) path_out = Path(concat([verts_right, path.vertices[i:]])) @@ -298,7 +297,7 @@ def split_path_inout(path, inside, tolerence=0.01, reorder_inout=False): path_out = Path(concat([verts_right, path.vertices[i:]]), concat([codes_right, path.codes[i:]])) - if reorder_inout and begin_inside == False: + if reorder_inout and begin_inside is False: path_in, path_out = path_out, path_in return path_in, path_out @@ -330,7 +329,7 @@ def check_if_parallel(dx1, dy1, dx2, dy2, tolerence=1.e-5): theta1 = np.arctan2(dx1, dy1) theta2 = np.arctan2(dx2, dy2) dtheta = np.abs(theta1 - theta2) - if dtheta < tolerence: + if dtheta < tolerence: return 1 elif np.abs(dtheta - np.pi) < tolerence: return -1 @@ -360,7 +359,6 @@ def get_parallels(bezier2, width): if parallel_test == -1: warnings.warn( "Lines do not intersect. A straight line is used instead.") - #cmx, cmy = 0.5*(c1x+c2x), 0.5*(c1y+c2y) cos_t1, sin_t1 = get_cos_sin(c1x, c1y, c2x, c2y) cos_t2, sin_t2 = cos_t1, sin_t1 else: @@ -373,10 +371,12 @@ def get_parallels(bezier2, width): # throught c1 and perpendicular to the tangential lines of the # bezier path at a distance of width. Same thing for c2_left and # c2_right with respect to c2. - c1x_left, c1y_left, c1x_right, c1y_right = \ - get_normal_points(c1x, c1y, cos_t1, sin_t1, width) - c2x_left, c2y_left, c2x_right, c2y_right = \ - get_normal_points(c2x, c2y, cos_t2, sin_t2, width) + c1x_left, c1y_left, c1x_right, c1y_right = ( + get_normal_points(c1x, c1y, cos_t1, sin_t1, width) + ) + c2x_left, c2y_left, c2x_right, c2y_right = ( + get_normal_points(c2x, c2y, cos_t2, sin_t2, width) + ) # find cm_left which is the intersectng point of a line through # c1_left with angle t1 and a line throught c2_left with angle @@ -384,18 +384,20 @@ def get_parallels(bezier2, width): if parallel_test != 0: # a special case for a straight line, i.e., angle between two # lines are smaller than some (arbitrtay) value. - cmx_left, cmy_left = \ - 0.5 * (c1x_left + c2x_left), 0.5 * (c1y_left + c2y_left) - cmx_right, cmy_right = \ - 0.5 * (c1x_right + c2x_right), 0.5 * (c1y_right + c2y_right) + cmx_left, cmy_left = ( + 0.5 * (c1x_left + c2x_left), 0.5 * (c1y_left + c2y_left) + ) + cmx_right, cmy_right = ( + 0.5 * (c1x_right + c2x_right), 0.5 * (c1y_right + c2y_right) + ) else: - cmx_left, cmy_left = \ - get_intersection(c1x_left, c1y_left, cos_t1, sin_t1, - c2x_left, c2y_left, cos_t2, sin_t2) + cmx_left, cmy_left = get_intersection(c1x_left, c1y_left, cos_t1, + sin_t1, c2x_left, c2y_left, + cos_t2, sin_t2) - cmx_right, cmy_right = \ - get_intersection(c1x_right, c1y_right, cos_t1, sin_t1, - c2x_right, c2y_right, cos_t2, sin_t2) + cmx_right, cmy_right = get_intersection(c1x_right, c1y_right, cos_t1, + sin_t1, c2x_right, c2y_right, + cos_t2, sin_t2) # the parralel bezier lines are created with control points of # [c1_left, cm_left, c2_left] and [c1_right, cm_right, c2_right] @@ -441,10 +443,12 @@ def make_wedged_bezier2(bezier2, width, w1=1., wm=0.5, w2=0.): # throught c1 and perpendicular to the tangential lines of the # bezier path at a distance of width. Same thing for c3_left and # c3_right with respect to c3. - c1x_left, c1y_left, c1x_right, c1y_right = \ - get_normal_points(c1x, c1y, cos_t1, sin_t1, width * w1) - c3x_left, c3y_left, c3x_right, c3y_right = \ - get_normal_points(c3x, c3y, cos_t2, sin_t2, width * w2) + c1x_left, c1y_left, c1x_right, c1y_right = ( + get_normal_points(c1x, c1y, cos_t1, sin_t1, width * w1) + ) + c3x_left, c3y_left, c3x_right, c3y_right = ( + get_normal_points(c3x, c3y, cos_t2, sin_t2, width * w2) + ) # find c12, c23 and c123 which are middle points of c1-cm, cm-c3 and # c12-c23 @@ -455,8 +459,9 @@ def make_wedged_bezier2(bezier2, width, w1=1., wm=0.5, w2=0.): # tangential angle of c123 (angle between c12 and c23) cos_t123, sin_t123 = get_cos_sin(c12x, c12y, c23x, c23y) - c123x_left, c123y_left, c123x_right, c123y_right = \ - get_normal_points(c123x, c123y, cos_t123, sin_t123, width * wm) + c123x_left, c123y_left, c123x_right, c123y_right = ( + get_normal_points(c123x, c123y, cos_t123, sin_t123, width * wm) + ) path_left = find_control_points(c1x_left, c1y_left, c123x_left, c123y_left, diff --git a/lib/matplotlib/mlab.py b/lib/matplotlib/mlab.py index 69160d0ba702..7f8035086be8 100644 --- a/lib/matplotlib/mlab.py +++ b/lib/matplotlib/mlab.py @@ -653,9 +653,9 @@ def _spectral_helper(x, y=None, NFFT=None, Fs=None, detrend_func=None, # if y is None use x for y same_data = True else: - #The checks for if y is x are so that we can use the same function to - #implement the core of psd(), csd(), and spectrogram() without doing - #extra calculations. We return the unaveraged Pxy, freqs, and t. + # The checks for if y is x are so that we can use the same function to + # implement the core of psd(), csd(), and spectrogram() without doing + # extra calculations. We return the unaveraged Pxy, freqs, and t. same_data = y is x if Fs is None: @@ -681,8 +681,8 @@ def _spectral_helper(x, y=None, NFFT=None, Fs=None, detrend_func=None, if not same_data and mode != 'psd': raise ValueError("x and y must be equal if mode is not 'psd'") - #Make sure we're dealing with a numpy array. If y and x were the same - #object to start with, keep them that way + # Make sure we're dealing with a numpy array. If y and x were the same + # object to start with, keep them that way x = np.asarray(x) if not same_data: y = np.asarray(y) @@ -817,7 +817,7 @@ def _single_spectrum_helper(x, mode, Fs=None, window=None, pad_to=None, return spec, freqs -#Split out these keyword docs so that they can be used elsewhere +# Split out these keyword docs so that they can be used elsewhere docstring.interpd.update(Spectral=cbook.dedent(""" Keyword arguments: @@ -1364,11 +1364,11 @@ def donothing_callback(*args): pass -def cohere_pairs( X, ij, NFFT=256, Fs=2, detrend=detrend_none, - window=window_hanning, noverlap=0, - preferSpeedOverMemory=True, - progressCallback=donothing_callback, - returnPxx=False): +def cohere_pairs(X, ij, NFFT=256, Fs=2, detrend=detrend_none, + window=window_hanning, noverlap=0, + preferSpeedOverMemory=True, + progressCallback=donothing_callback, + returnPxx=False): """ Call signature:: @@ -1450,21 +1450,24 @@ def cohere_pairs( X, ij, NFFT=256, Fs=2, detrend=detrend_none, # zero pad if X is too short if numRows < NFFT: tmp = X - X = np.zeros( (NFFT, numCols), X.dtype) - X[:numRows,:] = tmp + X = np.zeros((NFFT, numCols), X.dtype) + X[:numRows, :] = tmp del tmp numRows, numCols = X.shape # get all the columns of X that we are interested in by checking # the ij tuples allColumns = set() - for i,j in ij: - allColumns.add(i); allColumns.add(j) + for i, j in ij: + allColumns.add(i) + allColumns.add(j) Ncols = len(allColumns) # for real X, ignore the negative frequencies - if np.iscomplexobj(X): numFreqs = NFFT - else: numFreqs = NFFT//2+1 + if np.iscomplexobj(X): + numFreqs = NFFT + else: + numFreqs = NFFT//2+1 # cache the FFT of every windowed, detrended NFFT length segement # of every channel. If preferSpeedOverMemory, cache the conjugate @@ -1483,11 +1486,11 @@ def cohere_pairs( X, ij, NFFT=256, Fs=2, detrend=detrend_none, normVal = np.linalg.norm(windowVals)**2 for iCol in allColumns: progressCallback(i/Ncols, 'Cacheing FFTs') - Slices = np.zeros( (numSlices,numFreqs), dtype=np.complex_) + Slices = np.zeros((numSlices, numFreqs), dtype=np.complex_) for iSlice in slices: thisSlice = X[ind[iSlice]:ind[iSlice]+NFFT, iCol] thisSlice = windowVals*detrend(thisSlice) - Slices[iSlice,:] = np.fft.fft(thisSlice)[:numFreqs] + Slices[iSlice, :] = np.fft.fft(thisSlice)[:numFreqs] FFTSlices[iCol] = Slices if preferSpeedOverMemory: @@ -1501,21 +1504,22 @@ def cohere_pairs( X, ij, NFFT=256, Fs=2, detrend=detrend_none, Phase = {} count = 0 N = len(ij) - for i,j in ij: - count +=1 - if count%10==0: + for i, j in ij: + count += 1 + if count % 10 == 0: progressCallback(count/N, 'Computing coherences') if preferSpeedOverMemory: Pxy = FFTSlices[i] * FFTConjSlices[j] else: Pxy = FFTSlices[i] * np.conjugate(FFTSlices[j]) - if numSlices>1: Pxy = np.mean(Pxy, axis=0) - #Pxy = np.divide(Pxy, normVal) + if numSlices > 1: + Pxy = np.mean(Pxy, axis=0) +# Pxy = np.divide(Pxy, normVal) Pxy /= normVal - #Cxy[(i,j)] = np.divide(np.absolute(Pxy)**2, Pxx[i]*Pxx[j]) - Cxy[i,j] = abs(Pxy)**2 / (Pxx[i]*Pxx[j]) - Phase[i,j] = np.arctan2(Pxy.imag, Pxy.real) +# Cxy[(i,j)] = np.divide(np.absolute(Pxy)**2, Pxx[i]*Pxx[j]) + Cxy[i, j] = abs(Pxy)**2 / (Pxx[i]*Pxx[j]) + Phase[i, j] = np.arctan2(Pxy.imag, Pxy.real) freqs = Fs/NFFT*np.arange(numFreqs) if returnPxx: @@ -1523,6 +1527,7 @@ def cohere_pairs( X, ij, NFFT=256, Fs=2, detrend=detrend_none, else: return Cxy, Phase, freqs + def entropy(y, bins): r""" Return the entropy of the data in *y* in units of nat. @@ -1551,6 +1556,7 @@ def entropy(y, bins): S = -1.0 * np.sum(p * np.log(p)) + np.log(delta) return S + def normpdf(x, *args): "Return the normal pdf evaluated at *x*; args provides *mu*, *sigma*" mu, sigma = args @@ -1570,29 +1576,31 @@ def longest_contiguous_ones(x): equally long stretches, pick the first. """ x = np.ravel(x) - if len(x)==0: + if len(x) == 0: return np.array([]) - ind = (x==0).nonzero()[0] - if len(ind)==0: + ind = (x == 0).nonzero()[0] + if len(ind) == 0: return np.arange(len(x)) - if len(ind)==len(x): + if len(ind) == len(x): return np.array([]) - y = np.zeros( (len(x)+2,), x.dtype) + y = np.zeros((len(x)+2,), x.dtype) y[1:-1] = x dif = np.diff(y) - up = (dif == 1).nonzero()[0]; - dn = (dif == -1).nonzero()[0]; + up = (dif == 1).nonzero()[0] + dn = (dif == -1).nonzero()[0] i = (dn-up == max(dn - up)).nonzero()[0][0] ind = np.arange(up[i], dn[i]) return ind + def longest_ones(x): '''alias for longest_contiguous_ones''' return longest_contiguous_ones(x) + def prepca(P, frac=0): """ @@ -1618,15 +1626,15 @@ def prepca(P, frac=0): its successor seems to be called "processpcs". """ warnings.warn('This function is deprecated -- see class PCA instead') - U,s,v = np.linalg.svd(P) + U, s, v = np.linalg.svd(P) varEach = s**2/P.shape[1] totVar = varEach.sum() fracVar = varEach/totVar - ind = slice((fracVar>=frac).sum()) + ind = slice((fracVar >= frac).sum()) # select the components that are greater - Trans = U[:,ind].transpose() + Trans = U[:, ind].transpose() # The transformed data - Pcomponents = np.dot(Trans,P) + Pcomponents = np.dot(Trans, P) return Pcomponents, Trans, fracVar[ind] @@ -1639,8 +1647,8 @@ def __init__(self, a, standardize=True): Inputs: *a*: a numobservations x numdims array - *standardize*: True if input data are to be standardized. If False, only centering will be - carried out. + *standardize*: True if input data are to be standardized. If False, + only centering will be carried out. Attrs: @@ -1648,18 +1656,20 @@ def __init__(self, a, standardize=True): *numrows*, *numcols*: the dimensions of a - *mu* : a numdims array of means of a. This is the vector that points to the - origin of PCA space. + *mu*: a numdims array of means of a. This is the vector that points + to the origin of PCA space. - *sigma* : a numdims array of standard deviation of a + *sigma*: a numdims array of standard deviation of a - *fracs* : the proportion of variance of each of the principal components + *fracs*: the proportion of variance of each of the principal + components - *s* : the actual eigenvalues of the decomposition + *s*: the actual eigenvalues of the decomposition - *Wt* : the weight vector for projecting a numdims point or array into PCA space + *Wt*: the weight vector for projecting a numdims point or array into + PCA space - *Y* : a projected into PCA space + *Y*: a projected into PCA space The factor loadings are in the Wt factor, ie the factor @@ -1668,8 +1678,9 @@ def __init__(self, a, standardize=True): """ n, m = a.shape - if nnumcols') + if n < m: + raise RuntimeError('we assume data in a is organized with ' + 'numrows>numcols') self.numrows, self.numcols = n, m self.mu = a.mean(axis=0) @@ -1689,7 +1700,8 @@ def __init__(self, a, standardize=True): # The rows of Vh are the eigenvectors of a.H a. # The columns of U are the eigenvectors of a a.H. - # For row i in Vh and column i in U, the corresponding eigenvalue is s[i]**2. + # For row i in Vh and column i in U, the corresponding eigenvalue is + # s[i]**2. self.Wt = Vh @@ -1704,56 +1716,58 @@ def __init__(self, a, standardize=True): vars = self.s/float(len(s)) self.fracs = vars/vars.sum() - def project(self, x, minfrac=0.): - 'project x onto the principle axes, dropping any axes where fraction of variance=minfrac - if ndims==2: - Yreduced = Y[:,mask] + mask = self.fracs >= minfrac + if ndims == 2: + Yreduced = Y[:, mask] else: Yreduced = Y[mask] return Yreduced - - def center(self, x): - 'center and optionally standardize the data using the mean and sigma from training set a' + ''' + center and optionally standardize the data using the mean and sigma + from training set a + ''' if self.standardize: return (x - self.mu)/self.sigma else: return (x - self.mu) - - @staticmethod def _get_colinear(): c0 = np.array([ - 0.19294738, 0.6202667 , 0.45962655, 0.07608613, 0.135818 , + 0.19294738, 0.6202667, 0.45962655, 0.07608613, 0.135818, 0.83580842, 0.07218851, 0.48318321, 0.84472463, 0.18348462, 0.81585306, 0.96923926, 0.12835919, 0.35075355, 0.15807861, - 0.837437 , 0.10824303, 0.1723387 , 0.43926494, 0.83705486]) + 0.837437, 0.10824303, 0.1723387, 0.43926494, 0.83705486]) c1 = np.array([ - -1.17705601, -0.513883 , -0.26614584, 0.88067144, 1.00474954, - -1.1616545 , 0.0266109 , 0.38227157, 1.80489433, 0.21472396, + -1.17705601, -0.513883, -0.26614584, 0.88067144, 1.00474954, + -1.1616545, 0.0266109, 0.38227157, 1.80489433, 0.21472396, -1.41920399, -2.08158544, -0.10559009, 1.68999268, 0.34847107, - -0.4685737 , 1.23980423, -0.14638744, -0.35907697, 0.22442616]) + -0.4685737, 1.23980423, -0.14638744, -0.35907697, 0.22442616]) c2 = c0 + 2*c1 c3 = -3*c0 + 4*c1 a = np.array([c3, c0, c1, c2]).T return a -def prctile(x, p = (0.0, 25.0, 50.0, 75.0, 100.0)): + +def prctile(x, p=(0.0, 25.0, 50.0, 75.0, 100.0)): """ Return the percentiles of *x*. *p* can either be a sequence of percentile values or a scalar. If *p* is a sequence, the ith @@ -1776,7 +1790,7 @@ def _interpolate(a, b, fraction): values = np.array(x).ravel() # copy values.sort() - idxs = per /100. * (values.shape[0] - 1) + idxs = per/100. * (values.shape[0] - 1) ai = idxs.astype(np.int) bi = ai + 1 frac = idxs % 1 @@ -1793,7 +1807,8 @@ def _interpolate(a, b, fraction): bi[cond] -= 1 frac[cond] += 1 - return _interpolate(values[ai],values[bi],frac) + return _interpolate(values[ai], values[bi], frac) + def prctile_rank(x, p): """ @@ -1813,12 +1828,13 @@ def prctile_rank(x, p): else: p = np.asarray(p) - if p.max()<=1 or p.min()<0 or p.max()>100: + if p.max() <= 1 or p.min() < 0 or p.max() > 100: raise ValueError('percentiles should be in range 0..100, not 0..1') ptiles = prctile(x, p) return np.searchsorted(ptiles, x) + def center_matrix(M, dim=0): """ Return the matrix *M* with each row having zero mean and unit std. @@ -1830,12 +1846,11 @@ def center_matrix(M, dim=0): if dim: M = (M - M.mean(axis=0)) / M.std(axis=0) else: - M = (M - M.mean(axis=1)[:,np.newaxis]) - M = M / M.std(axis=1)[:,np.newaxis] + M = (M - M.mean(axis=1)[:, np.newaxis]) + M = M / M.std(axis=1)[:, np.newaxis] return M - def rk4(derivs, y0, t): """ Integrate 1D or ND system of ODEs using 4-th order Runge-Kutta. @@ -1882,12 +1897,12 @@ def derivs(x,t): scipy.integrate tools rather than this function. """ - try: Ny = len(y0) + try: + Ny = len(y0) except TypeError: - yout = np.zeros( (len(t),), np.float_) + yout = np.zeros((len(t),), np.float_) else: - yout = np.zeros( (len(t), Ny), np.float_) - + yout = np.zeros((len(t), Ny), np.float_) yout[0] = y0 i = 0 @@ -1922,7 +1937,8 @@ def bivariate_normal(X, Y, sigmax=1.0, sigmay=1.0, rho = sigmaxy/(sigmax*sigmay) z = Xmu**2/sigmax**2 + Ymu**2/sigmay**2 - 2*rho*Xmu*Ymu/(sigmax*sigmay) denom = 2*np.pi*sigmax*sigmay*np.sqrt(1-rho**2) - return np.exp( -z/(2*(1-rho**2))) / denom + return np.exp(-z/(2*(1-rho**2))) / denom + def get_xyz_where(Z, Cond): """ @@ -1932,27 +1948,30 @@ def get_xyz_where(Z, Cond): *z* are the values of *Z* at those indices. *x*, *y*, and *z* are 1D arrays. """ - X,Y = np.indices(Z.shape) + X, Y = np.indices(Z.shape) return X[Cond], Y[Cond], Z[Cond] -def get_sparse_matrix(M,N,frac=0.1): + +def get_sparse_matrix(M, N, frac=0.1): """ Return a *M* x *N* sparse matrix with *frac* elements randomly filled. """ - data = np.zeros((M,N))*0. + data = np.zeros((M, N))*0. for i in range(int(M*N*frac)): - x = np.random.randint(0,M-1) - y = np.random.randint(0,N-1) - data[x,y] = np.random.rand() + x = np.random.randint(0, M-1) + y = np.random.randint(0, N-1) + data[x, y] = np.random.rand() return data -def dist(x,y): + +def dist(x, y): """ Return the distance between two points. """ d = x-y - return np.sqrt(np.dot(d,d)) + return np.sqrt(np.dot(d, d)) + def dist_point_to_segment(p, s0, s1): """ @@ -1969,18 +1988,19 @@ def dist_point_to_segment(p, s0, s1): v = s1 - s0 w = p - s0 - c1 = np.dot(w,v); - if ( c1 <= 0 ): - return dist(p, s0); + c1 = np.dot(w, v) + if c1 <= 0: + return dist(p, s0) - c2 = np.dot(v,v) - if ( c2 <= c1 ): - return dist(p, s1); + c2 = np.dot(v, v) + if c2 <= c1: + return dist(p, s1) b = c1 / c2 - pb = s0 + b * v; + pb = s0 + b * v return dist(p, pb) + def segments_intersect(s1, s2): """ Return *True* if *s1* and *s2* intersect. @@ -2012,7 +2032,7 @@ def fftsurr(x, detrend=detrend_none, window=window_none): Compute an FFT phase randomized surrogate of *x*. """ if cbook.iterable(window): - x=window*detrend(x) + x = window*detrend(x) else: x = window(detrend(x)) z = np.fft.fft(x) @@ -2070,16 +2090,15 @@ def add(self, x, y): Add scalar *x* and *y* to the queue. """ if self.dataLim is not None: - xy = np.asarray([(x,y),]) + xy = np.asarray([(x, y)]) self.dataLim.update_from_data_xy(xy, None) ind = self._ind % self._nmax - #print 'adding to fifo:', ind, x, y self._xs[ind] = x self._ys[ind] = y - for N,funcs in six.iteritems(self.callbackd): - if (self._ind%N)==0: + for N, funcs in six.iteritems(self.callbackd): + if (self._ind % N) == 0: for func in funcs: func(self) @@ -2089,7 +2108,8 @@ def last(self): """ Get the last *x*, *y* or *None*. *None* if no data set. """ - if self._ind==0: return None, None + if self._ind == 0: + return None, None ind = (self._ind-1) % self._nmax return self._xs[ind], self._ys[ind] @@ -2098,7 +2118,7 @@ def asarrays(self): Return *x* and *y* as arrays; their length will be the len of data added or *nmax*. """ - if self._ind array. Works like :func:`map`, but it returns an array. This is just a convenient shorthand for ``numpy.array(map(...))``. """ - return np.array(list(map(fn,*args))) + return np.array(list(map(fn, *args))) def rms_flat(a): @@ -2211,6 +2232,7 @@ def rms_flat(a): """ return np.sqrt(np.mean(np.absolute(a)**2)) + def l1norm(a): """ Return the *l1* norm of *a*, flattened out. @@ -2219,6 +2241,7 @@ def l1norm(a): """ return np.sum(np.absolute(a)) + def l2norm(a): """ Return the *l2* norm of *a*, flattened out. @@ -2227,7 +2250,8 @@ def l2norm(a): """ return np.sqrt(np.sum(np.absolute(a)**2)) -def norm_flat(a,p=2): + +def norm_flat(a, p=2): """ norm(a,p=2) -> l-p norm of a.flat @@ -2238,12 +2262,13 @@ def norm_flat(a,p=2): """ # This function was being masked by a more general norm later in # the file. We may want to simply delete it. - if p=='Infinity': + if p == 'Infinity': return np.amax(np.absolute(a)) else: return (np.sum(np.absolute(a)**p))**(1.0/p) -def frange(xini,xfin=None,delta=None,**kw): + +def frange(xini, xfin=None, delta=None, **kw): """ frange([start,] stop[, step, keywords]) -> array of floats @@ -2283,27 +2308,26 @@ def frange(xini,xfin=None,delta=None,**kw): array([ 1. , 2.375, 3.75 , 5.125, 6.5 ]) """ - #defaults - kw.setdefault('closed',1) + # defaults + kw.setdefault('closed', 1) endpoint = kw['closed'] != 0 # funny logic to allow the *first* argument to be optional (like range()) # This was modified with a simpler version from a similar frange() found # at http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/66472 - if xfin == None: + if xfin is None: xfin = xini + 0.0 xini = 0.0 - if delta == None: + if delta is None: delta = 1.0 # compute # of points, spacing and return final list try: - npts=kw['npts'] - delta=(xfin-xini)/float(npts-endpoint) + npts = kw['npts'] + delta = (xfin-xini)/float(npts-endpoint) except KeyError: npts = int(round((xfin-xini)/delta)) + endpoint - #npts = int(floor((xfin-xini)/delta)*(1.0+1e-10)) + endpoint # round finds the nearest, so the endpoint can be up to # delta/2 larger than xfin. @@ -2336,21 +2360,23 @@ def identity(n, rank=2, dtype='l', typecode=None): iden[idx] = 1 return iden -def base_repr (number, base = 2, padding = 0): + +def base_repr(number, base=2, padding=0): """ Return the representation of a *number* in any given *base*. """ chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ' - if number < base: \ - return (padding - 1) * chars [0] + chars [int (number)] - max_exponent = int (math.log (number)/math.log (base)) - max_power = long (base) ** max_exponent - lead_digit = int (number/max_power) - return chars [lead_digit] + \ - base_repr (number - max_power * lead_digit, base, \ - max (padding - 1, max_exponent)) + if number < base: + return (padding - 1) * chars[0] + chars[int(number)] + max_exponent = int(math.log(number)/math.log(base)) + max_power = long(base) ** max_exponent + lead_digit = int(number/max_power) + return (chars[lead_digit] + + base_repr(number - max_power * lead_digit, base, + max(padding - 1, max_exponent))) -def binary_repr(number, max_length = 1025): + +def binary_repr(number, max_length=1025): """ Return the binary representation of the input *number* as a string. @@ -2362,15 +2388,17 @@ def binary_repr(number, max_length = 1025): which can be converted to a Python float. """ - #assert number < 2L << max_length - shifts = list(map (operator.rshift, max_length * [number], \ - range (max_length - 1, -1, -1))) - digits = list(map (operator.mod, shifts, max_length * [2])) - if not digits.count (1): return 0 - digits = digits [digits.index (1):] - return ''.join (map (repr, digits)).replace('L','') +# assert number < 2L << max_length + shifts = list(map(operator.rshift, max_length * [number], + range(max_length - 1, -1, -1))) + digits = list(map(operator.mod, shifts, max_length * [2])) + if not digits.count(1): + return 0 + digits = digits[digits.index(1):] + return ''.join(map(repr, digits)).replace('L', '') + -def log2(x,ln2 = math.log(2.0)): +def log2(x, ln2=math.log(2.0)): """ Return the log(*x*) in base 2. @@ -2379,7 +2407,7 @@ def log2(x,ln2 = math.log(2.0)): """ try: bin_n = binary_repr(x)[1:] - except (AssertionError,TypeError): + except (AssertionError, TypeError): return math.log(x)/ln2 else: if '1' in bin_n: @@ -2387,6 +2415,7 @@ def log2(x,ln2 = math.log(2.0)): else: return len(bin_n) + def ispower2(n): """ Returns the log base 2 of *n* if *n* is a power of 2, zero otherwise. @@ -2400,6 +2429,7 @@ def ispower2(n): else: return len(bin_n) + def isvector(X): """ Like the MATLAB function with the same name, returns *True* @@ -2410,30 +2440,40 @@ def isvector(X): If you just want to see if the array has 1 axis, use X.ndim == 1. """ - return np.prod(X.shape)==np.max(X.shape) + return np.prod(X.shape) == np.max(X.shape) -### end fperez numutils code +# end fperez numutils code -#helpers for loading, saving, manipulating and viewing numpy record arrays +# helpers for loading, saving, manipulating and viewing numpy record arrays def safe_isnan(x): ':func:`numpy.isnan` for arbitrary types' if cbook.is_string_like(x): return False - try: b = np.isnan(x) - except NotImplementedError: return False - except TypeError: return False - else: return b + try: + b = np.isnan(x) + except NotImplementedError: + return False + except TypeError: + return False + else: + return b + def safe_isinf(x): ':func:`numpy.isinf` for arbitrary types' if cbook.is_string_like(x): return False - try: b = np.isinf(x) - except NotImplementedError: return False - except TypeError: return False - else: return b + try: + b = np.isinf(x) + except NotImplementedError: + return False + except TypeError: + return False + else: + return b + def rec_append_fields(rec, names, arrs, dtypes=None): """ @@ -2442,11 +2482,11 @@ def rec_append_fields(rec, names, arrs, dtypes=None): *arrs* and *dtypes* do not have to be lists. They can just be the values themselves. """ - if (not cbook.is_string_like(names) and cbook.iterable(names) \ + if (not cbook.is_string_like(names) and cbook.iterable(names) and len(names) and cbook.is_string_like(names[0])): if len(names) != len(arrs): raise ValueError("number of arrays do not match number of names") - else: # we have only 1 name and 1 array + else: # we have only 1 name and 1 array names = [names] arrs = [arrs] arrs = list(map(np.asarray, arrs)) @@ -2477,7 +2517,7 @@ def rec_drop_fields(rec, names): names = set(names) newdtype = np.dtype([(name, rec.dtype[name]) for name in rec.dtype.names - if name not in names]) + if name not in names]) newrec = np.recarray(rec.shape, dtype=newdtype) for field in newdtype.names: @@ -2485,6 +2525,7 @@ def rec_drop_fields(rec, names): return newrec + def rec_keep_fields(rec, names): """ Return a new numpy record array with only fields listed in names @@ -2500,7 +2541,6 @@ def rec_keep_fields(rec, names): return np.rec.fromarrays(arrays, names=names) - def rec_groupby(r, groupby, stats): """ *r* is a numpy record array @@ -2547,7 +2587,6 @@ def rec_groupby(r, groupby, stats): return np.rec.fromrecords(rows, names=names) - def rec_summarize(r, summaryfuncs): """ *r* is a numpy record array @@ -2570,7 +2609,8 @@ def rec_summarize(r, summaryfuncs): return np.rec.fromarrays(arrays, names=names) -def rec_join(key, r1, r2, jointype='inner', defaults=None, r1postfix='1', r2postfix='2'): +def rec_join(key, r1, r2, jointype='inner', defaults=None, r1postfix='1', + r2postfix='2'): """ Join record arrays *r1* and *r2* on *key*; *key* is a tuple of field names -- if *key* is a string it is assumed to be a single @@ -2596,15 +2636,15 @@ def rec_join(key, r1, r2, jointype='inner', defaults=None, r1postfix='1', r2post for name in key: if name not in r1.dtype.names: - raise ValueError('r1 does not have key field %s'%name) + raise ValueError('r1 does not have key field %s' % name) if name not in r2.dtype.names: - raise ValueError('r2 does not have key field %s'%name) + raise ValueError('r2 does not have key field %s' % name) def makekey(row): return tuple([row[name] for name in key]) - r1d = dict([(makekey(row),i) for i,row in enumerate(r1)]) - r2d = dict([(makekey(row),i) for i,row in enumerate(r2)]) + r1d = dict([(makekey(row), i) for i, row in enumerate(r1)]) + r2d = dict([(makekey(row), i) for i, row in enumerate(r2)]) r1keys = set(r1d.keys()) r2keys = set(r2d.keys()) @@ -2626,7 +2666,10 @@ def makekey(row): right_len = len(right_ind) def key_desc(name): - 'if name is a string key, use the larger size of r1 or r2 before merging' + ''' + if name is a string key, use the larger size of r1 or r2 before + merging + ''' dt1 = r1.dtype[name] if dt1.type != np.string_: return (name, dt1.descr[0][1]) @@ -2636,30 +2679,35 @@ def key_desc(name): msg = "The '{}' fields in arrays 'r1' and 'r2' must have the same" msg += " dtype." raise ValueError(msg.format(name)) - if dt1.num>dt2.num: + if dt1.num > dt2.num: return (name, dt1.descr[0][1]) else: return (name, dt2.descr[0][1]) - keydesc = [key_desc(name) for name in key] def mapped_r1field(name): """ The column name in *newrec* that corresponds to the column in *r1*. """ - if name in key or name not in r2.dtype.names: return name - else: return name + r1postfix + if name in key or name not in r2.dtype.names: + return name + else: + return name + r1postfix def mapped_r2field(name): """ The column name in *newrec* that corresponds to the column in *r2*. """ - if name in key or name not in r1.dtype.names: return name - else: return name + r2postfix + if name in key or name not in r1.dtype.names: + return name + else: + return name + r2postfix - r1desc = [(mapped_r1field(desc[0]), desc[1]) for desc in r1.dtype.descr if desc[0] not in key] - r2desc = [(mapped_r2field(desc[0]), desc[1]) for desc in r2.dtype.descr if desc[0] not in key] + r1desc = [(mapped_r1field(desc[0]), desc[1]) for desc in r1.dtype.descr + if desc[0] not in key] + r2desc = [(mapped_r2field(desc[0]), desc[1]) for desc in r2.dtype.descr + if desc[0] not in key] newdtype = np.dtype(keydesc + r1desc + r2desc) newrec = np.recarray((common_len + left_len + right_len,), dtype=newdtype) @@ -2667,15 +2715,16 @@ def mapped_r2field(name): if defaults is not None: for thiskey in defaults: if thiskey not in newdtype.names: - warnings.warn('rec_join defaults key="%s" not in new dtype names "%s"'%( - thiskey, newdtype.names)) + warnings.warn('rec_join defaults key="%s" not in new dtype ' + 'names "%s"' % (thiskey, newdtype.names)) for name in newdtype.names: dt = newdtype[name] if dt.kind in ('f', 'i'): newrec[name] = 0 - if jointype != 'inner' and defaults is not None: # fill in the defaults enmasse + if jointype != 'inner' and defaults is not None: + # fill in the defaults enmasse newrec_fields = list(six.iterkeys(newrec.dtype.fields.keys)) for k, v in six.iteritems(defaults): if k in newrec_fields: @@ -2686,7 +2735,9 @@ def mapped_r2field(name): if common_len: newrec[newfield][:common_len] = r1[field][r1ind] if (jointype == "outer" or jointype == "leftouter") and left_len: - newrec[newfield][common_len:(common_len+left_len)] = r1[field][left_ind] + newrec[newfield][common_len:(common_len+left_len)] = ( + r1[field][left_ind] + ) for field in r2.dtype.names: newfield = mapped_r2field(field) @@ -2699,6 +2750,7 @@ def mapped_r2field(name): return newrec + def recs_join(key, name, recs, jointype='outer', missing=0., postfixes=None): """ Join a sequence of record arrays on single column key. @@ -2733,24 +2785,27 @@ def recs_join(key, name, recs, jointype='outer', missing=0., postfixes=None): """ results = [] - aligned_iters = cbook.align_iterators(operator.attrgetter(key), *[iter(r) for r in recs]) + aligned_iters = cbook.align_iterators(operator.attrgetter(key), + *[iter(r) for r in recs]) def extract(r): - if r is None: return missing - else: return r[name] - + if r is None: + return missing + else: + return r[name] if jointype == "outer": for rowkey, row in aligned_iters: results.append([rowkey] + list(map(extract, row))) elif jointype == "inner": for rowkey, row in aligned_iters: - if None not in row: # throw out any Nones + if None not in row: # throw out any Nones results.append([rowkey] + list(map(extract, row))) if postfixes is None: - postfixes = ['%d'%i for i in range(len(recs))] - names = ",".join([key] + ["%s%s" % (name, postfix) for postfix in postfixes]) + postfixes = ['%d' % i for i in range(len(recs))] + names = ",".join([key] + ["%s%s" % (name, postfix) + for postfix in postfixes]) return np.rec.fromrecords(results, names=names) @@ -2793,17 +2848,21 @@ def csv2rec(fname, comments='#', skiprows=0, checkrows=0, delimiter=',', - *missing*: a string whose value signals a missing field regardless of the column it appears in - - *use_mrecords*: if True, return an mrecords.fromrecords record array if any of the data are missing + - *use_mrecords*: if True, return an mrecords.fromrecords record array if + any of the data are missing - *dayfirst*: default is False so that MM-DD-YY has precedence over - DD-MM-YY. See http://labix.org/python-dateutil#head-b95ce2094d189a89f80f5ae52a05b4ab7b41af47 + DD-MM-YY. See http://labix.org/python-dateutil\ + #head-b95ce2094d189a89f80f5ae52a05b4ab7b41af47 for further information. - *yearfirst*: default is False so that MM-DD-YY has precedence over - YY-MM-DD. See http://labix.org/python-dateutil#head-b95ce2094d189a89f80f5ae52a05b4ab7b41af47 + YY-MM-DD. See http://labix.org/python-dateutil\ + #head-b95ce2094d189a89f80f5ae52a05b4ab7b41af47 for further information. - If no rows are found, *None* is returned -- see :file:`examples/loadrec.py` + If no rows are found, *None* is returned -- see + :file:`examples/loadrec.py` """ if converterd is None: @@ -2839,7 +2898,6 @@ def seek(self, arg): def fix(self, s): return ' '.join(s.split()) - def __next__(self): return self.fix(next(self.fh)) @@ -2847,14 +2905,16 @@ def __iter__(self): for line in self.fh: yield self.fix(line) - if delimiter==' ': + if delimiter == ' ': fh = FH(fh) reader = csv.reader(fh, delimiter=delimiter) + def process_skiprows(reader): if skiprows: for i, row in enumerate(reader): - if i>=(skiprows-1): break + if i >= (skiprows-1): + break return fh, reader @@ -2876,14 +2936,16 @@ def newfunc(name, val): return func(val) return newfunc - def mybool(x): - if x=='True': return True - elif x=='False': return False - else: raise ValueError('invalid bool') + if x == 'True': + return True + elif x == 'False': + return False + else: + raise ValueError('invalid bool') dateparser = dateutil.parser.parse - mydateparser = with_default_value(dateparser, datetime.date(1,1,1)) + mydateparser = with_default_value(dateparser, datetime.date(1, 1, 1)) myfloat = with_default_value(float, np.nan) myint = with_default_value(int, -1) mystr = with_default_value(str, '') @@ -2893,45 +2955,46 @@ def mydate(x): # try and return a date object d = dateparser(x, dayfirst=dayfirst, yearfirst=yearfirst) - if d.hour>0 or d.minute>0 or d.second>0: + if d.hour > 0 or d.minute > 0 or d.second > 0: raise ValueError('not a date') return d.date() - mydate = with_default_value(mydate, datetime.date(1,1,1)) + mydate = with_default_value(mydate, datetime.date(1, 1, 1)) def get_func(name, item, func): # promote functions in this order - funcmap = {mybool:myint,myint:myfloat, myfloat:mydate, mydate:mydateparser, mydateparser:mystr} - try: func(name, item) + funcmap = {mybool: myint, myint: myfloat, myfloat: mydate, + mydate: mydateparser, mydateparser: mystr} + try: + func(name, item) except: - if func==mystr: - raise ValueError('Could not find a working conversion function') - else: return get_func(name, item, funcmap[func]) # recurse - else: return func - + if func == mystr: + raise ValueError('Could not find a working conversion ' + 'function') + else: + return get_func(name, item, funcmap[func]) # recurse + else: + return func # map column names that clash with builtins -- TODO - extend this list itemd = { - 'return' : 'return_', - 'file' : 'file_', - 'print' : 'print_', + 'return': 'return_', + 'file': 'file_', + 'print': 'print_', } def get_converters(reader): converters = None for i, row in enumerate(reader): - if i==0: + if i == 0: converters = [mybool]*len(row) - if checkrows and i>checkrows: + if checkrows and i > checkrows: break - #print i, len(names), len(row) - #print 'converters', zip(converters, row) for j, (name, item) in enumerate(zip(names, row)): func = converterd.get(j) if func is None: func = converterd.get(name) if func is None: - #if not item.strip(): continue func = converters[j] if len(item.strip()): func = get_func(name, item, func) @@ -2946,8 +3009,8 @@ def get_converters(reader): if needheader: for row in reader: - #print 'csv2rec', row - if len(row) and comments is not None and row[0].startswith(comments): + if (len(row) and comments is not None and + row[0].startswith(comments)): continue headers = row break @@ -2962,12 +3025,12 @@ def get_converters(reader): item = item.strip().lower().replace(' ', '_') item = ''.join([c for c in item if c not in delete]) if not len(item): - item = 'column%d'%i + item = 'column%d' % i item = itemd.get(item, item) cnt = seen.get(item, 0) - if cnt>0: - names.append(item + '_%d'%cnt) + if cnt > 0: + names.append(item + '_%d' % cnt) else: names.append(item) seen[item] = cnt+1 @@ -2990,7 +3053,8 @@ def get_converters(reader): while 1: # skip past any comments and consume one line of column header row = next(reader) - if len(row) and comments is not None and row[0].startswith(comments): + if (len(row) and comments is not None and + row[0].startswith(comments)): continue break @@ -3005,17 +3069,21 @@ def get_converters(reader): continue # Ensure that the row returned always has the same nr of elements row.extend([''] * (len(converters) - len(row))) - rows.append([func(name, val) for func, name, val in zip(converters, names, row)]) - rowmasks.append([ismissing(name, val) for name, val in zip(names, row)]) + rows.append([func(name, val) + for func, name, val in zip(converters, names, row)]) + rowmasks.append([ismissing(name, val) + for name, val in zip(names, row)]) fh.close() if not len(rows): return None if use_mrecords and np.any(rowmasks): - try: from numpy.ma import mrecords + try: + from numpy.ma import mrecords except ImportError: - raise RuntimeError('numpy 1.05 or later is required for masked array support') + raise RuntimeError('numpy 1.05 or later is required for masked ' + 'array support') else: r = mrecords.fromrecords(rows, names=names, mask=rowmasks) else: @@ -3034,38 +3102,33 @@ def toval(self, x): def fromstr(self, s): return s - def __hash__(self): """ - override the hash function of any of the formatters, so that we don't create duplicate excel format styles + override the hash function of any of the formatters, so that we don't + create duplicate excel format styles """ return hash(self.__class__) + class FormatString(FormatObj): def tostr(self, x): val = repr(x) return val[1:-1] -#class FormatString(FormatObj): -# def tostr(self, x): -# return '"%r"'%self.toval(x) - - class FormatFormatStr(FormatObj): def __init__(self, fmt): self.fmt = fmt def tostr(self, x): - if x is None: return 'None' - return self.fmt%self.toval(x) - - + if x is None: + return 'None' + return self.fmt % self.toval(x) class FormatFloat(FormatFormatStr): def __init__(self, precision=4, scale=1.): - FormatFormatStr.__init__(self, '%%1.%df'%precision) + FormatFormatStr.__init__(self, '%%1.%df' % precision) self.precision = precision self.scale = scale @@ -3084,7 +3147,7 @@ def fromstr(self, s): class FormatInt(FormatObj): def tostr(self, x): - return '%d'%int(x) + return '%d' % int(x) def toval(self, x): return int(x) @@ -3092,19 +3155,20 @@ def toval(self, x): def fromstr(self, s): return int(s) -class FormatBool(FormatObj): - +class FormatBool(FormatObj): def toval(self, x): return str(x) def fromstr(self, s): return bool(s) + class FormatPercent(FormatFloat): def __init__(self, precision=4): FormatFloat.__init__(self, precision, scale=100.) + class FormatThousands(FormatFloat): def __init__(self, precision=4): FormatFloat.__init__(self, precision, scale=1e-3) @@ -3122,15 +3186,16 @@ def __init__(self, fmt): def __hash__(self): return hash((self.__class__, self.fmt)) - def toval(self, x): - if x is None: return 'None' + if x is None: + return 'None' return x.strftime(self.fmt) def fromstr(self, x): import dateutil.parser return dateutil.parser.parse(x).date() + class FormatDatetime(FormatDate): def __init__(self, fmt='%Y-%m-%d %H:%M:%S'): FormatDate.__init__(self, fmt) @@ -3140,19 +3205,18 @@ def fromstr(self, x): return dateutil.parser.parse(x) - - defaultformatd = { - np.bool_ : FormatBool(), - np.int16 : FormatInt(), - np.int32 : FormatInt(), - np.int64 : FormatInt(), - np.float32 : FormatFloat(), - np.float64 : FormatFloat(), - np.object_ : FormatObj(), - np.string_ : FormatString(), + np.bool_: FormatBool(), + np.int16: FormatInt(), + np.int32: FormatInt(), + np.int64: FormatInt(), + np.float32: FormatFloat(), + np.float64: FormatFloat(), + np.object_: FormatObj(), + np.string_: FormatString(), } + def get_formatd(r, formatd=None): 'build a formatd guaranteed to have a key for every dtype name' if formatd is None: @@ -3166,13 +3230,15 @@ def get_formatd(r, formatd=None): formatd[name] = format return formatd + def csvformat_factory(format): format = copy.deepcopy(format) if isinstance(format, FormatFloat): - format.scale = 1. # override scaling for storage + format.scale = 1. # override scaling for storage format.fmt = '%r' return format + def rec2txt(r, header=None, padding=3, precision=3, fields=None): """ Returns a textual representation of a record array. @@ -3209,22 +3275,27 @@ def rec2txt(r, header=None, padding=3, precision=3, fields=None): if cbook.is_numlike(precision): precision = [precision]*len(r.dtype) - def get_type(item,atype=int): - tdict = {None:int, int:float, float:str} - try: atype(str(item)) - except: return get_type(item,tdict[atype]) + def get_type(item, atype=int): + tdict = {None: int, int: float, float: str} + try: + atype(str(item)) + except: + return get_type(item, tdict[atype]) return atype def get_justify(colname, column, precision): ntype = type(column[0]) - if ntype==np.str or ntype==np.str_ or ntype==np.string0 or ntype==np.string_: - length = max(len(colname),column.itemsize) - return 0, length+padding, "%s" # left justify + if (ntype == np.str or ntype == np.str_ or ntype == np.string0 or + ntype == np.string_): + length = max(len(colname), column.itemsize) + return 0, length+padding, "%s" # left justify - if ntype==np.int or ntype==np.int16 or ntype==np.int32 or ntype==np.int64 or ntype==np.int8 or ntype==np.int_: - length = max(len(colname),np.max(list(map(len, list(map(str,column)))))) - return 1, length+padding, "%d" # right justify + if (ntype == np.int or ntype == np.int16 or ntype == np.int32 or + ntype == np.int64 or ntype == np.int8 or ntype == np.int_): + length = max(len(colname), + np.max(list(map(len, list(map(str, column)))))) + return 1, length+padding, "%d" # right justify # JDH: my powerbook does not have np.float96 using np 1.3.0 """ @@ -3232,37 +3303,48 @@ def get_justify(colname, column, precision): Out[2]: '1.3.0.dev5948' In [3]: !uname -a - Darwin Macintosh-5.local 9.4.0 Darwin Kernel Version 9.4.0: Mon Jun 9 19:30:53 PDT 2008; root:xnu-1228.5.20~1/RELEASE_I386 i386 i386 + Darwin Macintosh-5.local 9.4.0 Darwin Kernel Version 9.4.0: Mon Jun + 9 19:30:53 PDT 2008; root:xnu-1228.5.20~1/RELEASE_I386 i386 i386 In [4]: np.float96 --------------------------------------------------------------------------- - AttributeError Traceback (most recent call la + AttributeError Traceback (most recent call la """ - if ntype==np.float or ntype==np.float32 or ntype==np.float64 or (hasattr(np, 'float96') and (ntype==np.float96)) or ntype==np.float_: + if (ntype == np.float or ntype == np.float32 or ntype == np.float64 or + (hasattr(np, 'float96') and (ntype == np.float96)) or + ntype == np.float_): fmt = "%." + str(precision) + "f" - length = max(len(colname),np.max(list(map(len, list(map(lambda x:fmt%x,column)))))) + length = max( + len(colname), + np.max(list(map(len, list(map(lambda x: fmt % x, column))))) + ) return 1, length+padding, fmt # right justify - return 0, max(len(colname),np.max(list(map(len, list(map(str,column))))))+padding, "%s" + return (0, + max(len(colname), + np.max(list(map(len, list(map(str, column))))))+padding, + "%s") if header is None: header = r.dtype.names - justify_pad_prec = [get_justify(header[i],r.__getitem__(colname),precision[i]) for i, colname in enumerate(r.dtype.names)] + justify_pad_prec = [get_justify(header[i], r.__getitem__(colname), + precision[i]) + for i, colname in enumerate(r.dtype.names)] justify_pad_prec_spacer = [] for i in range(len(justify_pad_prec)): - just,pad,prec = justify_pad_prec[i] + just, pad, prec = justify_pad_prec[i] if i == 0: - justify_pad_prec_spacer.append((just,pad,prec,0)) + justify_pad_prec_spacer.append((just, pad, prec, 0)) else: - pjust,ppad,pprec = justify_pad_prec[i-1] + pjust, ppad, pprec = justify_pad_prec[i-1] if pjust == 0 and just == 1: - justify_pad_prec_spacer.append((just,pad-padding,prec,0)) + justify_pad_prec_spacer.append((just, pad-padding, prec, 0)) elif pjust == 1 and just == 0: - justify_pad_prec_spacer.append((just,pad,prec,padding)) + justify_pad_prec_spacer.append((just, pad, prec, padding)) else: - justify_pad_prec_spacer.append((just,pad,prec,0)) + justify_pad_prec_spacer.append((just, pad, prec, 0)) def format(item, just_pad_prec_spacer): just, pad, prec, spacer = just_pad_prec_spacer @@ -3270,24 +3352,25 @@ def format(item, just_pad_prec_spacer): return spacer*' ' + str(item).ljust(pad) else: if get_type(item) == float: - item = (prec%float(item)) + item = (prec % float(item)) elif get_type(item) == int: - item = (prec%int(item)) + item = (prec % int(item)) return item.rjust(pad) textl = [] - textl.append(''.join([format(colitem,justify_pad_prec_spacer[j]) for j, colitem in enumerate(header)])) + textl.append(''.join([format(colitem, justify_pad_prec_spacer[j]) + for j, colitem in enumerate(header)])) for i, row in enumerate(r): - textl.append(''.join([format(colitem,justify_pad_prec_spacer[j]) for j, colitem in enumerate(row)])) - if i==0: + textl.append(''.join([format(colitem, justify_pad_prec_spacer[j]) + for j, colitem in enumerate(row)])) + if i == 0: textl[0] = textl[0].rstrip() text = os.linesep.join(textl) return text - def rec2csv(r, fname, delimiter=',', formatd=None, missing='', missingd=None, withheader=True): """ @@ -3441,10 +3524,11 @@ def griddata(x, y, z, xi, yi, interp='nn'): from mpl_toolkits.natgrid import _natgrid except ImportError: raise RuntimeError("To use interp='nn' (Natural Neighbor " - "interpolation) in griddata, natgrid must be installed. " - "Either install it from http://sourceforge.net/projects/" - "matplotlib/files/matplotlib-toolkits, or use interp='linear' " - "instead.") + "interpolation) in griddata, natgrid must be " + "installed. Either install it from http://" + "sourceforge.net/projects/matplotlib/files/" + "matplotlib-toolkits, or use interp='linear' " + "instead.") if xi.ndim == 2: # natgrid expects 1D xi and yi arrays. @@ -3488,7 +3572,7 @@ def griddata(x, y, z, xi, yi, interp='nn'): ################################################## # Linear interpolation algorithms ################################################## -def less_simple_linear_interpolation( x, y, xi, extrap=False ): +def less_simple_linear_interpolation(x, y, xi, extrap=False): """ This function provides simple (but somewhat less so than :func:`cbook.simple_linear_interpolation`) linear interpolation. @@ -3500,7 +3584,8 @@ def less_simple_linear_interpolation( x, y, xi, extrap=False ): only for a small number of points in relatively non-intensive use cases. For real linear interpolation, use scipy. """ - if cbook.is_scalar(xi): xi = [xi] + if cbook.is_scalar(xi): + xi = [xi] x = np.asarray(x) y = np.asarray(y) @@ -3508,28 +3593,29 @@ def less_simple_linear_interpolation( x, y, xi, extrap=False ): s = list(y.shape) s[0] = len(xi) - yi = np.tile( np.nan, s ) + yi = np.tile(np.nan, s) - for ii,xx in enumerate(xi): + for ii, xx in enumerate(xi): bb = x == xx if np.any(bb): jj, = np.nonzero(bb) yi[ii] = y[jj[0]] - elif xxx[-1]: + elif xx > x[-1]: if extrap: yi[ii] = y[-1] else: - jj, = np.nonzero(x x[-1] + # except at the boundaries, where it may be that xi[j] < x[0] or + # xi[j] > x[-1] # the y-values that would come out from a linear interpolation: sidx = s.take(idx) @@ -3645,8 +3732,10 @@ def stineman_interp(xi,x,y,yp=None): yo = yidx + sidx * (xi - xidx) # the difference that comes when using the slopes given in yp - dy1 = (yp.take(idx)- sidx) * (xi - xidx) # using the yp slope of the left point - dy2 = (yp.take(idx+1)-sidx) * (xi - xidxp1) # using the yp slope of the right point + # using the yp slope of the left point + dy1 = (yp.take(idx) - sidx) * (xi - xidx) + # using the yp slope of the right point + dy2 = (yp.take(idx+1)-sidx) * (xi - xidxp1) dy1dy2 = dy1*dy2 # The following is optimized for Python. The solution actually @@ -3833,10 +3922,11 @@ def inside_poly(points, verts): that are inside the polygon. """ # Make a closed polygon path - poly = Path( verts ) + poly = Path(verts) # Check to see which points are contained withing the Path - return [ idx for idx, p in enumerate(points) if poly.contains_point(p) ] + return [idx for idx, p in enumerate(points) if poly.contains_point(p)] + def poly_below(xmin, xs, ys): """ @@ -3858,7 +3948,7 @@ def poly_below(xmin, xs, ys): ys = numpy.asarray(ys) Nx = len(xs) Ny = len(ys) - assert(Nx==Ny) + assert(Nx == Ny) x = xmin*numpy.ones(2*Nx) y = numpy.ones(2*Nx) x[:Nx] = xs @@ -3867,7 +3957,6 @@ def poly_below(xmin, xs, ys): return x, y - def poly_between(x, ylower, yupper): """ Given a sequence of *x*, *ylower* and *yupper*, return the polygon @@ -3878,7 +3967,8 @@ def poly_between(x, ylower, yupper): Return value is *x*, *y* arrays for use with :meth:`matplotlib.axes.Axes.fill`. """ - if ma.isMaskedArray(ylower) or ma.isMaskedArray(yupper) or ma.isMaskedArray(x): + if (ma.isMaskedArray(ylower) or ma.isMaskedArray(yupper) or + ma.isMaskedArray(x)): numpy = ma else: numpy = np @@ -3890,9 +3980,9 @@ def poly_between(x, ylower, yupper): if not cbook.iterable(yupper): yupper = yupper*numpy.ones(Nx) - x = numpy.concatenate( (x, x[::-1]) ) - y = numpy.concatenate( (yupper, ylower[::-1]) ) - return x,y + x = numpy.concatenate((x, x[::-1])) + y = numpy.concatenate((yupper, ylower[::-1])) + return x, y def is_closed_polygon(X): @@ -3909,7 +3999,8 @@ def contiguous_regions(mask): return a list of (ind0, ind1) such that mask[ind0:ind1].all() is True and we cover all such regions - TODO: this is a pure python implementation which probably has a much faster numpy impl + TODO: this is a pure python implementation which probably has a much + faster numpy impl """ in_region = None @@ -3961,9 +4052,12 @@ def cross_from_below(x, threshold): """ x = np.asarray(x) threshold = threshold - ind = np.nonzero( (x[:-1]=threshold))[0] - if len(ind): return ind+1 - else: return ind + ind = np.nonzero((x[:-1] < threshold) & (x[1:] >= threshold))[0] + if len(ind): + return ind+1 + else: + return ind + def cross_from_above(x, threshold): """ @@ -3978,14 +4072,17 @@ def cross_from_above(x, threshold): """ x = np.asarray(x) - ind = np.nonzero( (x[:-1]>=threshold) & (x[1:]= threshold) & (x[1:] < threshold))[0] + if len(ind): + return ind+1 + else: + return ind + ################################################## # Vector and path length geometry calculations ################################################## -def vector_lengths( X, P=2., axis=None ): +def vector_lengths(X, P=2., axis=None): """ Finds the length of a set of vectors in *n* dimensions. This is like the :func:`numpy.norm` function for vectors, but has the ability to @@ -3996,9 +4093,10 @@ def vector_lengths( X, P=2., axis=None ): compute over all elements of *X*. """ X = np.asarray(X) - return (np.sum(X**(P),axis=axis))**(1./P) + return (np.sum(X**(P), axis=axis))**(1./P) + -def distances_along_curve( X ): +def distances_along_curve(X): """ Computes the distance between a set of successive points in *N* dimensions. @@ -4006,8 +4104,9 @@ def distances_along_curve( X ): successive rows is computed. Distance is the standard Euclidean distance. """ - X = np.diff( X, axis=0 ) - return vector_lengths(X,axis=1) + X = np.diff(X, axis=0) + return vector_lengths(X, axis=1) + def path_length(X): """ @@ -4018,7 +4117,8 @@ def path_length(X): (i.e., the rows of *X*). """ X = distances_along_curve(X) - return np.concatenate( (np.zeros(1), np.cumsum(X)) ) + return np.concatenate((np.zeros(1), np.cumsum(X))) + def quad2cubic(q0x, q0y, q1x, q1y, q2x, q2y): """ @@ -4034,9 +4134,11 @@ def quad2cubic(q0x, q0y, q1x, q1y, q2x, q2y): # c3x, c3y = q2x, q2y return q0x, q0y, c1x, c1y, c2x, c2y, q2x, q2y + def offset_line(y, yerr): """ - Offsets an array *y* by +/- an error and returns a tuple (y - err, y + err). + Offsets an array *y* by +/- an error and returns a tuple + (y - err, y + err). The error term can be: @@ -4055,7 +4157,8 @@ def offset_line(y, yerr): show() """ - if cbook.is_numlike(yerr) or (cbook.iterable(yerr) and len(yerr) == len(y)): + if cbook.is_numlike(yerr) or (cbook.iterable(yerr) and + len(yerr) == len(y)): ymin = y - yerr ymax = y + yerr elif len(yerr) == 2: diff --git a/lib/matplotlib/path.py b/lib/matplotlib/path.py index 254104979409..e88e06efdd1f 100644 --- a/lib/matplotlib/path.py +++ b/lib/matplotlib/path.py @@ -82,11 +82,11 @@ class Path(object): """ # Path codes - STOP = 0 # 1 vertex - MOVETO = 1 # 1 vertex - LINETO = 2 # 1 vertex - CURVE3 = 3 # 2 vertices - CURVE4 = 4 # 3 vertices + STOP = 0 # 1 vertex + MOVETO = 1 # 1 vertex + LINETO = 2 # 1 vertex + CURVE3 = 3 # 2 vertices + CURVE4 = 4 # 3 vertices CLOSEPOLY = 79 # 1 vertex #: A dictionary mapping Path codes to the number of vertices that the @@ -100,8 +100,8 @@ class Path(object): code_type = np.uint8 - def __init__(self, vertices, codes=None, _interpolation_steps=1, closed=False, - readonly=False): + def __init__(self, vertices, codes=None, _interpolation_steps=1, + closed=False, readonly=False): """ Create a new path with the given vertices and codes. @@ -186,21 +186,26 @@ def _fast_from_codes_and_verts(cls, verts, codes, internals=None): pth._codes = codes pth._readonly = internals.pop('readonly', False) pth.should_simplify = internals.pop('should_simplify', True) - pth.simplify_threshold = internals.pop('simplify_threshold', - rcParams['path.simplify_threshold']) + pth.simplify_threshold = ( + internals.pop('simplify_threshold', + rcParams['path.simplify_threshold']) + ) pth._has_nonfinite = internals.pop('has_nonfinite', False) pth._interpolation_steps = internals.pop('interpolation_steps', 1) if internals: raise ValueError('Unexpected internals provided to ' '_fast_from_codes_and_verts: ' - '{0}'.format('\n *'.join(six.iterkeys(internals)))) + '{0}'.format('\n *'.join(six.iterkeys( + internals + )))) return pth def _update_values(self): self._should_simplify = ( rcParams['path.simplify'] and (len(self._vertices) >= 128 and - (self._codes is None or np.all(self._codes <= Path.LINETO)))) + (self._codes is None or np.all(self._codes <= Path.LINETO))) + ) self._simplify_threshold = rcParams['path.simplify_threshold'] self._has_nonfinite = not np.isfinite(self._vertices).all() @@ -307,11 +312,11 @@ def make_compound_path_from_polys(cls, XY): """ - # for each poly: 1 for the MOVETO, (numsides-1) for the LINETO, 1 for the - # CLOSEPOLY; the vert for the closepoly is ignored but we still need - # it to keep the codes aligned with the vertices + # for each poly: 1 for the MOVETO, (numsides-1) for the LINETO, 1 for + # the CLOSEPOLY; the vert for the closepoly is ignored but we still + # need it to keep the codes aligned with the vertices numpolys, numsides, two = XY.shape - assert(two==2) + assert(two == 2) stride = numsides + 1 nverts = numpolys * stride verts = np.zeros((nverts, 2)) @@ -319,7 +324,7 @@ def make_compound_path_from_polys(cls, XY): codes[0::stride] = cls.MOVETO codes[numsides::stride] = cls.CLOSEPOLY for i in range(numsides): - verts[i::stride] = XY[:,i] + verts[i::stride] = XY[:, i] return cls(verts, codes) @@ -422,8 +427,8 @@ def iter_segments(self, transform=None, remove_nans=True, clip=None, i += num_vertices def cleaned(self, transform=None, remove_nans=False, clip=None, - quantize=False, simplify=False, curves=False, - stroke_width=1.0, snap=False, sketch=None): + quantize=False, simplify=False, curves=False, + stroke_width=1.0, snap=False, sketch=None): """ Cleans up the path according to the parameters returning a new Path instance. @@ -473,7 +478,8 @@ def contains_point(self, point, transform=None, radius=0.0): """ if transform is not None: transform = transform.frozen() - result = _path.point_in_path(point[0], point[1], radius, self, transform) + result = _path.point_in_path(point[0], point[1], radius, self, + transform) return result def contains_points(self, points, transform=None, radius=0.0): @@ -592,6 +598,7 @@ def to_polygons(self, transform=None, width=0, height=0): return _path.convert_path_to_polygons(self, transform, width, height) _unit_rectangle = None + @classmethod def unit_rectangle(cls): """ @@ -600,8 +607,10 @@ def unit_rectangle(cls): """ if cls._unit_rectangle is None: cls._unit_rectangle = \ - cls([[0.0, 0.0], [1.0, 0.0], [1.0, 1.0], [0.0, 1.0], [0.0, 0.0]], - [cls.MOVETO, cls.LINETO, cls.LINETO, cls.LINETO, cls.CLOSEPOLY], + cls([[0.0, 0.0], [1.0, 0.0], [1.0, 1.0], [0.0, 1.0], + [0.0, 0.0]], + [cls.MOVETO, cls.LINETO, cls.LINETO, cls.LINETO, + cls.CLOSEPOLY], readonly=True) return cls._unit_rectangle @@ -719,7 +728,7 @@ def circle(cls, center=(0., 0.), radius=1., readonly=False): MAGIC45 = np.sqrt((MAGIC*MAGIC) / 2.0) vertices = np.array([[0.0, -1.0], - + [MAGIC, -1.0], [SQRTHALF-MAGIC45, -SQRTHALF-MAGIC45], [SQRTHALF, -SQRTHALF], @@ -826,7 +835,7 @@ def arc(cls, theta1, theta2, n=None, is_wedge=False): theta1 *= np.pi / 180.0 theta2 *= np.pi / 180.0 - twopi = np.pi * 2.0 + twopi = np.pi * 2.0 halfpi = np.pi * 0.5 eta1 = np.arctan2(np.sin(theta1), np.cos(theta1)) @@ -877,8 +886,8 @@ def arc(cls, theta1, theta2, n=None, is_wedge=False): vertex_offset = 1 end = length - vertices[vertex_offset :end:3, 0] = xA + alpha * xA_dot - vertices[vertex_offset :end:3, 1] = yA + alpha * yA_dot + vertices[vertex_offset:end:3, 0] = xA + alpha * xA_dot + vertices[vertex_offset:end:3, 1] = yA + alpha * yA_dot vertices[vertex_offset+1:end:3, 0] = xB - alpha * xB_dot vertices[vertex_offset+1:end:3, 1] = yB - alpha * yB_dot vertices[vertex_offset+2:end:3, 0] = xB diff --git a/lib/matplotlib/tests/test_coding_standards.py b/lib/matplotlib/tests/test_coding_standards.py index d3139fa81df3..d22a8f6dc1f8 100644 --- a/lib/matplotlib/tests/test_coding_standards.py +++ b/lib/matplotlib/tests/test_coding_standards.py @@ -168,15 +168,9 @@ def test_pep8_conformance_installed_files(): '_qhull.py', '_macosx.py'] - expected_bad_files = ['__init__.py', - '_cm.py', + expected_bad_files = ['_cm.py', '_mathtext_data.py', - '_pylab_helpers.py', - 'afm.py', - 'artist.py', - 'axis.py', 'backend_bases.py', - 'bezier.py', 'cbook.py', 'collections.py', 'dviread.py', @@ -186,8 +180,6 @@ def test_pep8_conformance_installed_files(): 'legend.py', 'legend_handler.py', 'mathtext.py', - 'mlab.py', - 'path.py', 'patheffects.py', 'pylab.py', 'pyplot.py', From bf4fa9a1016223b7a5e902e4e848c12a0dc1415a Mon Sep 17 00:00:00 2001 From: Cimarron Mittelsteadt Date: Sat, 13 Sep 2014 11:20:05 -0700 Subject: [PATCH 2/2] STY: No line split for URL --- lib/matplotlib/mlab.py | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/lib/matplotlib/mlab.py b/lib/matplotlib/mlab.py index 7f8035086be8..3adfd1779a48 100644 --- a/lib/matplotlib/mlab.py +++ b/lib/matplotlib/mlab.py @@ -2852,13 +2852,13 @@ def csv2rec(fname, comments='#', skiprows=0, checkrows=0, delimiter=',', any of the data are missing - *dayfirst*: default is False so that MM-DD-YY has precedence over - DD-MM-YY. See http://labix.org/python-dateutil\ - #head-b95ce2094d189a89f80f5ae52a05b4ab7b41af47 + DD-MM-YY. See + http://labix.org/python-dateutil#head-b95ce2094d189a89f80f5ae52a05b4ab7b41af47 for further information. - *yearfirst*: default is False so that MM-DD-YY has precedence over - YY-MM-DD. See http://labix.org/python-dateutil\ - #head-b95ce2094d189a89f80f5ae52a05b4ab7b41af47 + YY-MM-DD. See + http://labix.org/python-dateutil#head-b95ce2094d189a89f80f5ae52a05b4ab7b41af47 for further information. If no rows are found, *None* is returned -- see