FazBrowse GitHub Viewer | Trending |
URL:
| Home
Tools: [Download Repo ZIP]   [Original HTTPS Page]

GitHub Viewer

""" A collection of utility functions and classes. Originally, many (but not all) were from the Python Cookbook -- hence the name cbook. """ import collections import collections.abc import contextlib import functools import gzip import itertools import math import operator import os from pathlib import Path import shlex import subprocess import sys import time import traceback import types import weakref import numpy as np try: from numpy.exceptions import VisibleDeprecationWarning # numpy >= 1.25 except ImportError: from numpy import VisibleDeprecationWarning import matplotlib from matplotlib import _api, _c_internal_utils, mlab class _ExceptionInfo: """ A class to carry exception information around. This is used to store and later raise exceptions. It's an alternative to directly storing Exception instances that circumvents traceback-related issues: caching tracebacks can keep user's objects in local namespaces alive indefinitely, which can lead to very surprising memory issues for users and result in incorrect tracebacks. """ def __init__(self, cls, *args, notes=None): self._cls = cls self._args = args self._notes = notes if notes is not None else [] @classmethod def from_exception(cls, exc): return cls(type(exc), *exc.args, notes=getattr(exc, "__notes__", [])) def to_exception(self): exc = self._cls(*self._args) for note in self._notes: exc.add_note(note) return exc def _get_running_interactive_framework(): """ Return the interactive framework whose event loop is currently running, if any, or "headless" if no event loop can be started, or None. Returns ------- Optional[str] One of the following values: "qt", "gtk3", "gtk4", "wx", "tk", "macosx", "headless", ``None``. """ # Use ``sys.modules.get(name)`` rather than ``name in sys.modules`` as # entries can also have been explicitly set to None. QtWidgets = ( sys.modules.get("PyQt6.QtWidgets") or sys.modules.get("PySide6.QtWidgets") or sys.modules.get("PyQt5.QtWidgets") or sys.modules.get("PySide2.QtWidgets") ) if QtWidgets and QtWidgets.QApplication.instance(): return "qt" Gtk = sys.modules.get("gi.repository.Gtk") if Gtk: if Gtk.MAJOR_VERSION == 4: from gi.repository import GLib if GLib.main_depth(): return "gtk4" if Gtk.MAJOR_VERSION == 3 and Gtk.main_level(): return "gtk3" wx = sys.modules.get("wx") if wx and wx.GetApp(): return "wx" tkinter = sys.modules.get("tkinter") if tkinter: codes = {tkinter.mainloop.__code__, tkinter.Misc.mainloop.__code__} for frame in sys._current_frames().values(): while frame: if frame.f_code in codes: return "tk" frame = frame.f_back # Preemptively break reference cycle between locals and the frame. del frame macosx = sys.modules.get("matplotlib.backends._macosx") if macosx and macosx.event_loop_is_running(): return "macosx" if not _c_internal_utils.display_is_valid(): return "headless" return None def _exception_printer(exc): if _get_running_interactive_framework() in ["headless", None]: raise exc else: traceback.print_exc() class _StrongRef: """ Wrapper similar to a weakref, but keeping a strong reference to the object. """ def __init__(self, obj): self._obj = obj def __call__(self): return self._obj def __eq__(self, other): return isinstance(other, _StrongRef) and self._obj == other._obj def __hash__(self): return hash(self._obj) def _weak_or_strong_ref(func, callback): """ Return a `WeakMethod` wrapping *func* if possible, else a `_StrongRef`. """ try: return weakref.WeakMethod(func, callback) except TypeError: return _StrongRef(func) class _UnhashDict: """ A minimal dict-like class that also supports unhashable keys, storing them in a list of key-value pairs. This class only implements the interface needed for `CallbackRegistry`, and tries to minimize the overhead for the hashable case. """ def __init__(self, pairs): self._dict = {} self._pairs = [] for k, v in pairs: self[k] = v def __setitem__(self, key, value): try: self._dict[key] = value except TypeError: for i, (k, v) in enumerate(self._pairs): if k == key: self._pairs[i] = (key, value) break else: self._pairs.append((key, value)) def __getitem__(self, key): try: return self._dict[key] except TypeError: pass for k, v in self._pairs: if k == key: return v raise KeyError(key) def pop(self, key, *args): try: if key in self._dict: return self._dict.pop(key) except TypeError: for i, (k, v) in enumerate(self._pairs): if k == key: del self._pairs[i] return v if args: return args[0] raise KeyError(key) def __iter__(self): yield from self._dict for k, v in self._pairs: yield k class CallbackRegistry: """ Handle registering, processing, blocking, and disconnecting for a set of signals and callbacks: >>> def oneat(x): ... print('eat', x) >>> def ondrink(x): ... print('drink', x) >>> from matplotlib.cbook import CallbackRegistry >>> callbacks = CallbackRegistry() >>> id_eat = callbacks.connect('eat', oneat) >>> id_drink = callbacks.connect('drink', ondrink) >>> callbacks.process('drink', 123) drink 123 >>> callbacks.process('eat', 456) eat 456 >>> callbacks.process('be merry', 456) # nothing will be called >>> callbacks.disconnect(id_eat) >>> callbacks.process('eat', 456) # nothing will be called >>> with callbacks.blocked(signal='drink'): ... callbacks.process('drink', 123) # nothing will be called >>> callbacks.process('drink', 123) drink 123 >>> callbacks.disconnect(ondrink, signal='drink') # disconnect by func >>> callbacks.process('drink', 123) # nothing will be called In practice, one should always disconnect all callbacks when they are no longer needed to avoid dangling references (and thus memory leaks). However, real code in Matplotlib rarely does so, and due to its design, it is rather difficult to place this kind of code. To get around this, and prevent this class of memory leaks, we instead store weak references to bound methods only, so when the destination object needs to die, the CallbackRegistry won't keep it alive. Parameters ---------- exception_handler : callable, optional If not None, *exception_handler* must be a function that takes an `Exception` as single parameter. It gets called with any `Exception` raised by the callbacks during `CallbackRegistry.process`, and may either re-raise the exception or handle it in another manner. The default handler prints the exception (with `traceback.print_exc`) if an interactive event loop is running; it re-raises the exception if no interactive event loop is running. signals : list, optional If not None, *signals* is a list of signals that this registry handles: attempting to `process` or to `connect` to a signal not in the list throws a `ValueError`. The default, None, does not restrict the handled signals. """ # We maintain two mappings: # callbacks: signal -> {cid -> weakref-to-callback} # _func_cid_map: {(signal, weakref-to-callback) -> cid} def __init__(self, exception_handler=_exception_printer, *, signals=None): self._signals = None if signals is None else list(signals) # Copy it. self.exception_handler = exception_handler self.callbacks = {} self._cid_gen = itertools.count() self._func_cid_map = _UnhashDict([]) # A hidden variable that marks cids that need to be pickled. self._pickled_cids = set() def __getstate__(self): return { **vars(self), # In general, callbacks may not be pickled, so we just drop them, # unless directed otherwise by self._pickled_cids. "callbacks": {s: {cid: proxy() for cid, proxy in d.items() if cid in self._pickled_cids} for s, d in self.callbacks.items()}, # It is simpler to reconstruct this from callbacks in __setstate__. "_func_cid_map": None, "_cid_gen": next(self._cid_gen) } def __setstate__(self, state): cid_count = state.pop('_cid_gen') vars(self).update(state) self.callbacks = { s: {cid: _weak_or_strong_ref(func, functools.partial(self._remove_proxy, s)) for cid, func in d.items()} for s, d in self.callbacks.items()} self._func_cid_map = _UnhashDict( ((s, proxy), cid) for s, d in self.callbacks.items() for cid, proxy in d.items()) self._cid_gen = itertools.count(cid_count) def connect(self, signal, func): """Register *func* to be called when signal *signal* is generated.""" if self._signals is not None: _api.check_in_list(self._signals, signal=signal) proxy = _weak_or_strong_ref(func, functools.partial(self._remove_proxy, signal)) try: return self._func_cid_map[signal, proxy] except KeyError: cid = self._func_cid_map[signal, proxy] = next(self._cid_gen) self.callbacks.setdefault(signal, {})[cid] = proxy return cid def _connect_picklable(self, signal, func): """ Like `.connect`, but the callback is kept when pickling/unpickling. Currently internal-use only. """ cid = self.connect(signal, func) self._pickled_cids.add(cid) return cid # Keep a reference to sys.is_finalizing, as sys may have been cleared out # at that point. def _remove_proxy(self, signal, proxy, *, _is_finalizing=sys.is_finalizing): if _is_finalizing(): # Weakrefs can't be properly torn down at that point anymore. return cid = self._func_cid_map.pop((signal, proxy), None) if cid is not None: del self.callbacks[signal][cid] self._pickled_cids.discard(cid) else: # Not found return if len(self.callbacks[signal]) == 0: # Clean up empty dicts del self.callbacks[signal] @_api.rename_parameter("3.11", "cid", "cid_or_func") def disconnect(self, cid_or_func, *, signal=None): """ Disconnect a callback. Parameters ---------- cid_or_func : int or callable If an int, disconnect the callback with that connection id. If a callable, disconnect that function from signals. signal : optional Only used when *cid_or_func* is a callable. If given, disconnect the function only from that specific signal. If not given, disconnect from all signals the function is connected to. Notes ----- No error is raised if such a callback does not exist. """ if isinstance(cid_or_func, int): if signal is not None: raise ValueError( "signal cannot be specified when disconnecting by cid") for sig, proxy in self._func_cid_map: if self._func_cid_map[sig, proxy] == cid_or_func: break else: # Not found return self._remove_proxy(sig, proxy) elif signal is not None: # Disconnect from a specific signal proxy = _weak_or_strong_ref(cid_or_func, None) self._remove_proxy(signal, proxy) else: # Disconnect from all signals proxy = _weak_or_strong_ref(cid_or_func, None) for sig, prx in list(self._func_cid_map): if prx == proxy: self._remove_proxy(sig, proxy) def process(self, s, *args, **kwargs): """ Process signal *s*. All of the functions registered to receive callbacks on *s* will be called with ``*args`` and ``**kwargs``. """ if self._signals is not None: _api.check_in_list(self._signals, signal=s) for ref in list(self.callbacks.get(s, {}).values()): func = ref() if func is not None: try: func(*args, **kwargs) # this does not capture KeyboardInterrupt, SystemExit, # and GeneratorExit except Exception as exc: if self.exception_handler is not None: self.exception_handler(exc) else: raise @contextlib.contextmanager def blocked(self, *, signal=None): """ Block callback signals from being processed. A context manager to temporarily block/disable callback signals from being processed by the registered listeners. Parameters ---------- signal : str, optional The callback signal to block. The default is to block all signals. """ orig = self.callbacks try: if signal is None: # Empty out the callbacks self.callbacks = {} else: # Only remove the specific signal self.callbacks = {k: orig[k] for k in orig if k != signal} yield finally: self.callbacks = orig class silent_list(list): """ A list with a short ``repr()``. This is meant to be used for a homogeneous list of artists, so that they don't cause long, meaningless output. Instead of :: [, , ] one will get :: If ``self.type`` is None, the type name is obtained from the first item in the list (if any). """ def __init__(self, type, seq=None): self.type = type if seq is not None: self.extend(seq) def __repr__(self): if self.type is not None or len(self) != 0: tp = self.type if self.type is not None else type(self[0]).__name__ return f"" else: return "" def _local_over_kwdict( local_var, kwargs, *keys, warning_cls=_api.MatplotlibDeprecationWarning): out = local_var for key in keys: kwarg_val = kwargs.pop(key, None) if kwarg_val is not None: if out is None: out = kwarg_val else: _api.warn_external(f'"{key}" keyword argument will be ignored', warning_cls) return out def strip_math(s): """ Remove latex formatting from mathtext. Only handles fully math and fully non-math strings. """ if len(s) >= 2 and s[0] == s[-1] == "$": s = s[1:-1] for tex, plain in [ (r"\times", "x"), # Specifically for Formatter support. (r"\mathdefault", ""), (r"\rm", ""), (r"\cal", ""), (r"\tt", ""), (r"\it", ""), ("\\", ""), ("{", ""), ("}", ""), ]: s = s.replace(tex, plain) return s def _strip_comment(s): """Strip everything from the first unquoted #.""" pos = 0 while True: quote_pos = s.find('"', pos) hash_pos = s.find('#', pos) if quote_pos < 0: without_comment = s if hash_pos < 0 else s[:hash_pos] return without_comment.strip() elif 0 1: raise ValueError("Masked arrays must be 1-D") try: x = np.asanyarray(x) except (VisibleDeprecationWarning, ValueError): # NumPy 1.19 raises a warning about ragged arrays, but we want # to accept basically anything here. x = np.asanyarray(x, dtype=object) if x.ndim == 1: x = safe_masked_invalid(x) seqlist[i] = True if np.ma.is_masked(x): masks.append(np.ma.getmaskarray(x)) margs.append(x) # Possibly modified. if len(masks): mask = np.logical_or.reduce(masks) for i, x in enumerate(margs): if seqlist[i]: margs[i] = np.ma.array(x, mask=mask) return margs def _broadcast_with_masks(*args, compress=False): """ Broadcast inputs, combining all masked arrays. Parameters ---------- *args : array-like The inputs to broadcast. compress : bool, default: False Whether to compress the masked arrays. If False, the masked values are replaced by NaNs. Returns ------- list of array-like The broadcasted and masked inputs. """ # extract the masks, if any masks = [k.mask for k in args if isinstance(k, np.ma.MaskedArray)] # broadcast to match the shape bcast = np.broadcast_arrays(*args, *masks) inputs = bcast[:len(args)] masks = bcast[len(args):] if masks: # combine the masks into one mask = np.logical_or.reduce(masks) # put mask on and compress if compress: inputs = [np.ma.array(k, mask=mask).compressed() for k in inputs] else: inputs = [np.ma.array(k, mask=mask, dtype=float).filled(np.nan).ravel() for k in inputs] else: inputs = [np.ravel(k) for k in inputs] return inputs def boxplot_stats(X, whis=1.5, bootstrap=None, labels=None, autorange=False): r""" Return a list of dictionaries of statistics used to draw a series of box and whisker plots using `~.Axes.bxp`. Parameters ---------- X : array-like Data that will be represented in the boxplots. Should have 2 or fewer dimensions. whis : float or (float, float), default: 1.5 The position of the whiskers. If a float, the lower whisker is at the lowest datum above ``Q1 - whis*(Q3-Q1)``, and the upper whisker at the highest datum below ``Q3 + whis*(Q3-Q1)``, where Q1 and Q3 are the first and third quartiles. The default value of ``whis = 1.5`` corresponds to Tukey's original definition of boxplots. If a pair of floats, they indicate the percentiles at which to draw the whiskers (e.g., (5, 95)). In particular, setting this to (0, 100) results in whiskers covering the whole range of the data. In the edge case where ``Q1 == Q3``, *whis* is automatically set to (0, 100) (cover the whole range of the data) if *autorange* is True. Beyond the whiskers, data are considered outliers and are plotted as individual points. bootstrap : int, optional Number of times the confidence intervals around the median should be bootstrapped (percentile method). labels : list of str, optional Labels for each dataset. Length must be compatible with dimensions of *X*. autorange : bool, optional (False) When `True` and the data are distributed such that the 25th and 75th percentiles are equal, ``whis`` is set to (0, 100) such that the whisker ends are at the minimum and maximum of the data. Returns ------- list of dict A list of dictionaries containing the results for each column of data. Keys of each dictionary are the following: ======== =================================== Key Value Description ======== =================================== label tick label for the boxplot mean arithmetic mean value med 50th percentile q1 first quartile (25th percentile) q3 third quartile (75th percentile) iqr interquartile range cilo lower notch around the median cihi upper notch around the median whislo end of the lower whisker whishi end of the upper whisker fliers outliers ======== =================================== Notes ----- Non-bootstrapping approach to confidence interval uses Gaussian-based asymptotic approximation: .. math:: \mathrm{med} \pm 1.57 \times \frac{\mathrm{iqr}}{\sqrt{N}} General approach from: McGill, R., Tukey, J.W., and Larsen, W.A. (1978) "Variations of Boxplots", The American Statistician, 32:12-16. """ def _bootstrap_median(data, N=5000): # determine 95% confidence intervals of the median M = len(data) percentiles = [2.5, 97.5] bs_index = np.random.randint(M, size=(N, M)) bsData = data[bs_index] estimate = np.median(bsData, axis=1, overwrite_input=True) CI = np.percentile(estimate, percentiles) return CI def _compute_conf_interval(data, med, iqr, bootstrap): if bootstrap is not None: # Do a bootstrap estimate of notch locations. # get conf. intervals around median CI = _bootstrap_median(data, N=bootstrap) notch_min = CI[0] notch_max = CI[1] else: N = len(data) notch_min = med - 1.57 * iqr / np.sqrt(N) notch_max = med + 1.57 * iqr / np.sqrt(N) return notch_min, notch_max # output is a list of dicts bxpstats = [] # convert X to a list of lists X = _reshape_2D(X, "X") ncols = len(X) if labels is None: labels = itertools.repeat(None) elif len(labels) != ncols: raise ValueError(f"The number of labels ({len(labels)}) must match the" f" number of columns ({ncols}).") input_whis = whis for ii, (x, label) in enumerate(zip(X, labels)): # empty dict stats = {} if label is not None: stats['label'] = label # restore whis to the input values in case it got changed in the loop whis = input_whis # note tricksiness, append up here and then mutate below bxpstats.append(stats) # if empty, bail if len(x) == 0: stats['fliers'] = np.array([]) stats['mean'] = np.nan stats['med'] = np.nan stats['q1'] = np.nan stats['q3'] = np.nan stats['iqr'] = np.nan stats['cilo'] = np.nan stats['cihi'] = np.nan stats['whislo'] = np.nan stats['whishi'] = np.nan continue # up-convert to an array, just to be safe x = np.ma.asarray(x) x = x.data[~x.mask].ravel() # arithmetic mean stats['mean'] = np.mean(x) # medians and quartiles q1, med, q3 = np.percentile(x, [25, 50, 75]) # interquartile range stats['iqr'] = q3 - q1 if stats['iqr'] == 0 and autorange: whis = (0, 100) # conf. interval around median stats['cilo'], stats['cihi'] = _compute_conf_interval( x, med, stats['iqr'], bootstrap ) # lowest/highest non-outliers if np.iterable(whis) and not isinstance(whis, str): loval, hival = np.percentile(x, whis) elif np.isreal(whis): loval = q1 - whis * stats['iqr'] hival = q3 + whis * stats['iqr'] else: raise ValueError('whis must be a float or list of percentiles') # get high extreme wiskhi = x[x = loval] if len(wisklo) == 0 or np.min(wisklo) > q1: stats['whislo'] = q1 else: stats['whislo'] = np.min(wisklo) # compute a single array of outliers stats['fliers'] = np.concatenate([ x[x < stats['whislo']], x[x > stats['whishi']], ]) # add in the remaining stats stats['q1'], stats['med'], stats['q3'] = q1, med, q3 return bxpstats #: Maps short codes for line style to their full name used by backends. ls_mapper = {'-': 'solid', '--': 'dashed', '-.': 'dashdot', ':': 'dotted'} #: Maps full names for line styles used by backends to their short codes. ls_mapper_r = {v: k for k, v in ls_mapper.items()} def contiguous_regions(mask): """ Return a list of (ind0, ind1) such that ``mask[ind0:ind1].all()`` is True and we cover all such regions. """ mask = np.asarray(mask, dtype=bool) if not mask.size: return [] # Find the indices of region changes, and correct offset idx, = np.nonzero(mask[:-1] != mask[1:]) idx += 1 # List operations are faster for moderately sized arrays idx = idx.tolist() # Add first and/or last index if needed if mask[0]: idx = [0] + idx if mask[-1]: idx.append(len(mask)) return list(zip(idx[::2], idx[1::2])) def is_math_text(s): """ Return whether the string *s* contains math expressions. This is done by checking whether *s* contains an even number of non-escaped dollar signs. """ s = str(s) dollar_count = s.count(r'$') - s.count(r'\$') even_dollars = (dollar_count > 0 and dollar_count % 2 == 0) return even_dollars def _to_unmasked_float_array(x): """ Convert a sequence to a float array; if input was a masked array, masked values are converted to nans. """ if hasattr(x, 'mask'): return np.ma.asanyarray(x, float).filled(np.nan) else: return np.asanyarray(x, float) def _check_1d(x): """Convert scalars to 1D arrays; pass-through arrays as is.""" # Unpack in case of e.g. Pandas or xarray object x = _unpack_to_numpy(x) # plot requires `shape` and `ndim`. If passed an # object that doesn't provide them, then force to numpy array. # Note this will strip unit information. if (not hasattr(x, 'shape') or not hasattr(x, 'ndim') or len(x.shape) < 1): return np.atleast_1d(x) else: return x def _reshape_2D(X, name): """ Use Fortran ordering to convert ndarrays and lists of iterables to lists of 1D arrays. Lists of iterables are converted by applying `numpy.asanyarray` to each of their elements. 1D ndarrays are returned in a singleton list containing them. 2D ndarrays are converted to the list of their *columns*. *name* is used to generate the error message for invalid inputs. """ # Unpack in case of e.g. Pandas or xarray object X = _unpack_to_numpy(X) # Iterate over columns for ndarrays. if isinstance(X, np.ndarray): X = X.transpose() if len(X) == 0: return [[]] elif X.ndim == 1 and np.ndim(X[0]) == 0: # 1D array of scalars: directly return it. return [X] elif X.ndim in [1, 2]: # 2D array, or 1D array of iterables: flatten them first. return [np.reshape(x, -1) for x in X] else: raise ValueError(f'{name} must have 2 or fewer dimensions') # Iterate over list of iterables. if len(X) == 0: return [[]] result = [] is_1d = True for xi in X: # check if this is iterable, except for strings which we # treat as singletons. if not isinstance(xi, str): try: iter(xi) except TypeError: pass else: is_1d = False xi = np.asanyarray(xi) nd = np.ndim(xi) if nd > 1: raise ValueError(f'{name} must have 2 or fewer dimensions') result.append(xi.reshape(-1)) if is_1d: # 1D array of scalars: directly return it. return [np.reshape(result, -1)] else: # 2D array, or 1D array of iterables: use flattened version. return result def violin_stats(X, method=("GaussianKDE", "scott"), points=100, quantiles=None): """ Return a list of dictionaries of data which can be used to draw a series of violin plots. See the ``Returns`` section below to view the required keys of the dictionary. Users can skip this function and pass a user-defined set of dictionaries with the same keys to `~.axes.Axes.violin` instead of using Matplotlib to do the calculations. See the *Returns* section below for the keys that must be present in the dictionaries. Parameters ---------- X : 1D array or sequence of 1D arrays or 2D array Sample data that will be used to produce the gaussian kernel density estimates. Non-finite and masked values are ignored. Possible values: - 1D array: Statistics are computed for that array. - sequence of 1D arrays: Statistics are computed for each array in the sequence. - 2D array: Statistics are computed for each column in the array. method : (name, bw_method) or callable, The method used to calculate the kernel density estimate for each column of data. Valid values: - a tuple of the form ``(name, bw_method)`` where *name* currently must always be ``"GaussianKDE"`` and *bw_method* is the method used to calculate the estimator bandwidth. Supported values are 'scott', 'silverman' or a float or a callable. If a float, this will be used directly as `!kde.factor`. If a callable, it should take a `matplotlib.mlab.GaussianKDE` instance as its only parameter and return a float. - a callable with the signature :: def method(data: ndarray, coords: ndarray) -> ndarray It should return the KDE of *data* evaluated at *coords*. .. versionadded:: 3.11 Support for ``(name, bw_method)`` tuple. points : int, default: 100 Defines the number of points to evaluate each of the gaussian kernel density estimates at. quantiles : array-like, default: None Defines (if not None) a list of floats in interval [0, 1] for each column of data, which represents the quantiles that will be rendered for that column of data. Must have 2 or fewer dimensions. 1D array will be treated as a singleton list containing them. Returns ------- list of dict A list of dictionaries containing the results for each column of data. The dictionaries contain at least the following: - coords: A list of scalars containing the coordinates this particular kernel density estimate was evaluated at. - vals: A list of scalars containing the values of the kernel density estimate at each of the coordinates given in *coords*. - mean: The mean value for this column of data. - median: The median value for this column of data. - min: The minimum value for this column of data. - max: The maximum value for this column of data. - quantiles: The quantile values for this column of data. """ if isinstance(method, tuple): name, bw_method = method if name != "GaussianKDE": raise ValueError(f"Unknown KDE method name {name!r}. The only supported " 'named method is "GaussianKDE"') def _kde_method(x, coords): # fallback gracefully if the vector contains only one value if np.all(x[0] == x): return (x[0] == coords).astype(float) kde = mlab.GaussianKDE(x, bw_method) return kde.evaluate(coords) method = _kde_method # List of dictionaries describing each of the violins. vpstats = [] # Want X to be a list of data sequences X = _reshape_2D(X, "X") # Want quantiles to be as the same shape as data sequences if quantiles is not None and len(quantiles) != 0: quantiles = _reshape_2D(quantiles, "quantiles") # Else, mock quantiles if it's none or empty else: quantiles = [[]] * len(X) # quantiles should have the same size as dataset if len(X) != len(quantiles): raise ValueError("List of violinplot statistics and quantiles values" " must have the same length") # Zip x and quantiles for (x, quantile) in zip(X, quantiles): x = np.asarray(x) x, = delete_masked_points(x) if len(x) == 0: vpstats.append({ 'vals': np.array([]), 'coords': np.array([]), 'mean': np.nan, 'median': np.nan, 'min': np.nan, 'max': np.nan, 'quantiles': np.array([]), }) else: min_val = np.min(x) max_val = np.max(x) coords = np.linspace(min_val, max_val, points) vpstats.append({ 'vals': method(x, coords), 'coords': coords, 'mean': np.mean(x), 'median': np.median(x), 'min': min_val, 'max': max_val, 'quantiles': np.atleast_1d(np.percentile(x, 100 * quantile)) }) return vpstats def pts_to_prestep(x, *args): """ Convert continuous line to pre-steps. Given a set of ``N`` points, convert to ``2N - 1`` points, which when connected linearly give a step function which changes values at the beginning of the intervals. Parameters ---------- x : array The x location of the steps. May be empty. y1, ..., yp : array y arrays to be turned into steps; all must be the same length as ``x``. Returns ------- array The x and y values converted to steps in the same order as the input; can be unpacked as ``x_out, y1_out, ..., yp_out``. If the input is length ``N``, each of these arrays will be length ``2N + 1``. For ``N=0``, the length will be 0. Examples -------- >>> x_s, y1_s, y2_s = pts_to_prestep(x, y1, y2) """ steps = np.zeros((1 + len(args), max(2 * len(x) - 1, 0))) # In all `pts_to_*step` functions, only assign once using *x* and *args*, # as converting to an array may be expensive. steps[0, 0::2] = x steps[0, 1::2] = steps[0, 0:-2:2] steps[1:, 0::2] = args steps[1:, 1::2] = steps[1:, 2::2] return steps def pts_to_poststep(x, *args): """ Convert continuous line to post-steps. Given a set of ``N`` points convert to ``2N + 1`` points, which when connected linearly give a step function which changes values at the end of the intervals. Parameters ---------- x : array The x location of the steps. May be empty. y1, ..., yp : array y arrays to be turned into steps; all must be the same length as ``x``. Returns ------- array The x and y values converted to steps in the same order as the input; can be unpacked as ``x_out, y1_out, ..., yp_out``. If the input is length ``N``, each of these arrays will be length ``2N + 1``. For ``N=0``, the length will be 0. Examples -------- >>> x_s, y1_s, y2_s = pts_to_poststep(x, y1, y2) """ steps = np.zeros((1 + len(args), max(2 * len(x) - 1, 0))) steps[0, 0::2] = x steps[0, 1::2] = steps[0, 2::2] steps[1:, 0::2] = args steps[1:, 1::2] = steps[1:, 0:-2:2] return steps def pts_to_midstep(x, *args): """ Convert continuous line to mid-steps. Given a set of ``N`` points convert to ``2N`` points which when connected linearly give a step function which changes values at the middle of the intervals. Parameters ---------- x : array The x location of the steps. May be empty. y1, ..., yp : array y arrays to be turned into steps; all must be the same length as ``x``. Returns ------- array The x and y values converted to steps in the same order as the input; can be unpacked as ``x_out, y1_out, ..., yp_out``. If the input is length ``N``, each of these arrays will be length ``2N``. Examples -------- >>> x_s, y1_s, y2_s = pts_to_midstep(x, y1, y2) """ steps = np.zeros((1 + len(args), 2 * len(x))) x = np.asanyarray(x) steps[0, 1:-1:2] = steps[0, 2::2] = (x[:-1] + x[1:]) / 2 steps[0, :1] = x[:1] # Also works for zero-sized input. steps[0, -1:] = x[-1:] steps[1:, 0::2] = args steps[1:, 1::2] = steps[1:, 0::2] return steps STEP_LOOKUP_MAP = {'default': lambda x, y: (x, y), 'steps': pts_to_prestep, 'steps-pre': pts_to_prestep, 'steps-post': pts_to_poststep, 'steps-mid': pts_to_midstep} def index_of(y): """ A helper function to create reasonable x values for the given *y*. This is used for plotting (x, y) if x values are not explicitly given. First try ``y.index`` (assuming *y* is a `pandas.Series`), if that fails, use ``range(len(y))``. This will be extended in the future to deal with more types of labeled data. Parameters ---------- y : float or array-like Returns ------- x, y : ndarray The x and y values to plot. """ try: return y.index.to_numpy(), y.to_numpy() except AttributeError: pass try: y = _check_1d(y) except (VisibleDeprecationWarning, ValueError): # NumPy 1.19 will warn on ragged input, and we can't actually use it. pass else: return np.arange(y.shape[0], dtype=float), y raise ValueError('Input could not be cast to an at-least-1D NumPy array') def safe_first_element(obj): """ Return the first element in *obj*. This is a type-independent way of obtaining the first element, supporting both index access and the iterator protocol. """ if isinstance(obj, collections.abc.Iterator): # needed to accept `array.flat` as input. # np.flatiter reports as an instance of collections.Iterator but can still be # indexed via []. This has the side effect of re-setting the iterator, but # that is acceptable. try: return obj[0] except TypeError: pass raise RuntimeError("matplotlib does not support generators as input") return next(iter(obj)) def _safe_first_finite(obj): """ Return the first finite element in *obj* if one is available and skip_nonfinite is True. Otherwise, return the first element. This is a method for internal use. This is a type-independent way of obtaining the first finite element, supporting both index access and the iterator protocol. """ def safe_isfinite(val): if val is None: return False try: return math.isfinite(val) except (TypeError, ValueError): # if the outer object is 2d, then val is a 1d array, and # - math.isfinite(numpy.zeros(3)) raises TypeError # - math.isfinite(torch.zeros(3)) raises ValueError pass try: return np.isfinite(val) if np.isscalar(val) else True except TypeError: # This is something that NumPy cannot make heads or tails of, # assume "finite" return True if isinstance(obj, np.flatiter): # TODO do the finite filtering on this return obj[0] elif isinstance(obj, collections.abc.Iterator): raise RuntimeError("matplotlib does not support generators as input") else: for val in obj: if safe_isfinite(val): return val return safe_first_element(obj) def sanitize_sequence(data): """ Convert dictview objects to list. Other inputs are returned unchanged. """ return (list(data) if isinstance(data, collections.abc.MappingView) else data) def _resize_sequence(seq, N): """ Trim the given sequence to exactly N elements. If there are more elements in the sequence, cut it. If there are less elements in the sequence, repeat them. Implementation detail: We maintain type stability for the output for N len(seq); this was good enough for the present use cases but is not a fixed design decision. """ num_elements = len(seq) if N == num_elements: return seq elif N < num_elements: return seq[:N] else: return list(itertools.islice(itertools.cycle(seq), N)) def normalize_kwargs(kw, alias_mapping=None): """ Helper function to normalize kwarg inputs. Parameters ---------- kw : dict or None A dict of keyword arguments. None is explicitly supported and treated as an empty dict, to support functions with an optional parameter of the form ``props=None``. alias_mapping : Artist subclass or Artist instance A mapping between a canonical name to a list of aliases, in order of precedence from lowest to highest. If the canonical value is not in the list it is assumed to have the highest priority. If an Artist subclass or instance is passed, use its properties alias mapping. Raises ------ TypeError To match what Python raises if invalid arguments/keyword arguments are passed to a callable. """ from matplotlib.artist import Artist # deal with default value of alias_mapping if (isinstance(alias_mapping, type) and issubclass(alias_mapping, Artist) or isinstance(alias_mapping, Artist)): alias_to_prop = getattr(alias_mapping, "_alias_to_prop", {}) else: if alias_mapping is None: alias_mapping = {} _api.warn_deprecated("3.11", message=( "Passing a dict or None as alias_mapping to normalize_kwargs is " "deprecated since %(since)s and support will be removed " "%(removal)s; pass an Artist instance or type instead.")) # Convert old format to new format. alias_to_prop = {alias: prop for prop, aliases in alias_mapping.items() for alias in aliases} if kw is None: return {} canonicalized = {alias_to_prop.get(k, k): v for k, v in kw.items()} if len(canonicalized) == len(kw): return canonicalized canonical_to_seen = {} for k in kw: canonical = alias_to_prop.get(k, k) if canonical in canonical_to_seen: raise TypeError(f"Got both {canonical_to_seen[canonical]!r} and " f"{k!r}, which are aliases of one another") canonical_to_seen[canonical] = k @contextlib.contextmanager def _lock_path(path): """ Context manager for locking a path. Usage:: with _lock_path(path): ... Another thread or process that attempts to lock the same path will wait until this context manager is exited. The lock is implemented by creating a temporary file in the parent directory, so that directory must exist and be writable. """ path = Path(path) lock_path = path.with_name(path.name + ".matplotlib-lock") retries = 50 sleeptime = 0.1 for _ in range(retries): try: with lock_path.open("xb"): break except FileExistsError: time.sleep(sleeptime) else: raise TimeoutError("""\ Lock error: Matplotlib failed to acquire the following lock file: {} This maybe due to another process holding this lock file. If you are sure no other Matplotlib process is running, remove this file and try again.""".format( lock_path)) try: yield finally: lock_path.unlink() def _topmost_artist( artists, _cached_max=functools.partial(max, key=operator.attrgetter("zorder"))): """ Get the topmost artist of a list. In case of a tie, return the *last* of the tied artists, as it will be drawn on top of the others. `max` returns the first maximum in case of ties, so we need to iterate over the list in reverse order. """ return _cached_max(reversed(artists)) def _str_equal(obj, s): """ Return whether *obj* is a string equal to string *s*. This helper solely exists to handle the case where *obj* is a numpy array, because in such cases, a naive ``obj == s`` would yield an array, which cannot be used in a boolean context. """ return isinstance(obj, str) and obj == s def _str_lower_equal(obj, s): """ Return whether *obj* is a string equal, when lowercased, to string *s*. This helper solely exists to handle the case where *obj* is a numpy array, because in such cases, a naive ``obj == s`` would yield an array, which cannot be used in a boolean context. """ return isinstance(obj, str) and obj.lower() == s def _array_perimeter(arr): """ Get the elements on the perimeter of *arr*. Parameters ---------- arr : ndarray, shape (M, N) The input array. Returns ------- ndarray, shape (2*(M - 1) + 2*(N - 1),) The elements on the perimeter of the array:: [arr[0, 0], ..., arr[0, -1], ..., arr[-1, -1], ..., arr[-1, 0], ...] Examples -------- >>> i, j = np.ogrid[:3, :4] >>> a = i*10 + j >>> a array([[ 0, 1, 2, 3], [10, 11, 12, 13], [20, 21, 22, 23]]) >>> _array_perimeter(a) array([ 0, 1, 2, 3, 13, 23, 22, 21, 20, 10]) """ # note we use Python's half-open ranges to avoid repeating # the corners forward = np.s_[0:-1] # [0 ... -1) backward = np.s_[-1:0:-1] # [-1 ... 0) return np.concatenate(( arr[0, forward], arr[forward, -1], arr[-1, backward], arr[backward, 0], )) def _unfold(arr, axis, size, step): """ Append an extra dimension containing sliding windows along *axis*. All windows are of size *size* and begin with every *step* elements. Parameters ---------- arr : ndarray, shape (N_1, ..., N_k) The input array axis : int Axis along which the windows are extracted size : int Size of the windows step : int Stride between first elements of subsequent windows. Returns ------- ndarray, shape (N_1, ..., 1 + (N_axis-size)/step, ..., N_k, size) Examples -------- >>> i, j = np.ogrid[:3, :7] >>> a = i*10 + j >>> a array([[ 0, 1, 2, 3, 4, 5, 6], [10, 11, 12, 13, 14, 15, 16], [20, 21, 22, 23, 24, 25, 26]]) >>> _unfold(a, axis=1, size=3, step=2) array([[[ 0, 1, 2], [ 2, 3, 4], [ 4, 5, 6]], [[10, 11, 12], [12, 13, 14], [14, 15, 16]], [[20, 21, 22], [22, 23, 24], [24, 25, 26]]]) """ new_shape = [*arr.shape, size] new_strides = [*arr.strides, arr.strides[axis]] new_shape[axis] = (new_shape[axis] - size) // step + 1 new_strides[axis] = new_strides[axis] * step return np.lib.stride_tricks.as_strided(arr, shape=new_shape, strides=new_strides, writeable=False) def _array_patch_perimeters(x, rstride, cstride): """ Extract perimeters of patches from *arr*. Extracted patches are of size (*rstride* + 1) x (*cstride* + 1) and share perimeters with their neighbors. The ordering of the vertices matches that returned by ``_array_perimeter``. Parameters ---------- x : ndarray, shape (N, M) Input array rstride : int Vertical (row) stride between corresponding elements of each patch cstride : int Horizontal (column) stride between corresponding elements of each patch Returns ------- ndarray, shape (N/rstride * M/cstride, 2 * (rstride + cstride)) """ assert rstride > 0 and cstride > 0 assert (x.shape[0] - 1) % rstride == 0 assert (x.shape[1] - 1) % cstride == 0 # We build up each perimeter from four half-open intervals. Here is an # illustrated explanation for rstride == cstride == 3 # # T T T R # L R # L R # L B B B # # where T means that this element will be in the top array, R for right, # B for bottom and L for left. Each of the arrays below has a shape of: # # (number of perimeters that can be extracted vertically, # number of perimeters that can be extracted horizontally, # cstride for top and bottom and rstride for left and right) # # Note that _unfold doesn't incur any memory copies, so the only costly # operation here is the np.concatenate. top = _unfold(x[:-1:rstride, :-1], 1, cstride, cstride) bottom = _unfold(x[rstride::rstride, 1:], 1, cstride, cstride)[..., ::-1] right = _unfold(x[:-1, cstride::cstride], 0, rstride, rstride) left = _unfold(x[1:, :-1:cstride], 0, rstride, rstride)[..., ::-1] return (np.concatenate((top, right, bottom, left), axis=2) .reshape(-1, 2 * (rstride + cstride))) @contextlib.contextmanager def _setattr_cm(obj, **kwargs): """ Temporarily set some attributes; restore original state at context exit. """ sentinel = object() origs = {} for attr in kwargs: orig = getattr(obj, attr, sentinel) if attr in obj.__dict__ or orig is sentinel: # if we are pulling from the instance dict or the object # does not have this attribute we can trust the above origs[attr] = orig else: # if the attribute is not in the instance dict it must be # from the class level cls_orig = getattr(type(obj), attr) # if we are dealing with a property (but not a general descriptor) # we want to set the original value back. if isinstance(cls_orig, property): origs[attr] = orig # otherwise this is _something_ we are going to shadow at # the instance dict level from higher up in the MRO. We # are going to assume we can delattr(obj, attr) to clean # up after ourselves. It is possible that this code will # fail if used with a non-property custom descriptor which # implements __set__ (and __delete__ does not act like a # stack). However, this is an internal tool and we do not # currently have any custom descriptors. else: origs[attr] = sentinel try: for attr, val in kwargs.items(): setattr(obj, attr, val) yield finally: for attr, orig in origs.items(): if orig is sentinel: delattr(obj, attr) else: setattr(obj, attr, orig) class _OrderedSet(collections.abc.MutableSet): def __init__(self): self._od = collections.OrderedDict() def __contains__(self, key): return key in self._od def __iter__(self): return iter(self._od) def __len__(self): return len(self._od) def add(self, key): self._od.pop(key, None) self._od[key] = None def discard(self, key): self._od.pop(key, None) # Agg's buffers are unmultiplied RGBA8888, which neither PyQt

Back | FazBrowse Home | New Git URL