diff --git a/.gitattributes b/.gitattributes index cd4bf8fd24b821141d1594776ce634277e61e3e4..4c7b04bae4f3b12388d644d4e03ce13a6a4745ab 100644 --- a/.gitattributes +++ b/.gitattributes @@ -1006,3 +1006,4 @@ infer_4_30_0/lib/python3.10/site-packages/scipy/stats/__pycache__/_mstats_basic. infer_4_30_0/lib/python3.10/site-packages/scipy/stats/__pycache__/_distribution_infrastructure.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text infer_4_30_0/lib/python3.10/site-packages/scipy/signal/_peak_finding_utils.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text infer_4_30_0/lib/python3.10/site-packages/scipy/signal/_upfirdn_apply.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +infer_4_30_0/lib/python3.10/site-packages/pkg_resources/__pycache__/__init__.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text diff --git a/infer_4_30_0/lib/python3.10/site-packages/matplotlib/__init__.pyi b/infer_4_30_0/lib/python3.10/site-packages/matplotlib/__init__.pyi new file mode 100644 index 0000000000000000000000000000000000000000..88058ffd7def28740b4942d3851a5f43e49b086a --- /dev/null +++ b/infer_4_30_0/lib/python3.10/site-packages/matplotlib/__init__.pyi @@ -0,0 +1,124 @@ +__all__ = [ + "__bibtex__", + "__version__", + "__version_info__", + "set_loglevel", + "ExecutableNotFoundError", + "get_configdir", + "get_cachedir", + "get_data_path", + "matplotlib_fname", + "MatplotlibDeprecationWarning", + "RcParams", + "rc_params", + "rc_params_from_file", + "rcParamsDefault", + "rcParams", + "rcParamsOrig", + "defaultParams", + "rc", + "rcdefaults", + "rc_file_defaults", + "rc_file", + "rc_context", + "use", + "get_backend", + "interactive", + "is_interactive", + "colormaps", + "color_sequences", +] + +import os +from pathlib import Path + +from collections.abc import Callable, Generator +import contextlib +from packaging.version import Version + +from matplotlib._api import MatplotlibDeprecationWarning +from typing import Any, Literal, NamedTuple, overload + +class _VersionInfo(NamedTuple): + major: int + minor: int + micro: int + releaselevel: str + serial: int + +__bibtex__: str +__version__: str +__version_info__: _VersionInfo + +def set_loglevel(level: str) -> None: ... + +class _ExecInfo(NamedTuple): + executable: str + raw_version: str + version: Version + +class ExecutableNotFoundError(FileNotFoundError): ... + +def _get_executable_info(name: str) -> _ExecInfo: ... +def get_configdir() -> str: ... +def get_cachedir() -> str: ... +def get_data_path() -> str: ... +def matplotlib_fname() -> str: ... + +class RcParams(dict[str, Any]): + validate: dict[str, Callable] + def __init__(self, *args, **kwargs) -> None: ... + def _set(self, key: str, val: Any) -> None: ... + def _get(self, key: str) -> Any: ... + + def _update_raw(self, other_params: dict | RcParams) -> None: ... + + def _ensure_has_backend(self) -> None: ... + def __setitem__(self, key: str, val: Any) -> None: ... + def __getitem__(self, key: str) -> Any: ... + def __iter__(self) -> Generator[str, None, None]: ... + def __len__(self) -> int: ... + def find_all(self, pattern: str) -> RcParams: ... + def copy(self) -> RcParams: ... + +def rc_params(fail_on_error: bool = ...) -> RcParams: ... +def rc_params_from_file( + fname: str | Path | os.PathLike, + fail_on_error: bool = ..., + use_default_template: bool = ..., +) -> RcParams: ... + +rcParamsDefault: RcParams +rcParams: RcParams +rcParamsOrig: RcParams +defaultParams: dict[str, Any] + +def rc(group: str, **kwargs) -> None: ... +def rcdefaults() -> None: ... +def rc_file_defaults() -> None: ... +def rc_file( + fname: str | Path | os.PathLike, *, use_default_template: bool = ... +) -> None: ... +@contextlib.contextmanager +def rc_context( + rc: dict[str, Any] | None = ..., fname: str | Path | os.PathLike | None = ... +) -> Generator[None, None, None]: ... +def use(backend: str, *, force: bool = ...) -> None: ... +@overload +def get_backend(*, auto_select: Literal[True] = True) -> str: ... +@overload +def get_backend(*, auto_select: Literal[False]) -> str | None: ... +def interactive(b: bool) -> None: ... +def is_interactive() -> bool: ... + +def _preprocess_data( + func: Callable | None = ..., + *, + replace_names: list[str] | None = ..., + label_namer: str | None = ... +) -> Callable: ... + +from matplotlib.cm import _colormaps as colormaps # noqa: E402 +from matplotlib.cm import _multivar_colormaps as multivar_colormaps # noqa: E402 +from matplotlib.cm import _bivar_colormaps as bivar_colormaps # noqa: E402 +from matplotlib.colors import _color_sequences as color_sequences # noqa: E402 diff --git a/infer_4_30_0/lib/python3.10/site-packages/matplotlib/_afm.py b/infer_4_30_0/lib/python3.10/site-packages/matplotlib/_afm.py new file mode 100644 index 0000000000000000000000000000000000000000..558efe16392f7d386f642c86a8b028d10a778f25 --- /dev/null +++ b/infer_4_30_0/lib/python3.10/site-packages/matplotlib/_afm.py @@ -0,0 +1,532 @@ +""" +A python interface to Adobe Font Metrics Files. + +Although a number of other Python implementations exist, and may be more +complete than this, it was decided not to go with them because they were +either: + +1) copyrighted or used a non-BSD compatible license +2) had too many dependencies and a free standing lib was needed +3) did more than needed and it was easier to write afresh rather than + figure out how to get just what was needed. + +It is pretty easy to use, and has no external dependencies: + +>>> import matplotlib as mpl +>>> from pathlib import Path +>>> afm_path = Path(mpl.get_data_path(), 'fonts', 'afm', 'ptmr8a.afm') +>>> +>>> from matplotlib.afm import AFM +>>> with afm_path.open('rb') as fh: +... afm = AFM(fh) +>>> afm.string_width_height('What the heck?') +(6220.0, 694) +>>> afm.get_fontname() +'Times-Roman' +>>> afm.get_kern_dist('A', 'f') +0 +>>> afm.get_kern_dist('A', 'y') +-92.0 +>>> afm.get_bbox_char('!') +[130, -9, 238, 676] + +As in the Adobe Font Metrics File Format Specification, all dimensions +are given in units of 1/1000 of the scale factor (point size) of the font +being used. +""" + +from collections import namedtuple +import logging +import re + +from ._mathtext_data import uni2type1 + + +_log = logging.getLogger(__name__) + + +def _to_int(x): + # Some AFM files have floats where we are expecting ints -- there is + # probably a better way to handle this (support floats, round rather than + # truncate). But I don't know what the best approach is now and this + # change to _to_int should at least prevent Matplotlib from crashing on + # these. JDH (2009-11-06) + return int(float(x)) + + +def _to_float(x): + # Some AFM files use "," instead of "." as decimal separator -- this + # shouldn't be ambiguous (unless someone is wicked enough to use "," as + # thousands separator...). + if isinstance(x, bytes): + # Encoding doesn't really matter -- if we have codepoints >127 the call + # to float() will error anyways. + x = x.decode('latin-1') + return float(x.replace(',', '.')) + + +def _to_str(x): + return x.decode('utf8') + + +def _to_list_of_ints(s): + s = s.replace(b',', b' ') + return [_to_int(val) for val in s.split()] + + +def _to_list_of_floats(s): + return [_to_float(val) for val in s.split()] + + +def _to_bool(s): + if s.lower().strip() in (b'false', b'0', b'no'): + return False + else: + return True + + +def _parse_header(fh): + """ + Read the font metrics header (up to the char metrics) and returns + a dictionary mapping *key* to *val*. *val* will be converted to the + appropriate python type as necessary; e.g.: + + * 'False'->False + * '0'->0 + * '-168 -218 1000 898'-> [-168, -218, 1000, 898] + + Dictionary keys are + + StartFontMetrics, FontName, FullName, FamilyName, Weight, + ItalicAngle, IsFixedPitch, FontBBox, UnderlinePosition, + UnderlineThickness, Version, Notice, EncodingScheme, CapHeight, + XHeight, Ascender, Descender, StartCharMetrics + """ + header_converters = { + b'StartFontMetrics': _to_float, + b'FontName': _to_str, + b'FullName': _to_str, + b'FamilyName': _to_str, + b'Weight': _to_str, + b'ItalicAngle': _to_float, + b'IsFixedPitch': _to_bool, + b'FontBBox': _to_list_of_ints, + b'UnderlinePosition': _to_float, + b'UnderlineThickness': _to_float, + b'Version': _to_str, + # Some AFM files have non-ASCII characters (which are not allowed by + # the spec). Given that there is actually no public API to even access + # this field, just return it as straight bytes. + b'Notice': lambda x: x, + b'EncodingScheme': _to_str, + b'CapHeight': _to_float, # Is the second version a mistake, or + b'Capheight': _to_float, # do some AFM files contain 'Capheight'? -JKS + b'XHeight': _to_float, + b'Ascender': _to_float, + b'Descender': _to_float, + b'StdHW': _to_float, + b'StdVW': _to_float, + b'StartCharMetrics': _to_int, + b'CharacterSet': _to_str, + b'Characters': _to_int, + } + d = {} + first_line = True + for line in fh: + line = line.rstrip() + if line.startswith(b'Comment'): + continue + lst = line.split(b' ', 1) + key = lst[0] + if first_line: + # AFM spec, Section 4: The StartFontMetrics keyword + # [followed by a version number] must be the first line in + # the file, and the EndFontMetrics keyword must be the + # last non-empty line in the file. We just check the + # first header entry. + if key != b'StartFontMetrics': + raise RuntimeError('Not an AFM file') + first_line = False + if len(lst) == 2: + val = lst[1] + else: + val = b'' + try: + converter = header_converters[key] + except KeyError: + _log.error("Found an unknown keyword in AFM header (was %r)", key) + continue + try: + d[key] = converter(val) + except ValueError: + _log.error('Value error parsing header in AFM: %s, %s', key, val) + continue + if key == b'StartCharMetrics': + break + else: + raise RuntimeError('Bad parse') + return d + + +CharMetrics = namedtuple('CharMetrics', 'width, name, bbox') +CharMetrics.__doc__ = """ + Represents the character metrics of a single character. + + Notes + ----- + The fields do currently only describe a subset of character metrics + information defined in the AFM standard. + """ +CharMetrics.width.__doc__ = """The character width (WX).""" +CharMetrics.name.__doc__ = """The character name (N).""" +CharMetrics.bbox.__doc__ = """ + The bbox of the character (B) as a tuple (*llx*, *lly*, *urx*, *ury*).""" + + +def _parse_char_metrics(fh): + """ + Parse the given filehandle for character metrics information and return + the information as dicts. + + It is assumed that the file cursor is on the line behind + 'StartCharMetrics'. + + Returns + ------- + ascii_d : dict + A mapping "ASCII num of the character" to `.CharMetrics`. + name_d : dict + A mapping "character name" to `.CharMetrics`. + + Notes + ----- + This function is incomplete per the standard, but thus far parses + all the sample afm files tried. + """ + required_keys = {'C', 'WX', 'N', 'B'} + + ascii_d = {} + name_d = {} + for line in fh: + # We are defensively letting values be utf8. The spec requires + # ascii, but there are non-compliant fonts in circulation + line = _to_str(line.rstrip()) # Convert from byte-literal + if line.startswith('EndCharMetrics'): + return ascii_d, name_d + # Split the metric line into a dictionary, keyed by metric identifiers + vals = dict(s.strip().split(' ', 1) for s in line.split(';') if s) + # There may be other metrics present, but only these are needed + if not required_keys.issubset(vals): + raise RuntimeError('Bad char metrics line: %s' % line) + num = _to_int(vals['C']) + wx = _to_float(vals['WX']) + name = vals['N'] + bbox = _to_list_of_floats(vals['B']) + bbox = list(map(int, bbox)) + metrics = CharMetrics(wx, name, bbox) + # Workaround: If the character name is 'Euro', give it the + # corresponding character code, according to WinAnsiEncoding (see PDF + # Reference). + if name == 'Euro': + num = 128 + elif name == 'minus': + num = ord("\N{MINUS SIGN}") # 0x2212 + if num != -1: + ascii_d[num] = metrics + name_d[name] = metrics + raise RuntimeError('Bad parse') + + +def _parse_kern_pairs(fh): + """ + Return a kern pairs dictionary; keys are (*char1*, *char2*) tuples and + values are the kern pair value. For example, a kern pairs line like + ``KPX A y -50`` + + will be represented as:: + + d[ ('A', 'y') ] = -50 + + """ + + line = next(fh) + if not line.startswith(b'StartKernPairs'): + raise RuntimeError('Bad start of kern pairs data: %s' % line) + + d = {} + for line in fh: + line = line.rstrip() + if not line: + continue + if line.startswith(b'EndKernPairs'): + next(fh) # EndKernData + return d + vals = line.split() + if len(vals) != 4 or vals[0] != b'KPX': + raise RuntimeError('Bad kern pairs line: %s' % line) + c1, c2, val = _to_str(vals[1]), _to_str(vals[2]), _to_float(vals[3]) + d[(c1, c2)] = val + raise RuntimeError('Bad kern pairs parse') + + +CompositePart = namedtuple('CompositePart', 'name, dx, dy') +CompositePart.__doc__ = """ + Represents the information on a composite element of a composite char.""" +CompositePart.name.__doc__ = """Name of the part, e.g. 'acute'.""" +CompositePart.dx.__doc__ = """x-displacement of the part from the origin.""" +CompositePart.dy.__doc__ = """y-displacement of the part from the origin.""" + + +def _parse_composites(fh): + """ + Parse the given filehandle for composites information return them as a + dict. + + It is assumed that the file cursor is on the line behind 'StartComposites'. + + Returns + ------- + dict + A dict mapping composite character names to a parts list. The parts + list is a list of `.CompositePart` entries describing the parts of + the composite. + + Examples + -------- + A composite definition line:: + + CC Aacute 2 ; PCC A 0 0 ; PCC acute 160 170 ; + + will be represented as:: + + composites['Aacute'] = [CompositePart(name='A', dx=0, dy=0), + CompositePart(name='acute', dx=160, dy=170)] + + """ + composites = {} + for line in fh: + line = line.rstrip() + if not line: + continue + if line.startswith(b'EndComposites'): + return composites + vals = line.split(b';') + cc = vals[0].split() + name, _num_parts = cc[1], _to_int(cc[2]) + pccParts = [] + for s in vals[1:-1]: + pcc = s.split() + part = CompositePart(pcc[1], _to_float(pcc[2]), _to_float(pcc[3])) + pccParts.append(part) + composites[name] = pccParts + + raise RuntimeError('Bad composites parse') + + +def _parse_optional(fh): + """ + Parse the optional fields for kern pair data and composites. + + Returns + ------- + kern_data : dict + A dict containing kerning information. May be empty. + See `._parse_kern_pairs`. + composites : dict + A dict containing composite information. May be empty. + See `._parse_composites`. + """ + optional = { + b'StartKernData': _parse_kern_pairs, + b'StartComposites': _parse_composites, + } + + d = {b'StartKernData': {}, + b'StartComposites': {}} + for line in fh: + line = line.rstrip() + if not line: + continue + key = line.split()[0] + + if key in optional: + d[key] = optional[key](fh) + + return d[b'StartKernData'], d[b'StartComposites'] + + +class AFM: + + def __init__(self, fh): + """Parse the AFM file in file object *fh*.""" + self._header = _parse_header(fh) + self._metrics, self._metrics_by_name = _parse_char_metrics(fh) + self._kern, self._composite = _parse_optional(fh) + + def get_bbox_char(self, c, isord=False): + if not isord: + c = ord(c) + return self._metrics[c].bbox + + def string_width_height(self, s): + """ + Return the string width (including kerning) and string height + as a (*w*, *h*) tuple. + """ + if not len(s): + return 0, 0 + total_width = 0 + namelast = None + miny = 1e9 + maxy = 0 + for c in s: + if c == '\n': + continue + wx, name, bbox = self._metrics[ord(c)] + + total_width += wx + self._kern.get((namelast, name), 0) + l, b, w, h = bbox + miny = min(miny, b) + maxy = max(maxy, b + h) + + namelast = name + + return total_width, maxy - miny + + def get_str_bbox_and_descent(self, s): + """Return the string bounding box and the maximal descent.""" + if not len(s): + return 0, 0, 0, 0, 0 + total_width = 0 + namelast = None + miny = 1e9 + maxy = 0 + left = 0 + if not isinstance(s, str): + s = _to_str(s) + for c in s: + if c == '\n': + continue + name = uni2type1.get(ord(c), f"uni{ord(c):04X}") + try: + wx, _, bbox = self._metrics_by_name[name] + except KeyError: + name = 'question' + wx, _, bbox = self._metrics_by_name[name] + total_width += wx + self._kern.get((namelast, name), 0) + l, b, w, h = bbox + left = min(left, l) + miny = min(miny, b) + maxy = max(maxy, b + h) + + namelast = name + + return left, miny, total_width, maxy - miny, -miny + + def get_str_bbox(self, s): + """Return the string bounding box.""" + return self.get_str_bbox_and_descent(s)[:4] + + def get_name_char(self, c, isord=False): + """Get the name of the character, i.e., ';' is 'semicolon'.""" + if not isord: + c = ord(c) + return self._metrics[c].name + + def get_width_char(self, c, isord=False): + """ + Get the width of the character from the character metric WX field. + """ + if not isord: + c = ord(c) + return self._metrics[c].width + + def get_width_from_char_name(self, name): + """Get the width of the character from a type1 character name.""" + return self._metrics_by_name[name].width + + def get_height_char(self, c, isord=False): + """Get the bounding box (ink) height of character *c* (space is 0).""" + if not isord: + c = ord(c) + return self._metrics[c].bbox[-1] + + def get_kern_dist(self, c1, c2): + """ + Return the kerning pair distance (possibly 0) for chars *c1* and *c2*. + """ + name1, name2 = self.get_name_char(c1), self.get_name_char(c2) + return self.get_kern_dist_from_name(name1, name2) + + def get_kern_dist_from_name(self, name1, name2): + """ + Return the kerning pair distance (possibly 0) for chars + *name1* and *name2*. + """ + return self._kern.get((name1, name2), 0) + + def get_fontname(self): + """Return the font name, e.g., 'Times-Roman'.""" + return self._header[b'FontName'] + + @property + def postscript_name(self): # For consistency with FT2Font. + return self.get_fontname() + + def get_fullname(self): + """Return the font full name, e.g., 'Times-Roman'.""" + name = self._header.get(b'FullName') + if name is None: # use FontName as a substitute + name = self._header[b'FontName'] + return name + + def get_familyname(self): + """Return the font family name, e.g., 'Times'.""" + name = self._header.get(b'FamilyName') + if name is not None: + return name + + # FamilyName not specified so we'll make a guess + name = self.get_fullname() + extras = (r'(?i)([ -](regular|plain|italic|oblique|bold|semibold|' + r'light|ultralight|extra|condensed))+$') + return re.sub(extras, '', name) + + @property + def family_name(self): + """The font family name, e.g., 'Times'.""" + return self.get_familyname() + + def get_weight(self): + """Return the font weight, e.g., 'Bold' or 'Roman'.""" + return self._header[b'Weight'] + + def get_angle(self): + """Return the fontangle as float.""" + return self._header[b'ItalicAngle'] + + def get_capheight(self): + """Return the cap height as float.""" + return self._header[b'CapHeight'] + + def get_xheight(self): + """Return the xheight as float.""" + return self._header[b'XHeight'] + + def get_underline_thickness(self): + """Return the underline thickness as float.""" + return self._header[b'UnderlineThickness'] + + def get_horizontal_stem_width(self): + """ + Return the standard horizontal stem width as float, or *None* if + not specified in AFM file. + """ + return self._header.get(b'StdHW', None) + + def get_vertical_stem_width(self): + """ + Return the standard vertical stem width as float, or *None* if + not specified in AFM file. + """ + return self._header.get(b'StdVW', None) diff --git a/infer_4_30_0/lib/python3.10/site-packages/matplotlib/_cm_bivar.py b/infer_4_30_0/lib/python3.10/site-packages/matplotlib/_cm_bivar.py new file mode 100644 index 0000000000000000000000000000000000000000..53c0d48d7d6c5d3818a33df783a284e11c16662d --- /dev/null +++ b/infer_4_30_0/lib/python3.10/site-packages/matplotlib/_cm_bivar.py @@ -0,0 +1,1312 @@ +# auto-generated by https://github.com/trygvrad/multivariate_colormaps +# date: 2024-05-24 + +import numpy as np +from matplotlib.colors import SegmentedBivarColormap + +BiPeak = np.array( + [0.000, 0.674, 0.931, 0.000, 0.680, 0.922, 0.000, 0.685, 0.914, 0.000, + 0.691, 0.906, 0.000, 0.696, 0.898, 0.000, 0.701, 0.890, 0.000, 0.706, + 0.882, 0.000, 0.711, 0.875, 0.000, 0.715, 0.867, 0.000, 0.720, 0.860, + 0.000, 0.725, 0.853, 0.000, 0.729, 0.845, 0.000, 0.733, 0.838, 0.000, + 0.737, 0.831, 0.000, 0.741, 0.824, 0.000, 0.745, 0.816, 0.000, 0.749, + 0.809, 0.000, 0.752, 0.802, 0.000, 0.756, 0.794, 0.000, 0.759, 0.787, + 0.000, 0.762, 0.779, 0.000, 0.765, 0.771, 0.000, 0.767, 0.764, 0.000, + 0.770, 0.755, 0.000, 0.772, 0.747, 0.000, 0.774, 0.739, 0.000, 0.776, + 0.730, 0.000, 0.777, 0.721, 0.000, 0.779, 0.712, 0.021, 0.780, 0.702, + 0.055, 0.781, 0.693, 0.079, 0.782, 0.682, 0.097, 0.782, 0.672, 0.111, + 0.782, 0.661, 0.122, 0.782, 0.650, 0.132, 0.782, 0.639, 0.140, 0.781, + 0.627, 0.147, 0.781, 0.615, 0.154, 0.780, 0.602, 0.159, 0.778, 0.589, + 0.164, 0.777, 0.576, 0.169, 0.775, 0.563, 0.173, 0.773, 0.549, 0.177, + 0.771, 0.535, 0.180, 0.768, 0.520, 0.184, 0.766, 0.505, 0.187, 0.763, + 0.490, 0.190, 0.760, 0.474, 0.193, 0.756, 0.458, 0.196, 0.753, 0.442, + 0.200, 0.749, 0.425, 0.203, 0.745, 0.408, 0.206, 0.741, 0.391, 0.210, + 0.736, 0.373, 0.213, 0.732, 0.355, 0.216, 0.727, 0.337, 0.220, 0.722, + 0.318, 0.224, 0.717, 0.298, 0.227, 0.712, 0.278, 0.231, 0.707, 0.258, + 0.235, 0.701, 0.236, 0.239, 0.696, 0.214, 0.242, 0.690, 0.190, 0.246, + 0.684, 0.165, 0.250, 0.678, 0.136, 0.000, 0.675, 0.934, 0.000, 0.681, + 0.925, 0.000, 0.687, 0.917, 0.000, 0.692, 0.909, 0.000, 0.697, 0.901, + 0.000, 0.703, 0.894, 0.000, 0.708, 0.886, 0.000, 0.713, 0.879, 0.000, + 0.718, 0.872, 0.000, 0.722, 0.864, 0.000, 0.727, 0.857, 0.000, 0.731, + 0.850, 0.000, 0.736, 0.843, 0.000, 0.740, 0.836, 0.000, 0.744, 0.829, + 0.000, 0.748, 0.822, 0.000, 0.752, 0.815, 0.000, 0.755, 0.808, 0.000, + 0.759, 0.800, 0.000, 0.762, 0.793, 0.000, 0.765, 0.786, 0.000, 0.768, + 0.778, 0.000, 0.771, 0.770, 0.000, 0.773, 0.762, 0.051, 0.776, 0.754, + 0.087, 0.778, 0.746, 0.111, 0.780, 0.737, 0.131, 0.782, 0.728, 0.146, + 0.783, 0.719, 0.159, 0.784, 0.710, 0.171, 0.785, 0.700, 0.180, 0.786, + 0.690, 0.189, 0.786, 0.680, 0.196, 0.787, 0.669, 0.202, 0.787, 0.658, + 0.208, 0.786, 0.647, 0.213, 0.786, 0.635, 0.217, 0.785, 0.623, 0.221, + 0.784, 0.610, 0.224, 0.782, 0.597, 0.227, 0.781, 0.584, 0.230, 0.779, + 0.570, 0.232, 0.777, 0.556, 0.234, 0.775, 0.542, 0.236, 0.772, 0.527, + 0.238, 0.769, 0.512, 0.240, 0.766, 0.497, 0.242, 0.763, 0.481, 0.244, + 0.760, 0.465, 0.246, 0.756, 0.448, 0.248, 0.752, 0.432, 0.250, 0.748, + 0.415, 0.252, 0.744, 0.397, 0.254, 0.739, 0.379, 0.256, 0.735, 0.361, + 0.259, 0.730, 0.343, 0.261, 0.725, 0.324, 0.264, 0.720, 0.304, 0.266, + 0.715, 0.284, 0.269, 0.709, 0.263, 0.271, 0.704, 0.242, 0.274, 0.698, + 0.220, 0.277, 0.692, 0.196, 0.280, 0.686, 0.170, 0.283, 0.680, 0.143, + 0.000, 0.676, 0.937, 0.000, 0.682, 0.928, 0.000, 0.688, 0.920, 0.000, + 0.694, 0.913, 0.000, 0.699, 0.905, 0.000, 0.704, 0.897, 0.000, 0.710, + 0.890, 0.000, 0.715, 0.883, 0.000, 0.720, 0.876, 0.000, 0.724, 0.869, + 0.000, 0.729, 0.862, 0.000, 0.734, 0.855, 0.000, 0.738, 0.848, 0.000, + 0.743, 0.841, 0.000, 0.747, 0.834, 0.000, 0.751, 0.827, 0.000, 0.755, + 0.820, 0.000, 0.759, 0.813, 0.000, 0.762, 0.806, 0.003, 0.766, 0.799, + 0.066, 0.769, 0.792, 0.104, 0.772, 0.784, 0.131, 0.775, 0.777, 0.152, + 0.777, 0.769, 0.170, 0.780, 0.761, 0.185, 0.782, 0.753, 0.198, 0.784, + 0.744, 0.209, 0.786, 0.736, 0.219, 0.787, 0.727, 0.228, 0.788, 0.717, + 0.236, 0.789, 0.708, 0.243, 0.790, 0.698, 0.249, 0.791, 0.688, 0.254, + 0.791, 0.677, 0.259, 0.791, 0.666, 0.263, 0.791, 0.654, 0.266, 0.790, + 0.643, 0.269, 0.789, 0.631, 0.272, 0.788, 0.618, 0.274, 0.787, 0.605, + 0.276, 0.785, 0.592, 0.278, 0.783, 0.578, 0.279, 0.781, 0.564, 0.280, + 0.779, 0.549, 0.282, 0.776, 0.535, 0.283, 0.773, 0.519, 0.284, 0.770, + 0.504, 0.285, 0.767, 0.488, 0.286, 0.763, 0.472, 0.287, 0.759, 0.455, + 0.288, 0.756, 0.438, 0.289, 0.751, 0.421, 0.291, 0.747, 0.403, 0.292, + 0.742, 0.385, 0.293, 0.738, 0.367, 0.295, 0.733, 0.348, 0.296, 0.728, + 0.329, 0.298, 0.723, 0.310, 0.300, 0.717, 0.290, 0.302, 0.712, 0.269, + 0.304, 0.706, 0.247, 0.306, 0.700, 0.225, 0.308, 0.694, 0.201, 0.310, + 0.688, 0.176, 0.312, 0.682, 0.149, 0.000, 0.678, 0.939, 0.000, 0.683, + 0.931, 0.000, 0.689, 0.923, 0.000, 0.695, 0.916, 0.000, 0.701, 0.908, + 0.000, 0.706, 0.901, 0.000, 0.711, 0.894, 0.000, 0.717, 0.887, 0.000, + 0.722, 0.880, 0.000, 0.727, 0.873, 0.000, 0.732, 0.866, 0.000, 0.736, + 0.859, 0.000, 0.741, 0.853, 0.000, 0.745, 0.846, 0.000, 0.750, 0.839, + 0.000, 0.754, 0.833, 0.035, 0.758, 0.826, 0.091, 0.762, 0.819, 0.126, + 0.765, 0.812, 0.153, 0.769, 0.805, 0.174, 0.772, 0.798, 0.193, 0.775, + 0.791, 0.209, 0.778, 0.783, 0.223, 0.781, 0.776, 0.236, 0.784, 0.768, + 0.247, 0.786, 0.760, 0.257, 0.788, 0.752, 0.266, 0.790, 0.743, 0.273, + 0.791, 0.734, 0.280, 0.793, 0.725, 0.287, 0.794, 0.715, 0.292, 0.794, + 0.706, 0.297, 0.795, 0.695, 0.301, 0.795, 0.685, 0.305, 0.795, 0.674, + 0.308, 0.795, 0.662, 0.310, 0.794, 0.651, 0.312, 0.794, 0.638, 0.314, + 0.792, 0.626, 0.316, 0.791, 0.613, 0.317, 0.789, 0.599, 0.318, 0.787, + 0.586, 0.319, 0.785, 0.571, 0.320, 0.783, 0.557, 0.320, 0.780, 0.542, + 0.321, 0.777, 0.527, 0.321, 0.774, 0.511, 0.322, 0.770, 0.495, 0.322, + 0.767, 0.478, 0.323, 0.763, 0.462, 0.323, 0.759, 0.445, 0.324, 0.755, + 0.427, 0.325, 0.750, 0.410, 0.325, 0.745, 0.391, 0.326, 0.741, 0.373, + 0.327, 0.736, 0.354, 0.328, 0.730, 0.335, 0.329, 0.725, 0.315, 0.330, + 0.720, 0.295, 0.331, 0.714, 0.274, 0.333, 0.708, 0.253, 0.334, 0.702, + 0.230, 0.336, 0.696, 0.207, 0.337, 0.690, 0.182, 0.339, 0.684, 0.154, + 0.000, 0.679, 0.942, 0.000, 0.685, 0.934, 0.000, 0.691, 0.927, 0.000, + 0.696, 0.919, 0.000, 0.702, 0.912, 0.000, 0.708, 0.905, 0.000, 0.713, + 0.898, 0.000, 0.718, 0.891, 0.000, 0.724, 0.884, 0.000, 0.729, 0.877, + 0.000, 0.734, 0.871, 0.000, 0.739, 0.864, 0.000, 0.743, 0.857, 0.035, + 0.748, 0.851, 0.096, 0.752, 0.844, 0.133, 0.757, 0.838, 0.161, 0.761, + 0.831, 0.185, 0.765, 0.825, 0.205, 0.769, 0.818, 0.223, 0.772, 0.811, + 0.238, 0.776, 0.804, 0.252, 0.779, 0.797, 0.265, 0.782, 0.790, 0.276, + 0.785, 0.783, 0.286, 0.788, 0.775, 0.296, 0.790, 0.767, 0.304, 0.792, + 0.759, 0.311, 0.794, 0.751, 0.318, 0.796, 0.742, 0.324, 0.797, 0.733, + 0.329, 0.798, 0.723, 0.334, 0.799, 0.714, 0.338, 0.799, 0.703, 0.341, + 0.800, 0.693, 0.344, 0.800, 0.682, 0.347, 0.799, 0.670, 0.349, 0.799, + 0.659, 0.351, 0.798, 0.646, 0.352, 0.797, 0.634, 0.353, 0.795, 0.621, + 0.354, 0.794, 0.607, 0.354, 0.792, 0.593, 0.355, 0.789, 0.579, 0.355, + 0.787, 0.564, 0.355, 0.784, 0.549, 0.355, 0.781, 0.534, 0.355, 0.778, + 0.518, 0.355, 0.774, 0.502, 0.355, 0.770, 0.485, 0.355, 0.766, 0.468, + 0.355, 0.762, 0.451, 0.355, 0.758, 0.434, 0.355, 0.753, 0.416, 0.356, + 0.748, 0.397, 0.356, 0.743, 0.379, 0.356, 0.738, 0.360, 0.357, 0.733, + 0.340, 0.357, 0.728, 0.321, 0.358, 0.722, 0.300, 0.359, 0.716, 0.279, + 0.360, 0.710, 0.258, 0.361, 0.704, 0.235, 0.361, 0.698, 0.212, 0.362, + 0.692, 0.187, 0.363, 0.686, 0.160, 0.000, 0.680, 0.945, 0.000, 0.686, + 0.937, 0.000, 0.692, 0.930, 0.000, 0.698, 0.922, 0.000, 0.703, 0.915, + 0.000, 0.709, 0.908, 0.000, 0.715, 0.901, 0.000, 0.720, 0.894, 0.000, + 0.726, 0.888, 0.000, 0.731, 0.881, 0.007, 0.736, 0.875, 0.084, 0.741, + 0.869, 0.127, 0.746, 0.862, 0.159, 0.751, 0.856, 0.185, 0.755, 0.850, + 0.208, 0.760, 0.843, 0.227, 0.764, 0.837, 0.245, 0.768, 0.830, 0.260, + 0.772, 0.824, 0.275, 0.776, 0.817, 0.288, 0.779, 0.811, 0.300, 0.783, + 0.804, 0.310, 0.786, 0.797, 0.320, 0.789, 0.789, 0.329, 0.792, 0.782, + 0.337, 0.794, 0.774, 0.345, 0.796, 0.766, 0.351, 0.798, 0.758, 0.357, + 0.800, 0.749, 0.363, 0.801, 0.740, 0.367, 0.803, 0.731, 0.371, 0.803, + 0.721, 0.375, 0.804, 0.711, 0.378, 0.804, 0.701, 0.380, 0.804, 0.690, + 0.382, 0.804, 0.679, 0.384, 0.803, 0.667, 0.385, 0.802, 0.654, 0.386, + 0.801, 0.642, 0.386, 0.800, 0.629, 0.387, 0.798, 0.615, 0.387, 0.796, + 0.601, 0.387, 0.793, 0.587, 0.387, 0.791, 0.572, 0.387, 0.788, 0.557, + 0.386, 0.785, 0.541, 0.386, 0.781, 0.525, 0.385, 0.778, 0.509, 0.385, + 0.774, 0.492, 0.385, 0.770, 0.475, 0.384, 0.765, 0.457, 0.384, 0.761, + 0.440, 0.384, 0.756, 0.422, 0.384, 0.751, 0.403, 0.384, 0.746, 0.384, + 0.384, 0.741, 0.365, 0.384, 0.735, 0.346, 0.384, 0.730, 0.326, 0.384, + 0.724, 0.305, 0.384, 0.718, 0.284, 0.385, 0.712, 0.263, 0.385, 0.706, + 0.240, 0.386, 0.700, 0.217, 0.386, 0.694, 0.192, 0.387, 0.687, 0.165, + 0.000, 0.680, 0.948, 0.000, 0.687, 0.940, 0.000, 0.693, 0.933, 0.000, + 0.699, 0.925, 0.000, 0.705, 0.918, 0.000, 0.711, 0.912, 0.000, 0.716, + 0.905, 0.000, 0.722, 0.898, 0.050, 0.728, 0.892, 0.109, 0.733, 0.886, + 0.147, 0.738, 0.879, 0.177, 0.743, 0.873, 0.202, 0.748, 0.867, 0.224, + 0.753, 0.861, 0.243, 0.758, 0.855, 0.261, 0.763, 0.849, 0.277, 0.767, + 0.842, 0.292, 0.771, 0.836, 0.305, 0.775, 0.830, 0.318, 0.779, 0.823, + 0.329, 0.783, 0.817, 0.340, 0.787, 0.810, 0.350, 0.790, 0.803, 0.359, + 0.793, 0.796, 0.367, 0.796, 0.789, 0.374, 0.798, 0.782, 0.381, 0.801, + 0.774, 0.387, 0.803, 0.766, 0.393, 0.804, 0.757, 0.397, 0.806, 0.748, + 0.402, 0.807, 0.739, 0.405, 0.808, 0.729, 0.408, 0.809, 0.719, 0.411, + 0.809, 0.709, 0.413, 0.809, 0.698, 0.415, 0.808, 0.687, 0.416, 0.808, + 0.675, 0.417, 0.807, 0.663, 0.417, 0.806, 0.650, 0.417, 0.804, 0.637, + 0.418, 0.802, 0.623, 0.417, 0.800, 0.609, 0.417, 0.798, 0.594, 0.416, + 0.795, 0.579, 0.416, 0.792, 0.564, 0.415, 0.789, 0.548, 0.414, 0.785, + 0.532, 0.414, 0.781, 0.515, 0.413, 0.777, 0.499, 0.412, 0.773, 0.481, + 0.412, 0.769, 0.464, 0.411, 0.764, 0.446, 0.410, 0.759, 0.428, 0.410, + 0.754, 0.409, 0.409, 0.749, 0.390, 0.409, 0.743, 0.371, 0.409, 0.738, + 0.351, 0.409, 0.732, 0.331, 0.408, 0.726, 0.310, 0.408, 0.720, 0.289, + 0.408, 0.714, 0.268, 0.408, 0.708, 0.245, 0.409, 0.702, 0.222, 0.409, + 0.695, 0.197, 0.409, 0.689, 0.170, 0.000, 0.681, 0.950, 0.000, 0.688, + 0.943, 0.000, 0.694, 0.936, 0.000, 0.700, 0.929, 0.000, 0.706, 0.922, + 0.000, 0.712, 0.915, 0.074, 0.718, 0.908, 0.124, 0.724, 0.902, 0.159, + 0.730, 0.896, 0.188, 0.735, 0.890, 0.213, 0.740, 0.884, 0.235, 0.746, + 0.878, 0.255, 0.751, 0.872, 0.273, 0.756, 0.866, 0.289, 0.761, 0.860, + 0.305, 0.766, 0.854, 0.319, 0.770, 0.848, 0.332, 0.775, 0.842, 0.344, + 0.779, 0.836, 0.356, 0.783, 0.830, 0.366, 0.787, 0.823, 0.376, 0.790, + 0.817, 0.385, 0.794, 0.810, 0.394, 0.797, 0.803, 0.401, 0.800, 0.796, + 0.408, 0.802, 0.789, 0.414, 0.805, 0.781, 0.420, 0.807, 0.773, 0.425, + 0.809, 0.765, 0.430, 0.810, 0.756, 0.433, 0.812, 0.747, 0.437, 0.813, + 0.738, 0.440, 0.813, 0.728, 0.442, 0.814, 0.717, 0.444, 0.813, 0.706, + 0.445, 0.813, 0.695, 0.446, 0.812, 0.683, 0.446, 0.811, 0.671, 0.447, + 0.810, 0.658, 0.447, 0.809, 0.645, 0.446, 0.807, 0.631, 0.446, 0.804, + 0.617, 0.445, 0.802, 0.602, 0.444, 0.799, 0.587, 0.443, 0.796, 0.571, + 0.442, 0.792, 0.555, 0.441, 0.789, 0.539, 0.440, 0.785, 0.522, 0.439, + 0.781, 0.505, 0.438, 0.776, 0.488, 0.437, 0.772, 0.470, 0.436, 0.767, + 0.452, 0.435, 0.762, 0.433, 0.435, 0.757, 0.415, 0.434, 0.751, 0.396, + 0.433, 0.746, 0.376, 0.432, 0.740, 0.356, 0.432, 0.734, 0.336, 0.431, + 0.728, 0.315, 0.431, 0.722, 0.294, 0.431, 0.716, 0.272, 0.430, 0.710, + 0.250, 0.430, 0.703, 0.226, 0.430, 0.697, 0.201, 0.430, 0.690, 0.175, + 0.000, 0.682, 0.953, 0.000, 0.689, 0.946, 0.000, 0.695, 0.938, 0.002, + 0.701, 0.932, 0.086, 0.708, 0.925, 0.133, 0.714, 0.918, 0.167, 0.720, + 0.912, 0.196, 0.726, 0.906, 0.221, 0.731, 0.900, 0.243, 0.737, 0.894, + 0.263, 0.743, 0.888, 0.281, 0.748, 0.882, 0.298, 0.753, 0.876, 0.314, + 0.759, 0.870, 0.329, 0.764, 0.865, 0.342, 0.768, 0.859, 0.355, 0.773, + 0.853, 0.368, 0.778, 0.847, 0.379, 0.782, 0.842, 0.390, 0.786, 0.836, + 0.400, 0.790, 0.830, 0.409, 0.794, 0.823, 0.417, 0.798, 0.817, 0.425, + 0.801, 0.810, 0.433, 0.804, 0.803, 0.439, 0.807, 0.796, 0.445, 0.809, + 0.789, 0.451, 0.811, 0.781, 0.456, 0.813, 0.773, 0.460, 0.815, 0.764, + 0.463, 0.816, 0.755, 0.466, 0.817, 0.746, 0.469, 0.818, 0.736, 0.471, + 0.818, 0.725, 0.472, 0.818, 0.715, 0.473, 0.818, 0.703, 0.474, 0.817, + 0.691, 0.474, 0.816, 0.679, 0.474, 0.815, 0.666, 0.474, 0.813, 0.653, + 0.473, 0.811, 0.639, 0.473, 0.809, 0.624, 0.472, 0.806, 0.610, 0.471, + 0.803, 0.594, 0.469, 0.800, 0.579, 0.468, 0.796, 0.562, 0.467, 0.792, + 0.546, 0.466, 0.788, 0.529, 0.464, 0.784, 0.512, 0.463, 0.780, 0.494, + 0.462, 0.775, 0.476, 0.460, 0.770, 0.458, 0.459, 0.765, 0.439, 0.458, + 0.759, 0.420, 0.457, 0.754, 0.401, 0.456, 0.748, 0.381, 0.455, 0.742, + 0.361, 0.454, 0.736, 0.341, 0.453, 0.730, 0.320, 0.453, 0.724, 0.299, + 0.452, 0.718, 0.277, 0.452, 0.711, 0.254, 0.451, 0.705, 0.231, 0.451, + 0.698, 0.206, 0.450, 0.691, 0.179, 0.000, 0.683, 0.955, 0.013, 0.689, + 0.948, 0.092, 0.696, 0.941, 0.137, 0.702, 0.935, 0.171, 0.709, 0.928, + 0.200, 0.715, 0.922, 0.225, 0.721, 0.916, 0.247, 0.727, 0.909, 0.267, + 0.733, 0.904, 0.286, 0.739, 0.898, 0.303, 0.745, 0.892, 0.320, 0.750, + 0.886, 0.335, 0.756, 0.881, 0.350, 0.761, 0.875, 0.363, 0.766, 0.870, + 0.376, 0.771, 0.864, 0.388, 0.776, 0.859, 0.400, 0.781, 0.853, 0.411, + 0.785, 0.847, 0.421, 0.790, 0.842, 0.430, 0.794, 0.836, 0.439, 0.798, + 0.830, 0.448, 0.802, 0.824, 0.455, 0.805, 0.817, 0.462, 0.808, 0.810, + 0.469, 0.811, 0.804, 0.475, 0.814, 0.796, 0.480, 0.816, 0.789, 0.484, + 0.818, 0.781, 0.488, 0.820, 0.772, 0.492, 0.821, 0.763, 0.495, 0.822, + 0.754, 0.497, 0.823, 0.744, 0.499, 0.823, 0.734, 0.500, 0.823, 0.723, + 0.501, 0.823, 0.712, 0.501, 0.822, 0.700, 0.501, 0.821, 0.687, 0.501, + 0.819, 0.674, 0.500, 0.818, 0.661, 0.499, 0.815, 0.647, 0.498, 0.813, + 0.632, 0.497, 0.810, 0.617, 0.496, 0.807, 0.602, 0.494, 0.804, 0.586, + 0.493, 0.800, 0.569, 0.491, 0.796, 0.553, 0.490, 0.792, 0.536, 0.488, + 0.787, 0.518, 0.486, 0.783, 0.500, 0.485, 0.778, 0.482, 0.483, 0.773, + 0.463, 0.482, 0.767, 0.445, 0.480, 0.762, 0.425, 0.479, 0.756, 0.406, + 0.478, 0.750, 0.386, 0.477, 0.744, 0.366, 0.476, 0.738, 0.345, 0.475, + 0.732, 0.325, 0.474, 0.726, 0.303, 0.473, 0.719, 0.281, 0.472, 0.713, + 0.258, 0.471, 0.706, 0.235, 0.470, 0.699, 0.210, 0.469, 0.692, 0.184, + 0.095, 0.683, 0.958, 0.139, 0.690, 0.951, 0.173, 0.697, 0.944, 0.201, + 0.703, 0.938, 0.226, 0.710, 0.931, 0.249, 0.716, 0.925, 0.269, 0.723, + 0.919, 0.288, 0.729, 0.913, 0.306, 0.735, 0.907, 0.323, 0.741, 0.902, + 0.339, 0.747, 0.896, 0.354, 0.752, 0.891, 0.368, 0.758, 0.885, 0.382, + 0.764, 0.880, 0.394, 0.769, 0.875, 0.407, 0.774, 0.869, 0.418, 0.779, + 0.864, 0.429, 0.784, 0.859, 0.440, 0.789, 0.853, 0.450, 0.793, 0.848, + 0.459, 0.798, 0.842, 0.468, 0.802, 0.836, 0.476, 0.806, 0.830, 0.483, + 0.809, 0.824, 0.490, 0.812, 0.818, 0.496, 0.815, 0.811, 0.502, 0.818, + 0.804, 0.507, 0.821, 0.796, 0.512, 0.823, 0.789, 0.515, 0.825, 0.780, + 0.519, 0.826, 0.772, 0.521, 0.827, 0.762, 0.524, 0.828, 0.753, 0.525, + 0.828, 0.742, 0.526, 0.828, 0.732, 0.527, 0.828, 0.720, 0.527, 0.827, + 0.708, 0.527, 0.826, 0.696, 0.526, 0.824, 0.683, 0.525, 0.822, 0.669, + 0.524, 0.820, 0.655, 0.523, 0.817, 0.640, 0.522, 0.814, 0.625, 0.520, + 0.811, 0.609, 0.518, 0.808, 0.593, 0.516, 0.804, 0.576, 0.515, 0.800, + 0.559, 0.513, 0.795, 0.542, 0.511, 0.791, 0.524, 0.509, 0.786, 0.506, + 0.507, 0.781, 0.488, 0.505, 0.775, 0.469, 0.504, 0.770, 0.450, 0.502, + 0.764, 0.431, 0.500, 0.759, 0.411, 0.499, 0.753, 0.391, 0.497, 0.746, + 0.371, 0.496, 0.740, 0.350, 0.495, 0.734, 0.329, 0.494, 0.727, 0.307, + 0.492, 0.721, 0.285, 0.491, 0.714, 0.262, 0.490, 0.707, 0.239, 0.489, + 0.700, 0.214, 0.488, 0.693, 0.188, 0.172, 0.684, 0.961, 0.201, 0.691, + 0.954, 0.226, 0.698, 0.947, 0.248, 0.704, 0.941, 0.269, 0.711, 0.934, + 0.289, 0.717, 0.928, 0.307, 0.724, 0.922, 0.324, 0.730, 0.917, 0.340, + 0.736, 0.911, 0.356, 0.743, 0.906, 0.370, 0.749, 0.900, 0.384, 0.755, + 0.895, 0.398, 0.760, 0.890, 0.411, 0.766, 0.885, 0.423, 0.772, 0.880, + 0.435, 0.777, 0.874, 0.446, 0.782, 0.869, 0.457, 0.787, 0.864, 0.467, + 0.792, 0.859, 0.477, 0.797, 0.854, 0.486, 0.801, 0.848, 0.494, 0.806, + 0.843, 0.502, 0.810, 0.837, 0.510, 0.813, 0.831, 0.517, 0.817, 0.825, + 0.523, 0.820, 0.818, 0.528, 0.823, 0.811, 0.533, 0.825, 0.804, 0.538, + 0.828, 0.797, 0.542, 0.829, 0.788, 0.545, 0.831, 0.780, 0.547, 0.832, + 0.771, 0.549, 0.833, 0.761, 0.551, 0.833, 0.751, 0.552, 0.833, 0.740, + 0.552, 0.833, 0.729, 0.552, 0.832, 0.717, 0.551, 0.830, 0.704, 0.551, + 0.829, 0.691, 0.550, 0.827, 0.677, 0.548, 0.824, 0.663, 0.547, 0.822, + 0.648, 0.545, 0.819, 0.632, 0.543, 0.815, 0.617, 0.541, 0.812, 0.600, + 0.539, 0.808, 0.583, 0.537, 0.803, 0.566, 0.535, 0.799, 0.549, 0.533, + 0.794, 0.531, 0.531, 0.789, 0.512, 0.529, 0.784, 0.494, 0.527, 0.778, + 0.475, 0.525, 0.773, 0.455, 0.523, 0.767, 0.436, 0.521, 0.761, 0.416, + 0.519, 0.755, 0.396, 0.517, 0.748, 0.375, 0.516, 0.742, 0.354, 0.514, + 0.735, 0.333, 0.513, 0.729, 0.311, 0.511, 0.722, 0.289, 0.510, 0.715, + 0.266, 0.509, 0.708, 0.242, 0.507, 0.701, 0.218, 0.506, 0.694, 0.191, + 0.224, 0.684, 0.963, 0.247, 0.691, 0.956, 0.268, 0.698, 0.950, 0.287, + 0.705, 0.943, 0.305, 0.712, 0.937, 0.323, 0.719, 0.931, 0.339, 0.725, + 0.926, 0.355, 0.732, 0.920, 0.370, 0.738, 0.915, 0.385, 0.744, 0.909, + 0.399, 0.751, 0.904, 0.412, 0.757, 0.899, 0.425, 0.763, 0.894, 0.438, + 0.768, 0.889, 0.450, 0.774, 0.884, 0.461, 0.780, 0.879, 0.472, 0.785, + 0.875, 0.483, 0.790, 0.870, 0.493, 0.795, 0.865, 0.502, 0.800, 0.860, + 0.511, 0.805, 0.855, 0.520, 0.809, 0.849, 0.528, 0.814, 0.844, 0.535, + 0.818, 0.838, 0.542, 0.821, 0.832, 0.548, 0.824, 0.826, 0.554, 0.827, + 0.819, 0.559, 0.830, 0.812, 0.563, 0.832, 0.805, 0.567, 0.834, 0.797, + 0.570, 0.836, 0.788, 0.572, 0.837, 0.779, 0.574, 0.838, 0.770, 0.575, + 0.838, 0.760, 0.576, 0.838, 0.749, 0.576, 0.838, 0.737, 0.576, 0.837, + 0.725, 0.575, 0.835, 0.713, 0.574, 0.834, 0.699, 0.573, 0.831, 0.685, + 0.571, 0.829, 0.671, 0.570, 0.826, 0.656, 0.568, 0.823, 0.640, 0.566, + 0.819, 0.624, 0.563, 0.815, 0.607, 0.561, 0.811, 0.590, 0.559, 0.807, + 0.573, 0.556, 0.802, 0.555, 0.554, 0.797, 0.537, 0.552, 0.792, 0.518, + 0.549, 0.786, 0.499, 0.547, 0.781, 0.480, 0.545, 0.775, 0.460, 0.543, + 0.769, 0.441, 0.541, 0.763, 0.420, 0.539, 0.756, 0.400, 0.537, 0.750, + 0.379, 0.535, 0.743, 0.358, 0.533, 0.737, 0.337, 0.531, 0.730, 0.315, + 0.530, 0.723, 0.293, 0.528, 0.716, 0.270, 0.527, 0.709, 0.246, 0.525, + 0.702, 0.221, 0.524, 0.694, 0.195, 0.265, 0.685, 0.965, 0.284, 0.692, + 0.959, 0.303, 0.699, 0.952, 0.320, 0.706, 0.946, 0.337, 0.713, 0.940, + 0.353, 0.720, 0.935, 0.369, 0.726, 0.929, 0.384, 0.733, 0.924, 0.398, + 0.739, 0.918, 0.412, 0.746, 0.913, 0.425, 0.752, 0.908, 0.438, 0.759, + 0.903, 0.451, 0.765, 0.899, 0.463, 0.771, 0.894, 0.475, 0.777, 0.889, + 0.486, 0.782, 0.884, 0.497, 0.788, 0.880, 0.507, 0.793, 0.875, 0.517, + 0.799, 0.870, 0.527, 0.804, 0.866, 0.536, 0.809, 0.861, 0.544, 0.813, + 0.856, 0.552, 0.818, 0.850, 0.560, 0.822, 0.845, 0.566, 0.826, 0.839, + 0.573, 0.829, 0.833, 0.578, 0.832, 0.827, 0.583, 0.835, 0.820, 0.587, + 0.837, 0.813, 0.591, 0.839, 0.805, 0.594, 0.841, 0.797, 0.596, 0.842, + 0.788, 0.598, 0.843, 0.778, 0.599, 0.843, 0.768, 0.600, 0.843, 0.758, + 0.600, 0.843, 0.746, 0.599, 0.842, 0.734, 0.599, 0.840, 0.721, 0.597, + 0.838, 0.708, 0.596, 0.836, 0.694, 0.594, 0.834, 0.679, 0.592, 0.831, + 0.663, 0.590, 0.827, 0.648, 0.587, 0.823, 0.631, 0.585, 0.819, 0.614, + 0.582, 0.815, 0.597, 0.580, 0.810, 0.579, 0.577, 0.805, 0.561, 0.575, + 0.800, 0.542, 0.572, 0.795, 0.524, 0.569, 0.789, 0.504, 0.567, 0.783, + 0.485, 0.565, 0.777, 0.465, 0.562, 0.771, 0.445, 0.560, 0.765, 0.425, + 0.558, 0.758, 0.404, 0.556, 0.752, 0.383, 0.554, 0.745, 0.362, 0.552, + 0.738, 0.341, 0.550, 0.731, 0.319, 0.548, 0.724, 0.296, 0.546, 0.717, + 0.273, 0.544, 0.709, 0.249, 0.542, 0.702, 0.224, 0.541, 0.695, 0.198, + 0.299, 0.685, 0.968, 0.317, 0.692, 0.961, 0.334, 0.699, 0.955, 0.350, + 0.706, 0.949, 0.366, 0.713, 0.943, 0.381, 0.720, 0.938, 0.395, 0.727, + 0.932, 0.410, 0.734, 0.927, 0.423, 0.741, 0.922, 0.437, 0.747, 0.917, + 0.450, 0.754, 0.912, 0.463, 0.760, 0.907, 0.475, 0.767, 0.903, 0.487, + 0.773, 0.898, 0.498, 0.779, 0.894, 0.509, 0.785, 0.889, 0.520, 0.791, + 0.885, 0.531, 0.796, 0.880, 0.540, 0.802, 0.876, 0.550, 0.807, 0.871, + 0.559, 0.812, 0.867, 0.568, 0.817, 0.862, 0.576, 0.822, 0.857, 0.583, + 0.826, 0.852, 0.590, 0.830, 0.847, 0.596, 0.834, 0.841, 0.602, 0.837, + 0.835, 0.607, 0.840, 0.828, 0.611, 0.843, 0.821, 0.615, 0.845, 0.814, + 0.618, 0.846, 0.805, 0.620, 0.848, 0.797, 0.622, 0.848, 0.787, 0.623, + 0.849, 0.777, 0.623, 0.849, 0.766, 0.623, 0.848, 0.755, 0.622, 0.847, + 0.743, 0.621, 0.845, 0.730, 0.620, 0.843, 0.716, 0.618, 0.841, 0.702, + 0.616, 0.838, 0.687, 0.613, 0.835, 0.671, 0.611, 0.831, 0.655, 0.608, + 0.827, 0.638, 0.606, 0.823, 0.621, 0.603, 0.818, 0.604, 0.600, 0.814, + 0.585, 0.597, 0.808, 0.567, 0.594, 0.803, 0.548, 0.592, 0.797, 0.529, + 0.589, 0.792, 0.510, 0.586, 0.785, 0.490, 0.584, 0.779, 0.470, 0.581, + 0.773, 0.450, 0.579, 0.766, 0.429, 0.576, 0.760, 0.408, 0.574, 0.753, + 0.387, 0.572, 0.746, 0.366, 0.569, 0.739, 0.344, 0.567, 0.732, 0.322, + 0.565, 0.725, 0.299, 0.563, 0.717, 0.276, 0.561, 0.710, 0.252, 0.559, + 0.703, 0.227, 0.557, 0.695, 0.201, 0.329, 0.685, 0.970, 0.346, 0.692, + 0.964, 0.362, 0.699, 0.958, 0.377, 0.707, 0.952, 0.392, 0.714, 0.946, + 0.406, 0.721, 0.941, 0.420, 0.728, 0.935, 0.434, 0.735, 0.930, 0.447, + 0.742, 0.925, 0.460, 0.749, 0.920, 0.473, 0.756, 0.916, 0.485, 0.762, + 0.911, 0.497, 0.769, 0.907, 0.509, 0.775, 0.903, 0.521, 0.781, 0.898, + 0.532, 0.788, 0.894, 0.542, 0.794, 0.890, 0.553, 0.799, 0.886, 0.563, + 0.805, 0.882, 0.572, 0.811, 0.877, 0.581, 0.816, 0.873, 0.590, 0.821, + 0.868, 0.598, 0.826, 0.864, 0.606, 0.830, 0.859, 0.613, 0.834, 0.854, + 0.619, 0.838, 0.848, 0.625, 0.842, 0.842, 0.630, 0.845, 0.836, 0.634, + 0.848, 0.829, 0.638, 0.850, 0.822, 0.641, 0.852, 0.814, 0.643, 0.853, + 0.805, 0.645, 0.854, 0.796, 0.645, 0.854, 0.786, 0.646, 0.854, 0.775, + 0.645, 0.853, 0.764, 0.645, 0.852, 0.751, 0.643, 0.851, 0.738, 0.642, + 0.848, 0.725, 0.639, 0.846, 0.710, 0.637, 0.843, 0.695, 0.635, 0.839, + 0.679, 0.632, 0.836, 0.662, 0.629, 0.831, 0.645, 0.626, 0.827, 0.628, + 0.623, 0.822, 0.610, 0.620, 0.817, 0.592, 0.617, 0.811, 0.573, 0.614, + 0.806, 0.554, 0.611, 0.800, 0.534, 0.608, 0.794, 0.515, 0.605, 0.788, + 0.495, 0.602, 0.781, 0.474, 0.599, 0.775, 0.454, 0.597, 0.768, 0.433, + 0.594, 0.761, 0.412, 0.592, 0.754, 0.391, 0.589, 0.747, 0.369, 0.587, + 0.740, 0.347, 0.584, 0.733, 0.325, 0.582, 0.725, 0.302, 0.580, 0.718, + 0.279, 0.577, 0.710, 0.255, 0.575, 0.703, 0.230, 0.573, 0.695, 0.204, + 0.357, 0.685, 0.972, 0.372, 0.692, 0.966, 0.387, 0.700, 0.960, 0.401, + 0.707, 0.954, 0.416, 0.714, 0.949, 0.429, 0.722, 0.943, 0.443, 0.729, + 0.938, 0.456, 0.736, 0.933, 0.469, 0.743, 0.929, 0.482, 0.750, 0.924, + 0.494, 0.757, 0.919, 0.507, 0.764, 0.915, 0.519, 0.771, 0.911, 0.530, + 0.777, 0.907, 0.542, 0.784, 0.903, 0.553, 0.790, 0.899, 0.563, 0.796, + 0.895, 0.574, 0.802, 0.891, 0.584, 0.808, 0.887, 0.593, 0.814, 0.883, + 0.603, 0.820, 0.879, 0.611, 0.825, 0.875, 0.620, 0.830, 0.870, 0.627, + 0.835, 0.866, 0.635, 0.839, 0.861, 0.641, 0.843, 0.856, 0.647, 0.847, + 0.850, 0.652, 0.850, 0.844, 0.657, 0.853, 0.838, 0.660, 0.855, 0.831, + 0.663, 0.857, 0.823, 0.666, 0.859, 0.814, 0.667, 0.859, 0.805, 0.668, + 0.860, 0.795, 0.668, 0.860, 0.784, 0.667, 0.859, 0.773, 0.666, 0.858, + 0.760, 0.665, 0.856, 0.747, 0.663, 0.853, 0.733, 0.661, 0.851, 0.718, + 0.658, 0.847, 0.703, 0.655, 0.844, 0.687, 0.652, 0.840, 0.670, 0.649, + 0.835, 0.652, 0.646, 0.830, 0.635, 0.642, 0.825, 0.616, 0.639, 0.820, + 0.598, 0.636, 0.814, 0.579, 0.633, 0.808, 0.559, 0.629, 0.802, 0.539, + 0.626, 0.796, 0.519, 0.623, 0.790, 0.499, 0.620, 0.783, 0.479, 0.617, + 0.776, 0.458, 0.614, 0.769, 0.437, 0.611, 0.762, 0.416, 0.609, 0.755, + 0.394, 0.606, 0.748, 0.372, 0.603, 0.740, 0.350, 0.601, 0.733, 0.328, + 0.598, 0.726, 0.305, 0.596, 0.718, 0.282, 0.593, 0.710, 0.257, 0.591, + 0.703, 0.232, 0.589, 0.695, 0.206, 0.381, 0.684, 0.974, 0.396, 0.692, + 0.968, 0.410, 0.700, 0.962, 0.424, 0.707, 0.957, 0.438, 0.715, 0.951, + 0.451, 0.722, 0.946, 0.464, 0.729, 0.941, 0.477, 0.737, 0.936, 0.490, + 0.744, 0.932, 0.503, 0.751, 0.927, 0.515, 0.758, 0.923, 0.527, 0.765, + 0.919, 0.539, 0.772, 0.915, 0.550, 0.779, 0.911, 0.562, 0.786, 0.907, + 0.573, 0.792, 0.903, 0.584, 0.799, 0.900, 0.594, 0.805, 0.896, 0.604, + 0.811, 0.892, 0.614, 0.817, 0.889, 0.623, 0.823, 0.885, 0.632, 0.829, + 0.881, 0.641, 0.834, 0.877, 0.649, 0.839, 0.873, 0.656, 0.844, 0.868, + 0.663, 0.848, 0.863, 0.669, 0.852, 0.858, 0.674, 0.855, 0.852, 0.679, + 0.858, 0.846, 0.682, 0.861, 0.839, 0.685, 0.863, 0.832, 0.688, 0.864, + 0.823, 0.689, 0.865, 0.814, 0.690, 0.865, 0.804, 0.690, 0.865, 0.794, + 0.689, 0.864, 0.782, 0.688, 0.863, 0.769, 0.686, 0.861, 0.756, 0.684, + 0.858, 0.742, 0.681, 0.855, 0.726, 0.678, 0.852, 0.711, 0.675, 0.848, + 0.694, 0.672, 0.844, 0.677, 0.668, 0.839, 0.659, 0.665, 0.834, 0.641, + 0.662, 0.829, 0.622, 0.658, 0.823, 0.603, 0.655, 0.817, 0.584, 0.651, + 0.811, 0.564, 0.648, 0.805, 0.544, 0.644, 0.798, 0.524, 0.641, 0.791, + 0.503, 0.638, 0.785, 0.483, 0.635, 0.778, 0.462, 0.631, 0.770, 0.440, + 0.628, 0.763, 0.419, 0.625, 0.756, 0.397, 0.623, 0.748, 0.375, 0.620, + 0.741, 0.353, 0.617, 0.733, 0.330, 0.614, 0.726, 0.307, 0.612, 0.718, + 0.284, 0.609, 0.710, 0.260, 0.606, 0.702, 0.235, 0.604, 0.694, 0.208, + 0.404, 0.684, 0.977, 0.418, 0.692, 0.971, 0.432, 0.699, 0.965, 0.445, + 0.707, 0.959, 0.458, 0.715, 0.954, 0.472, 0.722, 0.949, 0.484, 0.730, + 0.944, 0.497, 0.737, 0.939, 0.510, 0.745, 0.935, 0.522, 0.752, 0.931, + 0.534, 0.759, 0.926, 0.546, 0.767, 0.922, 0.558, 0.774, 0.919, 0.569, + 0.781, 0.915, 0.581, 0.788, 0.911, 0.592, 0.794, 0.908, 0.603, 0.801, + 0.904, 0.613, 0.808, 0.901, 0.624, 0.814, 0.897, 0.633, 0.820, 0.894, + 0.643, 0.826, 0.891, 0.652, 0.832, 0.887, 0.661, 0.838, 0.883, 0.669, + 0.843, 0.879, 0.677, 0.848, 0.875, 0.684, 0.853, 0.871, 0.690, 0.857, + 0.866, 0.695, 0.860, 0.860, 0.700, 0.864, 0.855, 0.704, 0.866, 0.848, + 0.707, 0.869, 0.841, 0.709, 0.870, 0.833, 0.711, 0.871, 0.824, 0.711, + 0.871, 0.814, 0.711, 0.871, 0.803, 0.710, 0.870, 0.791, 0.709, 0.868, + 0.778, 0.707, 0.866, 0.765, 0.704, 0.864, 0.750, 0.701, 0.860, 0.735, + 0.698, 0.857, 0.718, 0.695, 0.852, 0.702, 0.691, 0.848, 0.684, 0.688, + 0.843, 0.666, 0.684, 0.837, 0.647, 0.680, 0.832, 0.628, 0.676, 0.826, + 0.609, 0.673, 0.820, 0.589, 0.669, 0.813, 0.569, 0.665, 0.807, 0.549, + 0.662, 0.800, 0.528, 0.658, 0.793, 0.507, 0.655, 0.786, 0.486, 0.651, + 0.779, 0.465, 0.648, 0.771, 0.444, 0.645, 0.764, 0.422, 0.642, 0.756, + 0.400, 0.639, 0.749, 0.378, 0.636, 0.741, 0.356, 0.633, 0.733, 0.333, + 0.630, 0.726, 0.310, 0.627, 0.718, 0.286, 0.624, 0.710, 0.262, 0.621, + 0.702, 0.237, 0.619, 0.694, 0.210, 0.425, 0.683, 0.979, 0.439, 0.691, + 0.973, 0.452, 0.699, 0.967, 0.465, 0.707, 0.962, 0.478, 0.715, 0.956, + 0.491, 0.722, 0.951, 0.503, 0.730, 0.947, 0.516, 0.738, 0.942, 0.528, + 0.745, 0.938, 0.540, 0.753, 0.934, 0.552, 0.760, 0.930, 0.564, 0.768, + 0.926, 0.576, 0.775, 0.922, 0.588, 0.782, 0.919, 0.599, 0.789, 0.915, + 0.610, 0.797, 0.912, 0.621, 0.803, 0.909, 0.632, 0.810, 0.906, 0.642, + 0.817, 0.902, 0.652, 0.823, 0.899, 0.662, 0.830, 0.896, 0.671, 0.836, + 0.893, 0.680, 0.842, 0.890, 0.689, 0.847, 0.886, 0.697, 0.853, 0.882, + 0.704, 0.857, 0.878, 0.710, 0.862, 0.874, 0.716, 0.866, 0.869, 0.721, + 0.869, 0.863, 0.725, 0.872, 0.857, 0.729, 0.874, 0.850, 0.731, 0.876, + 0.842, 0.732, 0.877, 0.833, 0.733, 0.877, 0.823, 0.732, 0.877, 0.812, + 0.731, 0.876, 0.800, 0.729, 0.874, 0.787, 0.727, 0.872, 0.773, 0.724, + 0.869, 0.759, 0.721, 0.865, 0.743, 0.718, 0.861, 0.726, 0.714, 0.857, + 0.709, 0.710, 0.852, 0.691, 0.706, 0.846, 0.672, 0.702, 0.841, 0.653, + 0.698, 0.835, 0.634, 0.694, 0.828, 0.614, 0.690, 0.822, 0.594, 0.686, + 0.815, 0.574, 0.683, 0.808, 0.553, 0.679, 0.801, 0.532, 0.675, 0.794, + 0.511, 0.672, 0.787, 0.490, 0.668, 0.779, 0.468, 0.665, 0.772, 0.446, + 0.661, 0.764, 0.425, 0.658, 0.757, 0.403, 0.654, 0.749, 0.380, 0.651, + 0.741, 0.358, 0.648, 0.733, 0.335, 0.645, 0.725, 0.312, 0.642, 0.717, + 0.288, 0.639, 0.709, 0.264, 0.636, 0.701, 0.238, 0.633, 0.693, 0.212, + 0.445, 0.682, 0.981, 0.458, 0.691, 0.975, 0.471, 0.699, 0.969, 0.484, + 0.707, 0.964, 0.496, 0.715, 0.959, 0.509, 0.722, 0.954, 0.521, 0.730, + 0.949, 0.534, 0.738, 0.945, 0.546, 0.746, 0.941, 0.558, 0.753, 0.937, + 0.570, 0.761, 0.933, 0.582, 0.769, 0.929, 0.593, 0.776, 0.926, 0.605, + 0.784, 0.922, 0.616, 0.791, 0.919, 0.628, 0.798, 0.916, 0.639, 0.806, + 0.913, 0.649, 0.813, 0.910, 0.660, 0.820, 0.907, 0.670, 0.826, 0.904, + 0.680, 0.833, 0.902, 0.690, 0.839, 0.899, 0.699, 0.846, 0.896, 0.708, + 0.851, 0.893, 0.716, 0.857, 0.889, 0.724, 0.862, 0.885, 0.731, 0.867, + 0.881, 0.737, 0.871, 0.877, 0.742, 0.875, 0.872, 0.746, 0.878, 0.866, + 0.750, 0.880, 0.859, 0.752, 0.882, 0.851, 0.753, 0.883, 0.843, 0.754, + 0.883, 0.833, 0.753, 0.883, 0.822, 0.752, 0.882, 0.810, 0.750, 0.880, + 0.797, 0.747, 0.877, 0.782, 0.744, 0.874, 0.767, 0.740, 0.870, 0.751, + 0.737, 0.866, 0.734, 0.733, 0.861, 0.716, 0.729, 0.855, 0.697, 0.724, + 0.850, 0.678, 0.720, 0.844, 0.659, 0.716, 0.837, 0.639, 0.712, 0.831, + 0.619, 0.708, 0.824, 0.598, 0.704, 0.817, 0.578, 0.699, 0.810, 0.557, + 0.696, 0.803, 0.535, 0.692, 0.795, 0.514, 0.688, 0.788, 0.493, 0.684, + 0.780, 0.471, 0.680, 0.772, 0.449, 0.677, 0.765, 0.427, 0.673, 0.757, + 0.405, 0.670, 0.749, 0.382, 0.666, 0.741, 0.360, 0.663, 0.733, 0.337, + 0.660, 0.725, 0.313, 0.657, 0.716, 0.289, 0.653, 0.708, 0.265, 0.650, + 0.700, 0.240, 0.647, 0.692, 0.213, 0.464, 0.681, 0.982, 0.476, 0.690, + 0.977, 0.489, 0.698, 0.971, 0.501, 0.706, 0.966, 0.514, 0.714, 0.961, + 0.526, 0.722, 0.956, 0.538, 0.730, 0.952, 0.550, 0.738, 0.947, 0.562, + 0.746, 0.943, 0.574, 0.754, 0.939, 0.586, 0.762, 0.936, 0.598, 0.769, + 0.932, 0.610, 0.777, 0.929, 0.621, 0.785, 0.926, 0.633, 0.792, 0.923, + 0.644, 0.800, 0.920, 0.655, 0.807, 0.917, 0.666, 0.815, 0.915, 0.677, + 0.822, 0.912, 0.688, 0.829, 0.909, 0.698, 0.836, 0.907, 0.708, 0.843, + 0.904, 0.717, 0.849, 0.902, 0.727, 0.855, 0.899, 0.735, 0.861, 0.896, + 0.743, 0.867, 0.893, 0.750, 0.872, 0.889, 0.757, 0.877, 0.885, 0.762, + 0.881, 0.880, 0.767, 0.884, 0.875, 0.770, 0.887, 0.868, 0.773, 0.888, + 0.861, 0.774, 0.889, 0.852, 0.774, 0.890, 0.842, 0.774, 0.889, 0.831, + 0.772, 0.888, 0.819, 0.770, 0.885, 0.806, 0.767, 0.883, 0.791, 0.763, + 0.879, 0.775, 0.759, 0.875, 0.759, 0.755, 0.870, 0.741, 0.751, 0.865, + 0.723, 0.747, 0.859, 0.704, 0.742, 0.853, 0.684, 0.738, 0.847, 0.664, + 0.733, 0.840, 0.644, 0.729, 0.833, 0.623, 0.724, 0.826, 0.603, 0.720, + 0.819, 0.581, 0.716, 0.811, 0.560, 0.712, 0.804, 0.539, 0.708, 0.796, + 0.517, 0.704, 0.788, 0.495, 0.700, 0.780, 0.473, 0.696, 0.772, 0.451, + 0.692, 0.764, 0.429, 0.688, 0.756, 0.407, 0.685, 0.748, 0.384, 0.681, + 0.740, 0.361, 0.678, 0.732, 0.338, 0.674, 0.724, 0.315, 0.671, 0.715, + 0.291, 0.667, 0.707, 0.266, 0.664, 0.699, 0.241, 0.661, 0.691, 0.214, + 0.481, 0.680, 0.984, 0.494, 0.689, 0.978, 0.506, 0.697, 0.973, 0.518, + 0.705, 0.968, 0.530, 0.713, 0.963, 0.542, 0.722, 0.958, 0.554, 0.730, + 0.954, 0.566, 0.738, 0.950, 0.578, 0.746, 0.946, 0.590, 0.754, 0.942, + 0.602, 0.762, 0.939, 0.614, 0.770, 0.935, 0.626, 0.778, 0.932, 0.637, + 0.786, 0.929, 0.649, 0.794, 0.926, 0.660, 0.801, 0.924, 0.671, 0.809, + 0.921, 0.683, 0.817, 0.919, 0.694, 0.824, 0.916, 0.704, 0.832, 0.914, + 0.715, 0.839, 0.912, 0.725, 0.846, 0.910, 0.735, 0.853, 0.908, 0.744, + 0.859, 0.905, 0.753, 0.866, 0.903, 0.762, 0.872, 0.900, 0.770, 0.877, + 0.897, 0.776, 0.882, 0.893, 0.782, 0.886, 0.889, 0.787, 0.890, 0.884, + 0.791, 0.893, 0.878, 0.794, 0.895, 0.871, 0.795, 0.896, 0.862, 0.795, + 0.896, 0.852, 0.794, 0.895, 0.841, 0.792, 0.894, 0.829, 0.789, 0.891, + 0.815, 0.786, 0.888, 0.800, 0.782, 0.884, 0.783, 0.778, 0.879, 0.766, + 0.774, 0.874, 0.748, 0.769, 0.868, 0.729, 0.764, 0.862, 0.710, 0.760, + 0.856, 0.690, 0.755, 0.849, 0.669, 0.750, 0.842, 0.649, 0.745, 0.835, + 0.628, 0.741, 0.827, 0.606, 0.736, 0.820, 0.585, 0.732, 0.812, 0.563, + 0.728, 0.804, 0.542, 0.723, 0.796, 0.520, 0.719, 0.788, 0.498, 0.715, + 0.780, 0.475, 0.711, 0.772, 0.453, 0.707, 0.764, 0.431, 0.703, 0.756, + 0.408, 0.699, 0.748, 0.386, 0.696, 0.739, 0.363, 0.692, 0.731, 0.339, + 0.688, 0.723, 0.316, 0.685, 0.714, 0.292, 0.681, 0.706, 0.267, 0.678, + 0.697, 0.242, 0.674, 0.689, 0.215, 0.498, 0.679, 0.986, 0.510, 0.687, + 0.980, 0.522, 0.696, 0.975, 0.534, 0.704, 0.970, 0.546, 0.712, 0.965, + 0.558, 0.721, 0.961, 0.570, 0.729, 0.956, 0.581, 0.737, 0.952, 0.593, + 0.746, 0.948, 0.605, 0.754, 0.945, 0.617, 0.762, 0.941, 0.629, 0.770, + 0.938, 0.640, 0.778, 0.935, 0.652, 0.786, 0.932, 0.664, 0.794, 0.930, + 0.675, 0.802, 0.927, 0.687, 0.810, 0.925, 0.698, 0.818, 0.923, 0.709, + 0.826, 0.921, 0.720, 0.834, 0.919, 0.731, 0.841, 0.917, 0.742, 0.849, + 0.915, 0.752, 0.856, 0.913, 0.762, 0.863, 0.911, 0.771, 0.870, 0.909, + 0.780, 0.876, 0.907, 0.788, 0.882, 0.904, 0.796, 0.887, 0.901, 0.802, + 0.892, 0.897, 0.807, 0.896, 0.893, 0.811, 0.899, 0.887, 0.814, 0.902, + 0.880, 0.815, 0.903, 0.872, 0.815, 0.903, 0.862, 0.814, 0.902, 0.851, + 0.812, 0.900, 0.838, 0.809, 0.897, 0.824, 0.805, 0.893, 0.808, 0.801, + 0.889, 0.791, 0.796, 0.884, 0.774, 0.791, 0.878, 0.755, 0.786, 0.872, + 0.735, 0.781, 0.865, 0.715, 0.776, 0.858, 0.695, 0.771, 0.851, 0.674, + 0.767, 0.844, 0.653, 0.762, 0.836, 0.631, 0.757, 0.829, 0.610, 0.752, + 0.821, 0.588, 0.748, 0.813, 0.566, 0.743, 0.805, 0.544, 0.739, 0.796, + 0.522, 0.734, 0.788, 0.500, 0.730, 0.780, 0.477, 0.726, 0.772, 0.455, + 0.722, 0.763, 0.432, 0.718, 0.755, 0.410, 0.714, 0.746, 0.387, 0.710, + 0.738, 0.364, 0.706, 0.730, 0.340, 0.702, 0.721, 0.317, 0.698, 0.713, + 0.293, 0.694, 0.704, 0.268, 0.691, 0.696, 0.243, 0.687, 0.687, 0.216, + 0.513, 0.677, 0.987, 0.525, 0.686, 0.982, 0.537, 0.694, 0.977, 0.549, + 0.703, 0.972, 0.561, 0.711, 0.967, 0.572, 0.720, 0.962, 0.584, 0.728, + 0.958, 0.596, 0.737, 0.954, 0.608, 0.745, 0.951, 0.619, 0.753, 0.947, + 0.631, 0.762, 0.944, 0.643, 0.770, 0.941, 0.655, 0.778, 0.938, 0.666, + 0.787, 0.935, 0.678, 0.795, 0.933, 0.689, 0.803, 0.930, 0.701, 0.811, + 0.928, 0.713, 0.820, 0.926, 0.724, 0.828, 0.925, 0.735, 0.836, 0.923, + 0.746, 0.844, 0.921, 0.757, 0.852, 0.920, 0.768, 0.859, 0.918, 0.778, + 0.867, 0.917, 0.788, 0.874, 0.915, 0.797, 0.881, 0.913, 0.806, 0.887, + 0.911, 0.814, 0.893, 0.909, 0.821, 0.898, 0.906, 0.827, 0.902, 0.902, + 0.831, 0.906, 0.897, 0.834, 0.908, 0.890, 0.836, 0.910, 0.882, 0.836, + 0.910, 0.873, 0.834, 0.909, 0.861, 0.832, 0.906, 0.848, 0.828, 0.903, + 0.833, 0.824, 0.899, 0.817, 0.819, 0.894, 0.799, 0.814, 0.888, 0.781, + 0.809, 0.882, 0.761, 0.804, 0.875, 0.741, 0.798, 0.868, 0.720, 0.793, + 0.861, 0.699, 0.788, 0.853, 0.678, 0.783, 0.845, 0.656, 0.777, 0.837, + 0.635, 0.772, 0.829, 0.613, 0.768, 0.821, 0.590, 0.763, 0.813, 0.568, + 0.758, 0.804, 0.546, 0.753, 0.796, 0.524, 0.749, 0.788, 0.501, 0.744, + 0.779, 0.479, 0.740, 0.771, 0.456, 0.736, 0.762, 0.433, 0.731, 0.754, + 0.411, 0.727, 0.745, 0.388, 0.723, 0.736, 0.365, 0.719, 0.728, 0.341, + 0.715, 0.719, 0.317, 0.711, 0.711, 0.293, 0.707, 0.702, 0.268, 0.704, + 0.694, 0.243, 0.700, 0.685, 0.216, 0.528, 0.675, 0.989, 0.540, 0.684, + 0.983, 0.551, 0.693, 0.978, 0.563, 0.701, 0.973, 0.575, 0.710, 0.969, + 0.586, 0.718, 0.964, 0.598, 0.727, 0.960, 0.610, 0.736, 0.956, 0.621, + 0.744, 0.953, 0.633, 0.753, 0.949, 0.645, 0.761, 0.946, 0.656, 0.770, + 0.943, 0.668, 0.778, 0.940, 0.680, 0.787, 0.938, 0.691, 0.795, 0.936, + 0.703, 0.804, 0.933, 0.715, 0.812, 0.932, 0.726, 0.821, 0.930, 0.738, + 0.829, 0.928, 0.749, 0.837, 0.927, 0.761, 0.846, 0.926, 0.772, 0.854, + 0.924, 0.783, 0.862, 0.923, 0.794, 0.870, 0.922, 0.804, 0.877, 0.921, + 0.814, 0.885, 0.920, 0.824, 0.892, 0.918, 0.832, 0.898, 0.917, 0.840, + 0.904, 0.914, 0.846, 0.909, 0.911, 0.851, 0.913, 0.906, 0.855, 0.915, + 0.901, 0.856, 0.917, 0.893, 0.856, 0.917, 0.883, 0.854, 0.915, 0.871, + 0.851, 0.913, 0.858, 0.847, 0.909, 0.842, 0.842, 0.904, 0.825, 0.837, + 0.898, 0.806, 0.831, 0.892, 0.787, 0.826, 0.885, 0.767, 0.820, 0.878, + 0.746, 0.814, 0.870, 0.725, 0.809, 0.862, 0.703, 0.803, 0.854, 0.681, + 0.798, 0.846, 0.659, 0.793, 0.838, 0.637, 0.788, 0.829, 0.615, 0.782, + 0.821, 0.592, 0.777, 0.812, 0.570, 0.773, 0.804, 0.548, 0.768, 0.795, + 0.525, 0.763, 0.787, 0.502, 0.758, 0.778, 0.480, 0.754, 0.769, 0.457, + 0.749, 0.761, 0.434, 0.745, 0.752, 0.411, 0.741, 0.743, 0.388, 0.737, + 0.735, 0.365, 0.732, 0.726, 0.342, 0.728, 0.717, 0.318, 0.724, 0.709, + 0.293, 0.720, 0.700, 0.269, 0.716, 0.691, 0.243, 0.712, 0.683, 0.216, + 0.542, 0.673, 0.990, 0.554, 0.682, 0.985, 0.565, 0.691, 0.980, 0.577, + 0.700, 0.975, 0.588, 0.708, 0.970, 0.600, 0.717, 0.966, 0.611, 0.726, + 0.962, 0.623, 0.734, 0.958, 0.634, 0.743, 0.955, 0.646, 0.752, 0.951, + 0.657, 0.760, 0.948, 0.669, 0.769, 0.945, 0.681, 0.778, 0.943, 0.692, + 0.786, 0.940, 0.704, 0.795, 0.938, 0.716, 0.804, 0.936, 0.728, 0.812, + 0.934, 0.739, 0.821, 0.933, 0.751, 0.830, 0.932, 0.763, 0.838, 0.930, + 0.774, 0.847, 0.929, 0.786, 0.856, 0.929, 0.797, 0.864, 0.928, 0.809, + 0.873, 0.927, 0.819, 0.881, 0.927, 0.830, 0.889, 0.926, 0.840, 0.896, + 0.925, 0.850, 0.903, 0.924, 0.858, 0.910, 0.922, 0.865, 0.915, 0.920, + 0.871, 0.920, 0.916, 0.875, 0.923, 0.911, 0.876, 0.924, 0.903, 0.876, + 0.924, 0.894, 0.873, 0.922, 0.882, 0.870, 0.919, 0.867, 0.865, 0.914, + 0.851, 0.860, 0.909, 0.832, 0.854, 0.902, 0.813, 0.848, 0.895, 0.793, + 0.842, 0.888, 0.772, 0.836, 0.880, 0.750, 0.830, 0.872, 0.729, 0.824, + 0.864, 0.707, 0.819, 0.855, 0.684, 0.813, 0.847, 0.662, 0.808, 0.838, + 0.639, 0.802, 0.829, 0.617, 0.797, 0.820, 0.594, 0.792, 0.812, 0.571, + 0.787, 0.803, 0.549, 0.782, 0.794, 0.526, 0.777, 0.785, 0.503, 0.772, + 0.776, 0.480, 0.767, 0.768, 0.458, 0.763, 0.759, 0.435, 0.758, 0.750, + 0.412, 0.754, 0.741, 0.388, 0.749, 0.732, 0.365, 0.745, 0.724, 0.342, + 0.741, 0.715, 0.318, 0.737, 0.706, 0.293, 0.732, 0.697, 0.269, 0.728, + 0.689, 0.243, 0.724, 0.680, 0.216, 0.556, 0.671, 0.992, 0.567, 0.680, + 0.986, 0.578, 0.689, 0.981, 0.590, 0.697, 0.976, 0.601, 0.706, 0.972, + 0.612, 0.715, 0.968, 0.624, 0.724, 0.964, 0.635, 0.733, 0.960, 0.646, + 0.741, 0.956, 0.658, 0.750, 0.953, 0.670, 0.759, 0.950, 0.681, 0.768, + 0.947, 0.693, 0.777, 0.945, 0.704, 0.786, 0.943, 0.716, 0.794, 0.941, + 0.728, 0.803, 0.939, 0.740, 0.812, 0.937, 0.752, 0.821, 0.936, 0.763, + 0.830, 0.935, 0.775, 0.839, 0.934, 0.787, 0.848, 0.933, 0.799, 0.857, + 0.932, 0.811, 0.866, 0.932, 0.822, 0.875, 0.932, 0.834, 0.883, 0.932, + 0.845, 0.892, 0.931, 0.856, 0.900, 0.931, 0.866, 0.908, 0.931, 0.876, + 0.915, 0.930, 0.884, 0.922, 0.929, 0.890, 0.927, 0.926, 0.895, 0.930, + 0.921, 0.896, 0.932, 0.914, 0.896, 0.932, 0.905, 0.893, 0.929, 0.892, + 0.888, 0.925, 0.876, 0.883, 0.920, 0.859, 0.877, 0.913, 0.840, 0.871, + 0.906, 0.819, 0.864, 0.898, 0.798, 0.858, 0.890, 0.776, 0.852, 0.882, + 0.754, 0.845, 0.873, 0.732, 0.839, 0.864, 0.709, 0.833, 0.855, 0.686, + 0.828, 0.846, 0.664, 0.822, 0.837, 0.641, 0.816, 0.828, 0.618, 0.811, + 0.819, 0.595, 0.806, 0.810, 0.572, 0.800, 0.801, 0.549, 0.795, 0.792, + 0.526, 0.790, 0.783, 0.504, 0.785, 0.774, 0.481, 0.781, 0.765, 0.458, + 0.776, 0.756, 0.435, 0.771, 0.748, 0.412, 0.766, 0.739, 0.388, 0.762, + 0.730, 0.365, 0.757, 0.721, 0.341, 0.753, 0.712, 0.318, 0.749, 0.703, + 0.293, 0.744, 0.695, 0.268, 0.740, 0.686, 0.243, 0.736, 0.677, 0.216, + 0.569, 0.668, 0.993, 0.580, 0.677, 0.987, 0.591, 0.686, 0.982, 0.602, + 0.695, 0.978, 0.613, 0.704, 0.973, 0.624, 0.713, 0.969, 0.635, 0.722, + 0.965, 0.647, 0.731, 0.961, 0.658, 0.740, 0.958, 0.670, 0.748, 0.955, + 0.681, 0.757, 0.952, 0.693, 0.766, 0.949, 0.704, 0.775, 0.947, 0.716, + 0.784, 0.945, 0.728, 0.793, 0.943, 0.739, 0.802, 0.941, 0.751, 0.812, + 0.939, 0.763, 0.821, 0.938, 0.775, 0.830, 0.937, 0.787, 0.839, 0.936, + 0.799, 0.848, 0.936, 0.811, 0.858, 0.936, 0.823, 0.867, 0.935, 0.835, + 0.876, 0.936, 0.847, 0.886, 0.936, 0.859, 0.895, 0.936, 0.870, 0.904, + 0.937, 0.882, 0.912, 0.937, 0.892, 0.920, 0.937, 0.901, 0.928, 0.937, + 0.909, 0.934, 0.936, 0.914, 0.938, 0.932, 0.917, 0.940, 0.926, 0.915, + 0.940, 0.916, 0.912, 0.936, 0.902, 0.906, 0.931, 0.885, 0.900, 0.925, + 0.866, 0.893, 0.917, 0.846, 0.887, 0.909, 0.824, 0.880, 0.900, 0.802, + 0.873, 0.891, 0.780, 0.867, 0.882, 0.757, 0.860, 0.873, 0.734, 0.854, + 0.864, 0.711, 0.848, 0.855, 0.688, 0.842, 0.845, 0.665, 0.836, 0.836, + 0.642, 0.830, 0.827, 0.619, 0.824, 0.818, 0.596, 0.819, 0.808, 0.573, + 0.814, 0.799, 0.549, 0.808, 0.790, 0.527, 0.803, 0.781, 0.504, 0.798, + 0.772, 0.481, 0.793, 0.763, 0.458, 0.788, 0.754, 0.434, 0.783, 0.745, + 0.411, 0.779, 0.736, 0.388, 0.774, 0.727, 0.365, 0.769, 0.718, 0.341, + 0.765, 0.709, 0.317, 0.760, 0.700, 0.293, 0.756, 0.691, 0.268, 0.751, + 0.683, 0.242, 0.747, 0.674, 0.215, 0.581, 0.665, 0.994, 0.592, 0.674, + 0.989, 0.603, 0.683, 0.984, 0.614, 0.692, 0.979, 0.625, 0.701, 0.974, + 0.636, 0.710, 0.970, 0.647, 0.719, 0.966, 0.658, 0.728, 0.963, 0.669, + 0.737, 0.959, 0.681, 0.746, 0.956, 0.692, 0.755, 0.953, 0.703, 0.765, + 0.951, 0.715, 0.774, 0.948, 0.727, 0.783, 0.946, 0.738, 0.792, 0.944, + 0.750, 0.801, 0.943, 0.762, 0.810, 0.941, 0.774, 0.820, 0.940, 0.786, + 0.829, 0.939, 0.798, 0.839, 0.939, 0.810, 0.848, 0.938, 0.822, 0.858, + 0.938, 0.834, 0.867, 0.939, 0.847, 0.877, 0.939, 0.859, 0.887, 0.940, + 0.871, 0.897, 0.940, 0.883, 0.906, 0.942, 0.896, 0.916, 0.943, 0.907, + 0.925, 0.944, 0.918, 0.933, 0.945, 0.927, 0.941, 0.945, 0.934, 0.946, + 0.943, 0.937, 0.949, 0.937, 0.935, 0.948, 0.927, 0.930, 0.943, 0.912, + 0.924, 0.937, 0.893, 0.916, 0.929, 0.872, 0.909, 0.920, 0.850, 0.902, + 0.911, 0.828, 0.895, 0.901, 0.805, 0.888, 0.892, 0.782, 0.881, 0.882, + 0.759, 0.874, 0.872, 0.735, 0.868, 0.863, 0.712, 0.861, 0.853, 0.689, + 0.855, 0.844, 0.665, 0.849, 0.834, 0.642, 0.843, 0.825, 0.619, 0.838, + 0.815, 0.596, 0.832, 0.806, 0.572, 0.826, 0.797, 0.549, 0.821, 0.787, + 0.526, 0.816, 0.778, 0.503, 0.811, 0.769, 0.480, 0.805, 0.760, 0.457, + 0.800, 0.751, 0.434, 0.795, 0.742, 0.411, 0.791, 0.733, 0.387, 0.786, + 0.724, 0.364, 0.781, 0.715, 0.340, 0.776, 0.706, 0.316, 0.772, 0.697, + 0.292, 0.767, 0.688, 0.267, 0.762, 0.679, 0.241, 0.758, 0.670, 0.215, + 0.593, 0.662, 0.995, 0.603, 0.671, 0.990, 0.614, 0.680, 0.985, 0.625, + 0.689, 0.980, 0.636, 0.699, 0.975, 0.647, 0.708, 0.971, 0.658, 0.717, + 0.967, 0.669, 0.726, 0.964, 0.680, 0.735, 0.960, 0.691, 0.744, 0.957, + 0.702, 0.753, 0.955, 0.714, 0.762, 0.952, 0.725, 0.771, 0.950, 0.737, + 0.781, 0.948, 0.748, 0.790, 0.946, 0.760, 0.799, 0.944, 0.772, 0.809, + 0.943, 0.784, 0.818, 0.942, 0.796, 0.828, 0.941, 0.808, 0.837, 0.941, + 0.820, 0.847, 0.940, 0.832, 0.857, 0.941, 0.844, 0.867, 0.941, 0.857, + 0.877, 0.942, 0.869, 0.887, 0.943, 0.882, 0.897, 0.944, 0.895, 0.908, + 0.945, 0.908, 0.918, 0.947, 0.920, 0.928, 0.949, 0.933, 0.938, 0.951, + 0.944, 0.947, 0.953, 0.953, 0.955, 0.954, 0.957, 0.958, 0.950, 0.954, + 0.956, 0.938, 0.948, 0.949, 0.920, 0.940, 0.941, 0.899, 0.932, 0.931, + 0.877, 0.924, 0.921, 0.854, 0.916, 0.911, 0.830, 0.909, 0.901, 0.807, + 0.901, 0.891, 0.783, 0.894, 0.881, 0.759, 0.887, 0.871, 0.736, 0.881, + 0.861, 0.712, 0.874, 0.851, 0.688, 0.868, 0.841, 0.665, 0.862, 0.832, + 0.642, 0.856, 0.822, 0.618, 0.850, 0.812, 0.595, 0.844, 0.803, 0.572, + 0.839, 0.793, 0.549, 0.833, 0.784, 0.525, 0.828, 0.775, 0.502, 0.822, + 0.766, 0.479, 0.817, 0.756, 0.456, 0.812, 0.747, 0.433, 0.807, 0.738, + 0.410, 0.802, 0.729, 0.387, 0.797, 0.720, 0.363, 0.792, 0.711, 0.339, + 0.787, 0.702, 0.315, 0.782, 0.693, 0.291, 0.778, 0.684, 0.266, 0.773, + 0.675, 0.240, 0.768, 0.666, 0.214, 0.604, 0.659, 0.996, 0.614, 0.668, + 0.990, 0.625, 0.677, 0.985, 0.636, 0.686, 0.981, 0.646, 0.695, 0.976, + 0.657, 0.704, 0.972, 0.668, 0.714, 0.968, 0.679, 0.723, 0.965, 0.690, + 0.732, 0.961, 0.701, 0.741, 0.958, 0.712, 0.750, 0.956, 0.723, 0.759, + 0.953, 0.735, 0.769, 0.951, 0.746, 0.778, 0.949, 0.758, 0.787, 0.947, + 0.769, 0.797, 0.945, 0.781, 0.806, 0.944, 0.793, 0.816, 0.943, 0.805, + 0.826, 0.943, 0.817, 0.836, 0.942, 0.829, 0.845, 0.942, 0.841, 0.855, + 0.942, 0.853, 0.866, 0.943, 0.866, 0.876, 0.943, 0.879, 0.886, 0.945, + 0.892, 0.897, 0.946, 0.905, 0.907, 0.948, 0.918, 0.918, 0.950, 0.931, + 0.930, 0.953, 0.945, 0.941, 0.956, 0.958, 0.952, 0.960, 0.971, 0.963, + 0.963, 0.978, 0.968, 0.963, 0.972, 0.963, 0.948, 0.963, 0.954, 0.926, + 0.954, 0.943, 0.903, 0.945, 0.931, 0.879, 0.937, 0.921, 0.855, 0.929, + 0.910, 0.831, 0.921, 0.899, 0.807, 0.914, 0.889, 0.783, 0.907, 0.878, + 0.759, 0.900, 0.868, 0.735, 0.893, 0.858, 0.711, 0.887, 0.848, 0.688, + 0.880, 0.838, 0.664, 0.874, 0.828, 0.641, 0.868, 0.818, 0.617, 0.862, + 0.809, 0.594, 0.856, 0.799, 0.571, 0.850, 0.790, 0.547, 0.845, 0.780, + 0.524, 0.839, 0.771, 0.501, 0.834, 0.762, 0.478, 0.828, 0.752, 0.455, + 0.823, 0.743, 0.432, 0.818, 0.734, 0.409, 0.813, 0.725, 0.385, 0.808, + 0.716, 0.362, 0.803, 0.707, 0.338, 0.798, 0.698, 0.314, 0.793, 0.689, + 0.290, 0.788, 0.680, 0.265, 0.783, 0.671, 0.239, 0.778, 0.662, 0.213, + 0.615, 0.655, 0.996, 0.625, 0.664, 0.991, 0.635, 0.673, 0.986, 0.646, + 0.683, 0.982, 0.656, 0.692, 0.977, 0.667, 0.701, 0.973, 0.678, 0.710, + 0.969, 0.688, 0.719, 0.966, 0.699, 0.729, 0.962, 0.710, 0.738, 0.959, + 0.721, 0.747, 0.956, 0.732, 0.756, 0.954, 0.744, 0.766, 0.952, 0.755, + 0.775, 0.950, 0.766, 0.784, 0.948, 0.778, 0.794, 0.946, 0.789, 0.804, + 0.945, 0.801, 0.813, 0.944, 0.813, 0.823, 0.943, 0.825, 0.833, 0.943, + 0.837, 0.843, 0.943, 0.849, 0.853, 0.943, 0.861, 0.863, 0.944, 0.874, + 0.873, 0.944, 0.886, 0.884, 0.946, 0.899, 0.895, 0.947, 0.912, 0.906, + 0.949, 0.926, 0.917, 0.952, 0.939, 0.928, 0.955, 0.953, 0.940, 0.958, + 0.967, 0.953, 0.963, 0.982, 0.966, 0.969, 0.994, 0.976, 0.972, 0.986, + 0.966, 0.952, 0.976, 0.953, 0.928, 0.966, 0.941, 0.903, 0.957, 0.929, + 0.878, 0.949, 0.918, 0.854, 0.941, 0.906, 0.830, 0.933, 0.896, 0.806, + 0.926, 0.885, 0.782, 0.918, 0.874, 0.758, 0.911, 0.864, 0.734, 0.905, + 0.854, 0.710, 0.898, 0.844, 0.686, 0.892, 0.834, 0.663, 0.885, 0.824, + 0.639, 0.879, 0.814, 0.616, 0.873, 0.804, 0.592, 0.867, 0.795, 0.569, + 0.861, 0.785, 0.546, 0.856, 0.776, 0.523, 0.850, 0.766, 0.500, 0.845, + 0.757, 0.477, 0.839, 0.748, 0.454, 0.834, 0.739, 0.430, 0.829, 0.729, + 0.407, 0.823, 0.720, 0.384, 0.818, 0.711, 0.361, 0.813, 0.702, 0.337, + 0.808, 0.693, 0.313, 0.803, 0.684, 0.289, 0.798, 0.675, 0.264, 0.793, + 0.666, 0.238, 0.788, 0.657, 0.211, 0.625, 0.651, 0.997, 0.635, 0.660, + 0.992, 0.645, 0.669, 0.987, 0.656, 0.679, 0.982, 0.666, 0.688, 0.978, + 0.676, 0.697, 0.974, 0.687, 0.706, 0.970, 0.698, 0.716, 0.966, 0.708, + 0.725, 0.963, 0.719, 0.734, 0.960, 0.730, 0.743, 0.957, 0.741, 0.753, + 0.954, 0.752, 0.762, 0.952, 0.763, 0.771, 0.950, 0.774, 0.781, 0.948, + 0.786, 0.790, 0.947, 0.797, 0.800, 0.945, 0.809, 0.810, 0.945, 0.820, + 0.819, 0.944, 0.832, 0.829, 0.943, 0.844, 0.839, 0.943, 0.856, 0.849, + 0.943, 0.868, 0.860, 0.944, 0.880, 0.870, 0.945, 0.893, 0.880, 0.946, + 0.905, 0.891, 0.947, 0.918, 0.902, 0.949, 0.931, 0.913, 0.951, 0.944, + 0.924, 0.954, 0.957, 0.936, 0.957, 0.971, 0.947, 0.961, 0.983, 0.958, + 0.964, 0.991, 0.963, 0.962, 0.990, 0.957, 0.946, 0.983, 0.946, 0.924, + 0.975, 0.935, 0.900, 0.967, 0.923, 0.876, 0.959, 0.912, 0.851, 0.951, + 0.901, 0.827, 0.943, 0.890, 0.803, 0.936, 0.880, 0.779, 0.929, 0.869, + 0.755, 0.922, 0.859, 0.732, 0.915, 0.849, 0.708, 0.909, 0.839, 0.684, + 0.902, 0.829, 0.661, 0.896, 0.819, 0.637, 0.890, 0.809, 0.614, 0.884, + 0.800, 0.591, 0.878, 0.790, 0.567, 0.872, 0.780, 0.544, 0.866, 0.771, + 0.521, 0.861, 0.762, 0.498, 0.855, 0.752, 0.475, 0.850, 0.743, 0.452, + 0.844, 0.734, 0.429, 0.839, 0.725, 0.406, 0.834, 0.715, 0.382, 0.828, + 0.706, 0.359, 0.823, 0.697, 0.335, 0.818, 0.688, 0.311, 0.813, 0.679, + 0.287, 0.808, 0.670, 0.262, 0.803, 0.662, 0.236, 0.798, 0.653, 0.210, + 0.635, 0.646, 0.998, 0.645, 0.656, 0.992, 0.655, 0.665, 0.987, 0.665, + 0.674, 0.983, 0.675, 0.684, 0.978, 0.685, 0.693, 0.974, 0.696, 0.702, + 0.970, 0.706, 0.711, 0.966, 0.717, 0.721, 0.963, 0.727, 0.730, 0.960, + 0.738, 0.739, 0.957, 0.749, 0.748, 0.955, 0.760, 0.758, 0.952, 0.771, + 0.767, 0.950, 0.782, 0.777, 0.948, 0.793, 0.786, 0.947, 0.804, 0.796, + 0.946, 0.816, 0.805, 0.945, 0.827, 0.815, 0.944, 0.839, 0.825, 0.943, + 0.850, 0.835, 0.943, 0.862, 0.845, 0.943, 0.874, 0.855, 0.943, 0.886, + 0.865, 0.944, 0.898, 0.875, 0.945, 0.910, 0.886, 0.946, 0.923, 0.896, + 0.948, 0.935, 0.907, 0.949, 0.947, 0.917, 0.951, 0.959, 0.927, 0.953, + 0.970, 0.937, 0.955, 0.980, 0.944, 0.955, 0.987, 0.946, 0.949, 0.989, + 0.942, 0.936, 0.985, 0.935, 0.916, 0.980, 0.925, 0.894, 0.973, 0.915, + 0.871, 0.966, 0.904, 0.847, 0.959, 0.894, 0.824, 0.952, 0.883, 0.800, + 0.945, 0.873, 0.776, 0.938, 0.863, 0.752, 0.932, 0.853, 0.729, 0.925, + 0.843, 0.705, 0.919, 0.833, 0.682, 0.912, 0.823, 0.658, 0.906, 0.813, + 0.635, 0.900, 0.803, 0.611, 0.894, 0.794, 0.588, 0.888, 0.784, 0.565, + 0.882, 0.775, 0.542, 0.876, 0.765, 0.519, 0.871, 0.756, 0.496, 0.865, + 0.747, 0.473, 0.859, 0.738, 0.450, 0.854, 0.728, 0.427, 0.848, 0.719, + 0.404, 0.843, 0.710, 0.380, 0.838, 0.701, 0.357, 0.833, 0.692, 0.333, + 0.827, 0.683, 0.310, 0.822, 0.674, 0.285, 0.817, 0.665, 0.260, 0.812, + 0.656, 0.235, 0.807, 0.648, 0.208, 0.644, 0.642, 0.998, 0.654, 0.651, + 0.993, 0.664, 0.660, 0.988, 0.674, 0.670, 0.983, 0.684, 0.679, 0.978, + 0.694, 0.688, 0.974, 0.704, 0.697, 0.970, 0.715, 0.707, 0.967, 0.725, + 0.716, 0.963, 0.735, 0.725, 0.960, 0.746, 0.735, 0.957, 0.757, 0.744, + 0.955, 0.767, 0.753, 0.952, 0.778, 0.763, 0.950, 0.789, 0.772, 0.948, + 0.800, 0.781, 0.947, 0.811, 0.791, 0.945, 0.822, 0.801, 0.944, 0.833, + 0.810, 0.943, 0.845, 0.820, 0.943, 0.856, 0.830, 0.942, 0.868, 0.839, + 0.942, 0.879, 0.849, 0.942, 0.891, 0.859, 0.943, 0.902, 0.869, 0.943, + 0.914, 0.879, 0.944, 0.926, 0.889, 0.945, 0.937, 0.899, 0.946, 0.949, + 0.908, 0.947, 0.959, 0.917, 0.948, 0.969, 0.924, 0.947, 0.978, 0.929, + 0.944, 0.984, 0.930, 0.937, 0.986, 0.927, 0.924, 0.986, 0.921, 0.907, + 0.982, 0.913, 0.887, 0.978, 0.904, 0.865, 0.972, 0.895, 0.842, 0.966, + 0.885, 0.819, 0.959, 0.875, 0.795, 0.953, 0.865, 0.772, 0.946, 0.855, + 0.749, 0.940, 0.846, 0.725, 0.934, 0.836, 0.702, 0.927, 0.826, 0.678, + 0.921, 0.816, 0.655, 0.915, 0.807, 0.632, 0.909, 0.797, 0.609, 0.903, + 0.788, 0.586, 0.897, 0.778, 0.562, 0.891, 0.769, 0.539, 0.886, 0.759, + 0.516, 0.880, 0.750, 0.493, 0.874, 0.741, 0.471, 0.869, 0.732, 0.448, + 0.863, 0.723, 0.425, 0.858, 0.713, 0.402, 0.852, 0.704, 0.378, 0.847, + 0.695, 0.355, 0.842, 0.686, 0.331, 0.836, 0.677, 0.308, 0.831, 0.669, + 0.283, 0.826, 0.660, 0.258, 0.821, 0.651, 0.233, 0.815, 0.642, 0.206, + 0.653, 0.636, 0.998, 0.663, 0.646, 0.993, 0.673, 0.655, 0.988, 0.682, + 0.665, 0.983, 0.692, 0.674, 0.979, 0.702, 0.683, 0.974, 0.712, 0.692, + 0.970, 0.722, 0.702, 0.967, 0.733, 0.711, 0.963, 0.743, 0.720, 0.960, + 0.753, 0.730, 0.957, 0.764, 0.739, 0.954, 0.774, 0.748, 0.952, 0.785, + 0.757, 0.950, 0.796, 0.767, 0.948, 0.806, 0.776, 0.946, 0.817, 0.786, + 0.945, 0.828, 0.795, 0.943, 0.839, 0.804, 0.942, 0.850, 0.814, 0.941, + 0.861, 0.824, 0.941, 0.872, 0.833, 0.940, 0.884, 0.843, 0.940, 0.895, + 0.852, 0.940, 0.906, 0.862, 0.940, 0.917, 0.871, 0.941, 0.928, 0.880, + 0.941, 0.939, 0.889, 0.941, 0.949, 0.897, 0.941, 0.959, 0.904, 0.940, + 0.968, 0.910, 0.938, 0.975, 0.914, 0.933, 0.981, 0.914, 0.925, 0.984, + 0.912, 0.913, 0.985, 0.907, 0.897, 0.983, 0.900, 0.878, 0.980, 0.893, + 0.857, 0.976, 0.884, 0.836, 0.971, 0.875, 0.813, 0.965, 0.866, 0.790, + 0.959, 0.856, 0.767, 0.954, 0.847, 0.744, 0.947, 0.837, 0.721, 0.941, + 0.828, 0.698, 0.935, 0.818, 0.675, 0.929, 0.809, 0.652, 0.923, 0.800, + 0.629, 0.917, 0.790, 0.605, 0.912, 0.781, 0.582, 0.906, 0.771, 0.560, + 0.900, 0.762, 0.537, 0.894, 0.753, 0.514, 0.889, 0.744, 0.491, 0.883, + 0.735, 0.468, 0.877, 0.725, 0.445, 0.872, 0.716, 0.422, 0.866, 0.707, + 0.399, 0.861, 0.698, 0.376, 0.856, 0.689, 0.353, 0.850, 0.680, 0.329, + 0.845, 0.672, 0.305, 0.840, 0.663, 0.281, 0.834, 0.654, 0.256, 0.829, + 0.645, 0.231, 0.824, 0.636, 0.204, 0.662, 0.631, 0.998, 0.672, 0.641, + 0.993, 0.681, 0.650, 0.988, 0.691, 0.659, 0.983, 0.700, 0.669, 0.979, + 0.710, 0.678, 0.974, 0.720, 0.687, 0.970, 0.730, 0.696, 0.966, 0.740, + 0.706, 0.963, 0.750, 0.715, 0.960, 0.760, 0.724, 0.957, 0.771, 0.733, + 0.954, 0.781, 0.742, 0.951, 0.791, 0.752, 0.949, 0.802, 0.761, 0.947, + 0.812, 0.770, 0.945, 0.823, 0.779, 0.943, 0.834, 0.789, 0.942, 0.844, + 0.798, 0.941, 0.855, 0.807, 0.940, 0.866, 0.817, 0.939, 0.877, 0.826, + 0.938, 0.887, 0.835, 0.938, 0.898, 0.844, 0.937, 0.909, 0.853, 0.937, + 0.919, 0.862, 0.937, 0.930, 0.870, 0.936, 0.940, 0.878, 0.936, 0.950, + 0.885, 0.934, 0.958, 0.891, 0.932, 0.967, 0.896, 0.928, 0.974, 0.898, + 0.922, 0.979, 0.899, 0.914, 0.982, 0.897, 0.902, 0.984, 0.893, 0.886, + 0.984, 0.887, 0.869, 0.982, 0.880, 0.849, 0.979, 0.872, 0.828, 0.975, + 0.864, 0.807, 0.970, 0.856, 0.785, 0.965, 0.847, 0.762, 0.959, 0.838, + 0.739, 0.954, 0.829, 0.717, 0.948, 0.819, 0.694, 0.943, 0.810, 0.671, + 0.937, 0.801, 0.648, 0.931, 0.792, 0.625, 0.925, 0.782, 0.602, 0.919, + 0.773, 0.579, 0.914, 0.764, 0.556, 0.908, 0.755, 0.533, 0.902, 0.746, + 0.511, 0.897, 0.737, 0.488, 0.891, 0.728, 0.465, 0.886, 0.719, 0.442, + 0.880, 0.710, 0.420, 0.875, 0.701, 0.397, 0.869, 0.692, 0.374, 0.864, + 0.683, 0.350, 0.858, 0.674, 0.327, 0.853, 0.665, 0.303, 0.848, 0.657, + 0.279, 0.842, 0.648, 0.254, 0.837, 0.639, 0.229, 0.832, 0.630, 0.202, + 0.671, 0.625, 0.998, 0.680, 0.635, 0.993, 0.689, 0.644, 0.988, 0.698, + 0.654, 0.983, 0.708, 0.663, 0.978, 0.718, 0.672, 0.974, 0.727, 0.681, + 0.970, 0.737, 0.691, 0.966, 0.747, 0.700, 0.962, 0.757, 0.709, 0.959, + 0.767, 0.718, 0.956, 0.777, 0.727, 0.953, 0.787, 0.736, 0.950, 0.797, + 0.745, 0.948, 0.807, 0.755, 0.946, 0.818, 0.764, 0.944, 0.828, 0.773, + 0.942, 0.839, 0.782, 0.940, 0.849, 0.791, 0.939, 0.859, 0.800, 0.938, + 0.870, 0.809, 0.937, 0.880, 0.818, 0.936, 0.891, 0.827, 0.935, 0.901, + 0.835, 0.934, 0.911, 0.844, 0.933, 0.921, 0.852, 0.932, 0.931, 0.859, + 0.931, 0.941, 0.866, 0.929, 0.950, 0.873, 0.927, 0.958, 0.878, 0.923, + 0.966, 0.881, 0.919, 0.972, 0.883, 0.912, 0.977, 0.883, 0.903, 0.981, + 0.882, 0.891, 0.983, 0.878, 0.876, 0.984, 0.873, 0.859, 0.983, 0.867, + 0.841, 0.980, 0.860, 0.821, 0.977, 0.853, 0.800, 0.974, 0.845, 0.778, + 0.969, 0.836, 0.756, 0.964, 0.828, 0.734, 0.959, 0.819, 0.712, 0.954, + 0.810, 0.689, 0.949, 0.801, 0.666, 0.943, 0.792, 0.644, 0.938, 0.783, + 0.621, 0.932, 0.774, 0.598, 0.927, 0.765, 0.575, 0.921, 0.756, 0.553, + 0.916, 0.747, 0.530, 0.910, 0.738, 0.507, 0.904, 0.729, 0.485, 0.899, + 0.721, 0.462, 0.893, 0.712, 0.439, 0.888, 0.703, 0.417, 0.882, 0.694, + 0.394, 0.877, 0.685, 0.371, 0.871, 0.676, 0.348, 0.866, 0.668, 0.324, + 0.861, 0.659, 0.301, 0.855, 0.650, 0.277, 0.850, 0.641, 0.252, 0.845, + 0.633, 0.226, 0.839, 0.624, 0.200, 0.679, 0.619, 0.998, 0.688, 0.629, + 0.993, 0.697, 0.638, 0.988, 0.706, 0.648, 0.983, 0.715, 0.657, 0.978, + 0.725, 0.666, 0.974, 0.734, 0.675, 0.969, 0.744, 0.684, 0.965, 0.754, + 0.693, 0.962, 0.763, 0.703, 0.958, 0.773, 0.712, 0.955, 0.783, 0.721, + 0.952, 0.793, 0.730, 0.949, 0.803, 0.739, 0.947, 0.813, 0.748, 0.944, + 0.823, 0.757, 0.942, 0.833, 0.766, 0.940, 0.843, 0.774, 0.938, 0.853, + 0.783, 0.937, 0.863, 0.792, 0.935, 0.874, 0.801, 0.934, 0.884, 0.809, + 0.932, 0.894, 0.818, 0.931, 0.904, 0.826, 0.930, 0.913, 0.833, 0.928, + 0.923, 0.841, 0.927, 0.932, 0.848, 0.925, 0.941, 0.854, 0.922, 0.950, + 0.859, 0.919, 0.957, 0.864, 0.915, 0.965, 0.867, 0.909, 0.971, 0.868, + 0.901, 0.976, 0.868, 0.892, 0.980, 0.867, 0.880, 0.982, 0.863, 0.866, + 0.983, 0.859, 0.849, 0.983, 0.854, 0.832, 0.982, 0.847, 0.812, 0.979, + 0.840, 0.792, 0.976, 0.833, 0.771, 0.973, 0.825, 0.750, 0.969, 0.817, + 0.728, 0.964, 0.809, 0.706, 0.959, 0.800, 0.684, 0.954, 0.792, 0.661, + 0.949, 0.783, 0.639, 0.944, 0.774, 0.617, 0.939, 0.766, 0.594, 0.933, + 0.757, 0.572, 0.928, 0.748, 0.549, 0.922, 0.739, 0.527, 0.917, 0.731, + 0.504, 0.911, 0.722, 0.481, 0.906, 0.713, 0.459, 0.901, 0.704, 0.436, + 0.895, 0.695, 0.414, 0.890, 0.687, 0.391, 0.884, 0.678, 0.368, 0.879, + 0.669, 0.345, 0.873, 0.661, 0.322, 0.868, 0.652, 0.298, 0.863, 0.643, + 0.274, 0.857, 0.635, 0.249, 0.852, 0.626, 0.224, 0.846, 0.617, 0.197, + 0.686, 0.613, 0.998, 0.695, 0.622, 0.993, 0.704, 0.632, 0.987, 0.713, + 0.641, 0.982, 0.722, 0.650, 0.977, 0.732, 0.660, 0.973, 0.741, 0.669, + 0.969, 0.750, 0.678, 0.965, 0.760, 0.687, 0.961, 0.769, 0.696, 0.957, + 0.779, 0.705, 0.954, 0.789, 0.714, 0.951, 0.798, 0.723, 0.948, 0.808, + 0.731, 0.945, 0.818, 0.740, 0.943, 0.828, 0.749, 0.940, 0.838, 0.758, + 0.938, 0.847, 0.766, 0.936, 0.857, 0.775, 0.934, 0.867, 0.783, 0.932, + 0.877, 0.792, 0.930, 0.887, 0.800, 0.929, 0.896, 0.808, 0.927, 0.906, + 0.815, 0.925, 0.915, 0.823, 0.923, 0.924, 0.829, 0.921, 0.933, 0.836, + 0.918, 0.942, 0.841, 0.915, 0.950, 0.846, 0.911, 0.957, 0.850, 0.906, + 0.964, 0.852, 0.899, 0.970, 0.853, 0.891, 0.975, 0.853, 0.881, 0.979, + 0.852, 0.869, 0.981, 0.849, 0.855, 0.983, 0.845, 0.840, 0.983, 0.840, + 0.822, 0.982, 0.834, 0.804, 0.981, 0.828, 0.784, 0.978, 0.821, 0.764, + 0.975, 0.814, 0.743, 0.972, 0.806, 0.722, 0.968, 0.798, 0.700, 0.964, + 0.790, 0.678, 0.959, 0.782, 0.656, 0.954, 0.773, 0.634, 0.949, 0.765, + 0.612, 0.944, 0.757, 0.590, 0.939, 0.748, 0.567, 0.934, 0.739, 0.545, + 0.929, 0.731, 0.523, 0.923, 0.722, 0.500, 0.918, 0.714, 0.478, 0.913, + 0.705, 0.456, 0.907, 0.696, 0.433, 0.902, 0.688, 0.411, 0.896, 0.679, + 0.388, 0.891, 0.670, 0.365, 0.886, 0.662, 0.342, 0.880, 0.653, 0.319, + 0.875, 0.645, 0.295, 0.869, 0.636, 0.271, 0.864, 0.628, 0.247, 0.859, + 0.619, 0.221, 0.853, 0.611, 0.195, 0.694, 0.606, 0.998, 0.703, 0.616, + 0.992, 0.711, 0.625, 0.987, 0.720, 0.634, 0.982, 0.729, 0.644, 0.977, + 0.738, 0.653, 0.972, 0.747, 0.662, 0.968, 0.757, 0.671, 0.964, 0.766, + 0.680, 0.960, 0.775, 0.689, 0.956, 0.785, 0.698, 0.953, 0.794, 0.706, + 0.949, 0.804, 0.715, 0.946, 0.813, 0.724, 0.943, 0.823, 0.732, 0.941, + 0.832, 0.741, 0.938, 0.842, 0.749, 0.936, 0.851, 0.758, 0.933, 0.861, + 0.766, 0.931, 0.870, 0.774, 0.929, 0.880, 0.782, 0.927, 0.889, 0.790, + 0.924, 0.899, 0.797, 0.922, 0.908, 0.805, 0.920, 0.917, 0.811, 0.917, + 0.925, 0.818, 0.914, 0.934, 0.823, 0.911, 0.942, 0.828, 0.907, 0.950, + 0.832, 0.902, 0.957, 0.836, 0.896, 0.963, 0.838, 0.889, 0.969, 0.839, + 0.881, 0.974, 0.838, 0.871, 0.978, 0.837, 0.859, 0.980, 0.834, 0.845, + 0.982, 0.831, 0.830, 0.983, 0.826, 0.813, 0.983, 0.821, 0.795, 0.982, + 0.815, 0.776, 0.980, 0.809, 0.757, 0.978, 0.802, 0.736, 0.975, 0.794, + 0.715, 0.971, 0.787, 0.694, 0.967, 0.779, 0.673, 0.963, 0.771, 0.651, + 0.959, 0.763, 0.629, 0.954, 0.755, 0.607, 0.949, 0.747, 0.585, 0.944, + 0.739, 0.563, 0.939, 0.730, 0.541, 0.934, 0.722, 0.519, 0.929, 0.714, + 0.496, 0.924, 0.705, 0.474, 0.919, 0.697, 0.452, 0.913, 0.688, 0.430, + 0.908, 0.680, 0.407, 0.903, 0.671, 0.385, 0.897, 0.663, 0.362, 0.892, + 0.654, 0.339, 0.887, 0.646, 0.316, 0.881, 0.637, 0.293, 0.876, 0.629, + 0.269, 0.870, 0.620, 0.244, 0.865, 0.612, 0.219, 0.860, 0.604, 0.192, + 0.701, 0.599, 0.997, 0.710, 0.609, 0.992, 0.718, 0.618, 0.986, 0.727, + 0.627, 0.981, 0.736, 0.636, 0.976, 0.745, 0.645, 0.971, 0.754, 0.655, + 0.967, 0.763, 0.663, 0.963, 0.772, 0.672, 0.959, 0.781, 0.681, 0.955, + 0.790, 0.690, 0.951, 0.799, 0.699, 0.948, 0.808, 0.707, 0.944, 0.818, + 0.716, 0.941, 0.827, 0.724, 0.938, 0.836, 0.732, 0.935, 0.846, 0.741, + 0.933, 0.855, 0.749, 0.930, 0.864, 0.757, 0.928, 0.874, 0.765, 0.925, + 0.883, 0.772, 0.923, 0.892, 0.780, 0.920, 0.901, 0.787, 0.917, 0.910, + 0.793, 0.914, 0.918, 0.800, 0.911, 0.927, 0.805, 0.908, 0.935, 0.811, + 0.904, 0.942, 0.815, 0.899, 0.950, 0.819, 0.894, 0.956, 0.821, 0.887, + 0.963, 0.823, 0.880, 0.968, 0.824, 0.871, 0.973, 0.824, 0.860, 0.977, + 0.822, 0.849, 0.980, 0.820, 0.835, 0.982, 0.817, 0.820, 0.983, 0.812, + 0.804, 0.983, 0.808, 0.786, 0.983, 0.802, 0.768, 0.981, 0.796, 0.749, + 0.979, 0.789, 0.729, 0.977, 0.783, 0.709, 0.974, 0.776, 0.688, 0.970, + 0.768, 0.667, 0.967, 0.761, 0.645, 0.963, 0.753, 0.624, 0.958, 0.745, + 0.602, 0.954, 0.737, 0.580, 0.949, 0.729, 0.558, 0.944, 0.721, 0.536, + 0.939, 0.713, 0.514, 0.934, 0.704, 0.492, 0.929, 0.696, 0.470, 0.924, + 0.688, 0.448, 0.919, 0.680, 0.426, 0.914, 0.671, 0.404, 0.908, 0.663, + 0.381, 0.903, 0.655, 0.359, 0.898, 0.646, 0.336, 0.893, 0.638, 0.313, + 0.887, 0.629, 0.290, 0.882, 0.621, 0.266, 0.876, 0.613, 0.241, 0.871, + 0.604, 0.216, 0.866, 0.596, 0.189, 0.708, 0.592, 0.997, 0.716, 0.601, + 0.991, 0.725, 0.611, 0.985, 0.733, 0.620, 0.980, 0.742, 0.629, 0.975, + 0.751, 0.638, 0.970, 0.759, 0.647, 0.966, 0.768, 0.656, 0.961, 0.777, + 0.665, 0.957, 0.786, 0.673, 0.953, 0.795, 0.682, 0.949, 0.804, 0.690, + 0.946, 0.813, 0.699, 0.942, 0.822, 0.707, 0.939, 0.831, 0.715, 0.936, + 0.840, 0.723, 0.933, 0.849, 0.731, 0.930, 0.859, 0.739, 0.927, 0.868, + 0.747, 0.924, 0.876, 0.754, 0.921, 0.885, 0.762, 0.918, 0.894, 0.769, + 0.915, 0.903, 0.775, 0.912, 0.911, 0.782, 0.909, 0.920, 0.787, 0.905, + 0.928, 0.793, 0.901, 0.935, 0.798, 0.896, 0.943, 0.802, 0.891, 0.950, + 0.805, 0.885, 0.956, 0.807, 0.878, 0.962, 0.809, 0.870, 0.967, 0.809, + 0.861, 0.972, 0.809, 0.850, 0.976, 0.808, 0.838, 0.979, 0.805, 0.825, + 0.981, 0.802, 0.810, 0.983, 0.799, 0.795, 0.983, 0.794, 0.778, 0.983, + 0.789, 0.760, 0.982, 0.783, 0.741, 0.981, 0.777, 0.721, 0.979, 0.771, + 0.701, 0.976, 0.764, 0.681, 0.973, 0.757, 0.660, 0.970, 0.750, 0.639, + 0.966, 0.742, 0.618, 0.962, 0.735, 0.597, 0.958, 0.727, 0.575, 0.953, + 0.719, 0.553, 0.949, 0.711, 0.532, 0.944, 0.703, 0.510, 0.939, 0.695, + 0.488, 0.934, 0.687, 0.466, 0.929, 0.679, 0.444, 0.924, 0.671, 0.422, + 0.919, 0.663, 0.400, 0.914, 0.654, 0.378, 0.909, 0.646, 0.355, 0.903, + 0.638, 0.333, 0.898, 0.630, 0.310, 0.893, 0.621, 0.287, 0.887, 0.613, + 0.263, 0.882, 0.605, 0.238, 0.877, 0.597, 0.213, 0.871, 0.589, 0.186, + 0.715, 0.584, 0.996, 0.723, 0.593, 0.990, 0.731, 0.603, 0.984, 0.739, + 0.612, 0.979, 0.748, 0.621, 0.974, 0.756, 0.630, 0.969, 0.765, 0.639, + 0.964, 0.774, 0.648, 0.960, 0.782, 0.656, 0.955, 0.791, 0.665, 0.951, + 0.800, 0.673, 0.947, 0.809, 0.682, 0.943, 0.818, 0.690, 0.940, 0.826, + 0.698, 0.936, 0.835, 0.706, 0.933, 0.844, 0.714, 0.930, 0.853, 0.722, + 0.926, 0.862, 0.729, 0.923, 0.871, 0.737, 0.920, 0.879, 0.744, 0.917, + 0.888, 0.751, 0.913, 0.896, 0.758, 0.910, 0.905, 0.764, 0.906, 0.913, + 0.770, 0.903, 0.921, 0.775, 0.898, 0.929, 0.780, 0.894, 0.936, 0.784, + 0.889, 0.943, 0.788, 0.883, 0.950, 0.791, 0.877, 0.956, 0.793, 0.869, + 0.962, 0.794, 0.861, 0.967, 0.795, 0.851, 0.971, 0.794, 0.841, 0.975, + 0.793, 0.829, 0.978, 0.791, 0.815, 0.981, 0.788, 0.801, 0.982, 0.785, + 0.785, 0.983, 0.780, 0.769, 0.983, 0.776, 0.751, 0.983, 0.770, 0.733, + 0.982, 0.764, 0.714, 0.980, 0.758, 0.694, 0.978, 0.752, 0.674, 0.975, + 0.745, 0.654, 0.972, 0.738, 0.633, 0.969, 0.731, 0.612, 0.965, 0.724, + 0.591, 0.961, 0.716, 0.570, 0.957, 0.709, 0.548, 0.953, 0.701, 0.527, + 0.948, 0.693, 0.505, 0.943, 0.685, 0.484, 0.939, 0.678, 0.462, 0.934, + 0.670, 0.440, 0.929, 0.662, 0.418, 0.924, 0.654, 0.396, 0.919, 0.646, + 0.374, 0.914, 0.637, 0.352, 0.908, 0.629, 0.329, 0.903, 0.621, 0.307, + 0.898, 0.613, 0.283, 0.893, 0.605, 0.260, 0.887, 0.597, 0.235, 0.882, + 0.589, 0.210, 0.876, 0.581, 0.183, 0.721, 0.576, 0.995, 0.729, 0.585, + 0.989, 0.737, 0.595, 0.983, 0.745, 0.604, 0.978, 0.754, 0.613, 0.973, + 0.762, 0.622, 0.968, 0.770, 0.631, 0.963, 0.779, 0.639, 0.958, 0.787, + 0.648, 0.954, 0.796, 0.656, 0.949, 0.805, 0.665, 0.945, 0.813, 0.673, + 0.941, 0.822, 0.681, 0.937, 0.830, 0.689, 0.933, 0.839, 0.697, 0.930, + 0.848, 0.704, 0.926, 0.856, 0.712, 0.923, 0.865, 0.719, 0.919, 0.873, + 0.726, 0.916, 0.882, 0.733, 0.912, 0.890, 0.740, 0.908, 0.898, 0.746, + 0.905, 0.906, 0.752, 0.901, 0.914, 0.757, 0.896, 0.922, 0.762, 0.892, + 0.929, 0.767, 0.887, 0.937, 0.771, 0.881, 0.943, 0.774, 0.875, 0.950, + 0.777, 0.868, 0.956, 0.779, 0.860, 0.961, 0.780, 0.851, 0.966, 0.780, + 0.842, 0.971, 0.780, 0.831, 0.975, 0.779, 0.819, 0.978, 0.777, 0.806, + 0.980, 0.774, 0.791, 0.982, 0.771, 0.776, 0.983, 0.767, 0.760, 0.984, + 0.762, 0.742, 0.983, 0.757, 0.725, 0.983, 0.752, 0.706, 0.981, 0.746, + 0.687, 0.979, 0.740, 0.667, 0.977, 0.733, 0.647, 0.974, 0.727, 0.627, + 0.971, 0.720, 0.606, 0.968, 0.713, 0.585, 0.964, 0.706, 0.564, 0.960, + 0.698, 0.543, 0.956, 0.691, 0.522, 0.952, 0.683, 0.501, 0.947, 0.676, + 0.479, 0.943, 0.668, 0.458, 0.938, 0.660, 0.436, 0.933, 0.652, 0.414, + 0.928, 0.644, 0.392, 0.923, 0.636, 0.370, 0.918, 0.629, 0.348, 0.913, + 0.621, 0.326, 0.908, 0.613, 0.303, 0.903, 0.605, 0.280, 0.897, 0.597, + 0.257, 0.892, 0.589, 0.232, 0.887, 0.581, 0.207, 0.881, 0.573, 0.180, + 0.727, 0.568, 0.994, 0.735, 0.577, 0.988, 0.743, 0.586, 0.982, 0.751, + 0.595, 0.977, 0.759, 0.604, 0.971, 0.767, 0.613, 0.966, 0.776, 0.622, + 0.961, 0.784, 0.630, 0.956, 0.792, 0.639, 0.951, 0.801, 0.647, 0.947, + 0.809, 0.655, 0.943, 0.817, 0.663, 0.938, 0.826, 0.671, 0.934, 0.834, + 0.679, 0.930, 0.843, 0.687, 0.927, 0.851, 0.694, 0.923, 0.859, 0.702, + 0.919, 0.868, 0.709, 0.915, 0.876, 0.715, 0.911, 0.884, 0.722, 0.907, + 0.892, 0.728, 0.903, 0.900, 0.734, 0.899, 0.908, 0.740, 0.895, 0.916, + 0.745, 0.890, 0.923, 0.750, 0.885, 0.930, 0.754, 0.879, 0.937, 0.758, + 0.873, 0.944, 0.761, 0.867, 0.950, 0.763, 0.859, 0.956, 0.765, 0.851, + 0.961, 0.766, 0.842, 0.966, 0.766, 0.832, 0.970, 0.766, 0.821, 0.974, + 0.764, 0.809, 0.977, 0.762, 0.796, 0.980, 0.760, 0.782, 0.982, 0.757, + 0.767, 0.983, 0.753, 0.751, 0.984, 0.749, 0.734, 0.984, 0.744, 0.716, + 0.983, 0.739, 0.698, 0.982, 0.733, 0.679, 0.980, 0.727, 0.660, 0.978, + 0.721, 0.640, 0.976, 0.715, 0.620, 0.973, 0.708, 0.600, 0.970, 0.701, + 0.579, 0.967, 0.694, 0.559, 0.963, 0.687, 0.538, 0.959, 0.680, 0.517, + 0.955, 0.673, 0.496, 0.951, 0.665, 0.474, 0.946, 0.658, 0.453, 0.942, + 0.650, 0.432, 0.937, 0.643, 0.410, 0.932, 0.635, 0.388, 0.927, 0.627, + 0.367, 0.922, 0.619, 0.345, 0.917, 0.612, 0.322, 0.912, 0.604, 0.300, + 0.907, 0.596, 0.277, 0.902, 0.588, 0.253, 0.897, 0.580, 0.229, 0.891, + 0.572, 0.204, 0.886, 0.564, 0.177, 0.733, 0.559, 0.993, 0.741, 0.568, + 0.987, 0.749, 0.577, 0.981, 0.757, 0.587, 0.975, 0.765, 0.595, 0.970, + 0.773, 0.604, 0.964, 0.781, 0.613, 0.959, 0.789, 0.621, 0.954, 0.797, + 0.630, 0.949, 0.805, 0.638, 0.945, 0.813, 0.646, 0.940, 0.821, 0.654, + 0.936, 0.830, 0.662, 0.931, 0.838, 0.669, 0.927, 0.846, 0.677, 0.923, + 0.854, 0.684, 0.919, 0.862, 0.691, 0.915, 0.870, 0.698, 0.911, 0.879, + 0.704, 0.907, 0.886, 0.711, 0.902, 0.894, 0.717, 0.898, 0.902, 0.722, + 0.893, 0.910, 0.727, 0.889, 0.917, 0.732, 0.883, 0.924, 0.737, 0.878, + 0.931, 0.741, 0.872, 0.938, 0.744, 0.866, 0.944, 0.747, 0.859, 0.950, + 0.749, 0.851, 0.956, 0.751, 0.842, 0.961, 0.751, 0.833, 0.966, 0.752, + 0.823, 0.970, 0.751, 0.812, 0.974, 0.750, 0.800, 0.977, 0.748, 0.787, + 0.979, 0.746, 0.773, 0.981, 0.743, 0.758, 0.983, 0.739, 0.742, 0.984, + 0.735, 0.725, 0.984, 0.731, 0.708, 0.983, 0.726, 0.690, 0.983, 0.721, + 0.672, 0.981, 0.715, 0.653, 0.980, 0.709, 0.633, 0.977, 0.703, 0.614, + 0.975, 0.697, 0.594, 0.972, 0.690, 0.573, 0.969, 0.683, 0.553, 0.965, + 0.676, 0.532, 0.962, 0.669, 0.512, 0.958, 0.662, 0.491, 0.954, 0.655, + 0.470, 0.949, 0.648, 0.448, 0.945, 0.640, 0.427, 0.941, 0.633, 0.406, + 0.936, 0.625, 0.384, 0.931, 0.618, 0.363, 0.926, 0.610, 0.341, 0.921, + 0.602, 0.319, 0.916, 0.595, 0.296, 0.911, 0.587, 0.273, 0.906, 0.579, + 0.250, 0.901, 0.571, 0.226, 0.896, 0.563, 0.201, 0.890, 0.556, 0.174, + 0.739, 0.550, 0.992, 0.747, 0.559, 0.986, 0.754, 0.568, 0.980, 0.762, + 0.577, 0.974, 0.770, 0.586, 0.968, 0.778, 0.595, 0.962, 0.785, 0.603, + 0.957, 0.793, 0.612, 0.952, 0.801, 0.620, 0.947, 0.809, 0.628, 0.942, + 0.817, 0.636, 0.937, 0.825, 0.644, 0.933, 0.833, 0.651, 0.928, 0.841, + 0.659, 0.924, 0.849, 0.666, 0.919, 0.857, 0.673, 0.915, 0.865, 0.680, + 0.911, 0.873, 0.686, 0.906, 0.881, 0.693, 0.902, 0.889, 0.699, 0.897, + 0.896, 0.705, 0.892, 0.904, 0.710, 0.887, 0.911, 0.715, 0.882, 0.918, + 0.720, 0.877, 0.925, 0.724, 0.871, 0.932, 0.727, 0.865, 0.938, 0.730, + 0.858, 0.944, 0.733, 0.850, 0.950, 0.735, 0.842, 0.956, 0.736, 0.834, + 0.961, 0.737, 0.824, 0.965, 0.737, 0.814, 0.970, 0.737, 0.802, 0.973, + 0.736, 0.790, 0.976, 0.734, 0.777, 0.979, 0.732, 0.763, 0.981, 0.729, + 0.749, 0.982, 0.726, 0.733, 0.983, 0.722, 0.717, 0.984, 0.717, 0.700, + 0.984, 0.713, 0.682, 0.983, 0.708, 0.664, 0.982, 0.702, 0.645, 0.980, + 0.697, 0.626, 0.979, 0.691, 0.607, 0.976, 0.685, 0.587, 0.974, 0.678, + 0.567, 0.971, 0.672, 0.547, 0.967, 0.665, 0.527, 0.964, 0.658, 0.506, + 0.960, 0.651, 0.485, 0.956, 0.644, 0.465, 0.952, 0.637, 0.444, 0.948, + 0.630, 0.423, 0.944, 0.623, 0.401, 0.939, 0.615, 0.380, 0.934, 0.608, + 0.358, 0.930, 0.600, 0.337, 0.925, 0.593, 0.315, 0.920, 0.585, 0.292, + 0.915, 0.578, 0.270, 0.910, 0.570, 0.246, 0.905, 0.562, 0.222, 0.899, + 0.555, 0.197, 0.894, 0.547, 0.171, 0.745, 0.540, 0.991, 0.752, 0.550, + 0.984, 0.760, 0.559, 0.978, 0.767, 0.568, 0.972, 0.775, 0.577, 0.966, + 0.782, 0.585, 0.960, 0.790, 0.594, 0.955, 0.798, 0.602, 0.950, 0.806, + 0.610, 0.944, 0.813, 0.618, 0.939, 0.821, 0.626, 0.934, 0.829, 0.634, + 0.930, 0.837, 0.641, 0.925, 0.845, 0.648, 0.920, 0.852, 0.655, 0.915, + 0.860, 0.662, 0.911, 0.868, 0.669, 0.906, 0.876, 0.675, 0.901, 0.883, + 0.681, 0.897, 0.891, 0.687, 0.892, 0.898, 0.692, 0.887, 0.905, 0.697, + 0.881, 0.912, 0.702, 0.876, 0.919, 0.707, 0.870, 0.926, 0.710, 0.864, + 0.932, 0.714, 0.857, 0.939, 0.717, 0.850, 0.945, 0.719, 0.842, 0.950, + 0.721, 0.834, 0.956, 0.722, 0.825, 0.961, 0.723, 0.815, 0.965, 0.723, + 0.804, 0.969, 0.723, 0.793, 0.973, 0.722, 0.781, 0.976, 0.720, 0.768, + 0.978, 0.718, 0.754, 0.981, 0.715, 0.739, 0.982, 0.712, 0.724, 0.983, + 0.708, 0.708, 0.984, 0.704, 0.691, 0.984, 0.700, 0.674, 0.983, 0.695, + 0.656, 0.982, 0.690, 0.638, 0.981, 0.684, 0.619, 0.979, 0.679, 0.600, + 0.977, 0.673, 0.581, 0.975, 0.666, 0.561, 0.972, 0.660, 0.541, 0.969, + 0.654, 0.521, 0.966, 0.647, 0.501, 0.962, 0.640, 0.480, 0.959, 0.634, + 0.459, 0.955, 0.627, 0.439, 0.951, 0.620, 0.418, 0.946, 0.612, 0.397, + 0.942, 0.605, 0.376, 0.937, 0.598, 0.354, 0.933, 0.591, 0.333, 0.928, + 0.583, 0.311, 0.923, 0.576, 0.289, 0.918, 0.568, 0.266, 0.913, 0.561, + 0.243, 0.908, 0.553, 0.219, 0.903, 0.546, 0.194, 0.898, 0.538, 0.167, + 0.750, 0.531, 0.989, 0.757, 0.540, 0.983, 0.765, 0.549, 0.976, 0.772, + 0.558, 0.970, 0.779, 0.567, 0.964, 0.787, 0.575, 0.958, 0.794, 0.584, + 0.953, 0.802, 0.592, 0.947, 0.810, 0.600, 0.942, 0.817, 0.608, 0.936, + 0.825, 0.615, 0.931, 0.833, 0.623, 0.926, 0.840, 0.630, 0.921, 0.848, + 0.637, 0.916, 0.855, 0.644, 0.911, 0.863, 0.651, 0.907, 0.870, 0.657, + 0.902, 0.878, 0.663, 0.897, 0.885, 0.669, 0.891, 0.893, 0.675, 0.886, + 0.900, 0.680, 0.881, 0.907, 0.685, 0.875, 0.914, 0.689, 0.869, 0.920, + 0.693, 0.863, 0.927, 0.697, 0.857, 0.933, 0.700, 0.850, 0.939, 0.703, + 0.842, 0.945, 0.705, 0.834, 0.950, 0.707, 0.825, 0.956, 0.708, 0.816, + 0.960, 0.709, 0.806, 0.965, 0.709, 0.795, 0.969, 0.708, 0.784, 0.972, + 0.707, 0.772, 0.975, 0.706, 0.759, 0.978, 0.704, 0.745, 0.980, 0.701, + 0.731, 0.982, 0.698, 0.715, 0.983, 0.694, 0.699, 0.984, 0.691, 0.683, + 0.984, 0.686, 0.666, 0.983, 0.682, 0.648, 0.983, 0.677, 0.630, 0.982, + 0.672, 0.612, 0.980, 0.666, 0.593, 0.978, 0.660, 0.574, 0.976, 0.655, + 0.554, 0.973, 0.648, 0.535, 0.971, 0.642, 0.515, 0.967, 0.636, 0.495, + 0.964, 0.629, 0.475, 0.961, 0.623, 0.454, 0.957, 0.616, 0.434, 0.953, + 0.609, 0.413, 0.949, 0.602, 0.392, 0.944, 0.595, 0.371, 0.940, 0.588, + 0.350, 0.936, 0.580, 0.328, 0.931, 0.573, 0.307, 0.926, 0.566, 0.285, + 0.921, 0.559, 0.262, 0.916, 0.551, 0.239, 0.911, 0.544, 0.215, 0.906, + 0.536, 0.190, 0.901, 0.529, 0.164, 0.755, 0.521, 0.988, 0.762, 0.530, + 0.981, 0.770, 0.539, 0.975, 0.777, 0.548, 0.968, 0.784, 0.557, 0.962, + 0.791, 0.565, 0.956, 0.799, 0.573, 0.950, 0.806, 0.582, 0.944, 0.814, + 0.589, 0.939, 0.821, 0.597, 0.933, 0.828, 0.605, 0.928, 0.836, 0.612, + 0.923, 0.843, 0.619, 0.918, 0.851, 0.626, 0.912, 0.858, 0.633, 0.907, + 0.866, 0.639, 0.902, 0.873, 0.645, 0.897, 0.880, 0.651, 0.892, 0.887, + 0.657, 0.886, 0.894, 0.662, 0.881, 0.901, 0.667, 0.875, 0.908, 0.672, + 0.869, 0.915, 0.676, 0.863, 0.921, 0.680, 0.856, 0.928, 0.684, 0.849, + 0.934, 0.687, 0.842, 0.940, 0.689, 0.834, 0.945, 0.691, 0.826, 0.951, + 0.693, 0.817, 0.956, 0.694, 0.807, 0.960, 0.695, 0.797, 0.964, 0.695, + 0.787, 0.968, 0.694, 0.775, 0.972, 0.693, 0.763, 0.975, 0.692, 0.750, + 0.977, 0.690, 0.736, 0.980, 0.687, 0.722, 0.981, 0.684, 0.707, 0.982, + 0.681, 0.691, 0.983, 0.677, 0.675, 0.984, 0.673, 0.658, 0.983, 0.669, + 0.641, 0.983, 0.664, 0.623, 0.982, 0.659, 0.605, 0.980, 0.654, 0.586, + 0.979, 0.648, 0.567, 0.977, 0.642, 0.548, 0.974, 0.637, 0.529, 0.972, + 0.630, 0.509, 0.969, 0.624, 0.489, 0.966, 0.618, 0.469, 0.962, 0.611, + 0.449, 0.959, 0.605, 0.429, 0.955, 0.598, 0.408, 0.951, 0.591, 0.387, + 0.947, 0.584, 0.367, 0.942, 0.577, 0.346, 0.938, 0.570, 0.324, 0.933, + 0.563, 0.303, 0.929, 0.556, 0.281, 0.924, 0.549, 0.258, 0.919, 0.541, + 0.235, 0.914, 0.534, 0.212, 0.909, 0.527, 0.187, 0.904, 0.519, 0.160, + 0.760, 0.510, 0.986, 0.767, 0.520, 0.979, 0.774, 0.529, 0.973, 0.781, + 0.538, 0.966, 0.788, 0.546, 0.960, 0.796, 0.555, 0.954, 0.803, 0.563, + 0.948, 0.810, 0.571, 0.942, 0.817, 0.579, 0.936, 0.825, 0.586, 0.930, + 0.832, 0.594, 0.925, 0.839, 0.601, 0.919, 0.846, 0.608, 0.914, 0.854, + 0.615, 0.908, 0.861, 0.621, 0.903, 0.868, 0.627, 0.897, 0.875, 0.633, + 0.892, 0.882, 0.639, 0.886, 0.889, 0.645, 0.881, 0.896, 0.650, 0.875, + 0.903, 0.655, 0.869, 0.909, 0.659, 0.863, 0.916, 0.663, 0.856, 0.922, + 0.667, 0.849, 0.928, 0.670, 0.842, 0.934, 0.673, 0.834, 0.940, 0.675, + 0.826, 0.945, 0.677, 0.818, 0.951, 0.679, 0.809, 0.955, 0.680, 0.799, + 0.960, 0.680, 0.789, 0.964, 0.680, 0.778, 0.968, 0.680, 0.766, 0.971, + 0.679, 0.754, 0.974, 0.677, 0.741, 0.977, 0.676, 0.727, 0.979, 0.673, + 0.713, 0.981, 0.670, 0.698, 0.982, 0.667, 0.682, 0.983, 0.664, 0.666, + 0.983, 0.660, 0.650, 0.983, 0.655, 0.633, 0.983, 0.651, 0.615, 0.982, + 0.646, 0.597, 0.981, 0.641, 0.579, 0.979, 0.636, 0.560, 0.977, 0.630, + 0.541, 0.975, 0.625, 0.522, 0.973, 0.619, 0.503, 0.970, 0.613, 0.483, + 0.967, 0.606, 0.463, 0.964, 0.600, 0.443, 0.960, 0.594, 0.423, 0.956, + 0.587, 0.403, 0.953, 0.580, 0.383, 0.949, 0.574, 0.362, 0.944, 0.567, + 0.341, 0.940, 0.560, 0.320, 0.936, 0.553, 0.298, 0.931, 0.546, 0.277, + 0.926, 0.539, 0.254, 0.922, 0.532, 0.232, 0.917, 0.524, 0.208, 0.912, + 0.517, 0.183, 0.906, 0.510, 0.156, 0.765, 0.499, 0.985, 0.772, 0.509, + 0.978, 0.779, 0.518, 0.971, 0.786, 0.527, 0.964, 0.793, 0.535, 0.957, + 0.800, 0.544, 0.951, 0.807, 0.552, 0.945, 0.814, 0.560, 0.939, 0.821, + 0.568, 0.933, 0.828, 0.575, 0.927, 0.835, 0.582, 0.921, 0.842, 0.589, + 0.915, 0.849, 0.596, 0.910, 0.856, 0.603, 0.904, 0.863, 0.609, 0.898, + 0.870, 0.615, 0.893, 0.877, 0.621, 0.887, 0.884, 0.627, 0.881, 0.891, + 0.632, 0.875, 0.898, 0.637, 0.869, 0.904, 0.642, 0.863, 0.911, 0.646, + 0.856, 0.917, 0.650, 0.849, 0.923, 0.653, 0.842, 0.929, 0.657, 0.835, + 0.935, 0.659, 0.827, 0.940, 0.662, 0.818, 0.946, 0.663, 0.810, 0.951, + 0.665, 0.800, 0.955, 0.666, 0.790, 0.960, 0.666, 0.780, 0.964, 0.666, + 0.769, 0.967, 0.666, 0.757, 0.971, 0.665, 0.745, 0.974, 0.663, 0.732, + 0.976, 0.662, 0.718, 0.978, 0.659, 0.704, 0.980, 0.657, 0.689, 0.981, + 0.654, 0.674, 0.982, 0.650, 0.658, 0.983, 0.646, 0.642, 0.983, 0.642, + 0.625, 0.983, 0.638, 0.608, 0.982, 0.633, 0.590, 0.981, 0.628, 0.572, + 0.979, 0.623, 0.553, 0.978, 0.618, 0.535, 0.976, 0.612, 0.516, 0.973, + 0.607, 0.497, 0.971, 0.601, 0.477, 0.968, 0.595, 0.458, 0.965, 0.589, + 0.438, 0.961, 0.582, 0.418, 0.958, 0.576, 0.398, 0.954, 0.569, 0.378, + 0.950, 0.563, 0.357, 0.946, 0.556, 0.336, 0.942, 0.549, 0.315, 0.938, + 0.542, 0.294, 0.933, 0.536, 0.273, 0.928, 0.529, 0.250, 0.924, 0.522, + 0.228, 0.919, 0.514, 0.204, 0.914, 0.507, 0.179, 0.909, 0.500, 0.153, + 0.770, 0.488, 0.983, 0.777, 0.498, 0.976, 0.783, 0.507, 0.969, 0.790, + 0.516, 0.962, 0.797, 0.524, 0.955, 0.804, 0.533, 0.948, 0.811, 0.541, + 0.942, 0.817, 0.549, 0.936, 0.824, 0.556, 0.930, 0.831, 0.564, 0.924, + 0.838, 0.571, 0.918, 0.845, 0.578, 0.912, 0.852, 0.584, 0.906, 0.859, + 0.591, 0.900, 0.866, 0.597, 0.894, 0.873, 0.603, 0.888, 0.879, 0.609, + 0.882, 0.886, 0.614, 0.876, 0.893, 0.619, 0.869, 0.899, 0.624, 0.863, + 0.906, 0.629, 0.856, 0.912, 0.633, 0.850, 0.918, 0.637, 0.843, 0.924, + 0.640, 0.835, 0.930, 0.643, 0.827, 0.935, 0.646, 0.819, 0.941, 0.648, + 0.811, 0.946, 0.649, 0.802, 0.951, 0.651, 0.792, 0.955, 0.652, 0.782, + 0.959, 0.652, 0.771, 0.963, 0.652, 0.760, 0.967, 0.652, 0.749, 0.970, + 0.651, 0.736, 0.973, 0.649, 0.723, 0.976, 0.647, 0.710, 0.978, 0.645, + 0.696, 0.980, 0.643, 0.681, 0.981, 0.640, 0.666, 0.982, 0.637, 0.650, + 0.982, 0.633, 0.634, 0.983, 0.629, 0.617, 0.982, 0.625, 0.600, 0.982, + 0.620, 0.582, 0.981, 0.616, 0.565, 0.979, 0.611, 0.546, 0.978, 0.605, + 0.528, 0.976, 0.600, 0.509, 0.974, 0.595, 0.490, 0.971, 0.589, 0.471, + 0.969, 0.583, 0.452, 0.966, 0.577, 0.432, 0.962, 0.571, 0.413, 0.959, + 0.565, 0.393, 0.955, 0.558, 0.373, 0.952, 0.552, 0.352, 0.948, 0.545, + 0.332, 0.943, 0.539, 0.311, 0.939, 0.532, 0.290, 0.935, 0.525, 0.268, + 0.930, 0.518, 0.246, 0.926, 0.511, 0.224, 0.921, 0.504, 0.200, 0.916, + 0.497, 0.175, 0.911, 0.490, 0.149, 0.775, 0.477, 0.981, 0.781, 0.486, + 0.974, 0.788, 0.495, 0.966, 0.794, 0.504, 0.959, 0.801, 0.513, 0.952, + 0.808, 0.521, 0.946, 0.814, 0.529, 0.939, 0.821, 0.537, 0.933, 0.828, + 0.545, 0.926, 0.835, 0.552, 0.920, 0.841, 0.559, 0.914, 0.848, 0.566, + 0.908, 0.855, 0.572, 0.901, 0.862, 0.579, 0.895, 0.868, 0.585, 0.889, + 0.875, 0.591, 0.883, 0.881, 0.596, 0.877, 0.888, 0.601, 0.870, 0.894, + 0.606, 0.864, 0.901, 0.611, 0.857, 0.907, 0.615, 0.850, 0.913, 0.619, + 0.843, 0.919, 0.623, 0.836, 0.925, 0.626, 0.828, 0.930, 0.629, 0.820, + 0.936, 0.632, 0.812, 0.941, 0.634, 0.803, 0.946, 0.635, 0.794, 0.951, + 0.637, 0.784, 0.955, 0.637, 0.774, 0.959, 0.638, 0.763, 0.963, 0.638, + 0.752, 0.967, 0.637, 0.740, 0.970, 0.636, 0.728, 0.973, 0.635, 0.715, + 0.975, 0.633, 0.701, 0.977, 0.631, 0.687, 0.979, 0.629, 0.672, 0.980, + 0.626, 0.657, 0.981, 0.623, 0.642, 0.982, 0.619, 0.626, 0.982, 0.616, + 0.609, 0.982, 0.612, 0.592, 0.981, 0.607, 0.575, 0.981, 0.603, 0.557, + 0.979, 0.598, 0.540, 0.978, 0.593, 0.521, 0.976, 0.588, 0.503, 0.974, + 0.582, 0.484, 0.972, 0.577, 0.465, 0.969, 0.571, 0.446, 0.966, 0.565, + 0.427, 0.963, 0.559, 0.407, 0.960, 0.553, 0.387, 0.956, 0.547, 0.368, + 0.953, 0.541, 0.347, 0.949, 0.534, 0.327, 0.945, 0.528, 0.306, 0.941, + 0.521, 0.285, 0.936, 0.514, 0.264, 0.932, 0.508, 0.242, 0.927, 0.501, + 0.220, 0.922, 0.494, 0.196, 0.918, 0.487, 0.172, 0.913, 0.480, 0.145, + 0.779, 0.465, 0.979, 0.785, 0.474, 0.971, 0.792, 0.484, 0.964, 0.798, + 0.492, 0.957, 0.805, 0.501, 0.950, 0.811, 0.509, 0.943, 0.818, 0.517, + 0.936, 0.824, 0.525, 0.929, 0.831, 0.533, 0.923, 0.838, 0.540, 0.916, + 0.844, 0.547, 0.910, 0.851, 0.554, 0.904, 0.857, 0.560, 0.897, 0.864, + 0.566, 0.891, 0.870, 0.572, 0.884, 0.877, 0.578, 0.878, 0.883, 0.583, + 0.871, 0.890, 0.589, 0.865, 0.896, 0.593, 0.858, 0.902, 0.598, 0.851, + 0.908, 0.602, 0.844, 0.914, 0.606, 0.837, 0.920, 0.609, 0.829, 0.925, + 0.613, 0.821, 0.931, 0.615, 0.813, 0.936, 0.618, 0.804, 0.941, 0.620, + 0.795, 0.946, 0.621, 0.786, 0.950, 0.622, 0.776, 0.955, 0.623, 0.765, + 0.959, 0.624, 0.755, 0.963, 0.624, 0.743, 0.966, 0.623, 0.731, 0.969, + 0.622, 0.719, 0.972, 0.621, 0.706, 0.974, 0.619, 0.693, 0.976, 0.617, + 0.679, 0.978, 0.615, 0.664, 0.979, 0.612, 0.649, 0.980, 0.609, 0.634, + 0.981, 0.606, 0.618, 0.981, 0.602, 0.601, 0.981, 0.598, 0.585, 0.981, + 0.594, 0.568, 0.980, 0.590, 0.550, 0.979, 0.585, 0.533, 0.978, 0.580, + 0.515, 0.976, 0.575, 0.496, 0.974, 0.570, 0.478, 0.972, 0.565, 0.459, + 0.969, 0.559, 0.440, 0.967, 0.553, 0.421, 0.964, 0.547, 0.402, 0.960, + 0.542, 0.382, 0.957, 0.535, 0.362, 0.953, 0.529, 0.342, 0.950, 0.523, + 0.322, 0.946, 0.517, 0.302, 0.942, 0.510, 0.281, 0.937, 0.504, 0.260, + 0.933, 0.497, 0.238, 0.929, 0.490, 0.216, 0.924, 0.484, 0.192, 0.919, + 0.477, 0.168, 0.914, 0.470, 0.141, 0.783, 0.453, 0.977, 0.789, 0.462, + 0.969, 0.796, 0.471, 0.962, 0.802, 0.480, 0.954, 0.808, 0.489, 0.947, + 0.815, 0.497, 0.940, 0.821, 0.505, 0.933, 0.828, 0.513, 0.926, 0.834, + 0.520, 0.919, 0.840, 0.527, 0.913, 0.847, 0.534, 0.906, 0.853, 0.541, + 0.899, 0.860, 0.548, 0.893, 0.866, 0.554, 0.886, 0.873, 0.560, 0.880, + 0.879, 0.565, 0.873, 0.885, 0.570, 0.866, 0.891, 0.575, 0.859, 0.897, + 0.580, 0.852, 0.903, 0.585, 0.845, 0.909, 0.589, 0.838, 0.915, 0.592, + 0.830, 0.921, 0.596, 0.822, 0.926, 0.599, 0.814, 0.931, 0.601, 0.805, + 0.936, 0.604, 0.797, 0.941, 0.606, 0.787, 0.946, 0.607, 0.778, 0.950, + 0.608, 0.768, 0.955, 0.609, 0.757, 0.958, 0.609, 0.746, 0.962, 0.609, + 0.735, 0.965, 0.609, 0.723, 0.968, 0.608, 0.710, 0.971, 0.607, 0.698, + 0.974, 0.605, 0.684, 0.976, 0.603, 0.670, 0.977, 0.601, 0.656, 0.979, + 0.598, 0.641, 0.980, 0.596, 0.626, 0.980, 0.592, 0.610, 0.981, 0.589, + 0.594, 0.981, 0.585, 0.577, 0.980, 0.581, 0.560, 0.980, 0.577, 0.543, + 0.979, 0.572, 0.526, 0.977, 0.568, 0.508, 0.976, 0.563, 0.490, 0.974, + 0.558, 0.471, 0.972, 0.552, 0.453, 0.969, 0.547, 0.434, 0.967, 0.541, + 0.415, 0.964, 0.536, 0.396, 0.961, 0.530, 0.377, 0.958, 0.524, 0.357, + 0.954, 0.518, 0.337, 0.950, 0.512, 0.317, 0.947, 0.505, 0.297, 0.943, + 0.499, 0.276, 0.938, 0.493, 0.255, 0.934, 0.486, 0.234, 0.930, 0.480, + 0.211, 0.925, 0.473, 0.188, 0.920, 0.466, 0.164, 0.916, 0.459, 0.137, + 0.787, 0.440, 0.975, 0.793, 0.450, 0.967, 0.799, 0.459, 0.959, 0.806, + 0.468, 0.952, 0.812, 0.476, 0.944, 0.818, 0.485, 0.937, 0.824, 0.493, + 0.930, 0.831, 0.500, 0.923, 0.837, 0.508, 0.916, 0.843, 0.515, 0.909, + 0.850, 0.522, 0.902, 0.856, 0.528, 0.895, 0.862, 0.535, 0.888, 0.868, + 0.541, 0.881, 0.874, 0.547, 0.875, 0.881, 0.552, 0.868, 0.887, 0.557, + 0.861, 0.893, 0.562, 0.853, 0.899, 0.567, 0.846, 0.904, 0.571, 0.839, + 0.910, 0.575, 0.831, 0.916, 0.579, 0.823, 0.921, 0.582, 0.815, 0.926, + 0.585, 0.807, 0.932, 0.587, 0.798, 0.937, 0.590, 0.789, 0.941, 0.591, + 0.780, 0.946, 0.593, 0.770, 0.950, 0.594, 0.760, 0.954, 0.595, 0.749, + 0.958, 0.595, 0.738, 0.962, 0.595, 0.727, 0.965, 0.595, 0.715, 0.968, + 0.594, 0.702, 0.970, 0.593, 0.689, 0.973, 0.591, 0.676, 0.975, 0.589, + 0.662, 0.976, 0.587, 0.648, 0.978, 0.585, 0.633, 0.979, 0.582, 0.618, + 0.980, 0.579, 0.602, 0.980, 0.575, 0.586, 0.980, 0.572, 0.570, 0.980, + 0.568, 0.553, 0.979, 0.564, 0.536, 0.978, 0.559, 0.518, 0.977, 0.555, + 0.501, 0.975, 0.550, 0.483, 0.974, 0.545, 0.465, 0.972, 0.540, 0.447, + 0.969, 0.535, 0.428, 0.967, 0.529, 0.409, 0.964, 0.524, 0.390, 0.961, + 0.518, 0.371, 0.958, 0.512, 0.352, 0.954, 0.506, 0.332, 0.951, 0.500, + 0.312, 0.947, 0.494, 0.292, 0.943, 0.488, 0.272, 0.939, 0.481, 0.251, + 0.935, 0.475, 0.229, 0.931, 0.469, 0.207, 0.926, 0.462, 0.184, 0.921, + 0.455, 0.159, 0.917, 0.449, 0.133, 0.791, 0.427, 0.973, 0.797, 0.437, + 0.964, 0.803, 0.446, 0.957, 0.809, 0.455, 0.949, 0.815, 0.464, 0.941, + 0.821, 0.472, 0.934, 0.827, 0.480, 0.926, 0.834, 0.488, 0.919, 0.840, + 0.495, 0.912, 0.846, 0.502, 0.905, 0.852, 0.509, 0.898, 0.858, 0.515, + 0.891, 0.864, 0.522, 0.884, 0.870, 0.528, 0.877, 0.876, 0.533, 0.870, + 0.882, 0.539, 0.862, 0.888, 0.544, 0.855, 0.894, 0.549, 0.848, 0.900, + 0.553, 0.840, 0.906, 0.557, 0.833, 0.911, 0.561, 0.825, 0.916, 0.565, + 0.817, 0.922, 0.568, 0.808, 0.927, 0.571, 0.800, 0.932, 0.573, 0.791, + 0.937, 0.575, 0.782, 0.941, 0.577, 0.772, 0.946, 0.579, 0.762, 0.950, + 0.580, 0.752, 0.954, 0.580, 0.741, 0.958, 0.581, 0.730, 0.961, 0.581, + 0.718, 0.964, 0.580, 0.706, 0.967, 0.580, 0.694, 0.970, 0.578, 0.681, + 0.972, 0.577, 0.667, 0.974, 0.575, 0.654, 0.976, 0.573, 0.639, 0.977, + 0.571, 0.625, 0.978, 0.568, 0.610, 0.979, 0.565, 0.594, 0.979, 0.562, + 0.578, 0.979, 0.558, 0.562, 0.979, 0.554, 0.545, 0.978, 0.550, 0.529, + 0.977, 0.546, 0.511, 0.976, 0.542, 0.494, 0.975, 0.537, 0.476, 0.973, + 0.532, 0.458, 0.971, 0.527, 0.440, 0.969, 0.522, 0.422, 0.967, 0.517, + 0.403, 0.964, 0.511, 0.385, 0.961, 0.506, 0.366, 0.958, 0.500, 0.347, + 0.955, 0.494, 0.327, 0.951, 0.488, 0.307, 0.947, 0.482, 0.287, 0.944, + 0.476, 0.267, 0.940, 0.470, 0.246, 0.935, 0.464, 0.225, 0.931, 0.458, + 0.203, 0.927, 0.451, 0.180, 0.922, 0.445, 0.155, 0.917, 0.438, 0.129, + 0.795, 0.413, 0.970, 0.801, 0.423, 0.962, 0.807, 0.433, 0.954, 0.813, + 0.442, 0.946, 0.818, 0.450, 0.938, 0.824, 0.459, 0.930, 0.830, 0.467, + 0.923, 0.836, 0.474, 0.915, 0.842, 0.482, 0.908, 0.848, 0.489, 0.901, + 0.854, 0.496, 0.894, 0.860, 0.502, 0.886, 0.866, 0.508, 0.879, 0.872, + 0.514, 0.872, 0.878, 0.520, 0.864, 0.884, 0.525, 0.857, 0.890, 0.530, + 0.850, 0.895, 0.535, 0.842, 0.901, 0.539, 0.834, 0.906, 0.543, 0.826, + 0.912, 0.547, 0.818, 0.917, 0.551, 0.810, 0.922, 0.554, 0.801, 0.927, + 0.557, 0.793, 0.932, 0.559, 0.783, 0.937, 0.561, 0.774, 0.941, 0.563, + 0.764, 0.946, 0.564, 0.754, 0.950, 0.565, 0.744, 0.953, 0.566, 0.733, + 0.957, 0.566, 0.722, 0.960, 0.566, 0.710, 0.963, 0.566, 0.698, 0.966, + 0.565, 0.685, 0.969, 0.564, 0.673, 0.971, 0.563, 0.659, 0.973, 0.561, + 0.645, 0.975, 0.559, 0.631, 0.976, 0.557, 0.617, 0.977, 0.554, 0.602, + 0.978, 0.551, 0.586, 0.978, 0.548, 0.571, 0.978, 0.545, 0.554, 0.978, + 0.541, 0.538, 0.977, 0.537, 0.521, 0.977, 0.533, 0.504, 0.976, 0.529, + 0.487, 0.974, 0.524, 0.470, 0.973, 0.519, 0.452, 0.971, 0.515, 0.434, + 0.969, 0.510, 0.416, 0.966, 0.504, 0.398, 0.964, 0.499, 0.379, 0.961, + 0.494, 0.360, 0.958, 0.488, 0.341, 0.955, 0.482, 0.322, 0.951, 0.477, + 0.302, 0.948, 0.471, 0.283, 0.944, 0.465, 0.262, 0.940, 0.459, 0.242, + 0.936, 0.452, 0.220, 0.932, 0.446, 0.198, 0.927, 0.440, 0.175, 0.923, + 0.434, 0.151, 0.918, 0.427, 0.124, 0.799, 0.399, 0.968, 0.804, 0.409, + 0.959, 0.810, 0.419, 0.951, 0.816, 0.428, 0.943, 0.822, 0.437, 0.935, + 0.827, 0.445, 0.927, 0.833, 0.453, 0.919, 0.839, 0.461, 0.912, 0.845, + 0.468, 0.904, 0.851, 0.475, 0.897, 0.857, 0.482, 0.889, 0.862, 0.489, + 0.882, 0.868, 0.495, 0.874, 0.874, 0.501, 0.867, 0.880, 0.506, 0.859, + 0.885, 0.511, 0.852, 0.891, 0.516, 0.844, 0.897, 0.521, 0.836, 0.902, + 0.525, 0.828, 0.907, 0.529, 0.820, 0.913, 0.533, 0.812, 0.918, 0.537, + 0.803, 0.923, 0.540, 0.794, 0.928, 0.542, 0.785, 0.932, 0.545, 0.776, + 0.937, 0.547, 0.767, 0.941, 0.549, 0.757, 0.945, 0.550, 0.747, 0.949, + 0.551, 0.736, 0.953, 0.552, 0.725, 0.956, 0.552, 0.714, 0.960, 0.552, + 0.702, 0.963, 0.552, 0.690, 0.965, 0.551, 0.677, 0.968, 0.550, 0.664, + 0.970, 0.549, 0.651, 0.972, 0.547, 0.637, 0.974, 0.545, 0.623, 0.975, + 0.543, 0.609, 0.976, 0.540, 0.594, 0.977, 0.537, 0.578, 0.977, 0.534, + 0.563, 0.977, 0.531, 0.547, 0.977, 0.527, 0.531, 0.976, 0.524, 0.514, + 0.976, 0.520, 0.497, 0.975, 0.516, 0.480, 0.973, 0.511, 0.463, 0.972, + 0.507, 0.446, 0.970, 0.502, 0.428, 0.968, 0.497, 0.410, 0.966, 0.492, + 0.392, 0.963, 0.487, 0.373, 0.960, 0.481, 0.355, 0.957, 0.476, 0.336, + 0.954, 0.470, 0.317, 0.951, 0.465, 0.297, 0.947, 0.459, 0.278, 0.944, + 0.453, 0.258, 0.940, 0.447, 0.237, 0.936, 0.441, 0.216, 0.932, 0.435, + 0.194, 0.927, 0.429, 0.171, 0.923, 0.422, 0.147, 0.918, 0.416, 0.120, + 0.802, 0.385, 0.965, 0.808, 0.395, 0.957, 0.813, 0.405, 0.948, 0.819, + 0.414, 0.940, 0.825, 0.423, 0.932, 0.830, 0.431, 0.924, 0.836, 0.439, + 0.916, 0.842, 0.447, 0.908, 0.847, 0.454, 0.900, 0.853, 0.462, 0.892, + 0.859, 0.468, 0.885, 0.864, 0.475, 0.877, 0.870, 0.481, 0.869, 0.876, + 0.487, 0.862, 0.881, 0.492, 0.854, 0.887, 0.498, 0.846, 0.892, 0.502, + 0.838, 0.898, 0.507, 0.830, 0.903, 0.511, 0.822, 0.908, 0.515, 0.814, + 0.913, 0.519, 0.805, 0.918, 0.522, 0.797, 0.923, 0.525, 0.788, 0.928, + 0.528, 0.778, 0.932, 0.530, 0.769, 0.937, 0.532, 0.759, 0.941, 0.534, + 0.749, 0.945, 0.535, 0.739, 0.949, 0.536, 0.728, 0.952, 0.537, 0.717, + 0.956, 0.537, 0.706, 0.959, 0.537, 0.694, 0.962, 0.537, 0.682, 0.964, + 0.536, 0.669, 0.967, 0.536, 0.656, 0.969, 0.534, 0.643, 0.971, 0.533, + 0.629, 0.972, 0.531, 0.615, 0.974, 0.529, 0.601, 0.975, 0.526, 0.586, + 0.975, 0.523, 0.571, 0.976, 0.521, 0.555, 0.976, 0.517, 0.540, 0.976, + 0.514, 0.523, 0.975, 0.510, 0.507, 0.975, 0.506, 0.490, 0.974, 0.502, + 0.474, 0.972, 0.498, 0.456, 0.971, 0.494, 0.439, 0.969, 0.489, 0.421, + 0.967, 0.484, 0.404, 0.965, 0.479, 0.386, 0.963, 0.474, 0.367, 0.960, + 0.469, 0.349, 0.957, 0.464, 0.330, 0.954, 0.458, 0.311, 0.951, 0.453, + 0.292, 0.947, 0.447, 0.273, 0.944, 0.441, 0.253, 0.940, 0.435, 0.232, + 0.936, 0.429, 0.211, 0.932, 0.423, 0.190, 0.927, 0.417, 0.167, 0.923, + 0.411, 0.142, 0.919, 0.405, 0.116, 0.806, 0.370, 0.963, 0.811, 0.380, + 0.954, 0.816, 0.390, 0.945, 0.822, 0.399, 0.937, 0.827, 0.408, 0.929, + 0.833, 0.417, 0.920, 0.838, 0.425, 0.912, 0.844, 0.433, 0.904, 0.850, + 0.440, 0.896, 0.855, 0.447, 0.888, 0.861, 0.454, 0.880, 0.866, 0.461, + 0.872, 0.872, 0.467, 0.865, 0.877, 0.473, 0.857, 0.883, 0.478, 0.849, + 0.888, 0.483, 0.841, 0.893, 0.488, 0.833, 0.899, 0.493, 0.824, 0.904, + 0.497, 0.816, 0.909, 0.501, 0.807, 0.914, 0.505, 0.799, 0.919, 0.508, + 0.790, 0.923, 0.511, 0.781, 0.928, 0.514, 0.771, 0.932, 0.516, 0.762, + 0.937, 0.518, 0.752, 0.941, 0.520, 0.742, 0.945, 0.521, 0.731, 0.948, + 0.522, 0.720, 0.952, 0.523, 0.709, 0.955, 0.523, 0.698, 0.958, 0.523, + 0.686, 0.961, 0.523, 0.674, 0.964, 0.522, 0.661, 0.966, 0.521, 0.648, + 0.968, 0.520, 0.635, 0.970, 0.518, 0.621, 0.971, 0.517, 0.607, 0.972, + 0.514, 0.593, 0.973, 0.512, 0.578, 0.974, 0.509, 0.563, 0.975, 0.507, + 0.548, 0.975, 0.503, 0.532, 0.975, 0.500, 0.516, 0.974, 0.497, 0.500, + 0.974, 0.493, 0.483, 0.973, 0.489, 0.467, 0.971, 0.485, 0.450, 0.970, + 0.480, 0.433, 0.968, 0.476, 0.415, 0.966, 0.471, 0.397, 0.964, 0.466, + 0.380, 0.962, 0.461, 0.362, 0.959, 0.456, 0.343, 0.956, 0.451, 0.325, + 0.953, 0.446, 0.306, 0.950, 0.440, 0.287, 0.947, 0.435, 0.268, 0.943, + 0.429, 0.248, 0.939, 0.423, 0.228, 0.936, 0.417, 0.207, 0.931, 0.411, + 0.185, 0.927, 0.405, 0.162, 0.923, 0.399, 0.138, 0.918, 0.393, 0.111, + 0.809, 0.354, 0.960, 0.814, 0.364, 0.951, 0.819, 0.375, 0.942, 0.825, + 0.384, 0.934, 0.830, 0.393, 0.925, 0.835, 0.402, 0.917, 0.841, 0.410, + 0.908, 0.846, 0.418, 0.900, 0.852, 0.426, 0.892, 0.857, 0.433, 0.884, + 0.863, 0.440, 0.876, 0.868, 0.446, 0.868, 0.873, 0.452, 0.860, 0.879, + 0.458, 0.852, 0.884, 0.464, 0.843, 0.889, 0.469, 0.835, 0.894, 0.474, + 0.827, 0.899, 0.478, 0.818, 0.904, 0.483, 0.810, 0.909, 0.486, 0.801, + 0.914, 0.490, 0.792, 0.919, 0.493, 0.783, 0.923, 0.496, 0.774, 0.928, + 0.499, 0.764, 0.932, 0.501, 0.755, 0.936, 0.503, 0.745, 0.940, 0.505, + 0.734, 0.944, 0.506, 0.724, 0.948, 0.507, 0.713, 0.951, 0.508, 0.701, + 0.954, 0.508, 0.690, 0.957, 0.508, 0.678, 0.960, 0.508, 0.666, 0.962, + 0.507, 0.653, 0.965, 0.507, 0.640, 0.967, 0.505, 0.627, 0.968, 0.504, + 0.613, 0.970, 0.502, 0.599, 0.971, 0.500, 0.585, 0.972, 0.498, 0.570, + 0.973, 0.495, 0.555, 0.973, 0.493, 0.540, 0.973, 0.490, 0.525, 0.973, + 0.486, 0.509, 0.973, 0.483, 0.493, 0.972, 0.479, 0.476, 0.971, 0.475, + 0.460, 0.970, 0.471, 0.443, 0.969, 0.467, 0.426, 0.967, 0.463, 0.409, + 0.965, 0.458, 0.391, 0.963, 0.453, 0.374, 0.961, 0.449, 0.356, 0.958, + 0.444, 0.338, 0.956, 0.438, 0.319, 0.953, 0.433, 0.301, 0.949, 0.428, + 0.282, 0.946, 0.422, 0.263, 0.943, 0.417, 0.243, 0.939, 0.411, 0.223, + 0.935, 0.405, 0.202, 0.931, 0.399, 0.181, 0.927, 0.393, 0.158, 0.923, + 0.387, 0.134, 0.918, 0.381, 0.107, + ]).reshape((65, 65, 3)) + +BiOrangeBlue = np.array( + [0.000, 0.000, 0.000, 0.000, 0.062, 0.125, 0.000, 0.125, 0.250, 0.000, + 0.188, 0.375, 0.000, 0.250, 0.500, 0.000, 0.312, 0.625, 0.000, 0.375, + 0.750, 0.000, 0.438, 0.875, 0.000, 0.500, 1.000, 0.125, 0.062, 0.000, + 0.125, 0.125, 0.125, 0.125, 0.188, 0.250, 0.125, 0.250, 0.375, 0.125, + 0.312, 0.500, 0.125, 0.375, 0.625, 0.125, 0.438, 0.750, 0.125, 0.500, + 0.875, 0.125, 0.562, 1.000, 0.250, 0.125, 0.000, 0.250, 0.188, 0.125, + 0.250, 0.250, 0.250, 0.250, 0.312, 0.375, 0.250, 0.375, 0.500, 0.250, + 0.438, 0.625, 0.250, 0.500, 0.750, 0.250, 0.562, 0.875, 0.250, 0.625, + 1.000, 0.375, 0.188, 0.000, 0.375, 0.250, 0.125, 0.375, 0.312, 0.250, + 0.375, 0.375, 0.375, 0.375, 0.438, 0.500, 0.375, 0.500, 0.625, 0.375, + 0.562, 0.750, 0.375, 0.625, 0.875, 0.375, 0.688, 1.000, 0.500, 0.250, + 0.000, 0.500, 0.312, 0.125, 0.500, 0.375, 0.250, 0.500, 0.438, 0.375, + 0.500, 0.500, 0.500, 0.500, 0.562, 0.625, 0.500, 0.625, 0.750, 0.500, + 0.688, 0.875, 0.500, 0.750, 1.000, 0.625, 0.312, 0.000, 0.625, 0.375, + 0.125, 0.625, 0.438, 0.250, 0.625, 0.500, 0.375, 0.625, 0.562, 0.500, + 0.625, 0.625, 0.625, 0.625, 0.688, 0.750, 0.625, 0.750, 0.875, 0.625, + 0.812, 1.000, 0.750, 0.375, 0.000, 0.750, 0.438, 0.125, 0.750, 0.500, + 0.250, 0.750, 0.562, 0.375, 0.750, 0.625, 0.500, 0.750, 0.688, 0.625, + 0.750, 0.750, 0.750, 0.750, 0.812, 0.875, 0.750, 0.875, 1.000, 0.875, + 0.438, 0.000, 0.875, 0.500, 0.125, 0.875, 0.562, 0.250, 0.875, 0.625, + 0.375, 0.875, 0.688, 0.500, 0.875, 0.750, 0.625, 0.875, 0.812, 0.750, + 0.875, 0.875, 0.875, 0.875, 0.938, 1.000, 1.000, 0.500, 0.000, 1.000, + 0.562, 0.125, 1.000, 0.625, 0.250, 1.000, 0.688, 0.375, 1.000, 0.750, + 0.500, 1.000, 0.812, 0.625, 1.000, 0.875, 0.750, 1.000, 0.938, 0.875, + 1.000, 1.000, 1.000, + ]).reshape((9, 9, 3)) + +cmaps = { + "BiPeak": SegmentedBivarColormap( + BiPeak, 256, "square", (.5, .5), name="BiPeak"), + "BiOrangeBlue": SegmentedBivarColormap( + BiOrangeBlue, 256, "square", (0, 0), name="BiOrangeBlue"), + "BiCone": SegmentedBivarColormap(BiPeak, 256, "circle", (.5, .5), name="BiCone"), +} diff --git a/infer_4_30_0/lib/python3.10/site-packages/matplotlib/_color_data.pyi b/infer_4_30_0/lib/python3.10/site-packages/matplotlib/_color_data.pyi new file mode 100644 index 0000000000000000000000000000000000000000..feb3de9c3043d55910e2649804352ae96ccbd1ec --- /dev/null +++ b/infer_4_30_0/lib/python3.10/site-packages/matplotlib/_color_data.pyi @@ -0,0 +1,6 @@ +from .typing import ColorType + +BASE_COLORS: dict[str, ColorType] +TABLEAU_COLORS: dict[str, ColorType] +XKCD_COLORS: dict[str, ColorType] +CSS4_COLORS: dict[str, ColorType] diff --git a/infer_4_30_0/lib/python3.10/site-packages/matplotlib/_constrained_layout.py b/infer_4_30_0/lib/python3.10/site-packages/matplotlib/_constrained_layout.py new file mode 100644 index 0000000000000000000000000000000000000000..5623e12a3c41d0d0d35041fd1dd9fb23e9938e51 --- /dev/null +++ b/infer_4_30_0/lib/python3.10/site-packages/matplotlib/_constrained_layout.py @@ -0,0 +1,801 @@ +""" +Adjust subplot layouts so that there are no overlapping Axes or Axes +decorations. All Axes decorations are dealt with (labels, ticks, titles, +ticklabels) and some dependent artists are also dealt with (colorbar, +suptitle). + +Layout is done via `~matplotlib.gridspec`, with one constraint per gridspec, +so it is possible to have overlapping Axes if the gridspecs overlap (i.e. +using `~matplotlib.gridspec.GridSpecFromSubplotSpec`). Axes placed using +``figure.subplots()`` or ``figure.add_subplots()`` will participate in the +layout. Axes manually placed via ``figure.add_axes()`` will not. + +See Tutorial: :ref:`constrainedlayout_guide` + +General idea: +------------- + +First, a figure has a gridspec that divides the figure into nrows and ncols, +with heights and widths set by ``height_ratios`` and ``width_ratios``, +often just set to 1 for an equal grid. + +Subplotspecs that are derived from this gridspec can contain either a +``SubPanel``, a ``GridSpecFromSubplotSpec``, or an ``Axes``. The ``SubPanel`` +and ``GridSpecFromSubplotSpec`` are dealt with recursively and each contain an +analogous layout. + +Each ``GridSpec`` has a ``_layoutgrid`` attached to it. The ``_layoutgrid`` +has the same logical layout as the ``GridSpec``. Each row of the grid spec +has a top and bottom "margin" and each column has a left and right "margin". +The "inner" height of each row is constrained to be the same (or as modified +by ``height_ratio``), and the "inner" width of each column is +constrained to be the same (as modified by ``width_ratio``), where "inner" +is the width or height of each column/row minus the size of the margins. + +Then the size of the margins for each row and column are determined as the +max width of the decorators on each Axes that has decorators in that margin. +For instance, a normal Axes would have a left margin that includes the +left ticklabels, and the ylabel if it exists. The right margin may include a +colorbar, the bottom margin the xaxis decorations, and the top margin the +title. + +With these constraints, the solver then finds appropriate bounds for the +columns and rows. It's possible that the margins take up the whole figure, +in which case the algorithm is not applied and a warning is raised. + +See the tutorial :ref:`constrainedlayout_guide` +for more discussion of the algorithm with examples. +""" + +import logging + +import numpy as np + +from matplotlib import _api, artist as martist +import matplotlib.transforms as mtransforms +import matplotlib._layoutgrid as mlayoutgrid + + +_log = logging.getLogger(__name__) + + +###################################################### +def do_constrained_layout(fig, h_pad, w_pad, + hspace=None, wspace=None, rect=(0, 0, 1, 1), + compress=False): + """ + Do the constrained_layout. Called at draw time in + ``figure.constrained_layout()`` + + Parameters + ---------- + fig : `~matplotlib.figure.Figure` + `.Figure` instance to do the layout in. + + h_pad, w_pad : float + Padding around the Axes elements in figure-normalized units. + + hspace, wspace : float + Fraction of the figure to dedicate to space between the + Axes. These are evenly spread between the gaps between the Axes. + A value of 0.2 for a three-column layout would have a space + of 0.1 of the figure width between each column. + If h/wspace < h/w_pad, then the pads are used instead. + + rect : tuple of 4 floats + Rectangle in figure coordinates to perform constrained layout in + [left, bottom, width, height], each from 0-1. + + compress : bool + Whether to shift Axes so that white space in between them is + removed. This is useful for simple grids of fixed-aspect Axes (e.g. + a grid of images). + + Returns + ------- + layoutgrid : private debugging structure + """ + + renderer = fig._get_renderer() + # make layoutgrid tree... + layoutgrids = make_layoutgrids(fig, None, rect=rect) + if not layoutgrids['hasgrids']: + _api.warn_external('There are no gridspecs with layoutgrids. ' + 'Possibly did not call parent GridSpec with the' + ' "figure" keyword') + return + + for _ in range(2): + # do the algorithm twice. This has to be done because decorations + # change size after the first re-position (i.e. x/yticklabels get + # larger/smaller). This second reposition tends to be much milder, + # so doing twice makes things work OK. + + # make margins for all the Axes and subfigures in the + # figure. Add margins for colorbars... + make_layout_margins(layoutgrids, fig, renderer, h_pad=h_pad, + w_pad=w_pad, hspace=hspace, wspace=wspace) + make_margin_suptitles(layoutgrids, fig, renderer, h_pad=h_pad, + w_pad=w_pad) + + # if a layout is such that a columns (or rows) margin has no + # constraints, we need to make all such instances in the grid + # match in margin size. + match_submerged_margins(layoutgrids, fig) + + # update all the variables in the layout. + layoutgrids[fig].update_variables() + + warn_collapsed = ('constrained_layout not applied because ' + 'axes sizes collapsed to zero. Try making ' + 'figure larger or Axes decorations smaller.') + if check_no_collapsed_axes(layoutgrids, fig): + reposition_axes(layoutgrids, fig, renderer, h_pad=h_pad, + w_pad=w_pad, hspace=hspace, wspace=wspace) + if compress: + layoutgrids = compress_fixed_aspect(layoutgrids, fig) + layoutgrids[fig].update_variables() + if check_no_collapsed_axes(layoutgrids, fig): + reposition_axes(layoutgrids, fig, renderer, h_pad=h_pad, + w_pad=w_pad, hspace=hspace, wspace=wspace) + else: + _api.warn_external(warn_collapsed) + + if ((suptitle := fig._suptitle) is not None and + suptitle.get_in_layout() and suptitle._autopos): + x, _ = suptitle.get_position() + suptitle.set_position( + (x, layoutgrids[fig].get_inner_bbox().y1 + h_pad)) + suptitle.set_verticalalignment('bottom') + else: + _api.warn_external(warn_collapsed) + reset_margins(layoutgrids, fig) + return layoutgrids + + +def make_layoutgrids(fig, layoutgrids, rect=(0, 0, 1, 1)): + """ + Make the layoutgrid tree. + + (Sub)Figures get a layoutgrid so we can have figure margins. + + Gridspecs that are attached to Axes get a layoutgrid so Axes + can have margins. + """ + + if layoutgrids is None: + layoutgrids = dict() + layoutgrids['hasgrids'] = False + if not hasattr(fig, '_parent'): + # top figure; pass rect as parent to allow user-specified + # margins + layoutgrids[fig] = mlayoutgrid.LayoutGrid(parent=rect, name='figlb') + else: + # subfigure + gs = fig._subplotspec.get_gridspec() + # it is possible the gridspec containing this subfigure hasn't + # been added to the tree yet: + layoutgrids = make_layoutgrids_gs(layoutgrids, gs) + # add the layoutgrid for the subfigure: + parentlb = layoutgrids[gs] + layoutgrids[fig] = mlayoutgrid.LayoutGrid( + parent=parentlb, + name='panellb', + parent_inner=True, + nrows=1, ncols=1, + parent_pos=(fig._subplotspec.rowspan, + fig._subplotspec.colspan)) + # recursively do all subfigures in this figure... + for sfig in fig.subfigs: + layoutgrids = make_layoutgrids(sfig, layoutgrids) + + # for each Axes at the local level add its gridspec: + for ax in fig._localaxes: + gs = ax.get_gridspec() + if gs is not None: + layoutgrids = make_layoutgrids_gs(layoutgrids, gs) + + return layoutgrids + + +def make_layoutgrids_gs(layoutgrids, gs): + """ + Make the layoutgrid for a gridspec (and anything nested in the gridspec) + """ + + if gs in layoutgrids or gs.figure is None: + return layoutgrids + # in order to do constrained_layout there has to be at least *one* + # gridspec in the tree: + layoutgrids['hasgrids'] = True + if not hasattr(gs, '_subplot_spec'): + # normal gridspec + parent = layoutgrids[gs.figure] + layoutgrids[gs] = mlayoutgrid.LayoutGrid( + parent=parent, + parent_inner=True, + name='gridspec', + ncols=gs._ncols, nrows=gs._nrows, + width_ratios=gs.get_width_ratios(), + height_ratios=gs.get_height_ratios()) + else: + # this is a gridspecfromsubplotspec: + subplot_spec = gs._subplot_spec + parentgs = subplot_spec.get_gridspec() + # if a nested gridspec it is possible the parent is not in there yet: + if parentgs not in layoutgrids: + layoutgrids = make_layoutgrids_gs(layoutgrids, parentgs) + subspeclb = layoutgrids[parentgs] + # gridspecfromsubplotspec need an outer container: + # get a unique representation: + rep = (gs, 'top') + if rep not in layoutgrids: + layoutgrids[rep] = mlayoutgrid.LayoutGrid( + parent=subspeclb, + name='top', + nrows=1, ncols=1, + parent_pos=(subplot_spec.rowspan, subplot_spec.colspan)) + layoutgrids[gs] = mlayoutgrid.LayoutGrid( + parent=layoutgrids[rep], + name='gridspec', + nrows=gs._nrows, ncols=gs._ncols, + width_ratios=gs.get_width_ratios(), + height_ratios=gs.get_height_ratios()) + return layoutgrids + + +def check_no_collapsed_axes(layoutgrids, fig): + """ + Check that no Axes have collapsed to zero size. + """ + for sfig in fig.subfigs: + ok = check_no_collapsed_axes(layoutgrids, sfig) + if not ok: + return False + for ax in fig.axes: + gs = ax.get_gridspec() + if gs in layoutgrids: # also implies gs is not None. + lg = layoutgrids[gs] + for i in range(gs.nrows): + for j in range(gs.ncols): + bb = lg.get_inner_bbox(i, j) + if bb.width <= 0 or bb.height <= 0: + return False + return True + + +def compress_fixed_aspect(layoutgrids, fig): + gs = None + for ax in fig.axes: + if ax.get_subplotspec() is None: + continue + ax.apply_aspect() + sub = ax.get_subplotspec() + _gs = sub.get_gridspec() + if gs is None: + gs = _gs + extraw = np.zeros(gs.ncols) + extrah = np.zeros(gs.nrows) + elif _gs != gs: + raise ValueError('Cannot do compressed layout if Axes are not' + 'all from the same gridspec') + orig = ax.get_position(original=True) + actual = ax.get_position(original=False) + dw = orig.width - actual.width + if dw > 0: + extraw[sub.colspan] = np.maximum(extraw[sub.colspan], dw) + dh = orig.height - actual.height + if dh > 0: + extrah[sub.rowspan] = np.maximum(extrah[sub.rowspan], dh) + + if gs is None: + raise ValueError('Cannot do compressed layout if no Axes ' + 'are part of a gridspec.') + w = np.sum(extraw) / 2 + layoutgrids[fig].edit_margin_min('left', w) + layoutgrids[fig].edit_margin_min('right', w) + + h = np.sum(extrah) / 2 + layoutgrids[fig].edit_margin_min('top', h) + layoutgrids[fig].edit_margin_min('bottom', h) + return layoutgrids + + +def get_margin_from_padding(obj, *, w_pad=0, h_pad=0, + hspace=0, wspace=0): + + ss = obj._subplotspec + gs = ss.get_gridspec() + + if hasattr(gs, 'hspace'): + _hspace = (gs.hspace if gs.hspace is not None else hspace) + _wspace = (gs.wspace if gs.wspace is not None else wspace) + else: + _hspace = (gs._hspace if gs._hspace is not None else hspace) + _wspace = (gs._wspace if gs._wspace is not None else wspace) + + _wspace = _wspace / 2 + _hspace = _hspace / 2 + + nrows, ncols = gs.get_geometry() + # there are two margins for each direction. The "cb" + # margins are for pads and colorbars, the non-"cb" are + # for the Axes decorations (labels etc). + margin = {'leftcb': w_pad, 'rightcb': w_pad, + 'bottomcb': h_pad, 'topcb': h_pad, + 'left': 0, 'right': 0, + 'top': 0, 'bottom': 0} + if _wspace / ncols > w_pad: + if ss.colspan.start > 0: + margin['leftcb'] = _wspace / ncols + if ss.colspan.stop < ncols: + margin['rightcb'] = _wspace / ncols + if _hspace / nrows > h_pad: + if ss.rowspan.stop < nrows: + margin['bottomcb'] = _hspace / nrows + if ss.rowspan.start > 0: + margin['topcb'] = _hspace / nrows + + return margin + + +def make_layout_margins(layoutgrids, fig, renderer, *, w_pad=0, h_pad=0, + hspace=0, wspace=0): + """ + For each Axes, make a margin between the *pos* layoutbox and the + *axes* layoutbox be a minimum size that can accommodate the + decorations on the axis. + + Then make room for colorbars. + + Parameters + ---------- + layoutgrids : dict + fig : `~matplotlib.figure.Figure` + `.Figure` instance to do the layout in. + renderer : `~matplotlib.backend_bases.RendererBase` subclass. + The renderer to use. + w_pad, h_pad : float, default: 0 + Width and height padding (in fraction of figure). + hspace, wspace : float, default: 0 + Width and height padding as fraction of figure size divided by + number of columns or rows. + """ + for sfig in fig.subfigs: # recursively make child panel margins + ss = sfig._subplotspec + gs = ss.get_gridspec() + + make_layout_margins(layoutgrids, sfig, renderer, + w_pad=w_pad, h_pad=h_pad, + hspace=hspace, wspace=wspace) + + margins = get_margin_from_padding(sfig, w_pad=0, h_pad=0, + hspace=hspace, wspace=wspace) + layoutgrids[gs].edit_outer_margin_mins(margins, ss) + + for ax in fig._localaxes: + if not ax.get_subplotspec() or not ax.get_in_layout(): + continue + + ss = ax.get_subplotspec() + gs = ss.get_gridspec() + + if gs not in layoutgrids: + return + + margin = get_margin_from_padding(ax, w_pad=w_pad, h_pad=h_pad, + hspace=hspace, wspace=wspace) + pos, bbox = get_pos_and_bbox(ax, renderer) + # the margin is the distance between the bounding box of the Axes + # and its position (plus the padding from above) + margin['left'] += pos.x0 - bbox.x0 + margin['right'] += bbox.x1 - pos.x1 + # remember that rows are ordered from top: + margin['bottom'] += pos.y0 - bbox.y0 + margin['top'] += bbox.y1 - pos.y1 + + # make margin for colorbars. These margins go in the + # padding margin, versus the margin for Axes decorators. + for cbax in ax._colorbars: + # note pad is a fraction of the parent width... + pad = colorbar_get_pad(layoutgrids, cbax) + # colorbars can be child of more than one subplot spec: + cbp_rspan, cbp_cspan = get_cb_parent_spans(cbax) + loc = cbax._colorbar_info['location'] + cbpos, cbbbox = get_pos_and_bbox(cbax, renderer) + if loc == 'right': + if cbp_cspan.stop == ss.colspan.stop: + # only increase if the colorbar is on the right edge + margin['rightcb'] += cbbbox.width + pad + elif loc == 'left': + if cbp_cspan.start == ss.colspan.start: + # only increase if the colorbar is on the left edge + margin['leftcb'] += cbbbox.width + pad + elif loc == 'top': + if cbp_rspan.start == ss.rowspan.start: + margin['topcb'] += cbbbox.height + pad + else: + if cbp_rspan.stop == ss.rowspan.stop: + margin['bottomcb'] += cbbbox.height + pad + # If the colorbars are wider than the parent box in the + # cross direction + if loc in ['top', 'bottom']: + if (cbp_cspan.start == ss.colspan.start and + cbbbox.x0 < bbox.x0): + margin['left'] += bbox.x0 - cbbbox.x0 + if (cbp_cspan.stop == ss.colspan.stop and + cbbbox.x1 > bbox.x1): + margin['right'] += cbbbox.x1 - bbox.x1 + # or taller: + if loc in ['left', 'right']: + if (cbp_rspan.stop == ss.rowspan.stop and + cbbbox.y0 < bbox.y0): + margin['bottom'] += bbox.y0 - cbbbox.y0 + if (cbp_rspan.start == ss.rowspan.start and + cbbbox.y1 > bbox.y1): + margin['top'] += cbbbox.y1 - bbox.y1 + # pass the new margins down to the layout grid for the solution... + layoutgrids[gs].edit_outer_margin_mins(margin, ss) + + # make margins for figure-level legends: + for leg in fig.legends: + inv_trans_fig = None + if leg._outside_loc and leg._bbox_to_anchor is None: + if inv_trans_fig is None: + inv_trans_fig = fig.transFigure.inverted().transform_bbox + bbox = inv_trans_fig(leg.get_tightbbox(renderer)) + w = bbox.width + 2 * w_pad + h = bbox.height + 2 * h_pad + legendloc = leg._outside_loc + if legendloc == 'lower': + layoutgrids[fig].edit_margin_min('bottom', h) + elif legendloc == 'upper': + layoutgrids[fig].edit_margin_min('top', h) + if legendloc == 'right': + layoutgrids[fig].edit_margin_min('right', w) + elif legendloc == 'left': + layoutgrids[fig].edit_margin_min('left', w) + + +def make_margin_suptitles(layoutgrids, fig, renderer, *, w_pad=0, h_pad=0): + # Figure out how large the suptitle is and make the + # top level figure margin larger. + + inv_trans_fig = fig.transFigure.inverted().transform_bbox + # get the h_pad and w_pad as distances in the local subfigure coordinates: + padbox = mtransforms.Bbox([[0, 0], [w_pad, h_pad]]) + padbox = (fig.transFigure - + fig.transSubfigure).transform_bbox(padbox) + h_pad_local = padbox.height + w_pad_local = padbox.width + + for sfig in fig.subfigs: + make_margin_suptitles(layoutgrids, sfig, renderer, + w_pad=w_pad, h_pad=h_pad) + + if fig._suptitle is not None and fig._suptitle.get_in_layout(): + p = fig._suptitle.get_position() + if getattr(fig._suptitle, '_autopos', False): + fig._suptitle.set_position((p[0], 1 - h_pad_local)) + bbox = inv_trans_fig(fig._suptitle.get_tightbbox(renderer)) + layoutgrids[fig].edit_margin_min('top', bbox.height + 2 * h_pad) + + if fig._supxlabel is not None and fig._supxlabel.get_in_layout(): + p = fig._supxlabel.get_position() + if getattr(fig._supxlabel, '_autopos', False): + fig._supxlabel.set_position((p[0], h_pad_local)) + bbox = inv_trans_fig(fig._supxlabel.get_tightbbox(renderer)) + layoutgrids[fig].edit_margin_min('bottom', + bbox.height + 2 * h_pad) + + if fig._supylabel is not None and fig._supylabel.get_in_layout(): + p = fig._supylabel.get_position() + if getattr(fig._supylabel, '_autopos', False): + fig._supylabel.set_position((w_pad_local, p[1])) + bbox = inv_trans_fig(fig._supylabel.get_tightbbox(renderer)) + layoutgrids[fig].edit_margin_min('left', bbox.width + 2 * w_pad) + + +def match_submerged_margins(layoutgrids, fig): + """ + Make the margins that are submerged inside an Axes the same size. + + This allows Axes that span two columns (or rows) that are offset + from one another to have the same size. + + This gives the proper layout for something like:: + fig = plt.figure(constrained_layout=True) + axs = fig.subplot_mosaic("AAAB\nCCDD") + + Without this routine, the Axes D will be wider than C, because the + margin width between the two columns in C has no width by default, + whereas the margins between the two columns of D are set by the + width of the margin between A and B. However, obviously the user would + like C and D to be the same size, so we need to add constraints to these + "submerged" margins. + + This routine makes all the interior margins the same, and the spacing + between the three columns in A and the two column in C are all set to the + margins between the two columns of D. + + See test_constrained_layout::test_constrained_layout12 for an example. + """ + + for sfig in fig.subfigs: + match_submerged_margins(layoutgrids, sfig) + + axs = [a for a in fig.get_axes() + if a.get_subplotspec() is not None and a.get_in_layout()] + + for ax1 in axs: + ss1 = ax1.get_subplotspec() + if ss1.get_gridspec() not in layoutgrids: + axs.remove(ax1) + continue + lg1 = layoutgrids[ss1.get_gridspec()] + + # interior columns: + if len(ss1.colspan) > 1: + maxsubl = np.max( + lg1.margin_vals['left'][ss1.colspan[1:]] + + lg1.margin_vals['leftcb'][ss1.colspan[1:]] + ) + maxsubr = np.max( + lg1.margin_vals['right'][ss1.colspan[:-1]] + + lg1.margin_vals['rightcb'][ss1.colspan[:-1]] + ) + for ax2 in axs: + ss2 = ax2.get_subplotspec() + lg2 = layoutgrids[ss2.get_gridspec()] + if lg2 is not None and len(ss2.colspan) > 1: + maxsubl2 = np.max( + lg2.margin_vals['left'][ss2.colspan[1:]] + + lg2.margin_vals['leftcb'][ss2.colspan[1:]]) + if maxsubl2 > maxsubl: + maxsubl = maxsubl2 + maxsubr2 = np.max( + lg2.margin_vals['right'][ss2.colspan[:-1]] + + lg2.margin_vals['rightcb'][ss2.colspan[:-1]]) + if maxsubr2 > maxsubr: + maxsubr = maxsubr2 + for i in ss1.colspan[1:]: + lg1.edit_margin_min('left', maxsubl, cell=i) + for i in ss1.colspan[:-1]: + lg1.edit_margin_min('right', maxsubr, cell=i) + + # interior rows: + if len(ss1.rowspan) > 1: + maxsubt = np.max( + lg1.margin_vals['top'][ss1.rowspan[1:]] + + lg1.margin_vals['topcb'][ss1.rowspan[1:]] + ) + maxsubb = np.max( + lg1.margin_vals['bottom'][ss1.rowspan[:-1]] + + lg1.margin_vals['bottomcb'][ss1.rowspan[:-1]] + ) + + for ax2 in axs: + ss2 = ax2.get_subplotspec() + lg2 = layoutgrids[ss2.get_gridspec()] + if lg2 is not None: + if len(ss2.rowspan) > 1: + maxsubt = np.max([np.max( + lg2.margin_vals['top'][ss2.rowspan[1:]] + + lg2.margin_vals['topcb'][ss2.rowspan[1:]] + ), maxsubt]) + maxsubb = np.max([np.max( + lg2.margin_vals['bottom'][ss2.rowspan[:-1]] + + lg2.margin_vals['bottomcb'][ss2.rowspan[:-1]] + ), maxsubb]) + for i in ss1.rowspan[1:]: + lg1.edit_margin_min('top', maxsubt, cell=i) + for i in ss1.rowspan[:-1]: + lg1.edit_margin_min('bottom', maxsubb, cell=i) + + +def get_cb_parent_spans(cbax): + """ + Figure out which subplotspecs this colorbar belongs to. + + Parameters + ---------- + cbax : `~matplotlib.axes.Axes` + Axes for the colorbar. + """ + rowstart = np.inf + rowstop = -np.inf + colstart = np.inf + colstop = -np.inf + for parent in cbax._colorbar_info['parents']: + ss = parent.get_subplotspec() + rowstart = min(ss.rowspan.start, rowstart) + rowstop = max(ss.rowspan.stop, rowstop) + colstart = min(ss.colspan.start, colstart) + colstop = max(ss.colspan.stop, colstop) + + rowspan = range(rowstart, rowstop) + colspan = range(colstart, colstop) + return rowspan, colspan + + +def get_pos_and_bbox(ax, renderer): + """ + Get the position and the bbox for the Axes. + + Parameters + ---------- + ax : `~matplotlib.axes.Axes` + renderer : `~matplotlib.backend_bases.RendererBase` subclass. + + Returns + ------- + pos : `~matplotlib.transforms.Bbox` + Position in figure coordinates. + bbox : `~matplotlib.transforms.Bbox` + Tight bounding box in figure coordinates. + """ + fig = ax.get_figure(root=False) + pos = ax.get_position(original=True) + # pos is in panel co-ords, but we need in figure for the layout + pos = pos.transformed(fig.transSubfigure - fig.transFigure) + tightbbox = martist._get_tightbbox_for_layout_only(ax, renderer) + if tightbbox is None: + bbox = pos + else: + bbox = tightbbox.transformed(fig.transFigure.inverted()) + return pos, bbox + + +def reposition_axes(layoutgrids, fig, renderer, *, + w_pad=0, h_pad=0, hspace=0, wspace=0): + """ + Reposition all the Axes based on the new inner bounding box. + """ + trans_fig_to_subfig = fig.transFigure - fig.transSubfigure + for sfig in fig.subfigs: + bbox = layoutgrids[sfig].get_outer_bbox() + sfig._redo_transform_rel_fig( + bbox=bbox.transformed(trans_fig_to_subfig)) + reposition_axes(layoutgrids, sfig, renderer, + w_pad=w_pad, h_pad=h_pad, + wspace=wspace, hspace=hspace) + + for ax in fig._localaxes: + if ax.get_subplotspec() is None or not ax.get_in_layout(): + continue + + # grid bbox is in Figure coordinates, but we specify in panel + # coordinates... + ss = ax.get_subplotspec() + gs = ss.get_gridspec() + if gs not in layoutgrids: + return + + bbox = layoutgrids[gs].get_inner_bbox(rows=ss.rowspan, + cols=ss.colspan) + + # transform from figure to panel for set_position: + newbbox = trans_fig_to_subfig.transform_bbox(bbox) + ax._set_position(newbbox) + + # move the colorbars: + # we need to keep track of oldw and oldh if there is more than + # one colorbar: + offset = {'left': 0, 'right': 0, 'bottom': 0, 'top': 0} + for nn, cbax in enumerate(ax._colorbars[::-1]): + if ax == cbax._colorbar_info['parents'][0]: + reposition_colorbar(layoutgrids, cbax, renderer, + offset=offset) + + +def reposition_colorbar(layoutgrids, cbax, renderer, *, offset=None): + """ + Place the colorbar in its new place. + + Parameters + ---------- + layoutgrids : dict + cbax : `~matplotlib.axes.Axes` + Axes for the colorbar. + renderer : `~matplotlib.backend_bases.RendererBase` subclass. + The renderer to use. + offset : array-like + Offset the colorbar needs to be pushed to in order to + account for multiple colorbars. + """ + + parents = cbax._colorbar_info['parents'] + gs = parents[0].get_gridspec() + fig = cbax.get_figure(root=False) + trans_fig_to_subfig = fig.transFigure - fig.transSubfigure + + cb_rspans, cb_cspans = get_cb_parent_spans(cbax) + bboxparent = layoutgrids[gs].get_bbox_for_cb(rows=cb_rspans, + cols=cb_cspans) + pb = layoutgrids[gs].get_inner_bbox(rows=cb_rspans, cols=cb_cspans) + + location = cbax._colorbar_info['location'] + anchor = cbax._colorbar_info['anchor'] + fraction = cbax._colorbar_info['fraction'] + aspect = cbax._colorbar_info['aspect'] + shrink = cbax._colorbar_info['shrink'] + + cbpos, cbbbox = get_pos_and_bbox(cbax, renderer) + + # Colorbar gets put at extreme edge of outer bbox of the subplotspec + # It needs to be moved in by: 1) a pad 2) its "margin" 3) by + # any colorbars already added at this location: + cbpad = colorbar_get_pad(layoutgrids, cbax) + if location in ('left', 'right'): + # fraction and shrink are fractions of parent + pbcb = pb.shrunk(fraction, shrink).anchored(anchor, pb) + # The colorbar is at the left side of the parent. Need + # to translate to right (or left) + if location == 'right': + lmargin = cbpos.x0 - cbbbox.x0 + dx = bboxparent.x1 - pbcb.x0 + offset['right'] + dx += cbpad + lmargin + offset['right'] += cbbbox.width + cbpad + pbcb = pbcb.translated(dx, 0) + else: + lmargin = cbpos.x0 - cbbbox.x0 + dx = bboxparent.x0 - pbcb.x0 # edge of parent + dx += -cbbbox.width - cbpad + lmargin - offset['left'] + offset['left'] += cbbbox.width + cbpad + pbcb = pbcb.translated(dx, 0) + else: # horizontal axes: + pbcb = pb.shrunk(shrink, fraction).anchored(anchor, pb) + if location == 'top': + bmargin = cbpos.y0 - cbbbox.y0 + dy = bboxparent.y1 - pbcb.y0 + offset['top'] + dy += cbpad + bmargin + offset['top'] += cbbbox.height + cbpad + pbcb = pbcb.translated(0, dy) + else: + bmargin = cbpos.y0 - cbbbox.y0 + dy = bboxparent.y0 - pbcb.y0 + dy += -cbbbox.height - cbpad + bmargin - offset['bottom'] + offset['bottom'] += cbbbox.height + cbpad + pbcb = pbcb.translated(0, dy) + + pbcb = trans_fig_to_subfig.transform_bbox(pbcb) + cbax.set_transform(fig.transSubfigure) + cbax._set_position(pbcb) + cbax.set_anchor(anchor) + if location in ['bottom', 'top']: + aspect = 1 / aspect + cbax.set_box_aspect(aspect) + cbax.set_aspect('auto') + return offset + + +def reset_margins(layoutgrids, fig): + """ + Reset the margins in the layoutboxes of *fig*. + + Margins are usually set as a minimum, so if the figure gets smaller + the minimum needs to be zero in order for it to grow again. + """ + for sfig in fig.subfigs: + reset_margins(layoutgrids, sfig) + for ax in fig.axes: + if ax.get_in_layout(): + gs = ax.get_gridspec() + if gs in layoutgrids: # also implies gs is not None. + layoutgrids[gs].reset_margins() + layoutgrids[fig].reset_margins() + + +def colorbar_get_pad(layoutgrids, cax): + parents = cax._colorbar_info['parents'] + gs = parents[0].get_gridspec() + + cb_rspans, cb_cspans = get_cb_parent_spans(cax) + bboxouter = layoutgrids[gs].get_inner_bbox(rows=cb_rspans, cols=cb_cspans) + + if cax._colorbar_info['location'] in ['right', 'left']: + size = bboxouter.width + else: + size = bboxouter.height + + return cax._colorbar_info['pad'] * size diff --git a/infer_4_30_0/lib/python3.10/site-packages/matplotlib/_docstring.py b/infer_4_30_0/lib/python3.10/site-packages/matplotlib/_docstring.py new file mode 100644 index 0000000000000000000000000000000000000000..8cc7d623efe5c3bb3421e78bccf63b75ee76614d --- /dev/null +++ b/infer_4_30_0/lib/python3.10/site-packages/matplotlib/_docstring.py @@ -0,0 +1,141 @@ +import inspect + +from . import _api + + +def kwarg_doc(text): + """ + Decorator for defining the kwdoc documentation of artist properties. + + This decorator can be applied to artist property setter methods. + The given text is stored in a private attribute ``_kwarg_doc`` on + the method. It is used to overwrite auto-generated documentation + in the *kwdoc list* for artists. The kwdoc list is used to document + ``**kwargs`` when they are properties of an artist. See e.g. the + ``**kwargs`` section in `.Axes.text`. + + The text should contain the supported types, as well as the default + value if applicable, e.g.: + + @_docstring.kwarg_doc("bool, default: :rc:`text.usetex`") + def set_usetex(self, usetex): + + See Also + -------- + matplotlib.artist.kwdoc + + """ + def decorator(func): + func._kwarg_doc = text + return func + return decorator + + +class Substitution: + """ + A decorator that performs %-substitution on an object's docstring. + + This decorator should be robust even if ``obj.__doc__`` is None (for + example, if -OO was passed to the interpreter). + + Usage: construct a docstring.Substitution with a sequence or dictionary + suitable for performing substitution; then decorate a suitable function + with the constructed object, e.g.:: + + sub_author_name = Substitution(author='Jason') + + @sub_author_name + def some_function(x): + "%(author)s wrote this function" + + # note that some_function.__doc__ is now "Jason wrote this function" + + One can also use positional arguments:: + + sub_first_last_names = Substitution('Edgar Allen', 'Poe') + + @sub_first_last_names + def some_function(x): + "%s %s wrote the Raven" + """ + def __init__(self, *args, **kwargs): + if args and kwargs: + raise TypeError("Only positional or keyword args are allowed") + self.params = args or kwargs + + def __call__(self, func): + if func.__doc__: + func.__doc__ = inspect.cleandoc(func.__doc__) % self.params + return func + + +class _ArtistKwdocLoader(dict): + def __missing__(self, key): + if not key.endswith(":kwdoc"): + raise KeyError(key) + name = key[:-len(":kwdoc")] + from matplotlib.artist import Artist, kwdoc + try: + cls, = (cls for cls in _api.recursive_subclasses(Artist) + if cls.__name__ == name) + except ValueError as e: + raise KeyError(key) from e + return self.setdefault(key, kwdoc(cls)) + + +class _ArtistPropertiesSubstitution: + """ + A class to substitute formatted placeholders in docstrings. + + This is realized in a single instance ``_docstring.interpd``. + + Use `~._ArtistPropertiesSubstition.register` to define placeholders and + their substitution, e.g. ``_docstring.interpd.register(name="some value")``. + + Use this as a decorator to apply the substitution:: + + @_docstring.interpd + def some_func(): + '''Replace %(name)s.''' + + Decorating a class triggers substitution both on the class docstring and + on the class' ``__init__`` docstring (which is a commonly required + pattern for Artist subclasses). + + Substitutions of the form ``%(classname:kwdoc)s`` (ending with the + literal ":kwdoc" suffix) trigger lookup of an Artist subclass with the + given *classname*, and are substituted with the `.kwdoc` of that class. + """ + + def __init__(self): + self.params = _ArtistKwdocLoader() + + def register(self, **kwargs): + """ + Register substitutions. + + ``_docstring.interpd.register(name="some value")`` makes "name" available + as a named parameter that will be replaced by "some value". + """ + self.params.update(**kwargs) + + def __call__(self, obj): + if obj.__doc__: + obj.__doc__ = inspect.cleandoc(obj.__doc__) % self.params + if isinstance(obj, type) and obj.__init__ != object.__init__: + self(obj.__init__) + return obj + + +def copy(source): + """Copy a docstring from another source function (if present).""" + def do_copy(target): + if source.__doc__: + target.__doc__ = source.__doc__ + return target + return do_copy + + +# Create a decorator that will house the various docstring snippets reused +# throughout Matplotlib. +interpd = _ArtistPropertiesSubstitution() diff --git a/infer_4_30_0/lib/python3.10/site-packages/matplotlib/_docstring.pyi b/infer_4_30_0/lib/python3.10/site-packages/matplotlib/_docstring.pyi new file mode 100644 index 0000000000000000000000000000000000000000..fb52d084612399f399e6bcd3f07bca85bb010ba0 --- /dev/null +++ b/infer_4_30_0/lib/python3.10/site-packages/matplotlib/_docstring.pyi @@ -0,0 +1,34 @@ +from collections.abc import Callable +from typing import Any, TypeVar, overload + + +_T = TypeVar('_T') + + +def kwarg_doc(text: str) -> Callable[[_T], _T]: ... + + +class Substitution: + @overload + def __init__(self, *args: str): ... + @overload + def __init__(self, **kwargs: str): ... + def __call__(self, func: _T) -> _T: ... + def update(self, *args, **kwargs): ... # type: ignore[no-untyped-def] + + +class _ArtistKwdocLoader(dict[str, str]): + def __missing__(self, key: str) -> str: ... + + +class _ArtistPropertiesSubstitution: + def __init__(self) -> None: ... + def register(self, **kwargs) -> None: ... + def __call__(self, obj: _T) -> _T: ... + + +def copy(source: Any) -> Callable[[_T], _T]: ... + + +dedent_interpd: _ArtistPropertiesSubstitution +interpd: _ArtistPropertiesSubstitution diff --git a/infer_4_30_0/lib/python3.10/site-packages/matplotlib/_enums.py b/infer_4_30_0/lib/python3.10/site-packages/matplotlib/_enums.py new file mode 100644 index 0000000000000000000000000000000000000000..75a09b7b5d8c7f9097e965d76fbae7bab2b41a01 --- /dev/null +++ b/infer_4_30_0/lib/python3.10/site-packages/matplotlib/_enums.py @@ -0,0 +1,177 @@ +""" +Enums representing sets of strings that Matplotlib uses as input parameters. + +Matplotlib often uses simple data types like strings or tuples to define a +concept; e.g. the line capstyle can be specified as one of 'butt', 'round', +or 'projecting'. The classes in this module are used internally and serve to +document these concepts formally. + +As an end-user you will not use these classes directly, but only the values +they define. +""" + +from enum import Enum +from matplotlib import _docstring + + +class JoinStyle(str, Enum): + """ + Define how the connection between two line segments is drawn. + + For a visual impression of each *JoinStyle*, `view these docs online + `, or run `JoinStyle.demo`. + + Lines in Matplotlib are typically defined by a 1D `~.path.Path` and a + finite ``linewidth``, where the underlying 1D `~.path.Path` represents the + center of the stroked line. + + By default, `~.backend_bases.GraphicsContextBase` defines the boundaries of + a stroked line to simply be every point within some radius, + ``linewidth/2``, away from any point of the center line. However, this + results in corners appearing "rounded", which may not be the desired + behavior if you are drawing, for example, a polygon or pointed star. + + **Supported values:** + + .. rst-class:: value-list + + 'miter' + the "arrow-tip" style. Each boundary of the filled-in area will + extend in a straight line parallel to the tangent vector of the + centerline at the point it meets the corner, until they meet in a + sharp point. + 'round' + stokes every point within a radius of ``linewidth/2`` of the center + lines. + 'bevel' + the "squared-off" style. It can be thought of as a rounded corner + where the "circular" part of the corner has been cut off. + + .. note:: + + Very long miter tips are cut off (to form a *bevel*) after a + backend-dependent limit called the "miter limit", which specifies the + maximum allowed ratio of miter length to line width. For example, the + PDF backend uses the default value of 10 specified by the PDF standard, + while the SVG backend does not even specify the miter limit, resulting + in a default value of 4 per the SVG specification. Matplotlib does not + currently allow the user to adjust this parameter. + + A more detailed description of the effect of a miter limit can be found + in the `Mozilla Developer Docs + `_ + + .. plot:: + :alt: Demo of possible JoinStyle's + + from matplotlib._enums import JoinStyle + JoinStyle.demo() + + """ + + miter = "miter" + round = "round" + bevel = "bevel" + + @staticmethod + def demo(): + """Demonstrate how each JoinStyle looks for various join angles.""" + import numpy as np + import matplotlib.pyplot as plt + + def plot_angle(ax, x, y, angle, style): + phi = np.radians(angle) + xx = [x + .5, x, x + .5*np.cos(phi)] + yy = [y, y, y + .5*np.sin(phi)] + ax.plot(xx, yy, lw=12, color='tab:blue', solid_joinstyle=style) + ax.plot(xx, yy, lw=1, color='black') + ax.plot(xx[1], yy[1], 'o', color='tab:red', markersize=3) + + fig, ax = plt.subplots(figsize=(5, 4), constrained_layout=True) + ax.set_title('Join style') + for x, style in enumerate(['miter', 'round', 'bevel']): + ax.text(x, 5, style) + for y, angle in enumerate([20, 45, 60, 90, 120]): + plot_angle(ax, x, y, angle, style) + if x == 0: + ax.text(-1.3, y, f'{angle} degrees') + ax.set_xlim(-1.5, 2.75) + ax.set_ylim(-.5, 5.5) + ax.set_axis_off() + fig.show() + + +JoinStyle.input_description = "{" \ + + ", ".join([f"'{js.name}'" for js in JoinStyle]) \ + + "}" + + +class CapStyle(str, Enum): + r""" + Define how the two endpoints (caps) of an unclosed line are drawn. + + How to draw the start and end points of lines that represent a closed curve + (i.e. that end in a `~.path.Path.CLOSEPOLY`) is controlled by the line's + `JoinStyle`. For all other lines, how the start and end points are drawn is + controlled by the *CapStyle*. + + For a visual impression of each *CapStyle*, `view these docs online + ` or run `CapStyle.demo`. + + By default, `~.backend_bases.GraphicsContextBase` draws a stroked line as + squared off at its endpoints. + + **Supported values:** + + .. rst-class:: value-list + + 'butt' + the line is squared off at its endpoint. + 'projecting' + the line is squared off as in *butt*, but the filled in area + extends beyond the endpoint a distance of ``linewidth/2``. + 'round' + like *butt*, but a semicircular cap is added to the end of the + line, of radius ``linewidth/2``. + + .. plot:: + :alt: Demo of possible CapStyle's + + from matplotlib._enums import CapStyle + CapStyle.demo() + + """ + butt = "butt" + projecting = "projecting" + round = "round" + + @staticmethod + def demo(): + """Demonstrate how each CapStyle looks for a thick line segment.""" + import matplotlib.pyplot as plt + + fig = plt.figure(figsize=(4, 1.2)) + ax = fig.add_axes([0, 0, 1, 0.8]) + ax.set_title('Cap style') + + for x, style in enumerate(['butt', 'round', 'projecting']): + ax.text(x+0.25, 0.85, style, ha='center') + xx = [x, x+0.5] + yy = [0, 0] + ax.plot(xx, yy, lw=12, color='tab:blue', solid_capstyle=style) + ax.plot(xx, yy, lw=1, color='black') + ax.plot(xx, yy, 'o', color='tab:red', markersize=3) + + ax.set_ylim(-.5, 1.5) + ax.set_axis_off() + fig.show() + + +CapStyle.input_description = "{" \ + + ", ".join([f"'{cs.name}'" for cs in CapStyle]) \ + + "}" + +_docstring.interpd.register( + JoinStyle=JoinStyle.input_description, + CapStyle=CapStyle.input_description, +) diff --git a/infer_4_30_0/lib/python3.10/site-packages/matplotlib/_mathtext.py b/infer_4_30_0/lib/python3.10/site-packages/matplotlib/_mathtext.py new file mode 100644 index 0000000000000000000000000000000000000000..6a1d9add9e8a4e677fa74568cbe5562b39239430 --- /dev/null +++ b/infer_4_30_0/lib/python3.10/site-packages/matplotlib/_mathtext.py @@ -0,0 +1,2861 @@ +""" +Implementation details for :mod:`.mathtext`. +""" + +from __future__ import annotations + +import abc +import copy +import enum +import functools +import logging +import os +import re +import types +import unicodedata +import string +import typing as T +from typing import NamedTuple + +import numpy as np +from pyparsing import ( + Empty, Forward, Literal, NotAny, oneOf, OneOrMore, Optional, + ParseBaseException, ParseException, ParseExpression, ParseFatalException, + ParserElement, ParseResults, QuotedString, Regex, StringEnd, ZeroOrMore, + pyparsing_common, Group) + +import matplotlib as mpl +from . import cbook +from ._mathtext_data import ( + latex_to_bakoma, stix_glyph_fixes, stix_virtual_fonts, tex2uni) +from .font_manager import FontProperties, findfont, get_font +from .ft2font import FT2Font, FT2Image, Kerning, LoadFlags + +from packaging.version import parse as parse_version +from pyparsing import __version__ as pyparsing_version +if parse_version(pyparsing_version).major < 3: + from pyparsing import nestedExpr as nested_expr +else: + from pyparsing import nested_expr + +if T.TYPE_CHECKING: + from collections.abc import Iterable + from .ft2font import Glyph + +ParserElement.enablePackrat() +_log = logging.getLogger("matplotlib.mathtext") + + +############################################################################## +# FONTS + + +def get_unicode_index(symbol: str) -> int: # Publicly exported. + r""" + Return the integer index (from the Unicode table) of *symbol*. + + Parameters + ---------- + symbol : str + A single (Unicode) character, a TeX command (e.g. r'\pi') or a Type1 + symbol name (e.g. 'phi'). + """ + try: # This will succeed if symbol is a single Unicode char + return ord(symbol) + except TypeError: + pass + try: # Is symbol a TeX symbol (i.e. \alpha) + return tex2uni[symbol.strip("\\")] + except KeyError as err: + raise ValueError( + f"{symbol!r} is not a valid Unicode character or TeX/Type1 symbol" + ) from err + + +class VectorParse(NamedTuple): + """ + The namedtuple type returned by ``MathTextParser("path").parse(...)``. + + Attributes + ---------- + width, height, depth : float + The global metrics. + glyphs : list + The glyphs including their positions. + rect : list + The list of rectangles. + """ + width: float + height: float + depth: float + glyphs: list[tuple[FT2Font, float, int, float, float]] + rects: list[tuple[float, float, float, float]] + +VectorParse.__module__ = "matplotlib.mathtext" + + +class RasterParse(NamedTuple): + """ + The namedtuple type returned by ``MathTextParser("agg").parse(...)``. + + Attributes + ---------- + ox, oy : float + The offsets are always zero. + width, height, depth : float + The global metrics. + image : FT2Image + A raster image. + """ + ox: float + oy: float + width: float + height: float + depth: float + image: FT2Image + +RasterParse.__module__ = "matplotlib.mathtext" + + +class Output: + r""" + Result of `ship`\ping a box: lists of positioned glyphs and rectangles. + + This class is not exposed to end users, but converted to a `VectorParse` or + a `RasterParse` by `.MathTextParser.parse`. + """ + + def __init__(self, box: Box): + self.box = box + self.glyphs: list[tuple[float, float, FontInfo]] = [] # (ox, oy, info) + self.rects: list[tuple[float, float, float, float]] = [] # (x1, y1, x2, y2) + + def to_vector(self) -> VectorParse: + w, h, d = map( + np.ceil, [self.box.width, self.box.height, self.box.depth]) + gs = [(info.font, info.fontsize, info.num, ox, h - oy + info.offset) + for ox, oy, info in self.glyphs] + rs = [(x1, h - y2, x2 - x1, y2 - y1) + for x1, y1, x2, y2 in self.rects] + return VectorParse(w, h + d, d, gs, rs) + + def to_raster(self, *, antialiased: bool) -> RasterParse: + # Metrics y's and mathtext y's are oriented in opposite directions, + # hence the switch between ymin and ymax. + xmin = min([*[ox + info.metrics.xmin for ox, oy, info in self.glyphs], + *[x1 for x1, y1, x2, y2 in self.rects], 0]) - 1 + ymin = min([*[oy - info.metrics.ymax for ox, oy, info in self.glyphs], + *[y1 for x1, y1, x2, y2 in self.rects], 0]) - 1 + xmax = max([*[ox + info.metrics.xmax for ox, oy, info in self.glyphs], + *[x2 for x1, y1, x2, y2 in self.rects], 0]) + 1 + ymax = max([*[oy - info.metrics.ymin for ox, oy, info in self.glyphs], + *[y2 for x1, y1, x2, y2 in self.rects], 0]) + 1 + w = xmax - xmin + h = ymax - ymin - self.box.depth + d = ymax - ymin - self.box.height + image = FT2Image(int(np.ceil(w)), int(np.ceil(h + max(d, 0)))) + + # Ideally, we could just use self.glyphs and self.rects here, shifting + # their coordinates by (-xmin, -ymin), but this yields slightly + # different results due to floating point slop; shipping twice is the + # old approach and keeps baseline images backcompat. + shifted = ship(self.box, (-xmin, -ymin)) + + for ox, oy, info in shifted.glyphs: + info.font.draw_glyph_to_bitmap( + image, int(ox), int(oy - info.metrics.iceberg), info.glyph, + antialiased=antialiased) + for x1, y1, x2, y2 in shifted.rects: + height = max(int(y2 - y1) - 1, 0) + if height == 0: + center = (y2 + y1) / 2 + y = int(center - (height + 1) / 2) + else: + y = int(y1) + image.draw_rect_filled(int(x1), y, int(np.ceil(x2)), y + height) + return RasterParse(0, 0, w, h + d, d, image) + + +class FontMetrics(NamedTuple): + """ + Metrics of a font. + + Attributes + ---------- + advance : float + The advance distance (in points) of the glyph. + height : float + The height of the glyph in points. + width : float + The width of the glyph in points. + xmin, xmax, ymin, ymax : float + The ink rectangle of the glyph. + iceberg : float + The distance from the baseline to the top of the glyph. (This corresponds to + TeX's definition of "height".) + slanted : bool + Whether the glyph should be considered as "slanted" (currently used for kerning + sub/superscripts). + """ + advance: float + height: float + width: float + xmin: float + xmax: float + ymin: float + ymax: float + iceberg: float + slanted: bool + + +class FontInfo(NamedTuple): + font: FT2Font + fontsize: float + postscript_name: str + metrics: FontMetrics + num: int + glyph: Glyph + offset: float + + +class Fonts(abc.ABC): + """ + An abstract base class for a system of fonts to use for mathtext. + + The class must be able to take symbol keys and font file names and + return the character metrics. It also delegates to a backend class + to do the actual drawing. + """ + + def __init__(self, default_font_prop: FontProperties, load_glyph_flags: LoadFlags): + """ + Parameters + ---------- + default_font_prop : `~.font_manager.FontProperties` + The default non-math font, or the base font for Unicode (generic) + font rendering. + load_glyph_flags : `.ft2font.LoadFlags` + Flags passed to the glyph loader (e.g. ``FT_Load_Glyph`` and + ``FT_Load_Char`` for FreeType-based fonts). + """ + self.default_font_prop = default_font_prop + self.load_glyph_flags = load_glyph_flags + + def get_kern(self, font1: str, fontclass1: str, sym1: str, fontsize1: float, + font2: str, fontclass2: str, sym2: str, fontsize2: float, + dpi: float) -> float: + """ + Get the kerning distance for font between *sym1* and *sym2*. + + See `~.Fonts.get_metrics` for a detailed description of the parameters. + """ + return 0. + + def _get_font(self, font: str) -> FT2Font: + raise NotImplementedError + + def _get_info(self, font: str, font_class: str, sym: str, fontsize: float, + dpi: float) -> FontInfo: + raise NotImplementedError + + def get_metrics(self, font: str, font_class: str, sym: str, fontsize: float, + dpi: float) -> FontMetrics: + r""" + Parameters + ---------- + font : str + One of the TeX font names: "tt", "it", "rm", "cal", "sf", "bf", + "default", "regular", "bb", "frak", "scr". "default" and "regular" + are synonyms and use the non-math font. + font_class : str + One of the TeX font names (as for *font*), but **not** "bb", + "frak", or "scr". This is used to combine two font classes. The + only supported combination currently is ``get_metrics("frak", "bf", + ...)``. + sym : str + A symbol in raw TeX form, e.g., "1", "x", or "\sigma". + fontsize : float + Font size in points. + dpi : float + Rendering dots-per-inch. + + Returns + ------- + FontMetrics + """ + info = self._get_info(font, font_class, sym, fontsize, dpi) + return info.metrics + + def render_glyph(self, output: Output, ox: float, oy: float, font: str, + font_class: str, sym: str, fontsize: float, dpi: float) -> None: + """ + At position (*ox*, *oy*), draw the glyph specified by the remaining + parameters (see `get_metrics` for their detailed description). + """ + info = self._get_info(font, font_class, sym, fontsize, dpi) + output.glyphs.append((ox, oy, info)) + + def render_rect_filled(self, output: Output, + x1: float, y1: float, x2: float, y2: float) -> None: + """ + Draw a filled rectangle from (*x1*, *y1*) to (*x2*, *y2*). + """ + output.rects.append((x1, y1, x2, y2)) + + def get_xheight(self, font: str, fontsize: float, dpi: float) -> float: + """ + Get the xheight for the given *font* and *fontsize*. + """ + raise NotImplementedError() + + def get_underline_thickness(self, font: str, fontsize: float, dpi: float) -> float: + """ + Get the line thickness that matches the given font. Used as a + base unit for drawing lines such as in a fraction or radical. + """ + raise NotImplementedError() + + def get_sized_alternatives_for_symbol(self, fontname: str, + sym: str) -> list[tuple[str, str]]: + """ + Override if your font provides multiple sizes of the same + symbol. Should return a list of symbols matching *sym* in + various sizes. The expression renderer will select the most + appropriate size for a given situation from this list. + """ + return [(fontname, sym)] + + +class TruetypeFonts(Fonts, metaclass=abc.ABCMeta): + """ + A generic base class for all font setups that use Truetype fonts + (through FT2Font). + """ + + def __init__(self, default_font_prop: FontProperties, load_glyph_flags: LoadFlags): + super().__init__(default_font_prop, load_glyph_flags) + # Per-instance cache. + self._get_info = functools.cache(self._get_info) # type: ignore[method-assign] + self._fonts = {} + self.fontmap: dict[str | int, str] = {} + + filename = findfont(self.default_font_prop) + default_font = get_font(filename) + self._fonts['default'] = default_font + self._fonts['regular'] = default_font + + def _get_font(self, font: str | int) -> FT2Font: + if font in self.fontmap: + basename = self.fontmap[font] + else: + # NOTE: An int is only passed by subclasses which have placed int keys into + # `self.fontmap`, so we must cast this to confirm it to typing. + basename = T.cast(str, font) + cached_font = self._fonts.get(basename) + if cached_font is None and os.path.exists(basename): + cached_font = get_font(basename) + self._fonts[basename] = cached_font + self._fonts[cached_font.postscript_name] = cached_font + self._fonts[cached_font.postscript_name.lower()] = cached_font + return T.cast(FT2Font, cached_font) # FIXME: Not sure this is guaranteed. + + def _get_offset(self, font: FT2Font, glyph: Glyph, fontsize: float, + dpi: float) -> float: + if font.postscript_name == 'Cmex10': + return (glyph.height / 64 / 2) + (fontsize/3 * dpi/72) + return 0. + + def _get_glyph(self, fontname: str, font_class: str, + sym: str) -> tuple[FT2Font, int, bool]: + raise NotImplementedError + + # The return value of _get_info is cached per-instance. + def _get_info(self, fontname: str, font_class: str, sym: str, fontsize: float, + dpi: float) -> FontInfo: + font, num, slanted = self._get_glyph(fontname, font_class, sym) + font.set_size(fontsize, dpi) + glyph = font.load_char(num, flags=self.load_glyph_flags) + + xmin, ymin, xmax, ymax = (val / 64 for val in glyph.bbox) + offset = self._get_offset(font, glyph, fontsize, dpi) + metrics = FontMetrics( + advance=glyph.linearHoriAdvance / 65536, + height=glyph.height / 64, + width=glyph.width / 64, + xmin=xmin, + xmax=xmax, + ymin=ymin + offset, + ymax=ymax + offset, + # iceberg is the equivalent of TeX's "height" + iceberg=glyph.horiBearingY / 64 + offset, + slanted=slanted + ) + + return FontInfo( + font=font, + fontsize=fontsize, + postscript_name=font.postscript_name, + metrics=metrics, + num=num, + glyph=glyph, + offset=offset + ) + + def get_xheight(self, fontname: str, fontsize: float, dpi: float) -> float: + font = self._get_font(fontname) + font.set_size(fontsize, dpi) + pclt = font.get_sfnt_table('pclt') + if pclt is None: + # Some fonts don't store the xHeight, so we do a poor man's xHeight + metrics = self.get_metrics( + fontname, mpl.rcParams['mathtext.default'], 'x', fontsize, dpi) + return metrics.iceberg + xHeight = (pclt['xHeight'] / 64.0) * (fontsize / 12.0) * (dpi / 100.0) + return xHeight + + def get_underline_thickness(self, font: str, fontsize: float, dpi: float) -> float: + # This function used to grab underline thickness from the font + # metrics, but that information is just too un-reliable, so it + # is now hardcoded. + return ((0.75 / 12.0) * fontsize * dpi) / 72.0 + + def get_kern(self, font1: str, fontclass1: str, sym1: str, fontsize1: float, + font2: str, fontclass2: str, sym2: str, fontsize2: float, + dpi: float) -> float: + if font1 == font2 and fontsize1 == fontsize2: + info1 = self._get_info(font1, fontclass1, sym1, fontsize1, dpi) + info2 = self._get_info(font2, fontclass2, sym2, fontsize2, dpi) + font = info1.font + return font.get_kerning(info1.num, info2.num, Kerning.DEFAULT) / 64 + return super().get_kern(font1, fontclass1, sym1, fontsize1, + font2, fontclass2, sym2, fontsize2, dpi) + + +class BakomaFonts(TruetypeFonts): + """ + Use the Bakoma TrueType fonts for rendering. + + Symbols are strewn about a number of font files, each of which has + its own proprietary 8-bit encoding. + """ + _fontmap = { + 'cal': 'cmsy10', + 'rm': 'cmr10', + 'tt': 'cmtt10', + 'it': 'cmmi10', + 'bf': 'cmb10', + 'sf': 'cmss10', + 'ex': 'cmex10', + } + + def __init__(self, default_font_prop: FontProperties, load_glyph_flags: LoadFlags): + self._stix_fallback = StixFonts(default_font_prop, load_glyph_flags) + + super().__init__(default_font_prop, load_glyph_flags) + for key, val in self._fontmap.items(): + fullpath = findfont(val) + self.fontmap[key] = fullpath + self.fontmap[val] = fullpath + + _slanted_symbols = set(r"\int \oint".split()) + + def _get_glyph(self, fontname: str, font_class: str, + sym: str) -> tuple[FT2Font, int, bool]: + font = None + if fontname in self.fontmap and sym in latex_to_bakoma: + basename, num = latex_to_bakoma[sym] + slanted = (basename == "cmmi10") or sym in self._slanted_symbols + font = self._get_font(basename) + elif len(sym) == 1: + slanted = (fontname == "it") + font = self._get_font(fontname) + if font is not None: + num = ord(sym) + if font is not None and font.get_char_index(num) != 0: + return font, num, slanted + else: + return self._stix_fallback._get_glyph(fontname, font_class, sym) + + # The Bakoma fonts contain many pre-sized alternatives for the + # delimiters. The AutoSizedChar class will use these alternatives + # and select the best (closest sized) glyph. + _size_alternatives = { + '(': [('rm', '('), ('ex', '\xa1'), ('ex', '\xb3'), + ('ex', '\xb5'), ('ex', '\xc3')], + ')': [('rm', ')'), ('ex', '\xa2'), ('ex', '\xb4'), + ('ex', '\xb6'), ('ex', '\x21')], + '{': [('cal', '{'), ('ex', '\xa9'), ('ex', '\x6e'), + ('ex', '\xbd'), ('ex', '\x28')], + '}': [('cal', '}'), ('ex', '\xaa'), ('ex', '\x6f'), + ('ex', '\xbe'), ('ex', '\x29')], + # The fourth size of '[' is mysteriously missing from the BaKoMa + # font, so I've omitted it for both '[' and ']' + '[': [('rm', '['), ('ex', '\xa3'), ('ex', '\x68'), + ('ex', '\x22')], + ']': [('rm', ']'), ('ex', '\xa4'), ('ex', '\x69'), + ('ex', '\x23')], + r'\lfloor': [('ex', '\xa5'), ('ex', '\x6a'), + ('ex', '\xb9'), ('ex', '\x24')], + r'\rfloor': [('ex', '\xa6'), ('ex', '\x6b'), + ('ex', '\xba'), ('ex', '\x25')], + r'\lceil': [('ex', '\xa7'), ('ex', '\x6c'), + ('ex', '\xbb'), ('ex', '\x26')], + r'\rceil': [('ex', '\xa8'), ('ex', '\x6d'), + ('ex', '\xbc'), ('ex', '\x27')], + r'\langle': [('ex', '\xad'), ('ex', '\x44'), + ('ex', '\xbf'), ('ex', '\x2a')], + r'\rangle': [('ex', '\xae'), ('ex', '\x45'), + ('ex', '\xc0'), ('ex', '\x2b')], + r'\__sqrt__': [('ex', '\x70'), ('ex', '\x71'), + ('ex', '\x72'), ('ex', '\x73')], + r'\backslash': [('ex', '\xb2'), ('ex', '\x2f'), + ('ex', '\xc2'), ('ex', '\x2d')], + r'/': [('rm', '/'), ('ex', '\xb1'), ('ex', '\x2e'), + ('ex', '\xcb'), ('ex', '\x2c')], + r'\widehat': [('rm', '\x5e'), ('ex', '\x62'), ('ex', '\x63'), + ('ex', '\x64')], + r'\widetilde': [('rm', '\x7e'), ('ex', '\x65'), ('ex', '\x66'), + ('ex', '\x67')], + r'<': [('cal', 'h'), ('ex', 'D')], + r'>': [('cal', 'i'), ('ex', 'E')] + } + + for alias, target in [(r'\leftparen', '('), + (r'\rightparent', ')'), + (r'\leftbrace', '{'), + (r'\rightbrace', '}'), + (r'\leftbracket', '['), + (r'\rightbracket', ']'), + (r'\{', '{'), + (r'\}', '}'), + (r'\[', '['), + (r'\]', ']')]: + _size_alternatives[alias] = _size_alternatives[target] + + def get_sized_alternatives_for_symbol(self, fontname: str, + sym: str) -> list[tuple[str, str]]: + return self._size_alternatives.get(sym, [(fontname, sym)]) + + +class UnicodeFonts(TruetypeFonts): + """ + An abstract base class for handling Unicode fonts. + + While some reasonably complete Unicode fonts (such as DejaVu) may + work in some situations, the only Unicode font I'm aware of with a + complete set of math symbols is STIX. + + This class will "fallback" on the Bakoma fonts when a required + symbol cannot be found in the font. + """ + + # Some glyphs are not present in the `cmr10` font, and must be brought in + # from `cmsy10`. Map the Unicode indices of those glyphs to the indices at + # which they are found in `cmsy10`. + _cmr10_substitutions = { + 0x00D7: 0x00A3, # Multiplication sign. + 0x2212: 0x00A1, # Minus sign. + } + + def __init__(self, default_font_prop: FontProperties, load_glyph_flags: LoadFlags): + # This must come first so the backend's owner is set correctly + fallback_rc = mpl.rcParams['mathtext.fallback'] + font_cls: type[TruetypeFonts] | None = { + 'stix': StixFonts, + 'stixsans': StixSansFonts, + 'cm': BakomaFonts + }.get(fallback_rc) + self._fallback_font = (font_cls(default_font_prop, load_glyph_flags) + if font_cls else None) + + super().__init__(default_font_prop, load_glyph_flags) + for texfont in "cal rm tt it bf sf bfit".split(): + prop = mpl.rcParams['mathtext.' + texfont] + font = findfont(prop) + self.fontmap[texfont] = font + prop = FontProperties('cmex10') + font = findfont(prop) + self.fontmap['ex'] = font + + # include STIX sized alternatives for glyphs if fallback is STIX + if isinstance(self._fallback_font, StixFonts): + stixsizedaltfonts = { + 0: 'STIXGeneral', + 1: 'STIXSizeOneSym', + 2: 'STIXSizeTwoSym', + 3: 'STIXSizeThreeSym', + 4: 'STIXSizeFourSym', + 5: 'STIXSizeFiveSym'} + + for size, name in stixsizedaltfonts.items(): + fullpath = findfont(name) + self.fontmap[size] = fullpath + self.fontmap[name] = fullpath + + _slanted_symbols = set(r"\int \oint".split()) + + def _map_virtual_font(self, fontname: str, font_class: str, + uniindex: int) -> tuple[str, int]: + return fontname, uniindex + + def _get_glyph(self, fontname: str, font_class: str, + sym: str) -> tuple[FT2Font, int, bool]: + try: + uniindex = get_unicode_index(sym) + found_symbol = True + except ValueError: + uniindex = ord('?') + found_symbol = False + _log.warning("No TeX to Unicode mapping for %a.", sym) + + fontname, uniindex = self._map_virtual_font( + fontname, font_class, uniindex) + + new_fontname = fontname + + # Only characters in the "Letter" class should be italicized in 'it' + # mode. Greek capital letters should be Roman. + if found_symbol: + if fontname == 'it' and uniindex < 0x10000: + char = chr(uniindex) + if (unicodedata.category(char)[0] != "L" + or unicodedata.name(char).startswith("GREEK CAPITAL")): + new_fontname = 'rm' + + slanted = (new_fontname == 'it') or sym in self._slanted_symbols + found_symbol = False + font = self._get_font(new_fontname) + if font is not None: + if (uniindex in self._cmr10_substitutions + and font.family_name == "cmr10"): + font = get_font( + cbook._get_data_path("fonts/ttf/cmsy10.ttf")) + uniindex = self._cmr10_substitutions[uniindex] + glyphindex = font.get_char_index(uniindex) + if glyphindex != 0: + found_symbol = True + + if not found_symbol: + if self._fallback_font: + if (fontname in ('it', 'regular') + and isinstance(self._fallback_font, StixFonts)): + fontname = 'rm' + + g = self._fallback_font._get_glyph(fontname, font_class, sym) + family = g[0].family_name + if family in list(BakomaFonts._fontmap.values()): + family = "Computer Modern" + _log.info("Substituting symbol %s from %s", sym, family) + return g + + else: + if (fontname in ('it', 'regular') + and isinstance(self, StixFonts)): + return self._get_glyph('rm', font_class, sym) + _log.warning("Font %r does not have a glyph for %a [U+%x], " + "substituting with a dummy symbol.", + new_fontname, sym, uniindex) + font = self._get_font('rm') + uniindex = 0xA4 # currency char, for lack of anything better + slanted = False + + return font, uniindex, slanted + + def get_sized_alternatives_for_symbol(self, fontname: str, + sym: str) -> list[tuple[str, str]]: + if self._fallback_font: + return self._fallback_font.get_sized_alternatives_for_symbol( + fontname, sym) + return [(fontname, sym)] + + +class DejaVuFonts(UnicodeFonts, metaclass=abc.ABCMeta): + _fontmap: dict[str | int, str] = {} + + def __init__(self, default_font_prop: FontProperties, load_glyph_flags: LoadFlags): + # This must come first so the backend's owner is set correctly + if isinstance(self, DejaVuSerifFonts): + self._fallback_font = StixFonts(default_font_prop, load_glyph_flags) + else: + self._fallback_font = StixSansFonts(default_font_prop, load_glyph_flags) + self.bakoma = BakomaFonts(default_font_prop, load_glyph_flags) + TruetypeFonts.__init__(self, default_font_prop, load_glyph_flags) + # Include Stix sized alternatives for glyphs + self._fontmap.update({ + 1: 'STIXSizeOneSym', + 2: 'STIXSizeTwoSym', + 3: 'STIXSizeThreeSym', + 4: 'STIXSizeFourSym', + 5: 'STIXSizeFiveSym', + }) + for key, name in self._fontmap.items(): + fullpath = findfont(name) + self.fontmap[key] = fullpath + self.fontmap[name] = fullpath + + def _get_glyph(self, fontname: str, font_class: str, + sym: str) -> tuple[FT2Font, int, bool]: + # Override prime symbol to use Bakoma. + if sym == r'\prime': + return self.bakoma._get_glyph(fontname, font_class, sym) + else: + # check whether the glyph is available in the display font + uniindex = get_unicode_index(sym) + font = self._get_font('ex') + if font is not None: + glyphindex = font.get_char_index(uniindex) + if glyphindex != 0: + return super()._get_glyph('ex', font_class, sym) + # otherwise return regular glyph + return super()._get_glyph(fontname, font_class, sym) + + +class DejaVuSerifFonts(DejaVuFonts): + """ + A font handling class for the DejaVu Serif fonts + + If a glyph is not found it will fallback to Stix Serif + """ + _fontmap = { + 'rm': 'DejaVu Serif', + 'it': 'DejaVu Serif:italic', + 'bf': 'DejaVu Serif:weight=bold', + 'bfit': 'DejaVu Serif:italic:bold', + 'sf': 'DejaVu Sans', + 'tt': 'DejaVu Sans Mono', + 'ex': 'DejaVu Serif Display', + 0: 'DejaVu Serif', + } + + +class DejaVuSansFonts(DejaVuFonts): + """ + A font handling class for the DejaVu Sans fonts + + If a glyph is not found it will fallback to Stix Sans + """ + _fontmap = { + 'rm': 'DejaVu Sans', + 'it': 'DejaVu Sans:italic', + 'bf': 'DejaVu Sans:weight=bold', + 'bfit': 'DejaVu Sans:italic:bold', + 'sf': 'DejaVu Sans', + 'tt': 'DejaVu Sans Mono', + 'ex': 'DejaVu Sans Display', + 0: 'DejaVu Sans', + } + + +class StixFonts(UnicodeFonts): + """ + A font handling class for the STIX fonts. + + In addition to what UnicodeFonts provides, this class: + + - supports "virtual fonts" which are complete alpha numeric + character sets with different font styles at special Unicode + code points, such as "Blackboard". + + - handles sized alternative characters for the STIXSizeX fonts. + """ + _fontmap: dict[str | int, str] = { + 'rm': 'STIXGeneral', + 'it': 'STIXGeneral:italic', + 'bf': 'STIXGeneral:weight=bold', + 'bfit': 'STIXGeneral:italic:bold', + 'nonunirm': 'STIXNonUnicode', + 'nonuniit': 'STIXNonUnicode:italic', + 'nonunibf': 'STIXNonUnicode:weight=bold', + 0: 'STIXGeneral', + 1: 'STIXSizeOneSym', + 2: 'STIXSizeTwoSym', + 3: 'STIXSizeThreeSym', + 4: 'STIXSizeFourSym', + 5: 'STIXSizeFiveSym', + } + _fallback_font = None + _sans = False + + def __init__(self, default_font_prop: FontProperties, load_glyph_flags: LoadFlags): + TruetypeFonts.__init__(self, default_font_prop, load_glyph_flags) + for key, name in self._fontmap.items(): + fullpath = findfont(name) + self.fontmap[key] = fullpath + self.fontmap[name] = fullpath + + def _map_virtual_font(self, fontname: str, font_class: str, + uniindex: int) -> tuple[str, int]: + # Handle these "fonts" that are actually embedded in + # other fonts. + font_mapping = stix_virtual_fonts.get(fontname) + if (self._sans and font_mapping is None + and fontname not in ('regular', 'default')): + font_mapping = stix_virtual_fonts['sf'] + doing_sans_conversion = True + else: + doing_sans_conversion = False + + if isinstance(font_mapping, dict): + try: + mapping = font_mapping[font_class] + except KeyError: + mapping = font_mapping['rm'] + elif isinstance(font_mapping, list): + mapping = font_mapping + else: + mapping = None + + if mapping is not None: + # Binary search for the source glyph + lo = 0 + hi = len(mapping) + while lo < hi: + mid = (lo+hi)//2 + range = mapping[mid] + if uniindex < range[0]: + hi = mid + elif uniindex <= range[1]: + break + else: + lo = mid + 1 + + if range[0] <= uniindex <= range[1]: + uniindex = uniindex - range[0] + range[3] + fontname = range[2] + elif not doing_sans_conversion: + # This will generate a dummy character + uniindex = 0x1 + fontname = mpl.rcParams['mathtext.default'] + + # Fix some incorrect glyphs. + if fontname in ('rm', 'it'): + uniindex = stix_glyph_fixes.get(uniindex, uniindex) + + # Handle private use area glyphs + if fontname in ('it', 'rm', 'bf', 'bfit') and 0xe000 <= uniindex <= 0xf8ff: + fontname = 'nonuni' + fontname + + return fontname, uniindex + + @functools.cache + def get_sized_alternatives_for_symbol( # type: ignore[override] + self, + fontname: str, + sym: str) -> list[tuple[str, str]] | list[tuple[int, str]]: + fixes = { + '\\{': '{', '\\}': '}', '\\[': '[', '\\]': ']', + '<': '\N{MATHEMATICAL LEFT ANGLE BRACKET}', + '>': '\N{MATHEMATICAL RIGHT ANGLE BRACKET}', + } + sym = fixes.get(sym, sym) + try: + uniindex = get_unicode_index(sym) + except ValueError: + return [(fontname, sym)] + alternatives = [(i, chr(uniindex)) for i in range(6) + if self._get_font(i).get_char_index(uniindex) != 0] + # The largest size of the radical symbol in STIX has incorrect + # metrics that cause it to be disconnected from the stem. + if sym == r'\__sqrt__': + alternatives = alternatives[:-1] + return alternatives + + +class StixSansFonts(StixFonts): + """ + A font handling class for the STIX fonts (that uses sans-serif + characters by default). + """ + _sans = True + + +############################################################################## +# TeX-LIKE BOX MODEL + +# The following is based directly on the document 'woven' from the +# TeX82 source code. This information is also available in printed +# form: +# +# Knuth, Donald E.. 1986. Computers and Typesetting, Volume B: +# TeX: The Program. Addison-Wesley Professional. +# +# The most relevant "chapters" are: +# Data structures for boxes and their friends +# Shipping pages out (ship()) +# Packaging (hpack() and vpack()) +# Data structures for math mode +# Subroutines for math mode +# Typesetting math formulas +# +# Many of the docstrings below refer to a numbered "node" in that +# book, e.g., node123 +# +# Note that (as TeX) y increases downward, unlike many other parts of +# matplotlib. + +# How much text shrinks when going to the next-smallest level. +SHRINK_FACTOR = 0.7 +# The number of different sizes of chars to use, beyond which they will not +# get any smaller +NUM_SIZE_LEVELS = 6 + + +class FontConstantsBase: + """ + A set of constants that controls how certain things, such as sub- + and superscripts are laid out. These are all metrics that can't + be reliably retrieved from the font metrics in the font itself. + """ + # Percentage of x-height of additional horiz. space after sub/superscripts + script_space: T.ClassVar[float] = 0.05 + + # Percentage of x-height that sub/superscripts drop below the baseline + subdrop: T.ClassVar[float] = 0.4 + + # Percentage of x-height that superscripts are raised from the baseline + sup1: T.ClassVar[float] = 0.7 + + # Percentage of x-height that subscripts drop below the baseline + sub1: T.ClassVar[float] = 0.3 + + # Percentage of x-height that subscripts drop below the baseline when a + # superscript is present + sub2: T.ClassVar[float] = 0.5 + + # Percentage of x-height that sub/superscripts are offset relative to the + # nucleus edge for non-slanted nuclei + delta: T.ClassVar[float] = 0.025 + + # Additional percentage of last character height above 2/3 of the + # x-height that superscripts are offset relative to the subscript + # for slanted nuclei + delta_slanted: T.ClassVar[float] = 0.2 + + # Percentage of x-height that superscripts and subscripts are offset for + # integrals + delta_integral: T.ClassVar[float] = 0.1 + + +class ComputerModernFontConstants(FontConstantsBase): + script_space = 0.075 + subdrop = 0.2 + sup1 = 0.45 + sub1 = 0.2 + sub2 = 0.3 + delta = 0.075 + delta_slanted = 0.3 + delta_integral = 0.3 + + +class STIXFontConstants(FontConstantsBase): + script_space = 0.1 + sup1 = 0.8 + sub2 = 0.6 + delta = 0.05 + delta_slanted = 0.3 + delta_integral = 0.3 + + +class STIXSansFontConstants(FontConstantsBase): + script_space = 0.05 + sup1 = 0.8 + delta_slanted = 0.6 + delta_integral = 0.3 + + +class DejaVuSerifFontConstants(FontConstantsBase): + pass + + +class DejaVuSansFontConstants(FontConstantsBase): + pass + + +# Maps font family names to the FontConstantBase subclass to use +_font_constant_mapping = { + 'DejaVu Sans': DejaVuSansFontConstants, + 'DejaVu Sans Mono': DejaVuSansFontConstants, + 'DejaVu Serif': DejaVuSerifFontConstants, + 'cmb10': ComputerModernFontConstants, + 'cmex10': ComputerModernFontConstants, + 'cmmi10': ComputerModernFontConstants, + 'cmr10': ComputerModernFontConstants, + 'cmss10': ComputerModernFontConstants, + 'cmsy10': ComputerModernFontConstants, + 'cmtt10': ComputerModernFontConstants, + 'STIXGeneral': STIXFontConstants, + 'STIXNonUnicode': STIXFontConstants, + 'STIXSizeFiveSym': STIXFontConstants, + 'STIXSizeFourSym': STIXFontConstants, + 'STIXSizeThreeSym': STIXFontConstants, + 'STIXSizeTwoSym': STIXFontConstants, + 'STIXSizeOneSym': STIXFontConstants, + # Map the fonts we used to ship, just for good measure + 'Bitstream Vera Sans': DejaVuSansFontConstants, + 'Bitstream Vera': DejaVuSansFontConstants, + } + + +def _get_font_constant_set(state: ParserState) -> type[FontConstantsBase]: + constants = _font_constant_mapping.get( + state.fontset._get_font(state.font).family_name, FontConstantsBase) + # STIX sans isn't really its own fonts, just different code points + # in the STIX fonts, so we have to detect this one separately. + if (constants is STIXFontConstants and + isinstance(state.fontset, StixSansFonts)): + return STIXSansFontConstants + return constants + + +class Node: + """A node in the TeX box model.""" + + def __init__(self) -> None: + self.size = 0 + + def __repr__(self) -> str: + return type(self).__name__ + + def get_kerning(self, next: Node | None) -> float: + return 0.0 + + def shrink(self) -> None: + """ + Shrinks one level smaller. There are only three levels of + sizes, after which things will no longer get smaller. + """ + self.size += 1 + + def render(self, output: Output, x: float, y: float) -> None: + """Render this node.""" + + +class Box(Node): + """A node with a physical location.""" + + def __init__(self, width: float, height: float, depth: float) -> None: + super().__init__() + self.width = width + self.height = height + self.depth = depth + + def shrink(self) -> None: + super().shrink() + if self.size < NUM_SIZE_LEVELS: + self.width *= SHRINK_FACTOR + self.height *= SHRINK_FACTOR + self.depth *= SHRINK_FACTOR + + def render(self, output: Output, # type: ignore[override] + x1: float, y1: float, x2: float, y2: float) -> None: + pass + + +class Vbox(Box): + """A box with only height (zero width).""" + + def __init__(self, height: float, depth: float): + super().__init__(0., height, depth) + + +class Hbox(Box): + """A box with only width (zero height and depth).""" + + def __init__(self, width: float): + super().__init__(width, 0., 0.) + + +class Char(Node): + """ + A single character. + + Unlike TeX, the font information and metrics are stored with each `Char` + to make it easier to lookup the font metrics when needed. Note that TeX + boxes have a width, height, and depth, unlike Type1 and TrueType which use + a full bounding box and an advance in the x-direction. The metrics must + be converted to the TeX model, and the advance (if different from width) + must be converted into a `Kern` node when the `Char` is added to its parent + `Hlist`. + """ + + def __init__(self, c: str, state: ParserState): + super().__init__() + self.c = c + self.fontset = state.fontset + self.font = state.font + self.font_class = state.font_class + self.fontsize = state.fontsize + self.dpi = state.dpi + # The real width, height and depth will be set during the + # pack phase, after we know the real fontsize + self._update_metrics() + + def __repr__(self) -> str: + return '`%s`' % self.c + + def _update_metrics(self) -> None: + metrics = self._metrics = self.fontset.get_metrics( + self.font, self.font_class, self.c, self.fontsize, self.dpi) + if self.c == ' ': + self.width = metrics.advance + else: + self.width = metrics.width + self.height = metrics.iceberg + self.depth = -(metrics.iceberg - metrics.height) + + def is_slanted(self) -> bool: + return self._metrics.slanted + + def get_kerning(self, next: Node | None) -> float: + """ + Return the amount of kerning between this and the given character. + + This method is called when characters are strung together into `Hlist` + to create `Kern` nodes. + """ + advance = self._metrics.advance - self.width + kern = 0. + if isinstance(next, Char): + kern = self.fontset.get_kern( + self.font, self.font_class, self.c, self.fontsize, + next.font, next.font_class, next.c, next.fontsize, + self.dpi) + return advance + kern + + def render(self, output: Output, x: float, y: float) -> None: + self.fontset.render_glyph( + output, x, y, + self.font, self.font_class, self.c, self.fontsize, self.dpi) + + def shrink(self) -> None: + super().shrink() + if self.size < NUM_SIZE_LEVELS: + self.fontsize *= SHRINK_FACTOR + self.width *= SHRINK_FACTOR + self.height *= SHRINK_FACTOR + self.depth *= SHRINK_FACTOR + + +class Accent(Char): + """ + The font metrics need to be dealt with differently for accents, + since they are already offset correctly from the baseline in + TrueType fonts. + """ + def _update_metrics(self) -> None: + metrics = self._metrics = self.fontset.get_metrics( + self.font, self.font_class, self.c, self.fontsize, self.dpi) + self.width = metrics.xmax - metrics.xmin + self.height = metrics.ymax - metrics.ymin + self.depth = 0 + + def shrink(self) -> None: + super().shrink() + self._update_metrics() + + def render(self, output: Output, x: float, y: float) -> None: + self.fontset.render_glyph( + output, x - self._metrics.xmin, y + self._metrics.ymin, + self.font, self.font_class, self.c, self.fontsize, self.dpi) + + +class List(Box): + """A list of nodes (either horizontal or vertical).""" + + def __init__(self, elements: T.Sequence[Node]): + super().__init__(0., 0., 0.) + self.shift_amount = 0. # An arbitrary offset + self.children = [*elements] # The child nodes of this list + # The following parameters are set in the vpack and hpack functions + self.glue_set = 0. # The glue setting of this list + self.glue_sign = 0 # 0: normal, -1: shrinking, 1: stretching + self.glue_order = 0 # The order of infinity (0 - 3) for the glue + + def __repr__(self) -> str: + return '{}[{}]'.format( + super().__repr__(), + self.width, self.height, + self.depth, self.shift_amount, + ', '.join([repr(x) for x in self.children])) + + def _set_glue(self, x: float, sign: int, totals: list[float], + error_type: str) -> None: + self.glue_order = o = next( + # Highest order of glue used by the members of this list. + (i for i in range(len(totals))[::-1] if totals[i] != 0), 0) + self.glue_sign = sign + if totals[o] != 0.: + self.glue_set = x / totals[o] + else: + self.glue_sign = 0 + self.glue_ratio = 0. + if o == 0: + if len(self.children): + _log.warning("%s %s: %r", + error_type, type(self).__name__, self) + + def shrink(self) -> None: + for child in self.children: + child.shrink() + super().shrink() + if self.size < NUM_SIZE_LEVELS: + self.shift_amount *= SHRINK_FACTOR + self.glue_set *= SHRINK_FACTOR + + +class Hlist(List): + """A horizontal list of boxes.""" + + def __init__(self, elements: T.Sequence[Node], w: float = 0.0, + m: T.Literal['additional', 'exactly'] = 'additional', + do_kern: bool = True): + super().__init__(elements) + if do_kern: + self.kern() + self.hpack(w=w, m=m) + + def kern(self) -> None: + """ + Insert `Kern` nodes between `Char` nodes to set kerning. + + The `Char` nodes themselves determine the amount of kerning they need + (in `~Char.get_kerning`), and this function just creates the correct + linked list. + """ + new_children = [] + num_children = len(self.children) + if num_children: + for i in range(num_children): + elem = self.children[i] + if i < num_children - 1: + next = self.children[i + 1] + else: + next = None + + new_children.append(elem) + kerning_distance = elem.get_kerning(next) + if kerning_distance != 0.: + kern = Kern(kerning_distance) + new_children.append(kern) + self.children = new_children + + def hpack(self, w: float = 0.0, + m: T.Literal['additional', 'exactly'] = 'additional') -> None: + r""" + Compute the dimensions of the resulting boxes, and adjust the glue if + one of those dimensions is pre-specified. The computed sizes normally + enclose all of the material inside the new box; but some items may + stick out if negative glue is used, if the box is overfull, or if a + ``\vbox`` includes other boxes that have been shifted left. + + Parameters + ---------- + w : float, default: 0 + A width. + m : {'exactly', 'additional'}, default: 'additional' + Whether to produce a box whose width is 'exactly' *w*; or a box + with the natural width of the contents, plus *w* ('additional'). + + Notes + ----- + The defaults produce a box with the natural width of the contents. + """ + # I don't know why these get reset in TeX. Shift_amount is pretty + # much useless if we do. + # self.shift_amount = 0. + h = 0. + d = 0. + x = 0. + total_stretch = [0.] * 4 + total_shrink = [0.] * 4 + for p in self.children: + if isinstance(p, Char): + x += p.width + h = max(h, p.height) + d = max(d, p.depth) + elif isinstance(p, Box): + x += p.width + if not np.isinf(p.height) and not np.isinf(p.depth): + s = getattr(p, 'shift_amount', 0.) + h = max(h, p.height - s) + d = max(d, p.depth + s) + elif isinstance(p, Glue): + glue_spec = p.glue_spec + x += glue_spec.width + total_stretch[glue_spec.stretch_order] += glue_spec.stretch + total_shrink[glue_spec.shrink_order] += glue_spec.shrink + elif isinstance(p, Kern): + x += p.width + self.height = h + self.depth = d + + if m == 'additional': + w += x + self.width = w + x = w - x + + if x == 0.: + self.glue_sign = 0 + self.glue_order = 0 + self.glue_ratio = 0. + return + if x > 0.: + self._set_glue(x, 1, total_stretch, "Overful") + else: + self._set_glue(x, -1, total_shrink, "Underful") + + +class Vlist(List): + """A vertical list of boxes.""" + + def __init__(self, elements: T.Sequence[Node], h: float = 0.0, + m: T.Literal['additional', 'exactly'] = 'additional'): + super().__init__(elements) + self.vpack(h=h, m=m) + + def vpack(self, h: float = 0.0, + m: T.Literal['additional', 'exactly'] = 'additional', + l: float = np.inf) -> None: + """ + Compute the dimensions of the resulting boxes, and to adjust the glue + if one of those dimensions is pre-specified. + + Parameters + ---------- + h : float, default: 0 + A height. + m : {'exactly', 'additional'}, default: 'additional' + Whether to produce a box whose height is 'exactly' *h*; or a box + with the natural height of the contents, plus *h* ('additional'). + l : float, default: np.inf + The maximum height. + + Notes + ----- + The defaults produce a box with the natural height of the contents. + """ + # I don't know why these get reset in TeX. Shift_amount is pretty + # much useless if we do. + # self.shift_amount = 0. + w = 0. + d = 0. + x = 0. + total_stretch = [0.] * 4 + total_shrink = [0.] * 4 + for p in self.children: + if isinstance(p, Box): + x += d + p.height + d = p.depth + if not np.isinf(p.width): + s = getattr(p, 'shift_amount', 0.) + w = max(w, p.width + s) + elif isinstance(p, Glue): + x += d + d = 0. + glue_spec = p.glue_spec + x += glue_spec.width + total_stretch[glue_spec.stretch_order] += glue_spec.stretch + total_shrink[glue_spec.shrink_order] += glue_spec.shrink + elif isinstance(p, Kern): + x += d + p.width + d = 0. + elif isinstance(p, Char): + raise RuntimeError( + "Internal mathtext error: Char node found in Vlist") + + self.width = w + if d > l: + x += d - l + self.depth = l + else: + self.depth = d + + if m == 'additional': + h += x + self.height = h + x = h - x + + if x == 0: + self.glue_sign = 0 + self.glue_order = 0 + self.glue_ratio = 0. + return + + if x > 0.: + self._set_glue(x, 1, total_stretch, "Overful") + else: + self._set_glue(x, -1, total_shrink, "Underful") + + +class Rule(Box): + """ + A solid black rectangle. + + It has *width*, *depth*, and *height* fields just as in an `Hlist`. + However, if any of these dimensions is inf, the actual value will be + determined by running the rule up to the boundary of the innermost + enclosing box. This is called a "running dimension". The width is never + running in an `Hlist`; the height and depth are never running in a `Vlist`. + """ + + def __init__(self, width: float, height: float, depth: float, state: ParserState): + super().__init__(width, height, depth) + self.fontset = state.fontset + + def render(self, output: Output, # type: ignore[override] + x: float, y: float, w: float, h: float) -> None: + self.fontset.render_rect_filled(output, x, y, x + w, y + h) + + +class Hrule(Rule): + """Convenience class to create a horizontal rule.""" + + def __init__(self, state: ParserState, thickness: float | None = None): + if thickness is None: + thickness = state.get_current_underline_thickness() + height = depth = thickness * 0.5 + super().__init__(np.inf, height, depth, state) + + +class Vrule(Rule): + """Convenience class to create a vertical rule.""" + + def __init__(self, state: ParserState): + thickness = state.get_current_underline_thickness() + super().__init__(thickness, np.inf, np.inf, state) + + +class _GlueSpec(NamedTuple): + width: float + stretch: float + stretch_order: int + shrink: float + shrink_order: int + + +_GlueSpec._named = { # type: ignore[attr-defined] + 'fil': _GlueSpec(0., 1., 1, 0., 0), + 'fill': _GlueSpec(0., 1., 2, 0., 0), + 'filll': _GlueSpec(0., 1., 3, 0., 0), + 'neg_fil': _GlueSpec(0., 0., 0, 1., 1), + 'neg_fill': _GlueSpec(0., 0., 0, 1., 2), + 'neg_filll': _GlueSpec(0., 0., 0, 1., 3), + 'empty': _GlueSpec(0., 0., 0, 0., 0), + 'ss': _GlueSpec(0., 1., 1, -1., 1), +} + + +class Glue(Node): + """ + Most of the information in this object is stored in the underlying + ``_GlueSpec`` class, which is shared between multiple glue objects. + (This is a memory optimization which probably doesn't matter anymore, but + it's easier to stick to what TeX does.) + """ + + def __init__(self, + glue_type: _GlueSpec | T.Literal["fil", "fill", "filll", + "neg_fil", "neg_fill", "neg_filll", + "empty", "ss"]): + super().__init__() + if isinstance(glue_type, str): + glue_spec = _GlueSpec._named[glue_type] # type: ignore[attr-defined] + elif isinstance(glue_type, _GlueSpec): + glue_spec = glue_type + else: + raise ValueError("glue_type must be a glue spec name or instance") + self.glue_spec = glue_spec + + def shrink(self) -> None: + super().shrink() + if self.size < NUM_SIZE_LEVELS: + g = self.glue_spec + self.glue_spec = g._replace(width=g.width * SHRINK_FACTOR) + + +class HCentered(Hlist): + """ + A convenience class to create an `Hlist` whose contents are + centered within its enclosing box. + """ + + def __init__(self, elements: list[Node]): + super().__init__([Glue('ss'), *elements, Glue('ss')], do_kern=False) + + +class VCentered(Vlist): + """ + A convenience class to create a `Vlist` whose contents are + centered within its enclosing box. + """ + + def __init__(self, elements: list[Node]): + super().__init__([Glue('ss'), *elements, Glue('ss')]) + + +class Kern(Node): + """ + A `Kern` node has a width field to specify a (normally + negative) amount of spacing. This spacing correction appears in + horizontal lists between letters like A and V when the font + designer said that it looks better to move them closer together or + further apart. A kern node can also appear in a vertical list, + when its *width* denotes additional spacing in the vertical + direction. + """ + + height = 0 + depth = 0 + + def __init__(self, width: float): + super().__init__() + self.width = width + + def __repr__(self) -> str: + return "k%.02f" % self.width + + def shrink(self) -> None: + super().shrink() + if self.size < NUM_SIZE_LEVELS: + self.width *= SHRINK_FACTOR + + +class AutoHeightChar(Hlist): + """ + A character as close to the given height and depth as possible. + + When using a font with multiple height versions of some characters (such as + the BaKoMa fonts), the correct glyph will be selected, otherwise this will + always just return a scaled version of the glyph. + """ + + def __init__(self, c: str, height: float, depth: float, state: ParserState, + always: bool = False, factor: float | None = None): + alternatives = state.fontset.get_sized_alternatives_for_symbol( + state.font, c) + + xHeight = state.fontset.get_xheight( + state.font, state.fontsize, state.dpi) + + state = state.copy() + target_total = height + depth + for fontname, sym in alternatives: + state.font = fontname + char = Char(sym, state) + # Ensure that size 0 is chosen when the text is regular sized but + # with descender glyphs by subtracting 0.2 * xHeight + if char.height + char.depth >= target_total - 0.2 * xHeight: + break + + shift = 0.0 + if state.font != 0 or len(alternatives) == 1: + if factor is None: + factor = target_total / (char.height + char.depth) + state.fontsize *= factor + char = Char(sym, state) + + shift = (depth - char.depth) + + super().__init__([char]) + self.shift_amount = shift + + +class AutoWidthChar(Hlist): + """ + A character as close to the given width as possible. + + When using a font with multiple width versions of some characters (such as + the BaKoMa fonts), the correct glyph will be selected, otherwise this will + always just return a scaled version of the glyph. + """ + + def __init__(self, c: str, width: float, state: ParserState, always: bool = False, + char_class: type[Char] = Char): + alternatives = state.fontset.get_sized_alternatives_for_symbol( + state.font, c) + + state = state.copy() + for fontname, sym in alternatives: + state.font = fontname + char = char_class(sym, state) + if char.width >= width: + break + + factor = width / char.width + state.fontsize *= factor + char = char_class(sym, state) + + super().__init__([char]) + self.width = char.width + + +def ship(box: Box, xy: tuple[float, float] = (0, 0)) -> Output: + """ + Ship out *box* at offset *xy*, converting it to an `Output`. + + Since boxes can be inside of boxes inside of boxes, the main work of `ship` + is done by two mutually recursive routines, `hlist_out` and `vlist_out`, + which traverse the `Hlist` nodes and `Vlist` nodes inside of horizontal + and vertical boxes. The global variables used in TeX to store state as it + processes have become local variables here. + """ + ox, oy = xy + cur_v = 0. + cur_h = 0. + off_h = ox + off_v = oy + box.height + output = Output(box) + + def clamp(value: float) -> float: + return -1e9 if value < -1e9 else +1e9 if value > +1e9 else value + + def hlist_out(box: Hlist) -> None: + nonlocal cur_v, cur_h, off_h, off_v + + cur_g = 0 + cur_glue = 0. + glue_order = box.glue_order + glue_sign = box.glue_sign + base_line = cur_v + left_edge = cur_h + + for p in box.children: + if isinstance(p, Char): + p.render(output, cur_h + off_h, cur_v + off_v) + cur_h += p.width + elif isinstance(p, Kern): + cur_h += p.width + elif isinstance(p, List): + # node623 + if len(p.children) == 0: + cur_h += p.width + else: + edge = cur_h + cur_v = base_line + p.shift_amount + if isinstance(p, Hlist): + hlist_out(p) + elif isinstance(p, Vlist): + # p.vpack(box.height + box.depth, 'exactly') + vlist_out(p) + else: + assert False, "unreachable code" + cur_h = edge + p.width + cur_v = base_line + elif isinstance(p, Box): + # node624 + rule_height = p.height + rule_depth = p.depth + rule_width = p.width + if np.isinf(rule_height): + rule_height = box.height + if np.isinf(rule_depth): + rule_depth = box.depth + if rule_height > 0 and rule_width > 0: + cur_v = base_line + rule_depth + p.render(output, + cur_h + off_h, cur_v + off_v, + rule_width, rule_height) + cur_v = base_line + cur_h += rule_width + elif isinstance(p, Glue): + # node625 + glue_spec = p.glue_spec + rule_width = glue_spec.width - cur_g + if glue_sign != 0: # normal + if glue_sign == 1: # stretching + if glue_spec.stretch_order == glue_order: + cur_glue += glue_spec.stretch + cur_g = round(clamp(box.glue_set * cur_glue)) + elif glue_spec.shrink_order == glue_order: + cur_glue += glue_spec.shrink + cur_g = round(clamp(box.glue_set * cur_glue)) + rule_width += cur_g + cur_h += rule_width + + def vlist_out(box: Vlist) -> None: + nonlocal cur_v, cur_h, off_h, off_v + + cur_g = 0 + cur_glue = 0. + glue_order = box.glue_order + glue_sign = box.glue_sign + left_edge = cur_h + cur_v -= box.height + top_edge = cur_v + + for p in box.children: + if isinstance(p, Kern): + cur_v += p.width + elif isinstance(p, List): + if len(p.children) == 0: + cur_v += p.height + p.depth + else: + cur_v += p.height + cur_h = left_edge + p.shift_amount + save_v = cur_v + p.width = box.width + if isinstance(p, Hlist): + hlist_out(p) + elif isinstance(p, Vlist): + vlist_out(p) + else: + assert False, "unreachable code" + cur_v = save_v + p.depth + cur_h = left_edge + elif isinstance(p, Box): + rule_height = p.height + rule_depth = p.depth + rule_width = p.width + if np.isinf(rule_width): + rule_width = box.width + rule_height += rule_depth + if rule_height > 0 and rule_depth > 0: + cur_v += rule_height + p.render(output, + cur_h + off_h, cur_v + off_v, + rule_width, rule_height) + elif isinstance(p, Glue): + glue_spec = p.glue_spec + rule_height = glue_spec.width - cur_g + if glue_sign != 0: # normal + if glue_sign == 1: # stretching + if glue_spec.stretch_order == glue_order: + cur_glue += glue_spec.stretch + cur_g = round(clamp(box.glue_set * cur_glue)) + elif glue_spec.shrink_order == glue_order: # shrinking + cur_glue += glue_spec.shrink + cur_g = round(clamp(box.glue_set * cur_glue)) + rule_height += cur_g + cur_v += rule_height + elif isinstance(p, Char): + raise RuntimeError( + "Internal mathtext error: Char node found in vlist") + + assert isinstance(box, Hlist) + hlist_out(box) + return output + + +############################################################################## +# PARSER + + +def Error(msg: str) -> ParserElement: + """Helper class to raise parser errors.""" + def raise_error(s: str, loc: int, toks: ParseResults) -> T.Any: + raise ParseFatalException(s, loc, msg) + + return Empty().setParseAction(raise_error) + + +class ParserState: + """ + Parser state. + + States are pushed and popped from a stack as necessary, and the "current" + state is always at the top of the stack. + + Upon entering and leaving a group { } or math/non-math, the stack is pushed + and popped accordingly. + """ + + def __init__(self, fontset: Fonts, font: str, font_class: str, fontsize: float, + dpi: float): + self.fontset = fontset + self._font = font + self.font_class = font_class + self.fontsize = fontsize + self.dpi = dpi + + def copy(self) -> ParserState: + return copy.copy(self) + + @property + def font(self) -> str: + return self._font + + @font.setter + def font(self, name: str) -> None: + if name in ('rm', 'it', 'bf', 'bfit'): + self.font_class = name + self._font = name + + def get_current_underline_thickness(self) -> float: + """Return the underline thickness for this state.""" + return self.fontset.get_underline_thickness( + self.font, self.fontsize, self.dpi) + + +def cmd(expr: str, args: ParserElement) -> ParserElement: + r""" + Helper to define TeX commands. + + ``cmd("\cmd", args)`` is equivalent to + ``"\cmd" - (args | Error("Expected \cmd{arg}{...}"))`` where the names in + the error message are taken from element names in *args*. If *expr* + already includes arguments (e.g. "\cmd{arg}{...}"), then they are stripped + when constructing the parse element, but kept (and *expr* is used as is) in + the error message. + """ + + def names(elt: ParserElement) -> T.Generator[str, None, None]: + if isinstance(elt, ParseExpression): + for expr in elt.exprs: + yield from names(expr) + elif elt.resultsName: + yield elt.resultsName + + csname = expr.split("{", 1)[0] + err = (csname + "".join("{%s}" % name for name in names(args)) + if expr == csname else expr) + return csname - (args | Error(f"Expected {err}")) + + +class Parser: + """ + A pyparsing-based parser for strings containing math expressions. + + Raw text may also appear outside of pairs of ``$``. + + The grammar is based directly on that in TeX, though it cuts a few corners. + """ + + class _MathStyle(enum.Enum): + DISPLAYSTYLE = 0 + TEXTSTYLE = 1 + SCRIPTSTYLE = 2 + SCRIPTSCRIPTSTYLE = 3 + + _binary_operators = set( + '+ * - \N{MINUS SIGN}' + r''' + \pm \sqcap \rhd + \mp \sqcup \unlhd + \times \vee \unrhd + \div \wedge \oplus + \ast \setminus \ominus + \star \wr \otimes + \circ \diamond \oslash + \bullet \bigtriangleup \odot + \cdot \bigtriangledown \bigcirc + \cap \triangleleft \dagger + \cup \triangleright \ddagger + \uplus \lhd \amalg + \dotplus \dotminus \Cap + \Cup \barwedge \boxdot + \boxminus \boxplus \boxtimes + \curlyvee \curlywedge \divideontimes + \doublebarwedge \leftthreetimes \rightthreetimes + \slash \veebar \barvee + \cupdot \intercal \amalg + \circledcirc \circleddash \circledast + \boxbar \obar \merge + \minuscolon \dotsminusdots + '''.split()) + + _relation_symbols = set(r''' + = < > : + \leq \geq \equiv \models + \prec \succ \sim \perp + \preceq \succeq \simeq \mid + \ll \gg \asymp \parallel + \subset \supset \approx \bowtie + \subseteq \supseteq \cong \Join + \sqsubset \sqsupset \neq \smile + \sqsubseteq \sqsupseteq \doteq \frown + \in \ni \propto \vdash + \dashv \dots \doteqdot \leqq + \geqq \lneqq \gneqq \lessgtr + \leqslant \geqslant \eqgtr \eqless + \eqslantless \eqslantgtr \lesseqgtr \backsim + \backsimeq \lesssim \gtrsim \precsim + \precnsim \gnsim \lnsim \succsim + \succnsim \nsim \lesseqqgtr \gtreqqless + \gtreqless \subseteqq \supseteqq \subsetneqq + \supsetneqq \lessapprox \approxeq \gtrapprox + \precapprox \succapprox \precnapprox \succnapprox + \npreccurlyeq \nsucccurlyeq \nsqsubseteq \nsqsupseteq + \sqsubsetneq \sqsupsetneq \nlesssim \ngtrsim + \nlessgtr \ngtrless \lnapprox \gnapprox + \napprox \approxeq \approxident \lll + \ggg \nparallel \Vdash \Vvdash + \nVdash \nvdash \vDash \nvDash + \nVDash \oequal \simneqq \triangle + \triangleq \triangleeq \triangleleft + \triangleright \ntriangleleft \ntriangleright + \trianglelefteq \ntrianglelefteq \trianglerighteq + \ntrianglerighteq \blacktriangleleft \blacktriangleright + \equalparallel \measuredrightangle \varlrtriangle + \Doteq \Bumpeq \Subset \Supset + \backepsilon \because \therefore \bot + \top \bumpeq \circeq \coloneq + \curlyeqprec \curlyeqsucc \eqcirc \eqcolon + \eqsim \fallingdotseq \gtrdot \gtrless + \ltimes \rtimes \lessdot \ne + \ncong \nequiv \ngeq \ngtr + \nleq \nless \nmid \notin + \nprec \nsubset \nsubseteq \nsucc + \nsupset \nsupseteq \pitchfork \preccurlyeq + \risingdotseq \subsetneq \succcurlyeq \supsetneq + \varpropto \vartriangleleft \scurel + \vartriangleright \rightangle \equal \backcong + \eqdef \wedgeq \questeq \between + \veeeq \disin \varisins \isins + \isindot \varisinobar \isinobar \isinvb + \isinE \nisd \varnis \nis + \varniobar \niobar \bagmember \ratio + \Equiv \stareq \measeq \arceq + \rightassert \rightModels \smallin \smallowns + \notsmallowns \nsimeq'''.split()) + + _arrow_symbols = set(r""" + \leftarrow \longleftarrow \uparrow \Leftarrow \Longleftarrow + \Uparrow \rightarrow \longrightarrow \downarrow \Rightarrow + \Longrightarrow \Downarrow \leftrightarrow \updownarrow + \longleftrightarrow \updownarrow \Leftrightarrow + \Longleftrightarrow \Updownarrow \mapsto \longmapsto \nearrow + \hookleftarrow \hookrightarrow \searrow \leftharpoonup + \rightharpoonup \swarrow \leftharpoondown \rightharpoondown + \nwarrow \rightleftharpoons \leadsto \dashrightarrow + \dashleftarrow \leftleftarrows \leftrightarrows \Lleftarrow + \Rrightarrow \twoheadleftarrow \leftarrowtail \looparrowleft + \leftrightharpoons \curvearrowleft \circlearrowleft \Lsh + \upuparrows \upharpoonleft \downharpoonleft \multimap + \leftrightsquigarrow \rightrightarrows \rightleftarrows + \rightrightarrows \rightleftarrows \twoheadrightarrow + \rightarrowtail \looparrowright \rightleftharpoons + \curvearrowright \circlearrowright \Rsh \downdownarrows + \upharpoonright \downharpoonright \rightsquigarrow \nleftarrow + \nrightarrow \nLeftarrow \nRightarrow \nleftrightarrow + \nLeftrightarrow \to \Swarrow \Searrow \Nwarrow \Nearrow + \leftsquigarrow \overleftarrow \overleftrightarrow \cwopencirclearrow + \downzigzagarrow \cupleftarrow \rightzigzagarrow \twoheaddownarrow + \updownarrowbar \twoheaduparrow \rightarrowbar \updownarrows + \barleftarrow \mapsfrom \mapsdown \mapsup \Ldsh \Rdsh + """.split()) + + _spaced_symbols = _binary_operators | _relation_symbols | _arrow_symbols + + _punctuation_symbols = set(r', ; . ! \ldotp \cdotp'.split()) + + _overunder_symbols = set(r''' + \sum \prod \coprod \bigcap \bigcup \bigsqcup \bigvee + \bigwedge \bigodot \bigotimes \bigoplus \biguplus + '''.split()) + + _overunder_functions = set("lim liminf limsup sup max min".split()) + + _dropsub_symbols = set(r'\int \oint \iint \oiint \iiint \oiiint \iiiint'.split()) + + _fontnames = set("rm cal it tt sf bf bfit " + "default bb frak scr regular".split()) + + _function_names = set(""" + arccos csc ker min arcsin deg lg Pr arctan det lim sec arg dim + liminf sin cos exp limsup sinh cosh gcd ln sup cot hom log tan + coth inf max tanh""".split()) + + _ambi_delims = set(r""" + | \| / \backslash \uparrow \downarrow \updownarrow \Uparrow + \Downarrow \Updownarrow . \vert \Vert""".split()) + _left_delims = set(r""" + ( [ \{ < \lfloor \langle \lceil \lbrace \leftbrace \lbrack \leftparen \lgroup + """.split()) + _right_delims = set(r""" + ) ] \} > \rfloor \rangle \rceil \rbrace \rightbrace \rbrack \rightparen \rgroup + """.split()) + _delims = _left_delims | _right_delims | _ambi_delims + + _small_greek = set([unicodedata.name(chr(i)).split()[-1].lower() for i in + range(ord('\N{GREEK SMALL LETTER ALPHA}'), + ord('\N{GREEK SMALL LETTER OMEGA}') + 1)]) + _latin_alphabets = set(string.ascii_letters) + + def __init__(self) -> None: + p = types.SimpleNamespace() + + def set_names_and_parse_actions() -> None: + for key, val in vars(p).items(): + if not key.startswith('_'): + # Set names on (almost) everything -- very useful for debugging + # token, placeable, and auto_delim are forward references which + # are left without names to ensure useful error messages + if key not in ("token", "placeable", "auto_delim"): + val.setName(key) + # Set actions + if hasattr(self, key): + val.setParseAction(getattr(self, key)) + + # Root definitions. + + # In TeX parlance, a csname is a control sequence name (a "\foo"). + def csnames(group: str, names: Iterable[str]) -> Regex: + ends_with_alpha = [] + ends_with_nonalpha = [] + for name in names: + if name[-1].isalpha(): + ends_with_alpha.append(name) + else: + ends_with_nonalpha.append(name) + return Regex( + r"\\(?P<{group}>(?:{alpha})(?![A-Za-z]){additional}{nonalpha})".format( + group=group, + alpha="|".join(map(re.escape, ends_with_alpha)), + additional="|" if ends_with_nonalpha else "", + nonalpha="|".join(map(re.escape, ends_with_nonalpha)), + ) + ) + + p.float_literal = Regex(r"[-+]?([0-9]+\.?[0-9]*|\.[0-9]+)") + p.space = oneOf(self._space_widths)("space") + + p.style_literal = oneOf( + [str(e.value) for e in self._MathStyle])("style_literal") + + p.symbol = Regex( + r"[a-zA-Z0-9 +\-*/<>=:,.;!\?&'@()\[\]|\U00000080-\U0001ffff]" + r"|\\[%${}\[\]_|]" + + r"|\\(?:{})(?![A-Za-z])".format( + "|".join(map(re.escape, tex2uni))) + )("sym").leaveWhitespace() + p.unknown_symbol = Regex(r"\\[A-Za-z]+")("name") + + p.font = csnames("font", self._fontnames) + p.start_group = Optional(r"\math" + oneOf(self._fontnames)("font")) + "{" + p.end_group = Literal("}") + + p.delim = oneOf(self._delims) + + # Mutually recursive definitions. (Minimizing the number of Forward + # elements is important for speed.) + p.auto_delim = Forward() + p.placeable = Forward() + p.named_placeable = Forward() + p.required_group = Forward() + p.optional_group = Forward() + p.token = Forward() + + # Workaround for placable being part of a cycle of definitions + # calling `p.placeable("name")` results in a copy, so not guaranteed + # to get the definition added after it is used. + # ref https://github.com/matplotlib/matplotlib/issues/25204 + # xref https://github.com/pyparsing/pyparsing/issues/95 + p.named_placeable <<= p.placeable + + set_names_and_parse_actions() # for mutually recursive definitions. + + p.optional_group <<= "{" + ZeroOrMore(p.token)("group") + "}" + p.required_group <<= "{" + OneOrMore(p.token)("group") + "}" + + p.customspace = cmd(r"\hspace", "{" + p.float_literal("space") + "}") + + p.accent = ( + csnames("accent", [*self._accent_map, *self._wide_accents]) + - p.named_placeable("sym")) + + p.function = csnames("name", self._function_names) + + p.group = p.start_group + ZeroOrMore(p.token)("group") + p.end_group + p.unclosed_group = (p.start_group + ZeroOrMore(p.token)("group") + StringEnd()) + + p.frac = cmd(r"\frac", p.required_group("num") + p.required_group("den")) + p.dfrac = cmd(r"\dfrac", p.required_group("num") + p.required_group("den")) + p.binom = cmd(r"\binom", p.required_group("num") + p.required_group("den")) + + p.genfrac = cmd( + r"\genfrac", + "{" + Optional(p.delim)("ldelim") + "}" + + "{" + Optional(p.delim)("rdelim") + "}" + + "{" + p.float_literal("rulesize") + "}" + + "{" + Optional(p.style_literal)("style") + "}" + + p.required_group("num") + + p.required_group("den")) + + p.sqrt = cmd( + r"\sqrt{value}", + Optional("[" + OneOrMore(NotAny("]") + p.token)("root") + "]") + + p.required_group("value")) + + p.overline = cmd(r"\overline", p.required_group("body")) + + p.overset = cmd( + r"\overset", + p.optional_group("annotation") + p.optional_group("body")) + p.underset = cmd( + r"\underset", + p.optional_group("annotation") + p.optional_group("body")) + + p.text = cmd(r"\text", QuotedString('{', '\\', endQuoteChar="}")) + + p.substack = cmd(r"\substack", + nested_expr(opener="{", closer="}", + content=Group(OneOrMore(p.token)) + + ZeroOrMore(Literal("\\\\").suppress()))("parts")) + + p.subsuper = ( + (Optional(p.placeable)("nucleus") + + OneOrMore(oneOf(["_", "^"]) - p.placeable)("subsuper") + + Regex("'*")("apostrophes")) + | Regex("'+")("apostrophes") + | (p.named_placeable("nucleus") + Regex("'*")("apostrophes")) + ) + + p.simple = p.space | p.customspace | p.font | p.subsuper + + p.token <<= ( + p.simple + | p.auto_delim + | p.unclosed_group + | p.unknown_symbol # Must be last + ) + + p.operatorname = cmd(r"\operatorname", "{" + ZeroOrMore(p.simple)("name") + "}") + + p.boldsymbol = cmd( + r"\boldsymbol", "{" + ZeroOrMore(p.simple)("value") + "}") + + p.placeable <<= ( + p.accent # Must be before symbol as all accents are symbols + | p.symbol # Must be second to catch all named symbols and single + # chars not in a group + | p.function + | p.operatorname + | p.group + | p.frac + | p.dfrac + | p.binom + | p.genfrac + | p.overset + | p.underset + | p.sqrt + | p.overline + | p.text + | p.boldsymbol + | p.substack + ) + + mdelim = r"\middle" - (p.delim("mdelim") | Error("Expected a delimiter")) + p.auto_delim <<= ( + r"\left" - (p.delim("left") | Error("Expected a delimiter")) + + ZeroOrMore(p.simple | p.auto_delim | mdelim)("mid") + + r"\right" - (p.delim("right") | Error("Expected a delimiter")) + ) + + # Leaf definitions. + p.math = OneOrMore(p.token) + p.math_string = QuotedString('$', '\\', unquoteResults=False) + p.non_math = Regex(r"(?:(?:\\[$])|[^$])*").leaveWhitespace() + p.main = ( + p.non_math + ZeroOrMore(p.math_string + p.non_math) + StringEnd() + ) + set_names_and_parse_actions() # for leaf definitions. + + self._expression = p.main + self._math_expression = p.math + + # To add space to nucleus operators after sub/superscripts + self._in_subscript_or_superscript = False + + def parse(self, s: str, fonts_object: Fonts, fontsize: float, dpi: float) -> Hlist: + """ + Parse expression *s* using the given *fonts_object* for + output, at the given *fontsize* and *dpi*. + + Returns the parse tree of `Node` instances. + """ + self._state_stack = [ + ParserState(fonts_object, 'default', 'rm', fontsize, dpi)] + self._em_width_cache: dict[tuple[str, float, float], float] = {} + try: + result = self._expression.parseString(s) + except ParseBaseException as err: + # explain becomes a plain method on pyparsing 3 (err.explain(0)). + raise ValueError("\n" + ParseException.explain(err, 0)) from None + self._state_stack = [] + self._in_subscript_or_superscript = False + # prevent operator spacing from leaking into a new expression + self._em_width_cache = {} + ParserElement.resetCache() + return T.cast(Hlist, result[0]) # Known return type from main. + + def get_state(self) -> ParserState: + """Get the current `State` of the parser.""" + return self._state_stack[-1] + + def pop_state(self) -> None: + """Pop a `State` off of the stack.""" + self._state_stack.pop() + + def push_state(self) -> None: + """Push a new `State` onto the stack, copying the current state.""" + self._state_stack.append(self.get_state().copy()) + + def main(self, toks: ParseResults) -> list[Hlist]: + return [Hlist(toks.asList())] + + def math_string(self, toks: ParseResults) -> ParseResults: + return self._math_expression.parseString(toks[0][1:-1], parseAll=True) + + def math(self, toks: ParseResults) -> T.Any: + hlist = Hlist(toks.asList()) + self.pop_state() + return [hlist] + + def non_math(self, toks: ParseResults) -> T.Any: + s = toks[0].replace(r'\$', '$') + symbols = [Char(c, self.get_state()) for c in s] + hlist = Hlist(symbols) + # We're going into math now, so set font to 'it' + self.push_state() + self.get_state().font = mpl.rcParams['mathtext.default'] + return [hlist] + + float_literal = staticmethod(pyparsing_common.convertToFloat) + + def text(self, toks: ParseResults) -> T.Any: + self.push_state() + state = self.get_state() + state.font = 'rm' + hlist = Hlist([Char(c, state) for c in toks[1]]) + self.pop_state() + return [hlist] + + def _make_space(self, percentage: float) -> Kern: + # In TeX, an em (the unit usually used to measure horizontal lengths) + # is not the width of the character 'm'; it is the same in different + # font styles (e.g. roman or italic). Mathtext, however, uses 'm' in + # the italic style so that horizontal spaces don't depend on the + # current font style. + state = self.get_state() + key = (state.font, state.fontsize, state.dpi) + width = self._em_width_cache.get(key) + if width is None: + metrics = state.fontset.get_metrics( + 'it', mpl.rcParams['mathtext.default'], 'm', + state.fontsize, state.dpi) + width = metrics.advance + self._em_width_cache[key] = width + return Kern(width * percentage) + + _space_widths = { + r'\,': 0.16667, # 3/18 em = 3 mu + r'\thinspace': 0.16667, # 3/18 em = 3 mu + r'\/': 0.16667, # 3/18 em = 3 mu + r'\>': 0.22222, # 4/18 em = 4 mu + r'\:': 0.22222, # 4/18 em = 4 mu + r'\;': 0.27778, # 5/18 em = 5 mu + r'\ ': 0.33333, # 6/18 em = 6 mu + r'~': 0.33333, # 6/18 em = 6 mu, nonbreakable + r'\enspace': 0.5, # 9/18 em = 9 mu + r'\quad': 1, # 1 em = 18 mu + r'\qquad': 2, # 2 em = 36 mu + r'\!': -0.16667, # -3/18 em = -3 mu + } + + def space(self, toks: ParseResults) -> T.Any: + num = self._space_widths[toks["space"]] + box = self._make_space(num) + return [box] + + def customspace(self, toks: ParseResults) -> T.Any: + return [self._make_space(toks["space"])] + + def symbol(self, s: str, loc: int, + toks: ParseResults | dict[str, str]) -> T.Any: + c = toks["sym"] + if c == "-": + # "U+2212 minus sign is the preferred representation of the unary + # and binary minus sign rather than the ASCII-derived U+002D + # hyphen-minus, because minus sign is unambiguous and because it + # is rendered with a more desirable length, usually longer than a + # hyphen." (https://www.unicode.org/reports/tr25/) + c = "\N{MINUS SIGN}" + try: + char = Char(c, self.get_state()) + except ValueError as err: + raise ParseFatalException(s, loc, + "Unknown symbol: %s" % c) from err + + if c in self._spaced_symbols: + # iterate until we find previous character, needed for cases + # such as $=-2$, ${ -2}$, $ -2$, or $ -2$. + prev_char = next((c for c in s[:loc][::-1] if c != ' '), '') + # Binary operators at start of string should not be spaced + # Also, operators in sub- or superscripts should not be spaced + if (self._in_subscript_or_superscript or ( + c in self._binary_operators and ( + len(s[:loc].split()) == 0 or prev_char in { + '{', *self._left_delims, *self._relation_symbols}))): + return [char] + else: + return [Hlist([self._make_space(0.2), + char, + self._make_space(0.2)], + do_kern=True)] + elif c in self._punctuation_symbols: + prev_char = next((c for c in s[:loc][::-1] if c != ' '), '') + next_char = next((c for c in s[loc + 1:] if c != ' '), '') + + # Do not space commas between brackets + if c == ',': + if prev_char == '{' and next_char == '}': + return [char] + + # Do not space dots as decimal separators + if c == '.' and prev_char.isdigit() and next_char.isdigit(): + return [char] + else: + return [Hlist([char, self._make_space(0.2)], do_kern=True)] + return [char] + + def unknown_symbol(self, s: str, loc: int, toks: ParseResults) -> T.Any: + raise ParseFatalException(s, loc, f"Unknown symbol: {toks['name']}") + + _accent_map = { + r'hat': r'\circumflexaccent', + r'breve': r'\combiningbreve', + r'bar': r'\combiningoverline', + r'grave': r'\combininggraveaccent', + r'acute': r'\combiningacuteaccent', + r'tilde': r'\combiningtilde', + r'dot': r'\combiningdotabove', + r'ddot': r'\combiningdiaeresis', + r'dddot': r'\combiningthreedotsabove', + r'ddddot': r'\combiningfourdotsabove', + r'vec': r'\combiningrightarrowabove', + r'"': r'\combiningdiaeresis', + r"`": r'\combininggraveaccent', + r"'": r'\combiningacuteaccent', + r'~': r'\combiningtilde', + r'.': r'\combiningdotabove', + r'^': r'\circumflexaccent', + r'overrightarrow': r'\rightarrow', + r'overleftarrow': r'\leftarrow', + r'mathring': r'\circ', + } + + _wide_accents = set(r"widehat widetilde widebar".split()) + + def accent(self, toks: ParseResults) -> T.Any: + state = self.get_state() + thickness = state.get_current_underline_thickness() + accent = toks["accent"] + sym = toks["sym"] + accent_box: Node + if accent in self._wide_accents: + accent_box = AutoWidthChar( + '\\' + accent, sym.width, state, char_class=Accent) + else: + accent_box = Accent(self._accent_map[accent], state) + if accent == 'mathring': + accent_box.shrink() + accent_box.shrink() + centered = HCentered([Hbox(sym.width / 4.0), accent_box]) + centered.hpack(sym.width, 'exactly') + return Vlist([ + centered, + Vbox(0., thickness * 2.0), + Hlist([sym]) + ]) + + def function(self, s: str, loc: int, toks: ParseResults) -> T.Any: + hlist = self.operatorname(s, loc, toks) + hlist.function_name = toks["name"] + return hlist + + def operatorname(self, s: str, loc: int, toks: ParseResults) -> T.Any: + self.push_state() + state = self.get_state() + state.font = 'rm' + hlist_list: list[Node] = [] + # Change the font of Chars, but leave Kerns alone + name = toks["name"] + for c in name: + if isinstance(c, Char): + c.font = 'rm' + c._update_metrics() + hlist_list.append(c) + elif isinstance(c, str): + hlist_list.append(Char(c, state)) + else: + hlist_list.append(c) + next_char_loc = loc + len(name) + 1 + if isinstance(name, ParseResults): + next_char_loc += len('operatorname{}') + next_char = next((c for c in s[next_char_loc:] if c != ' '), '') + delimiters = self._delims | {'^', '_'} + if (next_char not in delimiters and + name not in self._overunder_functions): + # Add thin space except when followed by parenthesis, bracket, etc. + hlist_list += [self._make_space(self._space_widths[r'\,'])] + self.pop_state() + # if followed by a super/subscript, set flag to true + # This flag tells subsuper to add space after this operator + if next_char in {'^', '_'}: + self._in_subscript_or_superscript = True + else: + self._in_subscript_or_superscript = False + + return Hlist(hlist_list) + + def start_group(self, toks: ParseResults) -> T.Any: + self.push_state() + # Deal with LaTeX-style font tokens + if toks.get("font"): + self.get_state().font = toks.get("font") + return [] + + def group(self, toks: ParseResults) -> T.Any: + grp = Hlist(toks.get("group", [])) + return [grp] + + def required_group(self, toks: ParseResults) -> T.Any: + return Hlist(toks.get("group", [])) + + optional_group = required_group + + def end_group(self) -> T.Any: + self.pop_state() + return [] + + def unclosed_group(self, s: str, loc: int, toks: ParseResults) -> T.Any: + raise ParseFatalException(s, len(s), "Expected '}'") + + def font(self, toks: ParseResults) -> T.Any: + self.get_state().font = toks["font"] + return [] + + def is_overunder(self, nucleus: Node) -> bool: + if isinstance(nucleus, Char): + return nucleus.c in self._overunder_symbols + elif isinstance(nucleus, Hlist) and hasattr(nucleus, 'function_name'): + return nucleus.function_name in self._overunder_functions + return False + + def is_dropsub(self, nucleus: Node) -> bool: + if isinstance(nucleus, Char): + return nucleus.c in self._dropsub_symbols + return False + + def is_slanted(self, nucleus: Node) -> bool: + if isinstance(nucleus, Char): + return nucleus.is_slanted() + return False + + def subsuper(self, s: str, loc: int, toks: ParseResults) -> T.Any: + nucleus = toks.get("nucleus", Hbox(0)) + subsuper = toks.get("subsuper", []) + napostrophes = len(toks.get("apostrophes", [])) + + if not subsuper and not napostrophes: + return nucleus + + sub = super = None + while subsuper: + op, arg, *subsuper = subsuper + if op == '_': + if sub is not None: + raise ParseFatalException("Double subscript") + sub = arg + else: + if super is not None: + raise ParseFatalException("Double superscript") + super = arg + + state = self.get_state() + rule_thickness = state.fontset.get_underline_thickness( + state.font, state.fontsize, state.dpi) + xHeight = state.fontset.get_xheight( + state.font, state.fontsize, state.dpi) + + if napostrophes: + if super is None: + super = Hlist([]) + for i in range(napostrophes): + super.children.extend(self.symbol(s, loc, {"sym": "\\prime"})) + # kern() and hpack() needed to get the metrics right after + # extending + super.kern() + super.hpack() + + # Handle over/under symbols, such as sum or prod + if self.is_overunder(nucleus): + vlist = [] + shift = 0. + width = nucleus.width + if super is not None: + super.shrink() + width = max(width, super.width) + if sub is not None: + sub.shrink() + width = max(width, sub.width) + + vgap = rule_thickness * 3.0 + if super is not None: + hlist = HCentered([super]) + hlist.hpack(width, 'exactly') + vlist.extend([hlist, Vbox(0, vgap)]) + hlist = HCentered([nucleus]) + hlist.hpack(width, 'exactly') + vlist.append(hlist) + if sub is not None: + hlist = HCentered([sub]) + hlist.hpack(width, 'exactly') + vlist.extend([Vbox(0, vgap), hlist]) + shift = hlist.height + vgap + nucleus.depth + vlt = Vlist(vlist) + vlt.shift_amount = shift + result = Hlist([vlt]) + return [result] + + # We remove kerning on the last character for consistency (otherwise + # it will compute kerning based on non-shrunk characters and may put + # them too close together when superscripted) + # We change the width of the last character to match the advance to + # consider some fonts with weird metrics: e.g. stix's f has a width of + # 7.75 and a kerning of -4.0 for an advance of 3.72, and we want to put + # the superscript at the advance + last_char = nucleus + if isinstance(nucleus, Hlist): + new_children = nucleus.children + if len(new_children): + # remove last kern + if (isinstance(new_children[-1], Kern) and + hasattr(new_children[-2], '_metrics')): + new_children = new_children[:-1] + last_char = new_children[-1] + if hasattr(last_char, '_metrics'): + last_char.width = last_char._metrics.advance + # create new Hlist without kerning + nucleus = Hlist(new_children, do_kern=False) + else: + if isinstance(nucleus, Char): + last_char.width = last_char._metrics.advance + nucleus = Hlist([nucleus]) + + # Handle regular sub/superscripts + constants = _get_font_constant_set(state) + lc_height = last_char.height + lc_baseline = 0 + if self.is_dropsub(last_char): + lc_baseline = last_char.depth + + # Compute kerning for sub and super + superkern = constants.delta * xHeight + subkern = constants.delta * xHeight + if self.is_slanted(last_char): + superkern += constants.delta * xHeight + superkern += (constants.delta_slanted * + (lc_height - xHeight * 2. / 3.)) + if self.is_dropsub(last_char): + subkern = (3 * constants.delta - + constants.delta_integral) * lc_height + superkern = (3 * constants.delta + + constants.delta_integral) * lc_height + else: + subkern = 0 + + x: List + if super is None: + # node757 + # Note: One of super or sub must be a Node if we're in this function, but + # mypy can't know this, since it can't interpret pyparsing expressions, + # hence the cast. + x = Hlist([Kern(subkern), T.cast(Node, sub)]) + x.shrink() + if self.is_dropsub(last_char): + shift_down = lc_baseline + constants.subdrop * xHeight + else: + shift_down = constants.sub1 * xHeight + x.shift_amount = shift_down + else: + x = Hlist([Kern(superkern), super]) + x.shrink() + if self.is_dropsub(last_char): + shift_up = lc_height - constants.subdrop * xHeight + else: + shift_up = constants.sup1 * xHeight + if sub is None: + x.shift_amount = -shift_up + else: # Both sub and superscript + y = Hlist([Kern(subkern), sub]) + y.shrink() + if self.is_dropsub(last_char): + shift_down = lc_baseline + constants.subdrop * xHeight + else: + shift_down = constants.sub2 * xHeight + # If sub and superscript collide, move super up + clr = (2.0 * rule_thickness - + ((shift_up - x.depth) - (y.height - shift_down))) + if clr > 0.: + shift_up += clr + x = Vlist([ + x, + Kern((shift_up - x.depth) - (y.height - shift_down)), + y]) + x.shift_amount = shift_down + + if not self.is_dropsub(last_char): + x.width += constants.script_space * xHeight + + # Do we need to add a space after the nucleus? + # To find out, check the flag set by operatorname + spaced_nucleus = [nucleus, x] + if self._in_subscript_or_superscript: + spaced_nucleus += [self._make_space(self._space_widths[r'\,'])] + self._in_subscript_or_superscript = False + + result = Hlist(spaced_nucleus) + return [result] + + def _genfrac(self, ldelim: str, rdelim: str, rule: float | None, style: _MathStyle, + num: Hlist, den: Hlist) -> T.Any: + state = self.get_state() + thickness = state.get_current_underline_thickness() + + for _ in range(style.value): + num.shrink() + den.shrink() + cnum = HCentered([num]) + cden = HCentered([den]) + width = max(num.width, den.width) + cnum.hpack(width, 'exactly') + cden.hpack(width, 'exactly') + vlist = Vlist([cnum, # numerator + Vbox(0, thickness * 2.0), # space + Hrule(state, rule), # rule + Vbox(0, thickness * 2.0), # space + cden # denominator + ]) + + # Shift so the fraction line sits in the middle of the + # equals sign + metrics = state.fontset.get_metrics( + state.font, mpl.rcParams['mathtext.default'], + '=', state.fontsize, state.dpi) + shift = (cden.height - + ((metrics.ymax + metrics.ymin) / 2 - + thickness * 3.0)) + vlist.shift_amount = shift + + result = [Hlist([vlist, Hbox(thickness * 2.)])] + if ldelim or rdelim: + if ldelim == '': + ldelim = '.' + if rdelim == '': + rdelim = '.' + return self._auto_sized_delimiter(ldelim, + T.cast(list[Box | Char | str], + result), + rdelim) + return result + + def style_literal(self, toks: ParseResults) -> T.Any: + return self._MathStyle(int(toks["style_literal"])) + + def genfrac(self, toks: ParseResults) -> T.Any: + return self._genfrac( + toks.get("ldelim", ""), toks.get("rdelim", ""), + toks["rulesize"], toks.get("style", self._MathStyle.TEXTSTYLE), + toks["num"], toks["den"]) + + def frac(self, toks: ParseResults) -> T.Any: + return self._genfrac( + "", "", self.get_state().get_current_underline_thickness(), + self._MathStyle.TEXTSTYLE, toks["num"], toks["den"]) + + def dfrac(self, toks: ParseResults) -> T.Any: + return self._genfrac( + "", "", self.get_state().get_current_underline_thickness(), + self._MathStyle.DISPLAYSTYLE, toks["num"], toks["den"]) + + def binom(self, toks: ParseResults) -> T.Any: + return self._genfrac( + "(", ")", 0, + self._MathStyle.TEXTSTYLE, toks["num"], toks["den"]) + + def _genset(self, s: str, loc: int, toks: ParseResults) -> T.Any: + annotation = toks["annotation"] + body = toks["body"] + thickness = self.get_state().get_current_underline_thickness() + + annotation.shrink() + centered_annotation = HCentered([annotation]) + centered_body = HCentered([body]) + width = max(centered_annotation.width, centered_body.width) + centered_annotation.hpack(width, 'exactly') + centered_body.hpack(width, 'exactly') + + vgap = thickness * 3 + if s[loc + 1] == "u": # \underset + vlist = Vlist([ + centered_body, # body + Vbox(0, vgap), # space + centered_annotation # annotation + ]) + # Shift so the body sits in the same vertical position + vlist.shift_amount = centered_body.depth + centered_annotation.height + vgap + else: # \overset + vlist = Vlist([ + centered_annotation, # annotation + Vbox(0, vgap), # space + centered_body # body + ]) + + # To add horizontal gap between symbols: wrap the Vlist into + # an Hlist and extend it with an Hbox(0, horizontal_gap) + return vlist + + overset = underset = _genset + + def sqrt(self, toks: ParseResults) -> T.Any: + root = toks.get("root") + body = toks["value"] + state = self.get_state() + thickness = state.get_current_underline_thickness() + + # Determine the height of the body, and add a little extra to + # the height so it doesn't seem cramped + height = body.height - body.shift_amount + thickness * 5.0 + depth = body.depth + body.shift_amount + check = AutoHeightChar(r'\__sqrt__', height, depth, state, always=True) + height = check.height - check.shift_amount + depth = check.depth + check.shift_amount + + # Put a little extra space to the left and right of the body + padded_body = Hlist([Hbox(2 * thickness), body, Hbox(2 * thickness)]) + rightside = Vlist([Hrule(state), Glue('fill'), padded_body]) + # Stretch the glue between the hrule and the body + rightside.vpack(height + (state.fontsize * state.dpi) / (100.0 * 12.0), + 'exactly', depth) + + # Add the root and shift it upward so it is above the tick. + # The value of 0.6 is a hard-coded hack ;) + if not root: + root = Box(check.width * 0.5, 0., 0.) + else: + root = Hlist(root) + root.shrink() + root.shrink() + + root_vlist = Vlist([Hlist([root])]) + root_vlist.shift_amount = -height * 0.6 + + hlist = Hlist([root_vlist, # Root + # Negative kerning to put root over tick + Kern(-check.width * 0.5), + check, # Check + rightside]) # Body + return [hlist] + + def overline(self, toks: ParseResults) -> T.Any: + body = toks["body"] + + state = self.get_state() + thickness = state.get_current_underline_thickness() + + height = body.height - body.shift_amount + thickness * 3.0 + depth = body.depth + body.shift_amount + + # Place overline above body + rightside = Vlist([Hrule(state), Glue('fill'), Hlist([body])]) + + # Stretch the glue between the hrule and the body + rightside.vpack(height + (state.fontsize * state.dpi) / (100.0 * 12.0), + 'exactly', depth) + + hlist = Hlist([rightside]) + return [hlist] + + def _auto_sized_delimiter(self, front: str, + middle: list[Box | Char | str], + back: str) -> T.Any: + state = self.get_state() + if len(middle): + height = max([x.height for x in middle if not isinstance(x, str)]) + depth = max([x.depth for x in middle if not isinstance(x, str)]) + factor = None + for idx, el in enumerate(middle): + if el == r'\middle': + c = T.cast(str, middle[idx + 1]) # Should be one of p.delims. + if c != '.': + middle[idx + 1] = AutoHeightChar( + c, height, depth, state, factor=factor) + else: + middle.remove(c) + del middle[idx] + # There should only be \middle and its delimiter as str, which have + # just been removed. + middle_part = T.cast(list[Box | Char], middle) + else: + height = 0 + depth = 0 + factor = 1.0 + middle_part = [] + + parts: list[Node] = [] + # \left. and \right. aren't supposed to produce any symbols + if front != '.': + parts.append( + AutoHeightChar(front, height, depth, state, factor=factor)) + parts.extend(middle_part) + if back != '.': + parts.append( + AutoHeightChar(back, height, depth, state, factor=factor)) + hlist = Hlist(parts) + return hlist + + def auto_delim(self, toks: ParseResults) -> T.Any: + return self._auto_sized_delimiter( + toks["left"], + # if "mid" in toks ... can be removed when requiring pyparsing 3. + toks["mid"].asList() if "mid" in toks else [], + toks["right"]) + + def boldsymbol(self, toks: ParseResults) -> T.Any: + self.push_state() + state = self.get_state() + hlist: list[Node] = [] + name = toks["value"] + for c in name: + if isinstance(c, Hlist): + k = c.children[1] + if isinstance(k, Char): + k.font = "bf" + k._update_metrics() + hlist.append(c) + elif isinstance(c, Char): + c.font = "bf" + if (c.c in self._latin_alphabets or + c.c[1:] in self._small_greek): + c.font = "bfit" + c._update_metrics() + c._update_metrics() + hlist.append(c) + else: + hlist.append(c) + self.pop_state() + + return Hlist(hlist) + + def substack(self, toks: ParseResults) -> T.Any: + parts = toks["parts"] + state = self.get_state() + thickness = state.get_current_underline_thickness() + + hlist = [Hlist(k) for k in parts[0]] + max_width = max(map(lambda c: c.width, hlist)) + + vlist = [] + for sub in hlist: + cp = HCentered([sub]) + cp.hpack(max_width, 'exactly') + vlist.append(cp) + + stack = [val + for pair in zip(vlist, [Vbox(0, thickness * 2)] * len(vlist)) + for val in pair] + del stack[-1] + vlt = Vlist(stack) + result = [Hlist([vlt])] + return result diff --git a/infer_4_30_0/lib/python3.10/site-packages/matplotlib/_mathtext_data.py b/infer_4_30_0/lib/python3.10/site-packages/matplotlib/_mathtext_data.py new file mode 100644 index 0000000000000000000000000000000000000000..5819ee7430447f9ef5f6e760b65cdd5933ef9395 --- /dev/null +++ b/infer_4_30_0/lib/python3.10/site-packages/matplotlib/_mathtext_data.py @@ -0,0 +1,1742 @@ +""" +font data tables for truetype and afm computer modern fonts +""" + +from __future__ import annotations +from typing import overload + +latex_to_bakoma = { + '\\__sqrt__' : ('cmex10', 0x70), + '\\bigcap' : ('cmex10', 0x5c), + '\\bigcup' : ('cmex10', 0x5b), + '\\bigodot' : ('cmex10', 0x4b), + '\\bigoplus' : ('cmex10', 0x4d), + '\\bigotimes' : ('cmex10', 0x4f), + '\\biguplus' : ('cmex10', 0x5d), + '\\bigvee' : ('cmex10', 0x5f), + '\\bigwedge' : ('cmex10', 0x5e), + '\\coprod' : ('cmex10', 0x61), + '\\int' : ('cmex10', 0x5a), + '\\langle' : ('cmex10', 0xad), + '\\leftangle' : ('cmex10', 0xad), + '\\leftbrace' : ('cmex10', 0xa9), + '\\oint' : ('cmex10', 0x49), + '\\prod' : ('cmex10', 0x59), + '\\rangle' : ('cmex10', 0xae), + '\\rightangle' : ('cmex10', 0xae), + '\\rightbrace' : ('cmex10', 0xaa), + '\\sum' : ('cmex10', 0x58), + '\\widehat' : ('cmex10', 0x62), + '\\widetilde' : ('cmex10', 0x65), + '\\{' : ('cmex10', 0xa9), + '\\}' : ('cmex10', 0xaa), + '{' : ('cmex10', 0xa9), + '}' : ('cmex10', 0xaa), + + ',' : ('cmmi10', 0x3b), + '.' : ('cmmi10', 0x3a), + '/' : ('cmmi10', 0x3d), + '<' : ('cmmi10', 0x3c), + '>' : ('cmmi10', 0x3e), + '\\alpha' : ('cmmi10', 0xae), + '\\beta' : ('cmmi10', 0xaf), + '\\chi' : ('cmmi10', 0xc2), + '\\combiningrightarrowabove' : ('cmmi10', 0x7e), + '\\delta' : ('cmmi10', 0xb1), + '\\ell' : ('cmmi10', 0x60), + '\\epsilon' : ('cmmi10', 0xb2), + '\\eta' : ('cmmi10', 0xb4), + '\\flat' : ('cmmi10', 0x5b), + '\\frown' : ('cmmi10', 0x5f), + '\\gamma' : ('cmmi10', 0xb0), + '\\imath' : ('cmmi10', 0x7b), + '\\iota' : ('cmmi10', 0xb6), + '\\jmath' : ('cmmi10', 0x7c), + '\\kappa' : ('cmmi10', 0x2219), + '\\lambda' : ('cmmi10', 0xb8), + '\\leftharpoondown' : ('cmmi10', 0x29), + '\\leftharpoonup' : ('cmmi10', 0x28), + '\\mu' : ('cmmi10', 0xb9), + '\\natural' : ('cmmi10', 0x5c), + '\\nu' : ('cmmi10', 0xba), + '\\omega' : ('cmmi10', 0x21), + '\\phi' : ('cmmi10', 0xc1), + '\\pi' : ('cmmi10', 0xbc), + '\\psi' : ('cmmi10', 0xc3), + '\\rho' : ('cmmi10', 0xbd), + '\\rightharpoondown' : ('cmmi10', 0x2b), + '\\rightharpoonup' : ('cmmi10', 0x2a), + '\\sharp' : ('cmmi10', 0x5d), + '\\sigma' : ('cmmi10', 0xbe), + '\\smile' : ('cmmi10', 0x5e), + '\\tau' : ('cmmi10', 0xbf), + '\\theta' : ('cmmi10', 0xb5), + '\\triangleleft' : ('cmmi10', 0x2f), + '\\triangleright' : ('cmmi10', 0x2e), + '\\upsilon' : ('cmmi10', 0xc0), + '\\varepsilon' : ('cmmi10', 0x22), + '\\varphi' : ('cmmi10', 0x27), + '\\varrho' : ('cmmi10', 0x25), + '\\varsigma' : ('cmmi10', 0x26), + '\\vartheta' : ('cmmi10', 0x23), + '\\wp' : ('cmmi10', 0x7d), + '\\xi' : ('cmmi10', 0xbb), + '\\zeta' : ('cmmi10', 0xb3), + + '!' : ('cmr10', 0x21), + '%' : ('cmr10', 0x25), + '&' : ('cmr10', 0x26), + '(' : ('cmr10', 0x28), + ')' : ('cmr10', 0x29), + '+' : ('cmr10', 0x2b), + '0' : ('cmr10', 0x30), + '1' : ('cmr10', 0x31), + '2' : ('cmr10', 0x32), + '3' : ('cmr10', 0x33), + '4' : ('cmr10', 0x34), + '5' : ('cmr10', 0x35), + '6' : ('cmr10', 0x36), + '7' : ('cmr10', 0x37), + '8' : ('cmr10', 0x38), + '9' : ('cmr10', 0x39), + ':' : ('cmr10', 0x3a), + ';' : ('cmr10', 0x3b), + '=' : ('cmr10', 0x3d), + '?' : ('cmr10', 0x3f), + '@' : ('cmr10', 0x40), + '[' : ('cmr10', 0x5b), + '\\#' : ('cmr10', 0x23), + '\\$' : ('cmr10', 0x24), + '\\%' : ('cmr10', 0x25), + '\\Delta' : ('cmr10', 0xa2), + '\\Gamma' : ('cmr10', 0xa1), + '\\Lambda' : ('cmr10', 0xa4), + '\\Omega' : ('cmr10', 0xad), + '\\Phi' : ('cmr10', 0xa9), + '\\Pi' : ('cmr10', 0xa6), + '\\Psi' : ('cmr10', 0xaa), + '\\Sigma' : ('cmr10', 0xa7), + '\\Theta' : ('cmr10', 0xa3), + '\\Upsilon' : ('cmr10', 0xa8), + '\\Xi' : ('cmr10', 0xa5), + '\\circumflexaccent' : ('cmr10', 0x5e), + '\\combiningacuteaccent' : ('cmr10', 0xb6), + '\\combiningbreve' : ('cmr10', 0xb8), + '\\combiningdiaeresis' : ('cmr10', 0xc4), + '\\combiningdotabove' : ('cmr10', 0x5f), + '\\combininggraveaccent' : ('cmr10', 0xb5), + '\\combiningoverline' : ('cmr10', 0xb9), + '\\combiningtilde' : ('cmr10', 0x7e), + '\\leftbracket' : ('cmr10', 0x5b), + '\\leftparen' : ('cmr10', 0x28), + '\\rightbracket' : ('cmr10', 0x5d), + '\\rightparen' : ('cmr10', 0x29), + '\\widebar' : ('cmr10', 0xb9), + ']' : ('cmr10', 0x5d), + + '*' : ('cmsy10', 0xa4), + '\N{MINUS SIGN}' : ('cmsy10', 0xa1), + '\\Downarrow' : ('cmsy10', 0x2b), + '\\Im' : ('cmsy10', 0x3d), + '\\Leftarrow' : ('cmsy10', 0x28), + '\\Leftrightarrow' : ('cmsy10', 0x2c), + '\\P' : ('cmsy10', 0x7b), + '\\Re' : ('cmsy10', 0x3c), + '\\Rightarrow' : ('cmsy10', 0x29), + '\\S' : ('cmsy10', 0x78), + '\\Uparrow' : ('cmsy10', 0x2a), + '\\Updownarrow' : ('cmsy10', 0x6d), + '\\Vert' : ('cmsy10', 0x6b), + '\\aleph' : ('cmsy10', 0x40), + '\\approx' : ('cmsy10', 0xbc), + '\\ast' : ('cmsy10', 0xa4), + '\\asymp' : ('cmsy10', 0xb3), + '\\backslash' : ('cmsy10', 0x6e), + '\\bigcirc' : ('cmsy10', 0xb0), + '\\bigtriangledown' : ('cmsy10', 0x35), + '\\bigtriangleup' : ('cmsy10', 0x34), + '\\bot' : ('cmsy10', 0x3f), + '\\bullet' : ('cmsy10', 0xb2), + '\\cap' : ('cmsy10', 0x5c), + '\\cdot' : ('cmsy10', 0xa2), + '\\circ' : ('cmsy10', 0xb1), + '\\clubsuit' : ('cmsy10', 0x7c), + '\\cup' : ('cmsy10', 0x5b), + '\\dag' : ('cmsy10', 0x79), + '\\dashv' : ('cmsy10', 0x61), + '\\ddag' : ('cmsy10', 0x7a), + '\\diamond' : ('cmsy10', 0xa6), + '\\diamondsuit' : ('cmsy10', 0x7d), + '\\div' : ('cmsy10', 0xa5), + '\\downarrow' : ('cmsy10', 0x23), + '\\emptyset' : ('cmsy10', 0x3b), + '\\equiv' : ('cmsy10', 0xb4), + '\\exists' : ('cmsy10', 0x39), + '\\forall' : ('cmsy10', 0x38), + '\\geq' : ('cmsy10', 0xb8), + '\\gg' : ('cmsy10', 0xc0), + '\\heartsuit' : ('cmsy10', 0x7e), + '\\in' : ('cmsy10', 0x32), + '\\infty' : ('cmsy10', 0x31), + '\\lbrace' : ('cmsy10', 0x66), + '\\lceil' : ('cmsy10', 0x64), + '\\leftarrow' : ('cmsy10', 0xc3), + '\\leftrightarrow' : ('cmsy10', 0x24), + '\\leq' : ('cmsy10', 0x2219), + '\\lfloor' : ('cmsy10', 0x62), + '\\ll' : ('cmsy10', 0xbf), + '\\mid' : ('cmsy10', 0x6a), + '\\mp' : ('cmsy10', 0xa8), + '\\nabla' : ('cmsy10', 0x72), + '\\nearrow' : ('cmsy10', 0x25), + '\\neg' : ('cmsy10', 0x3a), + '\\ni' : ('cmsy10', 0x33), + '\\nwarrow' : ('cmsy10', 0x2d), + '\\odot' : ('cmsy10', 0xaf), + '\\ominus' : ('cmsy10', 0xaa), + '\\oplus' : ('cmsy10', 0xa9), + '\\oslash' : ('cmsy10', 0xae), + '\\otimes' : ('cmsy10', 0xad), + '\\pm' : ('cmsy10', 0xa7), + '\\prec' : ('cmsy10', 0xc1), + '\\preceq' : ('cmsy10', 0xb9), + '\\prime' : ('cmsy10', 0x30), + '\\propto' : ('cmsy10', 0x2f), + '\\rbrace' : ('cmsy10', 0x67), + '\\rceil' : ('cmsy10', 0x65), + '\\rfloor' : ('cmsy10', 0x63), + '\\rightarrow' : ('cmsy10', 0x21), + '\\searrow' : ('cmsy10', 0x26), + '\\sim' : ('cmsy10', 0xbb), + '\\simeq' : ('cmsy10', 0x27), + '\\slash' : ('cmsy10', 0x36), + '\\spadesuit' : ('cmsy10', 0xc4), + '\\sqcap' : ('cmsy10', 0x75), + '\\sqcup' : ('cmsy10', 0x74), + '\\sqsubseteq' : ('cmsy10', 0x76), + '\\sqsupseteq' : ('cmsy10', 0x77), + '\\subset' : ('cmsy10', 0xbd), + '\\subseteq' : ('cmsy10', 0xb5), + '\\succ' : ('cmsy10', 0xc2), + '\\succeq' : ('cmsy10', 0xba), + '\\supset' : ('cmsy10', 0xbe), + '\\supseteq' : ('cmsy10', 0xb6), + '\\swarrow' : ('cmsy10', 0x2e), + '\\times' : ('cmsy10', 0xa3), + '\\to' : ('cmsy10', 0x21), + '\\top' : ('cmsy10', 0x3e), + '\\uparrow' : ('cmsy10', 0x22), + '\\updownarrow' : ('cmsy10', 0x6c), + '\\uplus' : ('cmsy10', 0x5d), + '\\vdash' : ('cmsy10', 0x60), + '\\vee' : ('cmsy10', 0x5f), + '\\vert' : ('cmsy10', 0x6a), + '\\wedge' : ('cmsy10', 0x5e), + '\\wr' : ('cmsy10', 0x6f), + '\\|' : ('cmsy10', 0x6b), + '|' : ('cmsy10', 0x6a), + + '\\_' : ('cmtt10', 0x5f) +} + +# Automatically generated. + +type12uni = { + 'aring' : 229, + 'quotedblright' : 8221, + 'V' : 86, + 'dollar' : 36, + 'four' : 52, + 'Yacute' : 221, + 'P' : 80, + 'underscore' : 95, + 'p' : 112, + 'Otilde' : 213, + 'perthousand' : 8240, + 'zero' : 48, + 'dotlessi' : 305, + 'Scaron' : 352, + 'zcaron' : 382, + 'egrave' : 232, + 'section' : 167, + 'Icircumflex' : 206, + 'ntilde' : 241, + 'ampersand' : 38, + 'dotaccent' : 729, + 'degree' : 176, + 'K' : 75, + 'acircumflex' : 226, + 'Aring' : 197, + 'k' : 107, + 'smalltilde' : 732, + 'Agrave' : 192, + 'divide' : 247, + 'ocircumflex' : 244, + 'asciitilde' : 126, + 'two' : 50, + 'E' : 69, + 'scaron' : 353, + 'F' : 70, + 'bracketleft' : 91, + 'asciicircum' : 94, + 'f' : 102, + 'ordmasculine' : 186, + 'mu' : 181, + 'paragraph' : 182, + 'nine' : 57, + 'v' : 118, + 'guilsinglleft' : 8249, + 'backslash' : 92, + 'six' : 54, + 'A' : 65, + 'icircumflex' : 238, + 'a' : 97, + 'ogonek' : 731, + 'q' : 113, + 'oacute' : 243, + 'ograve' : 242, + 'edieresis' : 235, + 'comma' : 44, + 'otilde' : 245, + 'guillemotright' : 187, + 'ecircumflex' : 234, + 'greater' : 62, + 'uacute' : 250, + 'L' : 76, + 'bullet' : 8226, + 'cedilla' : 184, + 'ydieresis' : 255, + 'l' : 108, + 'logicalnot' : 172, + 'exclamdown' : 161, + 'endash' : 8211, + 'agrave' : 224, + 'Adieresis' : 196, + 'germandbls' : 223, + 'Odieresis' : 214, + 'space' : 32, + 'quoteright' : 8217, + 'ucircumflex' : 251, + 'G' : 71, + 'quoteleft' : 8216, + 'W' : 87, + 'Q' : 81, + 'g' : 103, + 'w' : 119, + 'question' : 63, + 'one' : 49, + 'ring' : 730, + 'figuredash' : 8210, + 'B' : 66, + 'iacute' : 237, + 'Ydieresis' : 376, + 'R' : 82, + 'b' : 98, + 'r' : 114, + 'Ccedilla' : 199, + 'minus' : 8722, + 'Lslash' : 321, + 'Uacute' : 218, + 'yacute' : 253, + 'Ucircumflex' : 219, + 'quotedbl' : 34, + 'onehalf' : 189, + 'Thorn' : 222, + 'M' : 77, + 'eight' : 56, + 'multiply' : 215, + 'grave' : 96, + 'Ocircumflex' : 212, + 'm' : 109, + 'Ugrave' : 217, + 'guilsinglright' : 8250, + 'Ntilde' : 209, + 'questiondown' : 191, + 'Atilde' : 195, + 'ccedilla' : 231, + 'Z' : 90, + 'copyright' : 169, + 'yen' : 165, + 'Eacute' : 201, + 'H' : 72, + 'X' : 88, + 'Idieresis' : 207, + 'bar' : 124, + 'h' : 104, + 'x' : 120, + 'udieresis' : 252, + 'ordfeminine' : 170, + 'braceleft' : 123, + 'macron' : 175, + 'atilde' : 227, + 'Acircumflex' : 194, + 'Oslash' : 216, + 'C' : 67, + 'quotedblleft' : 8220, + 'S' : 83, + 'exclam' : 33, + 'Zcaron' : 381, + 'equal' : 61, + 's' : 115, + 'eth' : 240, + 'Egrave' : 200, + 'hyphen' : 45, + 'period' : 46, + 'igrave' : 236, + 'colon' : 58, + 'Ecircumflex' : 202, + 'trademark' : 8482, + 'Aacute' : 193, + 'cent' : 162, + 'lslash' : 322, + 'c' : 99, + 'N' : 78, + 'breve' : 728, + 'Oacute' : 211, + 'guillemotleft' : 171, + 'n' : 110, + 'idieresis' : 239, + 'braceright' : 125, + 'seven' : 55, + 'brokenbar' : 166, + 'ugrave' : 249, + 'periodcentered' : 183, + 'sterling' : 163, + 'I' : 73, + 'Y' : 89, + 'Eth' : 208, + 'emdash' : 8212, + 'i' : 105, + 'daggerdbl' : 8225, + 'y' : 121, + 'plusminus' : 177, + 'less' : 60, + 'Udieresis' : 220, + 'D' : 68, + 'five' : 53, + 'T' : 84, + 'oslash' : 248, + 'acute' : 180, + 'd' : 100, + 'OE' : 338, + 'Igrave' : 204, + 't' : 116, + 'parenright' : 41, + 'adieresis' : 228, + 'quotesingle' : 39, + 'twodotenleader' : 8229, + 'slash' : 47, + 'ellipsis' : 8230, + 'numbersign' : 35, + 'odieresis' : 246, + 'O' : 79, + 'oe' : 339, + 'o' : 111, + 'Edieresis' : 203, + 'plus' : 43, + 'dagger' : 8224, + 'three' : 51, + 'hungarumlaut' : 733, + 'parenleft' : 40, + 'fraction' : 8260, + 'registered' : 174, + 'J' : 74, + 'dieresis' : 168, + 'Ograve' : 210, + 'j' : 106, + 'z' : 122, + 'ae' : 230, + 'semicolon' : 59, + 'at' : 64, + 'Iacute' : 205, + 'percent' : 37, + 'bracketright' : 93, + 'AE' : 198, + 'asterisk' : 42, + 'aacute' : 225, + 'U' : 85, + 'eacute' : 233, + 'e' : 101, + 'thorn' : 254, + 'u' : 117, +} + +uni2type1 = {v: k for k, v in type12uni.items()} + +# The script below is to sort and format the tex2uni dict + +## For decimal values: int(hex(v), 16) +# newtex = {k: hex(v) for k, v in tex2uni.items()} +# sd = dict(sorted(newtex.items(), key=lambda item: item[0])) +# +## For formatting the sorted dictionary with proper spacing +## the value '24' comes from finding the longest string in +## the newtex keys with len(max(newtex, key=len)) +# for key in sd: +# print("{0:24} : {1: _EntryTypeOut: ... + + +@overload +def _normalize_stix_fontcodes(d: list[_EntryTypeIn]) -> list[_EntryTypeOut]: ... + + +@overload +def _normalize_stix_fontcodes(d: dict[str, list[_EntryTypeIn] | + dict[str, list[_EntryTypeIn]]] + ) -> dict[str, list[_EntryTypeOut] | + dict[str, list[_EntryTypeOut]]]: ... + + +def _normalize_stix_fontcodes(d): + if isinstance(d, tuple): + return tuple(ord(x) if isinstance(x, str) and len(x) == 1 else x for x in d) + elif isinstance(d, list): + return [_normalize_stix_fontcodes(x) for x in d] + elif isinstance(d, dict): + return {k: _normalize_stix_fontcodes(v) for k, v in d.items()} + + +stix_virtual_fonts: dict[str, dict[str, list[_EntryTypeOut]] | list[_EntryTypeOut]] +stix_virtual_fonts = _normalize_stix_fontcodes(_stix_virtual_fonts) + +# Free redundant list now that it has been normalized +del _stix_virtual_fonts + +# Fix some incorrect glyphs. +stix_glyph_fixes = { + # Cap and Cup glyphs are swapped. + 0x22d2: 0x22d3, + 0x22d3: 0x22d2, +} diff --git a/infer_4_30_0/lib/python3.10/site-packages/matplotlib/_path.pyi b/infer_4_30_0/lib/python3.10/site-packages/matplotlib/_path.pyi new file mode 100644 index 0000000000000000000000000000000000000000..456905528b28e0f4eea31ec9d86433fb43767b85 --- /dev/null +++ b/infer_4_30_0/lib/python3.10/site-packages/matplotlib/_path.pyi @@ -0,0 +1,9 @@ +from collections.abc import Sequence + +import numpy as np + +from .transforms import BboxBase + +def affine_transform(points: np.ndarray, trans: np.ndarray) -> np.ndarray: ... +def count_bboxes_overlapping_bbox(bbox: BboxBase, bboxes: Sequence[BboxBase]) -> int: ... +def update_path_extents(path, trans, rect, minpos, ignore): ... diff --git a/infer_4_30_0/lib/python3.10/site-packages/matplotlib/_pylab_helpers.pyi b/infer_4_30_0/lib/python3.10/site-packages/matplotlib/_pylab_helpers.pyi new file mode 100644 index 0000000000000000000000000000000000000000..bdd8cfba3173030b37b24af412970cbb62fee3ef --- /dev/null +++ b/infer_4_30_0/lib/python3.10/site-packages/matplotlib/_pylab_helpers.pyi @@ -0,0 +1,29 @@ +from collections import OrderedDict + +from matplotlib.backend_bases import FigureManagerBase +from matplotlib.figure import Figure + +class Gcf: + figs: OrderedDict[int, FigureManagerBase] + @classmethod + def get_fig_manager(cls, num: int) -> FigureManagerBase | None: ... + @classmethod + def destroy(cls, num: int | FigureManagerBase) -> None: ... + @classmethod + def destroy_fig(cls, fig: Figure) -> None: ... + @classmethod + def destroy_all(cls) -> None: ... + @classmethod + def has_fignum(cls, num: int) -> bool: ... + @classmethod + def get_all_fig_managers(cls) -> list[FigureManagerBase]: ... + @classmethod + def get_num_fig_managers(cls) -> int: ... + @classmethod + def get_active(cls) -> FigureManagerBase | None: ... + @classmethod + def _set_new_active_manager(cls, manager: FigureManagerBase) -> None: ... + @classmethod + def set_active(cls, manager: FigureManagerBase) -> None: ... + @classmethod + def draw_all(cls, force: bool = ...) -> None: ... diff --git a/infer_4_30_0/lib/python3.10/site-packages/matplotlib/_qhull.pyi b/infer_4_30_0/lib/python3.10/site-packages/matplotlib/_qhull.pyi new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/infer_4_30_0/lib/python3.10/site-packages/matplotlib/_tight_layout.py b/infer_4_30_0/lib/python3.10/site-packages/matplotlib/_tight_layout.py new file mode 100644 index 0000000000000000000000000000000000000000..548da79fff04320193a7170d5cf0f9b9fa743c0a --- /dev/null +++ b/infer_4_30_0/lib/python3.10/site-packages/matplotlib/_tight_layout.py @@ -0,0 +1,301 @@ +""" +Routines to adjust subplot params so that subplots are +nicely fit in the figure. In doing so, only axis labels, tick labels, Axes +titles and offsetboxes that are anchored to Axes are currently considered. + +Internally, this module assumes that the margins (left margin, etc.) which are +differences between ``Axes.get_tightbbox`` and ``Axes.bbox`` are independent of +Axes position. This may fail if ``Axes.adjustable`` is ``datalim`` as well as +such cases as when left or right margin are affected by xlabel. +""" + +import numpy as np + +import matplotlib as mpl +from matplotlib import _api, artist as martist +from matplotlib.font_manager import FontProperties +from matplotlib.transforms import Bbox + + +def _auto_adjust_subplotpars( + fig, renderer, shape, span_pairs, subplot_list, + ax_bbox_list=None, pad=1.08, h_pad=None, w_pad=None, rect=None): + """ + Return a dict of subplot parameters to adjust spacing between subplots + or ``None`` if resulting Axes would have zero height or width. + + Note that this function ignores geometry information of subplot itself, but + uses what is given by the *shape* and *subplot_list* parameters. Also, the + results could be incorrect if some subplots have ``adjustable=datalim``. + + Parameters + ---------- + shape : tuple[int, int] + Number of rows and columns of the grid. + span_pairs : list[tuple[slice, slice]] + List of rowspans and colspans occupied by each subplot. + subplot_list : list of subplots + List of subplots that will be used to calculate optimal subplot_params. + pad : float + Padding between the figure edge and the edges of subplots, as a + fraction of the font size. + h_pad, w_pad : float + Padding (height/width) between edges of adjacent subplots, as a + fraction of the font size. Defaults to *pad*. + rect : tuple + (left, bottom, right, top), default: None. + """ + rows, cols = shape + + font_size_inch = (FontProperties( + size=mpl.rcParams["font.size"]).get_size_in_points() / 72) + pad_inch = pad * font_size_inch + vpad_inch = h_pad * font_size_inch if h_pad is not None else pad_inch + hpad_inch = w_pad * font_size_inch if w_pad is not None else pad_inch + + if len(span_pairs) != len(subplot_list) or len(subplot_list) == 0: + raise ValueError + + if rect is None: + margin_left = margin_bottom = margin_right = margin_top = None + else: + margin_left, margin_bottom, _right, _top = rect + margin_right = 1 - _right if _right else None + margin_top = 1 - _top if _top else None + + vspaces = np.zeros((rows + 1, cols)) + hspaces = np.zeros((rows, cols + 1)) + + if ax_bbox_list is None: + ax_bbox_list = [ + Bbox.union([ax.get_position(original=True) for ax in subplots]) + for subplots in subplot_list] + + for subplots, ax_bbox, (rowspan, colspan) in zip( + subplot_list, ax_bbox_list, span_pairs): + if all(not ax.get_visible() for ax in subplots): + continue + + bb = [] + for ax in subplots: + if ax.get_visible(): + bb += [martist._get_tightbbox_for_layout_only(ax, renderer)] + + tight_bbox_raw = Bbox.union(bb) + tight_bbox = fig.transFigure.inverted().transform_bbox(tight_bbox_raw) + + hspaces[rowspan, colspan.start] += ax_bbox.xmin - tight_bbox.xmin # l + hspaces[rowspan, colspan.stop] += tight_bbox.xmax - ax_bbox.xmax # r + vspaces[rowspan.start, colspan] += tight_bbox.ymax - ax_bbox.ymax # t + vspaces[rowspan.stop, colspan] += ax_bbox.ymin - tight_bbox.ymin # b + + fig_width_inch, fig_height_inch = fig.get_size_inches() + + # margins can be negative for Axes with aspect applied, so use max(, 0) to + # make them nonnegative. + if not margin_left: + margin_left = max(hspaces[:, 0].max(), 0) + pad_inch/fig_width_inch + suplabel = fig._supylabel + if suplabel and suplabel.get_in_layout(): + rel_width = fig.transFigure.inverted().transform_bbox( + suplabel.get_window_extent(renderer)).width + margin_left += rel_width + pad_inch/fig_width_inch + if not margin_right: + margin_right = max(hspaces[:, -1].max(), 0) + pad_inch/fig_width_inch + if not margin_top: + margin_top = max(vspaces[0, :].max(), 0) + pad_inch/fig_height_inch + if fig._suptitle and fig._suptitle.get_in_layout(): + rel_height = fig.transFigure.inverted().transform_bbox( + fig._suptitle.get_window_extent(renderer)).height + margin_top += rel_height + pad_inch/fig_height_inch + if not margin_bottom: + margin_bottom = max(vspaces[-1, :].max(), 0) + pad_inch/fig_height_inch + suplabel = fig._supxlabel + if suplabel and suplabel.get_in_layout(): + rel_height = fig.transFigure.inverted().transform_bbox( + suplabel.get_window_extent(renderer)).height + margin_bottom += rel_height + pad_inch/fig_height_inch + + if margin_left + margin_right >= 1: + _api.warn_external('Tight layout not applied. The left and right ' + 'margins cannot be made large enough to ' + 'accommodate all Axes decorations.') + return None + if margin_bottom + margin_top >= 1: + _api.warn_external('Tight layout not applied. The bottom and top ' + 'margins cannot be made large enough to ' + 'accommodate all Axes decorations.') + return None + + kwargs = dict(left=margin_left, + right=1 - margin_right, + bottom=margin_bottom, + top=1 - margin_top) + + if cols > 1: + hspace = hspaces[:, 1:-1].max() + hpad_inch / fig_width_inch + # axes widths: + h_axes = (1 - margin_right - margin_left - hspace * (cols - 1)) / cols + if h_axes < 0: + _api.warn_external('Tight layout not applied. tight_layout ' + 'cannot make Axes width small enough to ' + 'accommodate all Axes decorations') + return None + else: + kwargs["wspace"] = hspace / h_axes + if rows > 1: + vspace = vspaces[1:-1, :].max() + vpad_inch / fig_height_inch + v_axes = (1 - margin_top - margin_bottom - vspace * (rows - 1)) / rows + if v_axes < 0: + _api.warn_external('Tight layout not applied. tight_layout ' + 'cannot make Axes height small enough to ' + 'accommodate all Axes decorations.') + return None + else: + kwargs["hspace"] = vspace / v_axes + + return kwargs + + +def get_subplotspec_list(axes_list, grid_spec=None): + """ + Return a list of subplotspec from the given list of Axes. + + For an instance of Axes that does not support subplotspec, None is inserted + in the list. + + If grid_spec is given, None is inserted for those not from the given + grid_spec. + """ + subplotspec_list = [] + for ax in axes_list: + axes_or_locator = ax.get_axes_locator() + if axes_or_locator is None: + axes_or_locator = ax + + if hasattr(axes_or_locator, "get_subplotspec"): + subplotspec = axes_or_locator.get_subplotspec() + if subplotspec is not None: + subplotspec = subplotspec.get_topmost_subplotspec() + gs = subplotspec.get_gridspec() + if grid_spec is not None: + if gs != grid_spec: + subplotspec = None + elif gs.locally_modified_subplot_params(): + subplotspec = None + else: + subplotspec = None + + subplotspec_list.append(subplotspec) + + return subplotspec_list + + +def get_tight_layout_figure(fig, axes_list, subplotspec_list, renderer, + pad=1.08, h_pad=None, w_pad=None, rect=None): + """ + Return subplot parameters for tight-layouted-figure with specified padding. + + Parameters + ---------- + fig : Figure + axes_list : list of Axes + subplotspec_list : list of `.SubplotSpec` + The subplotspecs of each Axes. + renderer : renderer + pad : float + Padding between the figure edge and the edges of subplots, as a + fraction of the font size. + h_pad, w_pad : float + Padding (height/width) between edges of adjacent subplots. Defaults to + *pad*. + rect : tuple (left, bottom, right, top), default: None. + rectangle in normalized figure coordinates + that the whole subplots area (including labels) will fit into. + Defaults to using the entire figure. + + Returns + ------- + subplotspec or None + subplotspec kwargs to be passed to `.Figure.subplots_adjust` or + None if tight_layout could not be accomplished. + """ + + # Multiple Axes can share same subplotspec (e.g., if using axes_grid1); + # we need to group them together. + ss_to_subplots = {ss: [] for ss in subplotspec_list} + for ax, ss in zip(axes_list, subplotspec_list): + ss_to_subplots[ss].append(ax) + if ss_to_subplots.pop(None, None): + _api.warn_external( + "This figure includes Axes that are not compatible with " + "tight_layout, so results might be incorrect.") + if not ss_to_subplots: + return {} + subplot_list = list(ss_to_subplots.values()) + ax_bbox_list = [ss.get_position(fig) for ss in ss_to_subplots] + + max_nrows = max(ss.get_gridspec().nrows for ss in ss_to_subplots) + max_ncols = max(ss.get_gridspec().ncols for ss in ss_to_subplots) + + span_pairs = [] + for ss in ss_to_subplots: + # The intent here is to support Axes from different gridspecs where + # one's nrows (or ncols) is a multiple of the other (e.g. 2 and 4), + # but this doesn't actually work because the computed wspace, in + # relative-axes-height, corresponds to different physical spacings for + # the 2-row grid and the 4-row grid. Still, this code is left, mostly + # for backcompat. + rows, cols = ss.get_gridspec().get_geometry() + div_row, mod_row = divmod(max_nrows, rows) + div_col, mod_col = divmod(max_ncols, cols) + if mod_row != 0: + _api.warn_external('tight_layout not applied: number of rows ' + 'in subplot specifications must be ' + 'multiples of one another.') + return {} + if mod_col != 0: + _api.warn_external('tight_layout not applied: number of ' + 'columns in subplot specifications must be ' + 'multiples of one another.') + return {} + span_pairs.append(( + slice(ss.rowspan.start * div_row, ss.rowspan.stop * div_row), + slice(ss.colspan.start * div_col, ss.colspan.stop * div_col))) + + kwargs = _auto_adjust_subplotpars(fig, renderer, + shape=(max_nrows, max_ncols), + span_pairs=span_pairs, + subplot_list=subplot_list, + ax_bbox_list=ax_bbox_list, + pad=pad, h_pad=h_pad, w_pad=w_pad) + + # kwargs can be none if tight_layout fails... + if rect is not None and kwargs is not None: + # if rect is given, the whole subplots area (including + # labels) will fit into the rect instead of the + # figure. Note that the rect argument of + # *auto_adjust_subplotpars* specify the area that will be + # covered by the total area of axes.bbox. Thus we call + # auto_adjust_subplotpars twice, where the second run + # with adjusted rect parameters. + + left, bottom, right, top = rect + if left is not None: + left += kwargs["left"] + if bottom is not None: + bottom += kwargs["bottom"] + if right is not None: + right -= (1 - kwargs["right"]) + if top is not None: + top -= (1 - kwargs["top"]) + + kwargs = _auto_adjust_subplotpars(fig, renderer, + shape=(max_nrows, max_ncols), + span_pairs=span_pairs, + subplot_list=subplot_list, + ax_bbox_list=ax_bbox_list, + pad=pad, h_pad=h_pad, w_pad=w_pad, + rect=(left, bottom, right, top)) + + return kwargs diff --git a/infer_4_30_0/lib/python3.10/site-packages/matplotlib/_tri.pyi b/infer_4_30_0/lib/python3.10/site-packages/matplotlib/_tri.pyi new file mode 100644 index 0000000000000000000000000000000000000000..a0c710fc2309fbfac3f37297eda919d86de32c76 --- /dev/null +++ b/infer_4_30_0/lib/python3.10/site-packages/matplotlib/_tri.pyi @@ -0,0 +1,36 @@ +# This is a private module implemented in C++ +from typing import final + +import numpy as np +import numpy.typing as npt + +@final +class TrapezoidMapTriFinder: + def __init__(self, triangulation: Triangulation): ... + def find_many(self, x: npt.NDArray[np.float64], y: npt.NDArray[np.float64]) -> npt.NDArray[np.int_]: ... + def get_tree_stats(self) -> list[int | float]: ... + def initialize(self) -> None: ... + def print_tree(self) -> None: ... + +@final +class TriContourGenerator: + def __init__(self, triangulation: Triangulation, z: npt.NDArray[np.float64]): ... + def create_contour(self, level: float) -> tuple[list[float], list[int]]: ... + def create_filled_contour(self, lower_level: float, upper_level: float) -> tuple[list[float], list[int]]: ... + +@final +class Triangulation: + def __init__( + self, + x: npt.NDArray[np.float64], + y: npt.NDArray[np.float64], + triangles: npt.NDArray[np.int_], + mask: npt.NDArray[np.bool_] | tuple[()], + edges: npt.NDArray[np.int_] | tuple[()], + neighbors: npt.NDArray[np.int_] | tuple[()], + correct_triangle_orientation: bool, + ): ... + def calculate_plane_coefficients(self, z: npt.ArrayLike) -> npt.NDArray[np.float64]: ... + def get_edges(self) -> npt.NDArray[np.int_]: ... + def get_neighbors(self) -> npt.NDArray[np.int_]: ... + def set_mask(self, mask: npt.NDArray[np.bool_] | tuple[()]) -> None: ... diff --git a/infer_4_30_0/lib/python3.10/site-packages/matplotlib/_version.py b/infer_4_30_0/lib/python3.10/site-packages/matplotlib/_version.py new file mode 100644 index 0000000000000000000000000000000000000000..81c484cb9624bffb260c72c1b2ffbe899379cde3 --- /dev/null +++ b/infer_4_30_0/lib/python3.10/site-packages/matplotlib/_version.py @@ -0,0 +1 @@ +version = "3.10.1" diff --git a/infer_4_30_0/lib/python3.10/site-packages/matplotlib/artist.py b/infer_4_30_0/lib/python3.10/site-packages/matplotlib/artist.py new file mode 100644 index 0000000000000000000000000000000000000000..c87c789048c4982e1b25507fe3c360e003a0def6 --- /dev/null +++ b/infer_4_30_0/lib/python3.10/site-packages/matplotlib/artist.py @@ -0,0 +1,1855 @@ +from collections import namedtuple +import contextlib +from functools import cache, reduce, wraps +import inspect +from inspect import Signature, Parameter +import logging +from numbers import Number, Real +import operator +import re +import warnings + +import numpy as np + +import matplotlib as mpl +from . import _api, cbook +from .path import Path +from .transforms import (BboxBase, Bbox, IdentityTransform, Transform, TransformedBbox, + TransformedPatchPath, TransformedPath) + +_log = logging.getLogger(__name__) + + +def _prevent_rasterization(draw): + # We assume that by default artists are not allowed to rasterize (unless + # its draw method is explicitly decorated). If it is being drawn after a + # rasterized artist and it has reached a raster_depth of 0, we stop + # rasterization so that it does not affect the behavior of normal artist + # (e.g., change in dpi). + + @wraps(draw) + def draw_wrapper(artist, renderer, *args, **kwargs): + if renderer._raster_depth == 0 and renderer._rasterizing: + # Only stop when we are not in a rasterized parent + # and something has been rasterized since last stop. + renderer.stop_rasterizing() + renderer._rasterizing = False + + return draw(artist, renderer, *args, **kwargs) + + draw_wrapper._supports_rasterization = False + return draw_wrapper + + +def allow_rasterization(draw): + """ + Decorator for Artist.draw method. Provides routines + that run before and after the draw call. The before and after functions + are useful for changing artist-dependent renderer attributes or making + other setup function calls, such as starting and flushing a mixed-mode + renderer. + """ + + @wraps(draw) + def draw_wrapper(artist, renderer): + try: + if artist.get_rasterized(): + if renderer._raster_depth == 0 and not renderer._rasterizing: + renderer.start_rasterizing() + renderer._rasterizing = True + renderer._raster_depth += 1 + else: + if renderer._raster_depth == 0 and renderer._rasterizing: + # Only stop when we are not in a rasterized parent + # and something has be rasterized since last stop + renderer.stop_rasterizing() + renderer._rasterizing = False + + if artist.get_agg_filter() is not None: + renderer.start_filter() + + return draw(artist, renderer) + finally: + if artist.get_agg_filter() is not None: + renderer.stop_filter(artist.get_agg_filter()) + if artist.get_rasterized(): + renderer._raster_depth -= 1 + if (renderer._rasterizing and (fig := artist.get_figure(root=True)) and + fig.suppressComposite): + # restart rasterizing to prevent merging + renderer.stop_rasterizing() + renderer.start_rasterizing() + + draw_wrapper._supports_rasterization = True + return draw_wrapper + + +def _finalize_rasterization(draw): + """ + Decorator for Artist.draw method. Needed on the outermost artist, i.e. + Figure, to finish up if the render is still in rasterized mode. + """ + @wraps(draw) + def draw_wrapper(artist, renderer, *args, **kwargs): + result = draw(artist, renderer, *args, **kwargs) + if renderer._rasterizing: + renderer.stop_rasterizing() + renderer._rasterizing = False + return result + return draw_wrapper + + +def _stale_axes_callback(self, val): + if self.axes: + self.axes.stale = val + + +_XYPair = namedtuple("_XYPair", "x y") + + +class _Unset: + def __repr__(self): + return "" +_UNSET = _Unset() + + +class Artist: + """ + Abstract base class for objects that render into a FigureCanvas. + + Typically, all visible elements in a figure are subclasses of Artist. + """ + + zorder = 0 + + def __init_subclass__(cls): + + # Decorate draw() method so that all artists are able to stop + # rastrization when necessary. If the artist's draw method is already + # decorated (has a `_supports_rasterization` attribute), it won't be + # decorated. + + if not hasattr(cls.draw, "_supports_rasterization"): + cls.draw = _prevent_rasterization(cls.draw) + + # Inject custom set() methods into the subclass with signature and + # docstring based on the subclasses' properties. + + if not hasattr(cls.set, '_autogenerated_signature'): + # Don't overwrite cls.set if the subclass or one of its parents + # has defined a set method set itself. + # If there was no explicit definition, cls.set is inherited from + # the hierarchy of auto-generated set methods, which hold the + # flag _autogenerated_signature. + return + + cls.set = lambda self, **kwargs: Artist.set(self, **kwargs) + cls.set.__name__ = "set" + cls.set.__qualname__ = f"{cls.__qualname__}.set" + cls._update_set_signature_and_docstring() + + _PROPERTIES_EXCLUDED_FROM_SET = [ + 'navigate_mode', # not a user-facing function + 'figure', # changing the figure is such a profound operation + # that we don't want this in set() + '3d_properties', # cannot be used as a keyword due to leading digit + ] + + @classmethod + def _update_set_signature_and_docstring(cls): + """ + Update the signature of the set function to list all properties + as keyword arguments. + + Property aliases are not listed in the signature for brevity, but + are still accepted as keyword arguments. + """ + cls.set.__signature__ = Signature( + [Parameter("self", Parameter.POSITIONAL_OR_KEYWORD), + *[Parameter(prop, Parameter.KEYWORD_ONLY, default=_UNSET) + for prop in ArtistInspector(cls).get_setters() + if prop not in Artist._PROPERTIES_EXCLUDED_FROM_SET]]) + cls.set._autogenerated_signature = True + + cls.set.__doc__ = ( + "Set multiple properties at once.\n\n" + "Supported properties are\n\n" + + kwdoc(cls)) + + def __init__(self): + self._stale = True + self.stale_callback = None + self._axes = None + self._parent_figure = None + + self._transform = None + self._transformSet = False + self._visible = True + self._animated = False + self._alpha = None + self.clipbox = None + self._clippath = None + self._clipon = True + self._label = '' + self._picker = None + self._rasterized = False + self._agg_filter = None + # Normally, artist classes need to be queried for mouseover info if and + # only if they override get_cursor_data. + self._mouseover = type(self).get_cursor_data != Artist.get_cursor_data + self._callbacks = cbook.CallbackRegistry(signals=["pchanged"]) + try: + self.axes = None + except AttributeError: + # Handle self.axes as a read-only property, as in Figure. + pass + self._remove_method = None + self._url = None + self._gid = None + self._snap = None + self._sketch = mpl.rcParams['path.sketch'] + self._path_effects = mpl.rcParams['path.effects'] + self._sticky_edges = _XYPair([], []) + self._in_layout = True + + def __getstate__(self): + d = self.__dict__.copy() + d['stale_callback'] = None + return d + + def remove(self): + """ + Remove the artist from the figure if possible. + + The effect will not be visible until the figure is redrawn, e.g., + with `.FigureCanvasBase.draw_idle`. Call `~.axes.Axes.relim` to + update the Axes limits if desired. + + Note: `~.axes.Axes.relim` will not see collections even if the + collection was added to the Axes with *autolim* = True. + + Note: there is no support for removing the artist's legend entry. + """ + + # There is no method to set the callback. Instead, the parent should + # set the _remove_method attribute directly. This would be a + # protected attribute if Python supported that sort of thing. The + # callback has one parameter, which is the child to be removed. + if self._remove_method is not None: + self._remove_method(self) + # clear stale callback + self.stale_callback = None + _ax_flag = False + if hasattr(self, 'axes') and self.axes: + # remove from the mouse hit list + self.axes._mouseover_set.discard(self) + self.axes.stale = True + self.axes = None # decouple the artist from the Axes + _ax_flag = True + + if (fig := self.get_figure(root=False)) is not None: + if not _ax_flag: + fig.stale = True + self._parent_figure = None + + else: + raise NotImplementedError('cannot remove artist') + # TODO: the fix for the collections relim problem is to move the + # limits calculation into the artist itself, including the property of + # whether or not the artist should affect the limits. Then there will + # be no distinction between axes.add_line, axes.add_patch, etc. + # TODO: add legend support + + def have_units(self): + """Return whether units are set on any axis.""" + ax = self.axes + return ax and any(axis.have_units() for axis in ax._axis_map.values()) + + def convert_xunits(self, x): + """ + Convert *x* using the unit type of the xaxis. + + If the artist is not contained in an Axes or if the xaxis does not + have units, *x* itself is returned. + """ + ax = getattr(self, 'axes', None) + if ax is None or ax.xaxis is None: + return x + return ax.xaxis.convert_units(x) + + def convert_yunits(self, y): + """ + Convert *y* using the unit type of the yaxis. + + If the artist is not contained in an Axes or if the yaxis does not + have units, *y* itself is returned. + """ + ax = getattr(self, 'axes', None) + if ax is None or ax.yaxis is None: + return y + return ax.yaxis.convert_units(y) + + @property + def axes(self): + """The `~.axes.Axes` instance the artist resides in, or *None*.""" + return self._axes + + @axes.setter + def axes(self, new_axes): + if (new_axes is not None and self._axes is not None + and new_axes != self._axes): + raise ValueError("Can not reset the Axes. You are probably trying to reuse " + "an artist in more than one Axes which is not supported") + self._axes = new_axes + if new_axes is not None and new_axes is not self: + self.stale_callback = _stale_axes_callback + + @property + def stale(self): + """ + Whether the artist is 'stale' and needs to be re-drawn for the output + to match the internal state of the artist. + """ + return self._stale + + @stale.setter + def stale(self, val): + self._stale = val + + # if the artist is animated it does not take normal part in the + # draw stack and is not expected to be drawn as part of the normal + # draw loop (when not saving) so do not propagate this change + if self._animated: + return + + if val and self.stale_callback is not None: + self.stale_callback(self, val) + + def get_window_extent(self, renderer=None): + """ + Get the artist's bounding box in display space. + + The bounding box' width and height are nonnegative. + + Subclasses should override for inclusion in the bounding box + "tight" calculation. Default is to return an empty bounding + box at 0, 0. + + Be careful when using this function, the results will not update + if the artist window extent of the artist changes. The extent + can change due to any changes in the transform stack, such as + changing the Axes limits, the figure size, or the canvas used + (as is done when saving a figure). This can lead to unexpected + behavior where interactive figures will look fine on the screen, + but will save incorrectly. + """ + return Bbox([[0, 0], [0, 0]]) + + def get_tightbbox(self, renderer=None): + """ + Like `.Artist.get_window_extent`, but includes any clipping. + + Parameters + ---------- + renderer : `~matplotlib.backend_bases.RendererBase` subclass, optional + renderer that will be used to draw the figures (i.e. + ``fig.canvas.get_renderer()``) + + Returns + ------- + `.Bbox` or None + The enclosing bounding box (in figure pixel coordinates). + Returns None if clipping results in no intersection. + """ + bbox = self.get_window_extent(renderer) + if self.get_clip_on(): + clip_box = self.get_clip_box() + if clip_box is not None: + bbox = Bbox.intersection(bbox, clip_box) + clip_path = self.get_clip_path() + if clip_path is not None and bbox is not None: + clip_path = clip_path.get_fully_transformed_path() + bbox = Bbox.intersection(bbox, clip_path.get_extents()) + return bbox + + def add_callback(self, func): + """ + Add a callback function that will be called whenever one of the + `.Artist`'s properties changes. + + Parameters + ---------- + func : callable + The callback function. It must have the signature:: + + def func(artist: Artist) -> Any + + where *artist* is the calling `.Artist`. Return values may exist + but are ignored. + + Returns + ------- + int + The observer id associated with the callback. This id can be + used for removing the callback with `.remove_callback` later. + + See Also + -------- + remove_callback + """ + # Wrapping func in a lambda ensures it can be connected multiple times + # and never gets weakref-gc'ed. + return self._callbacks.connect("pchanged", lambda: func(self)) + + def remove_callback(self, oid): + """ + Remove a callback based on its observer id. + + See Also + -------- + add_callback + """ + self._callbacks.disconnect(oid) + + def pchanged(self): + """ + Call all of the registered callbacks. + + This function is triggered internally when a property is changed. + + See Also + -------- + add_callback + remove_callback + """ + self._callbacks.process("pchanged") + + def is_transform_set(self): + """ + Return whether the Artist has an explicitly set transform. + + This is *True* after `.set_transform` has been called. + """ + return self._transformSet + + def set_transform(self, t): + """ + Set the artist transform. + + Parameters + ---------- + t : `~matplotlib.transforms.Transform` + """ + self._transform = t + self._transformSet = True + self.pchanged() + self.stale = True + + def get_transform(self): + """Return the `.Transform` instance used by this artist.""" + if self._transform is None: + self._transform = IdentityTransform() + elif (not isinstance(self._transform, Transform) + and hasattr(self._transform, '_as_mpl_transform')): + self._transform = self._transform._as_mpl_transform(self.axes) + return self._transform + + def get_children(self): + r"""Return a list of the child `.Artist`\s of this `.Artist`.""" + return [] + + def _different_canvas(self, event): + """ + Check whether an *event* occurred on a canvas other that this artist's canvas. + + If this method returns True, the event definitely occurred on a different + canvas; if it returns False, either it occurred on the same canvas, or we may + not have enough information to know. + + Subclasses should start their definition of `contains` as follows:: + + if self._different_canvas(mouseevent): + return False, {} + # subclass-specific implementation follows + """ + return (getattr(event, "canvas", None) is not None + and (fig := self.get_figure(root=True)) is not None + and event.canvas is not fig.canvas) + + def contains(self, mouseevent): + """ + Test whether the artist contains the mouse event. + + Parameters + ---------- + mouseevent : `~matplotlib.backend_bases.MouseEvent` + + Returns + ------- + contains : bool + Whether any values are within the radius. + details : dict + An artist-specific dictionary of details of the event context, + such as which points are contained in the pick radius. See the + individual Artist subclasses for details. + """ + _log.warning("%r needs 'contains' method", self.__class__.__name__) + return False, {} + + def pickable(self): + """ + Return whether the artist is pickable. + + See Also + -------- + .Artist.set_picker, .Artist.get_picker, .Artist.pick + """ + return self.get_figure(root=False) is not None and self._picker is not None + + def pick(self, mouseevent): + """ + Process a pick event. + + Each child artist will fire a pick event if *mouseevent* is over + the artist and the artist has picker set. + + See Also + -------- + .Artist.set_picker, .Artist.get_picker, .Artist.pickable + """ + from .backend_bases import PickEvent # Circular import. + # Pick self + if self.pickable(): + picker = self.get_picker() + if callable(picker): + inside, prop = picker(self, mouseevent) + else: + inside, prop = self.contains(mouseevent) + if inside: + PickEvent("pick_event", self.get_figure(root=True).canvas, + mouseevent, self, **prop)._process() + + # Pick children + for a in self.get_children(): + # make sure the event happened in the same Axes + ax = getattr(a, 'axes', None) + if (isinstance(a, mpl.figure.SubFigure) + or mouseevent.inaxes is None or ax is None + or mouseevent.inaxes == ax): + # we need to check if mouseevent.inaxes is None + # because some objects associated with an Axes (e.g., a + # tick label) can be outside the bounding box of the + # Axes and inaxes will be None + # also check that ax is None so that it traverse objects + # which do not have an axes property but children might + a.pick(mouseevent) + + def set_picker(self, picker): + """ + Define the picking behavior of the artist. + + Parameters + ---------- + picker : None or bool or float or callable + This can be one of the following: + + - *None*: Picking is disabled for this artist (default). + + - A boolean: If *True* then picking will be enabled and the + artist will fire a pick event if the mouse event is over + the artist. + + - A float: If picker is a number it is interpreted as an + epsilon tolerance in points and the artist will fire + off an event if its data is within epsilon of the mouse + event. For some artists like lines and patch collections, + the artist may provide additional data to the pick event + that is generated, e.g., the indices of the data within + epsilon of the pick event + + - A function: If picker is callable, it is a user supplied + function which determines whether the artist is hit by the + mouse event:: + + hit, props = picker(artist, mouseevent) + + to determine the hit test. if the mouse event is over the + artist, return *hit=True* and props is a dictionary of + properties you want added to the PickEvent attributes. + """ + self._picker = picker + + def get_picker(self): + """ + Return the picking behavior of the artist. + + The possible values are described in `.Artist.set_picker`. + + See Also + -------- + .Artist.set_picker, .Artist.pickable, .Artist.pick + """ + return self._picker + + def get_url(self): + """Return the url.""" + return self._url + + def set_url(self, url): + """ + Set the url for the artist. + + Parameters + ---------- + url : str + """ + self._url = url + + def get_gid(self): + """Return the group id.""" + return self._gid + + def set_gid(self, gid): + """ + Set the (group) id for the artist. + + Parameters + ---------- + gid : str + """ + self._gid = gid + + def get_snap(self): + """ + Return the snap setting. + + See `.set_snap` for details. + """ + if mpl.rcParams['path.snap']: + return self._snap + else: + return False + + def set_snap(self, snap): + """ + Set the snapping behavior. + + Snapping aligns positions with the pixel grid, which results in + clearer images. For example, if a black line of 1px width was + defined at a position in between two pixels, the resulting image + would contain the interpolated value of that line in the pixel grid, + which would be a grey value on both adjacent pixel positions. In + contrast, snapping will move the line to the nearest integer pixel + value, so that the resulting image will really contain a 1px wide + black line. + + Snapping is currently only supported by the Agg and MacOSX backends. + + Parameters + ---------- + snap : bool or None + Possible values: + + - *True*: Snap vertices to the nearest pixel center. + - *False*: Do not modify vertex positions. + - *None*: (auto) If the path contains only rectilinear line + segments, round to the nearest pixel center. + """ + self._snap = snap + self.stale = True + + def get_sketch_params(self): + """ + Return the sketch parameters for the artist. + + Returns + ------- + tuple or None + + A 3-tuple with the following elements: + + - *scale*: The amplitude of the wiggle perpendicular to the + source line. + - *length*: The length of the wiggle along the line. + - *randomness*: The scale factor by which the length is + shrunken or expanded. + + Returns *None* if no sketch parameters were set. + """ + return self._sketch + + def set_sketch_params(self, scale=None, length=None, randomness=None): + """ + Set the sketch parameters. + + Parameters + ---------- + scale : float, optional + The amplitude of the wiggle perpendicular to the source + line, in pixels. If scale is `None`, or not provided, no + sketch filter will be provided. + length : float, optional + The length of the wiggle along the line, in pixels + (default 128.0) + randomness : float, optional + The scale factor by which the length is shrunken or + expanded (default 16.0) + + The PGF backend uses this argument as an RNG seed and not as + described above. Using the same seed yields the same random shape. + + .. ACCEPTS: (scale: float, length: float, randomness: float) + """ + if scale is None: + self._sketch = None + else: + self._sketch = (scale, length or 128.0, randomness or 16.0) + self.stale = True + + def set_path_effects(self, path_effects): + """ + Set the path effects. + + Parameters + ---------- + path_effects : list of `.AbstractPathEffect` + """ + self._path_effects = path_effects + self.stale = True + + def get_path_effects(self): + return self._path_effects + + def get_figure(self, root=False): + """ + Return the `.Figure` or `.SubFigure` instance the artist belongs to. + + Parameters + ---------- + root : bool, default=False + If False, return the (Sub)Figure this artist is on. If True, + return the root Figure for a nested tree of SubFigures. + """ + if root and self._parent_figure is not None: + return self._parent_figure.get_figure(root=True) + + return self._parent_figure + + def set_figure(self, fig): + """ + Set the `.Figure` or `.SubFigure` instance the artist belongs to. + + Parameters + ---------- + fig : `~matplotlib.figure.Figure` or `~matplotlib.figure.SubFigure` + """ + # if this is a no-op just return + if self._parent_figure is fig: + return + # if we currently have a figure (the case of both `self.figure` + # and *fig* being none is taken care of above) we then user is + # trying to change the figure an artist is associated with which + # is not allowed for the same reason as adding the same instance + # to more than one Axes + if self._parent_figure is not None: + raise RuntimeError("Can not put single artist in " + "more than one figure") + self._parent_figure = fig + if self._parent_figure and self._parent_figure is not self: + self.pchanged() + self.stale = True + + figure = property(get_figure, set_figure, + doc=("The (Sub)Figure that the artist is on. For more " + "control, use the `get_figure` method.")) + + def set_clip_box(self, clipbox): + """ + Set the artist's clip `.Bbox`. + + Parameters + ---------- + clipbox : `~matplotlib.transforms.BboxBase` or None + Will typically be created from a `.TransformedBbox`. For instance, + ``TransformedBbox(Bbox([[0, 0], [1, 1]]), ax.transAxes)`` is the default + clipping for an artist added to an Axes. + + """ + _api.check_isinstance((BboxBase, None), clipbox=clipbox) + if clipbox != self.clipbox: + self.clipbox = clipbox + self.pchanged() + self.stale = True + + def set_clip_path(self, path, transform=None): + """ + Set the artist's clip path. + + Parameters + ---------- + path : `~matplotlib.patches.Patch` or `.Path` or `.TransformedPath` or None + The clip path. If given a `.Path`, *transform* must be provided as + well. If *None*, a previously set clip path is removed. + transform : `~matplotlib.transforms.Transform`, optional + Only used if *path* is a `.Path`, in which case the given `.Path` + is converted to a `.TransformedPath` using *transform*. + + Notes + ----- + For efficiency, if *path* is a `.Rectangle` this method will set the + clipping box to the corresponding rectangle and set the clipping path + to ``None``. + + For technical reasons (support of `~.Artist.set`), a tuple + (*path*, *transform*) is also accepted as a single positional + parameter. + + .. ACCEPTS: Patch or (Path, Transform) or None + """ + from matplotlib.patches import Patch, Rectangle + + success = False + if transform is None: + if isinstance(path, Rectangle): + self.clipbox = TransformedBbox(Bbox.unit(), + path.get_transform()) + self._clippath = None + success = True + elif isinstance(path, Patch): + self._clippath = TransformedPatchPath(path) + success = True + elif isinstance(path, tuple): + path, transform = path + + if path is None: + self._clippath = None + success = True + elif isinstance(path, Path): + self._clippath = TransformedPath(path, transform) + success = True + elif isinstance(path, TransformedPatchPath): + self._clippath = path + success = True + elif isinstance(path, TransformedPath): + self._clippath = path + success = True + + if not success: + raise TypeError( + "Invalid arguments to set_clip_path, of type " + f"{type(path).__name__} and {type(transform).__name__}") + # This may result in the callbacks being hit twice, but guarantees they + # will be hit at least once. + self.pchanged() + self.stale = True + + def get_alpha(self): + """ + Return the alpha value used for blending - not supported on all + backends. + """ + return self._alpha + + def get_visible(self): + """Return the visibility.""" + return self._visible + + def get_animated(self): + """Return whether the artist is animated.""" + return self._animated + + def get_in_layout(self): + """ + Return boolean flag, ``True`` if artist is included in layout + calculations. + + E.g. :ref:`constrainedlayout_guide`, + `.Figure.tight_layout()`, and + ``fig.savefig(fname, bbox_inches='tight')``. + """ + return self._in_layout + + def _fully_clipped_to_axes(self): + """ + Return a boolean flag, ``True`` if the artist is clipped to the Axes + and can thus be skipped in layout calculations. Requires `get_clip_on` + is True, one of `clip_box` or `clip_path` is set, ``clip_box.extents`` + is equivalent to ``ax.bbox.extents`` (if set), and ``clip_path._patch`` + is equivalent to ``ax.patch`` (if set). + """ + # Note that ``clip_path.get_fully_transformed_path().get_extents()`` + # cannot be directly compared to ``axes.bbox.extents`` because the + # extents may be undefined (i.e. equivalent to ``Bbox.null()``) + # before the associated artist is drawn, and this method is meant + # to determine whether ``axes.get_tightbbox()`` may bypass drawing + clip_box = self.get_clip_box() + clip_path = self.get_clip_path() + return (self.axes is not None + and self.get_clip_on() + and (clip_box is not None or clip_path is not None) + and (clip_box is None + or np.all(clip_box.extents == self.axes.bbox.extents)) + and (clip_path is None + or isinstance(clip_path, TransformedPatchPath) + and clip_path._patch is self.axes.patch)) + + def get_clip_on(self): + """Return whether the artist uses clipping.""" + return self._clipon + + def get_clip_box(self): + """Return the clipbox.""" + return self.clipbox + + def get_clip_path(self): + """Return the clip path.""" + return self._clippath + + def get_transformed_clip_path_and_affine(self): + """ + Return the clip path with the non-affine part of its + transformation applied, and the remaining affine part of its + transformation. + """ + if self._clippath is not None: + return self._clippath.get_transformed_path_and_affine() + return None, None + + def set_clip_on(self, b): + """ + Set whether the artist uses clipping. + + When False, artists will be visible outside the Axes which + can lead to unexpected results. + + Parameters + ---------- + b : bool + """ + self._clipon = b + # This may result in the callbacks being hit twice, but ensures they + # are hit at least once + self.pchanged() + self.stale = True + + def _set_gc_clip(self, gc): + """Set the clip properly for the gc.""" + if self._clipon: + if self.clipbox is not None: + gc.set_clip_rectangle(self.clipbox) + gc.set_clip_path(self._clippath) + else: + gc.set_clip_rectangle(None) + gc.set_clip_path(None) + + def get_rasterized(self): + """Return whether the artist is to be rasterized.""" + return self._rasterized + + def set_rasterized(self, rasterized): + """ + Force rasterized (bitmap) drawing for vector graphics output. + + Rasterized drawing is not supported by all artists. If you try to + enable this on an artist that does not support it, the command has no + effect and a warning will be issued. + + This setting is ignored for pixel-based output. + + See also :doc:`/gallery/misc/rasterization_demo`. + + Parameters + ---------- + rasterized : bool + """ + supports_rasterization = getattr(self.draw, + "_supports_rasterization", False) + if rasterized and not supports_rasterization: + _api.warn_external(f"Rasterization of '{self}' will be ignored") + + self._rasterized = rasterized + + def get_agg_filter(self): + """Return filter function to be used for agg filter.""" + return self._agg_filter + + def set_agg_filter(self, filter_func): + """ + Set the agg filter. + + Parameters + ---------- + filter_func : callable + A filter function, which takes a (m, n, depth) float array + and a dpi value, and returns a (m, n, depth) array and two + offsets from the bottom left corner of the image + + .. ACCEPTS: a filter function, which takes a (m, n, 3) float array + and a dpi value, and returns a (m, n, 3) array and two offsets + from the bottom left corner of the image + """ + self._agg_filter = filter_func + self.stale = True + + def draw(self, renderer): + """ + Draw the Artist (and its children) using the given renderer. + + This has no effect if the artist is not visible (`.Artist.get_visible` + returns False). + + Parameters + ---------- + renderer : `~matplotlib.backend_bases.RendererBase` subclass. + + Notes + ----- + This method is overridden in the Artist subclasses. + """ + if not self.get_visible(): + return + self.stale = False + + def set_alpha(self, alpha): + """ + Set the alpha value used for blending - not supported on all backends. + + Parameters + ---------- + alpha : float or None + *alpha* must be within the 0-1 range, inclusive. + """ + if alpha is not None and not isinstance(alpha, Real): + raise TypeError( + f'alpha must be numeric or None, not {type(alpha)}') + if alpha is not None and not (0 <= alpha <= 1): + raise ValueError(f'alpha ({alpha}) is outside 0-1 range') + if alpha != self._alpha: + self._alpha = alpha + self.pchanged() + self.stale = True + + def _set_alpha_for_array(self, alpha): + """ + Set the alpha value used for blending - not supported on all backends. + + Parameters + ---------- + alpha : array-like or float or None + All values must be within the 0-1 range, inclusive. + Masked values and nans are not supported. + """ + if isinstance(alpha, str): + raise TypeError("alpha must be numeric or None, not a string") + if not np.iterable(alpha): + Artist.set_alpha(self, alpha) + return + alpha = np.asarray(alpha) + if not (0 <= alpha.min() and alpha.max() <= 1): + raise ValueError('alpha must be between 0 and 1, inclusive, ' + f'but min is {alpha.min()}, max is {alpha.max()}') + self._alpha = alpha + self.pchanged() + self.stale = True + + def set_visible(self, b): + """ + Set the artist's visibility. + + Parameters + ---------- + b : bool + """ + if b != self._visible: + self._visible = b + self.pchanged() + self.stale = True + + def set_animated(self, b): + """ + Set whether the artist is intended to be used in an animation. + + If True, the artist is excluded from regular drawing of the figure. + You have to call `.Figure.draw_artist` / `.Axes.draw_artist` + explicitly on the artist. This approach is used to speed up animations + using blitting. + + See also `matplotlib.animation` and + :ref:`blitting`. + + Parameters + ---------- + b : bool + """ + if self._animated != b: + self._animated = b + self.pchanged() + + def set_in_layout(self, in_layout): + """ + Set if artist is to be included in layout calculations, + E.g. :ref:`constrainedlayout_guide`, + `.Figure.tight_layout()`, and + ``fig.savefig(fname, bbox_inches='tight')``. + + Parameters + ---------- + in_layout : bool + """ + self._in_layout = in_layout + + def get_label(self): + """Return the label used for this artist in the legend.""" + return self._label + + def set_label(self, s): + """ + Set a label that will be displayed in the legend. + + Parameters + ---------- + s : object + *s* will be converted to a string by calling `str`. + """ + label = str(s) if s is not None else None + if label != self._label: + self._label = label + self.pchanged() + self.stale = True + + def get_zorder(self): + """Return the artist's zorder.""" + return self.zorder + + def set_zorder(self, level): + """ + Set the zorder for the artist. Artists with lower zorder + values are drawn first. + + Parameters + ---------- + level : float + """ + if level is None: + level = self.__class__.zorder + if level != self.zorder: + self.zorder = level + self.pchanged() + self.stale = True + + @property + def sticky_edges(self): + """ + ``x`` and ``y`` sticky edge lists for autoscaling. + + When performing autoscaling, if a data limit coincides with a value in + the corresponding sticky_edges list, then no margin will be added--the + view limit "sticks" to the edge. A typical use case is histograms, + where one usually expects no margin on the bottom edge (0) of the + histogram. + + Moreover, margin expansion "bumps" against sticky edges and cannot + cross them. For example, if the upper data limit is 1.0, the upper + view limit computed by simple margin application is 1.2, but there is a + sticky edge at 1.1, then the actual upper view limit will be 1.1. + + This attribute cannot be assigned to; however, the ``x`` and ``y`` + lists can be modified in place as needed. + + Examples + -------- + >>> artist.sticky_edges.x[:] = (xmin, xmax) + >>> artist.sticky_edges.y[:] = (ymin, ymax) + + """ + return self._sticky_edges + + def update_from(self, other): + """Copy properties from *other* to *self*.""" + self._transform = other._transform + self._transformSet = other._transformSet + self._visible = other._visible + self._alpha = other._alpha + self.clipbox = other.clipbox + self._clipon = other._clipon + self._clippath = other._clippath + self._label = other._label + self._sketch = other._sketch + self._path_effects = other._path_effects + self.sticky_edges.x[:] = other.sticky_edges.x.copy() + self.sticky_edges.y[:] = other.sticky_edges.y.copy() + self.pchanged() + self.stale = True + + def properties(self): + """Return a dictionary of all the properties of the artist.""" + return ArtistInspector(self).properties() + + def _update_props(self, props, errfmt): + """ + Helper for `.Artist.set` and `.Artist.update`. + + *errfmt* is used to generate error messages for invalid property + names; it gets formatted with ``type(self)`` for "{cls}" and the + property name for "{prop_name}". + """ + ret = [] + with cbook._setattr_cm(self, eventson=False): + for k, v in props.items(): + # Allow attributes we want to be able to update through + # art.update, art.set, setp. + if k == "axes": + ret.append(setattr(self, k, v)) + else: + func = getattr(self, f"set_{k}", None) + if not callable(func): + raise AttributeError( + errfmt.format(cls=type(self), prop_name=k), + name=k) + ret.append(func(v)) + if ret: + self.pchanged() + self.stale = True + return ret + + def update(self, props): + """ + Update this artist's properties from the dict *props*. + + Parameters + ---------- + props : dict + """ + return self._update_props( + props, "{cls.__name__!r} object has no property {prop_name!r}") + + def _internal_update(self, kwargs): + """ + Update artist properties without prenormalizing them, but generating + errors as if calling `set`. + + The lack of prenormalization is to maintain backcompatibility. + """ + return self._update_props( + kwargs, "{cls.__name__}.set() got an unexpected keyword argument " + "{prop_name!r}") + + def set(self, **kwargs): + # docstring and signature are auto-generated via + # Artist._update_set_signature_and_docstring() at the end of the + # module. + return self._internal_update(cbook.normalize_kwargs(kwargs, self)) + + @contextlib.contextmanager + def _cm_set(self, **kwargs): + """ + `.Artist.set` context-manager that restores original values at exit. + """ + orig_vals = {k: getattr(self, f"get_{k}")() for k in kwargs} + try: + self.set(**kwargs) + yield + finally: + self.set(**orig_vals) + + def findobj(self, match=None, include_self=True): + """ + Find artist objects. + + Recursively find all `.Artist` instances contained in the artist. + + Parameters + ---------- + match + A filter criterion for the matches. This can be + + - *None*: Return all objects contained in artist. + - A function with signature ``def match(artist: Artist) -> bool``. + The result will only contain artists for which the function + returns *True*. + - A class instance: e.g., `.Line2D`. The result will only contain + artists of this class or its subclasses (``isinstance`` check). + + include_self : bool + Include *self* in the list to be checked for a match. + + Returns + ------- + list of `.Artist` + + """ + if match is None: # always return True + def matchfunc(x): + return True + elif isinstance(match, type) and issubclass(match, Artist): + def matchfunc(x): + return isinstance(x, match) + elif callable(match): + matchfunc = match + else: + raise ValueError('match must be None, a matplotlib.artist.Artist ' + 'subclass, or a callable') + + artists = reduce(operator.iadd, + [c.findobj(matchfunc) for c in self.get_children()], []) + if include_self and matchfunc(self): + artists.append(self) + return artists + + def get_cursor_data(self, event): + """ + Return the cursor data for a given event. + + .. note:: + This method is intended to be overridden by artist subclasses. + As an end-user of Matplotlib you will most likely not call this + method yourself. + + Cursor data can be used by Artists to provide additional context + information for a given event. The default implementation just returns + *None*. + + Subclasses can override the method and return arbitrary data. However, + when doing so, they must ensure that `.format_cursor_data` can convert + the data to a string representation. + + The only current use case is displaying the z-value of an `.AxesImage` + in the status bar of a plot window, while moving the mouse. + + Parameters + ---------- + event : `~matplotlib.backend_bases.MouseEvent` + + See Also + -------- + format_cursor_data + + """ + return None + + def format_cursor_data(self, data): + """ + Return a string representation of *data*. + + .. note:: + This method is intended to be overridden by artist subclasses. + As an end-user of Matplotlib you will most likely not call this + method yourself. + + The default implementation converts ints and floats and arrays of ints + and floats into a comma-separated string enclosed in square brackets, + unless the artist has an associated colorbar, in which case scalar + values are formatted using the colorbar's formatter. + + See Also + -------- + get_cursor_data + """ + if np.ndim(data) == 0 and hasattr(self, "_format_cursor_data_override"): + # workaround for ScalarMappable to be able to define its own + # format_cursor_data(). See ScalarMappable._format_cursor_data_override + # for details. + return self._format_cursor_data_override(data) + else: + try: + data[0] + except (TypeError, IndexError): + data = [data] + data_str = ', '.join(f'{item:0.3g}' for item in data + if isinstance(item, Number)) + return "[" + data_str + "]" + + def get_mouseover(self): + """ + Return whether this artist is queried for custom context information + when the mouse cursor moves over it. + """ + return self._mouseover + + def set_mouseover(self, mouseover): + """ + Set whether this artist is queried for custom context information when + the mouse cursor moves over it. + + Parameters + ---------- + mouseover : bool + + See Also + -------- + get_cursor_data + .ToolCursorPosition + .NavigationToolbar2 + """ + self._mouseover = bool(mouseover) + ax = self.axes + if ax: + if self._mouseover: + ax._mouseover_set.add(self) + else: + ax._mouseover_set.discard(self) + + mouseover = property(get_mouseover, set_mouseover) # backcompat. + + +def _get_tightbbox_for_layout_only(obj, *args, **kwargs): + """ + Matplotlib's `.Axes.get_tightbbox` and `.Axis.get_tightbbox` support a + *for_layout_only* kwarg; this helper tries to use the kwarg but skips it + when encountering third-party subclasses that do not support it. + """ + try: + return obj.get_tightbbox(*args, **{**kwargs, "for_layout_only": True}) + except TypeError: + return obj.get_tightbbox(*args, **kwargs) + + +class ArtistInspector: + """ + A helper class to inspect an `~matplotlib.artist.Artist` and return + information about its settable properties and their current values. + """ + + def __init__(self, o): + r""" + Initialize the artist inspector with an `Artist` or an iterable of + `Artist`\s. If an iterable is used, we assume it is a homogeneous + sequence (all `Artist`\s are of the same type) and it is your + responsibility to make sure this is so. + """ + if not isinstance(o, Artist): + if np.iterable(o): + o = list(o) + if len(o): + o = o[0] + + self.oorig = o + if not isinstance(o, type): + o = type(o) + self.o = o + + self.aliasd = self.get_aliases() + + def get_aliases(self): + """ + Get a dict mapping property fullnames to sets of aliases for each alias + in the :class:`~matplotlib.artist.ArtistInspector`. + + e.g., for lines:: + + {'markerfacecolor': {'mfc'}, + 'linewidth' : {'lw'}, + } + """ + names = [name for name in dir(self.o) + if name.startswith(('set_', 'get_')) + and callable(getattr(self.o, name))] + aliases = {} + for name in names: + func = getattr(self.o, name) + if not self.is_alias(func): + continue + propname = re.search(f"`({name[:4]}.*)`", # get_.*/set_.* + inspect.getdoc(func)).group(1) + aliases.setdefault(propname[4:], set()).add(name[4:]) + return aliases + + _get_valid_values_regex = re.compile( + r"\n\s*(?:\.\.\s+)?ACCEPTS:\s*((?:.|\n)*?)(?:$|(?:\n\n))" + ) + + def get_valid_values(self, attr): + """ + Get the legal arguments for the setter associated with *attr*. + + This is done by querying the docstring of the setter for a line that + begins with "ACCEPTS:" or ".. ACCEPTS:", and then by looking for a + numpydoc-style documentation for the setter's first argument. + """ + + name = 'set_%s' % attr + if not hasattr(self.o, name): + raise AttributeError(f'{self.o} has no function {name}') + func = getattr(self.o, name) + + if hasattr(func, '_kwarg_doc'): + return func._kwarg_doc + + docstring = inspect.getdoc(func) + if docstring is None: + return 'unknown' + + if docstring.startswith('Alias for '): + return None + + match = self._get_valid_values_regex.search(docstring) + if match is not None: + return re.sub("\n *", " ", match.group(1)) + + # Much faster than list(inspect.signature(func).parameters)[1], + # although barely relevant wrt. matplotlib's total import time. + param_name = func.__code__.co_varnames[1] + # We could set the presence * based on whether the parameter is a + # varargs (it can't be a varkwargs) but it's not really worth it. + match = re.search(fr"(?m)^ *\*?{param_name} : (.+)", docstring) + if match: + return match.group(1) + + return 'unknown' + + def _replace_path(self, source_class): + """ + Changes the full path to the public API path that is used + in sphinx. This is needed for links to work. + """ + replace_dict = {'_base._AxesBase': 'Axes', + '_axes.Axes': 'Axes'} + for key, value in replace_dict.items(): + source_class = source_class.replace(key, value) + return source_class + + def get_setters(self): + """ + Get the attribute strings with setters for object. + + For example, for a line, return ``['markerfacecolor', 'linewidth', + ....]``. + """ + setters = [] + for name in dir(self.o): + if not name.startswith('set_'): + continue + func = getattr(self.o, name) + if (not callable(func) + or self.number_of_parameters(func) < 2 + or self.is_alias(func)): + continue + setters.append(name[4:]) + return setters + + @staticmethod + @cache + def number_of_parameters(func): + """Return number of parameters of the callable *func*.""" + return len(inspect.signature(func).parameters) + + @staticmethod + @cache + def is_alias(method): + """ + Return whether the object *method* is an alias for another method. + """ + + ds = inspect.getdoc(method) + if ds is None: + return False + + return ds.startswith('Alias for ') + + def aliased_name(self, s): + """ + Return 'PROPNAME or alias' if *s* has an alias, else return 'PROPNAME'. + + For example, for the line markerfacecolor property, which has an + alias, return 'markerfacecolor or mfc' and for the transform + property, which does not, return 'transform'. + """ + aliases = ''.join(' or %s' % x for x in sorted(self.aliasd.get(s, []))) + return s + aliases + + _NOT_LINKABLE = { + # A set of property setter methods that are not available in our + # current docs. This is a workaround used to prevent trying to link + # these setters which would lead to "target reference not found" + # warnings during doc build. + 'matplotlib.image._ImageBase.set_alpha', + 'matplotlib.image._ImageBase.set_array', + 'matplotlib.image._ImageBase.set_data', + 'matplotlib.image._ImageBase.set_filternorm', + 'matplotlib.image._ImageBase.set_filterrad', + 'matplotlib.image._ImageBase.set_interpolation', + 'matplotlib.image._ImageBase.set_interpolation_stage', + 'matplotlib.image._ImageBase.set_resample', + 'matplotlib.text._AnnotationBase.set_annotation_clip', + } + + def aliased_name_rest(self, s, target): + """ + Return 'PROPNAME or alias' if *s* has an alias, else return 'PROPNAME', + formatted for reST. + + For example, for the line markerfacecolor property, which has an + alias, return 'markerfacecolor or mfc' and for the transform + property, which does not, return 'transform'. + """ + # workaround to prevent "reference target not found" + if target in self._NOT_LINKABLE: + return f'``{s}``' + + aliases = ''.join( + f' or :meth:`{a} <{target}>`' for a in sorted(self.aliasd.get(s, []))) + return f':meth:`{s} <{target}>`{aliases}' + + def pprint_setters(self, prop=None, leadingspace=2): + """ + If *prop* is *None*, return a list of strings of all settable + properties and their valid values. + + If *prop* is not *None*, it is a valid property name and that + property will be returned as a string of property : valid + values. + """ + if leadingspace: + pad = ' ' * leadingspace + else: + pad = '' + if prop is not None: + accepts = self.get_valid_values(prop) + return f'{pad}{prop}: {accepts}' + + lines = [] + for prop in sorted(self.get_setters()): + accepts = self.get_valid_values(prop) + name = self.aliased_name(prop) + lines.append(f'{pad}{name}: {accepts}') + return lines + + def pprint_setters_rest(self, prop=None, leadingspace=4): + """ + If *prop* is *None*, return a list of reST-formatted strings of all + settable properties and their valid values. + + If *prop* is not *None*, it is a valid property name and that + property will be returned as a string of "property : valid" + values. + """ + if leadingspace: + pad = ' ' * leadingspace + else: + pad = '' + if prop is not None: + accepts = self.get_valid_values(prop) + return f'{pad}{prop}: {accepts}' + + prop_and_qualnames = [] + for prop in sorted(self.get_setters()): + # Find the parent method which actually provides the docstring. + for cls in self.o.__mro__: + method = getattr(cls, f"set_{prop}", None) + if method and method.__doc__ is not None: + break + else: # No docstring available. + method = getattr(self.o, f"set_{prop}") + prop_and_qualnames.append( + (prop, f"{method.__module__}.{method.__qualname__}")) + + names = [self.aliased_name_rest(prop, target) + .replace('_base._AxesBase', 'Axes') + .replace('_axes.Axes', 'Axes') + for prop, target in prop_and_qualnames] + accepts = [self.get_valid_values(prop) + for prop, _ in prop_and_qualnames] + + col0_len = max(len(n) for n in names) + col1_len = max(len(a) for a in accepts) + table_formatstr = pad + ' ' + '=' * col0_len + ' ' + '=' * col1_len + + return [ + '', + pad + '.. table::', + pad + ' :class: property-table', + '', + table_formatstr, + pad + ' ' + 'Property'.ljust(col0_len) + + ' ' + 'Description'.ljust(col1_len), + table_formatstr, + *[pad + ' ' + n.ljust(col0_len) + ' ' + a.ljust(col1_len) + for n, a in zip(names, accepts)], + table_formatstr, + '', + ] + + def properties(self): + """Return a dictionary mapping property name -> value.""" + o = self.oorig + getters = [name for name in dir(o) + if name.startswith('get_') and callable(getattr(o, name))] + getters.sort() + d = {} + for name in getters: + func = getattr(o, name) + if self.is_alias(func): + continue + try: + with warnings.catch_warnings(): + warnings.simplefilter('ignore') + val = func() + except Exception: + continue + else: + d[name[4:]] = val + return d + + def pprint_getters(self): + """Return the getters and actual values as list of strings.""" + lines = [] + for name, val in sorted(self.properties().items()): + if getattr(val, 'shape', ()) != () and len(val) > 6: + s = str(val[:6]) + '...' + else: + s = str(val) + s = s.replace('\n', ' ') + if len(s) > 50: + s = s[:50] + '...' + name = self.aliased_name(name) + lines.append(f' {name} = {s}') + return lines + + +def getp(obj, property=None): + """ + Return the value of an `.Artist`'s *property*, or print all of them. + + Parameters + ---------- + obj : `~matplotlib.artist.Artist` + The queried artist; e.g., a `.Line2D`, a `.Text`, or an `~.axes.Axes`. + + property : str or None, default: None + If *property* is 'somename', this function returns + ``obj.get_somename()``. + + If it's None (or unset), it *prints* all gettable properties from + *obj*. Many properties have aliases for shorter typing, e.g. 'lw' is + an alias for 'linewidth'. In the output, aliases and full property + names will be listed as: + + property or alias = value + + e.g.: + + linewidth or lw = 2 + + See Also + -------- + setp + """ + if property is None: + insp = ArtistInspector(obj) + ret = insp.pprint_getters() + print('\n'.join(ret)) + return + return getattr(obj, 'get_' + property)() + +# alias +get = getp + + +def setp(obj, *args, file=None, **kwargs): + """ + Set one or more properties on an `.Artist`, or list allowed values. + + Parameters + ---------- + obj : `~matplotlib.artist.Artist` or list of `.Artist` + The artist(s) whose properties are being set or queried. When setting + properties, all artists are affected; when querying the allowed values, + only the first instance in the sequence is queried. + + For example, two lines can be made thicker and red with a single call: + + >>> x = arange(0, 1, 0.01) + >>> lines = plot(x, sin(2*pi*x), x, sin(4*pi*x)) + >>> setp(lines, linewidth=2, color='r') + + file : file-like, default: `sys.stdout` + Where `setp` writes its output when asked to list allowed values. + + >>> with open('output.log') as file: + ... setp(line, file=file) + + The default, ``None``, means `sys.stdout`. + + *args, **kwargs + The properties to set. The following combinations are supported: + + - Set the linestyle of a line to be dashed: + + >>> line, = plot([1, 2, 3]) + >>> setp(line, linestyle='--') + + - Set multiple properties at once: + + >>> setp(line, linewidth=2, color='r') + + - List allowed values for a line's linestyle: + + >>> setp(line, 'linestyle') + linestyle: {'-', '--', '-.', ':', '', (offset, on-off-seq), ...} + + - List all properties that can be set, and their allowed values: + + >>> setp(line) + agg_filter: a filter function, ... + [long output listing omitted] + + `setp` also supports MATLAB style string/value pairs. For example, the + following are equivalent: + + >>> setp(lines, 'linewidth', 2, 'color', 'r') # MATLAB style + >>> setp(lines, linewidth=2, color='r') # Python style + + See Also + -------- + getp + """ + + if isinstance(obj, Artist): + objs = [obj] + else: + objs = list(cbook.flatten(obj)) + + if not objs: + return + + insp = ArtistInspector(objs[0]) + + if not kwargs and len(args) < 2: + if args: + print(insp.pprint_setters(prop=args[0]), file=file) + else: + print('\n'.join(insp.pprint_setters()), file=file) + return + + if len(args) % 2: + raise ValueError('The set args must be string, value pairs') + + funcvals = dict(zip(args[::2], args[1::2])) + ret = [o.update(funcvals) for o in objs] + [o.set(**kwargs) for o in objs] + return list(cbook.flatten(ret)) + + +def kwdoc(artist): + r""" + Inspect an `~matplotlib.artist.Artist` class (using `.ArtistInspector`) and + return information about its settable properties and their current values. + + Parameters + ---------- + artist : `~matplotlib.artist.Artist` or an iterable of `Artist`\s + + Returns + ------- + str + The settable properties of *artist*, as plain text if + :rc:`docstring.hardcopy` is False and as a rst table (intended for + use in Sphinx) if it is True. + """ + ai = ArtistInspector(artist) + return ('\n'.join(ai.pprint_setters_rest(leadingspace=4)) + if mpl.rcParams['docstring.hardcopy'] else + 'Properties:\n' + '\n'.join(ai.pprint_setters(leadingspace=4))) + +# We defer this to the end of them module, because it needs ArtistInspector +# to be defined. +Artist._update_set_signature_and_docstring() diff --git a/infer_4_30_0/lib/python3.10/site-packages/matplotlib/axis.pyi b/infer_4_30_0/lib/python3.10/site-packages/matplotlib/axis.pyi new file mode 100644 index 0000000000000000000000000000000000000000..f2c5b1fc586d5a33237ace5ec264b6f6fde49080 --- /dev/null +++ b/infer_4_30_0/lib/python3.10/site-packages/matplotlib/axis.pyi @@ -0,0 +1,280 @@ +from collections.abc import Callable, Iterable, Sequence +import datetime +from typing import Any, Literal, overload +from typing_extensions import Self # < Py 3.11 + +import numpy as np +from numpy.typing import ArrayLike + +import matplotlib.artist as martist +from matplotlib import cbook +from matplotlib.axes import Axes +from matplotlib.backend_bases import RendererBase +from matplotlib.lines import Line2D +from matplotlib.text import Text +from matplotlib.ticker import Locator, Formatter +from matplotlib.transforms import Transform, Bbox +from matplotlib.typing import ColorType +from matplotlib.units import ConversionInterface + + +GRIDLINE_INTERPOLATION_STEPS: int + +class Tick(martist.Artist): + axes: Axes + tick1line: Line2D + tick2line: Line2D + gridline: Line2D + label1: Text + label2: Text + def __init__( + self, + axes: Axes, + loc: float, + *, + size: float | None = ..., + width: float | None = ..., + color: ColorType | None = ..., + tickdir: Literal["in", "inout", "out"] | None = ..., + pad: float | None = ..., + labelsize: float | None = ..., + labelcolor: ColorType | None = ..., + labelfontfamily: str | Sequence[str] | None = ..., + zorder: float | None = ..., + gridOn: bool | None = ..., + tick1On: bool = ..., + tick2On: bool = ..., + label1On: bool = ..., + label2On: bool = ..., + major: bool = ..., + labelrotation: float = ..., + grid_color: ColorType | None = ..., + grid_linestyle: str | None = ..., + grid_linewidth: float | None = ..., + grid_alpha: float | None = ..., + **kwargs + ) -> None: ... + def get_tickdir(self) -> Literal["in", "inout", "out"]: ... + def get_tick_padding(self) -> float: ... + def get_children(self) -> list[martist.Artist]: ... + stale: bool + def set_pad(self, val: float) -> None: ... + def get_pad(self) -> None: ... + def get_loc(self) -> float: ... + def set_url(self, url: str | None) -> None: ... + def get_view_interval(self) -> ArrayLike: ... + def update_position(self, loc: float) -> None: ... + +class XTick(Tick): + __name__: str + def __init__(self, *args, **kwargs) -> None: ... + stale: bool + def update_position(self, loc: float) -> None: ... + def get_view_interval(self) -> np.ndarray: ... + +class YTick(Tick): + __name__: str + def __init__(self, *args, **kwargs) -> None: ... + stale: bool + def update_position(self, loc: float) -> None: ... + def get_view_interval(self) -> np.ndarray: ... + +class Ticker: + def __init__(self) -> None: ... + @property + def locator(self) -> Locator | None: ... + @locator.setter + def locator(self, locator: Locator) -> None: ... + @property + def formatter(self) -> Formatter | None: ... + @formatter.setter + def formatter(self, formatter: Formatter) -> None: ... + +class _LazyTickList: + def __init__(self, major: bool) -> None: ... + @overload + def __get__(self, instance: None, owner: None) -> Self: ... + @overload + def __get__(self, instance: Axis, owner: type[Axis]) -> list[Tick]: ... + +class Axis(martist.Artist): + OFFSETTEXTPAD: int + isDefault_label: bool + axes: Axes + major: Ticker + minor: Ticker + callbacks: cbook.CallbackRegistry + label: Text + offsetText: Text + labelpad: float + pickradius: float + def __init__(self, axes, *, pickradius: float = ..., + clear: bool = ...) -> None: ... + @property + def isDefault_majloc(self) -> bool: ... + @isDefault_majloc.setter + def isDefault_majloc(self, value: bool) -> None: ... + @property + def isDefault_majfmt(self) -> bool: ... + @isDefault_majfmt.setter + def isDefault_majfmt(self, value: bool) -> None: ... + @property + def isDefault_minloc(self) -> bool: ... + @isDefault_minloc.setter + def isDefault_minloc(self, value: bool) -> None: ... + @property + def isDefault_minfmt(self) -> bool: ... + @isDefault_minfmt.setter + def isDefault_minfmt(self, value: bool) -> None: ... + majorTicks: _LazyTickList + minorTicks: _LazyTickList + def get_remove_overlapping_locs(self) -> bool: ... + def set_remove_overlapping_locs(self, val: bool) -> None: ... + @property + def remove_overlapping_locs(self) -> bool: ... + @remove_overlapping_locs.setter + def remove_overlapping_locs(self, val: bool) -> None: ... + stale: bool + def set_label_coords( + self, x: float, y: float, transform: Transform | None = ... + ) -> None: ... + def get_transform(self) -> Transform: ... + def get_scale(self) -> str: ... + def limit_range_for_scale( + self, vmin: float, vmax: float + ) -> tuple[float, float]: ... + def get_children(self) -> list[martist.Artist]: ... + # TODO units + converter: Any + units: Any + def clear(self) -> None: ... + def reset_ticks(self) -> None: ... + def minorticks_on(self) -> None: ... + def minorticks_off(self) -> None: ... + def set_tick_params( + self, + which: Literal["major", "minor", "both"] = ..., + reset: bool = ..., + **kwargs + ) -> None: ... + def get_tick_params( + self, which: Literal["major", "minor"] = ... + ) -> dict[str, Any]: ... + def get_view_interval(self) -> tuple[float, float]: ... + def set_view_interval( + self, vmin: float, vmax: float, ignore: bool = ... + ) -> None: ... + def get_data_interval(self) -> tuple[float, float]: ... + def set_data_interval( + self, vmin: float, vmax: float, ignore: bool = ... + ) -> None: ... + def get_inverted(self) -> bool: ... + def set_inverted(self, inverted: bool) -> None: ... + def set_default_intervals(self) -> None: ... + def get_tightbbox( + self, renderer: RendererBase | None = ..., *, for_layout_only: bool = ... + ) -> Bbox | None: ... + def get_tick_padding(self) -> float: ... + def get_gridlines(self) -> list[Line2D]: ... + def get_label(self) -> Text: ... + def get_offset_text(self) -> Text: ... + def get_pickradius(self) -> float: ... + def get_majorticklabels(self) -> list[Text]: ... + def get_minorticklabels(self) -> list[Text]: ... + def get_ticklabels( + self, minor: bool = ..., which: Literal["major", "minor", "both"] | None = ... + ) -> list[Text]: ... + def get_majorticklines(self) -> list[Line2D]: ... + def get_minorticklines(self) -> list[Line2D]: ... + def get_ticklines(self, minor: bool = ...) -> list[Line2D]: ... + def get_majorticklocs(self) -> np.ndarray: ... + def get_minorticklocs(self) -> np.ndarray: ... + def get_ticklocs(self, *, minor: bool = ...) -> np.ndarray: ... + def get_ticks_direction(self, minor: bool = ...) -> np.ndarray: ... + def get_label_text(self) -> str: ... + def get_major_locator(self) -> Locator: ... + def get_minor_locator(self) -> Locator: ... + def get_major_formatter(self) -> Formatter: ... + def get_minor_formatter(self) -> Formatter: ... + def get_major_ticks(self, numticks: int | None = ...) -> list[Tick]: ... + def get_minor_ticks(self, numticks: int | None = ...) -> list[Tick]: ... + def grid( + self, + visible: bool | None = ..., + which: Literal["major", "minor", "both"] = ..., + **kwargs + ) -> None: ... + # TODO units + def update_units(self, data): ... + def have_units(self) -> bool: ... + def convert_units(self, x): ... + def get_converter(self) -> ConversionInterface | None: ... + def set_converter(self, converter: ConversionInterface) -> None: ... + def set_units(self, u) -> None: ... + def get_units(self): ... + def set_label_text( + self, label: str, fontdict: dict[str, Any] | None = ..., **kwargs + ) -> Text: ... + def set_major_formatter( + self, formatter: Formatter | str | Callable[[float, float], str] + ) -> None: ... + def set_minor_formatter( + self, formatter: Formatter | str | Callable[[float, float], str] + ) -> None: ... + def set_major_locator(self, locator: Locator) -> None: ... + def set_minor_locator(self, locator: Locator) -> None: ... + def set_pickradius(self, pickradius: float) -> None: ... + def set_ticklabels( + self, + labels: Iterable[str | Text], + *, + minor: bool = ..., + fontdict: dict[str, Any] | None = ..., + **kwargs + ) -> list[Text]: ... + def set_ticks( + self, + ticks: ArrayLike, + labels: Iterable[str] | None = ..., + *, + minor: bool = ..., + **kwargs + ) -> list[Tick]: ... + def axis_date(self, tz: str | datetime.tzinfo | None = ...) -> None: ... + def get_tick_space(self) -> int: ... + def get_label_position(self) -> Literal["top", "bottom"]: ... + def set_label_position( + self, position: Literal["top", "bottom", "left", "right"] + ) -> None: ... + def get_minpos(self) -> float: ... + +class XAxis(Axis): + __name__: str + axis_name: str + def __init__(self, *args, **kwargs) -> None: ... + label_position: Literal["bottom", "top"] + stale: bool + def set_label_position(self, position: Literal["bottom", "top"]) -> None: ... # type: ignore[override] + def set_ticks_position( + self, position: Literal["top", "bottom", "both", "default", "none"] + ) -> None: ... + def tick_top(self) -> None: ... + def tick_bottom(self) -> None: ... + def get_ticks_position(self) -> Literal["top", "bottom", "default", "unknown"]: ... + def get_tick_space(self) -> int: ... + +class YAxis(Axis): + __name__: str + axis_name: str + def __init__(self, *args, **kwargs) -> None: ... + label_position: Literal["left", "right"] + stale: bool + def set_label_position(self, position: Literal["left", "right"]) -> None: ... # type: ignore[override] + def set_offset_position(self, position: Literal["left", "right"]) -> None: ... + def set_ticks_position( + self, position: Literal["left", "right", "both", "default", "none"] + ) -> None: ... + def tick_right(self) -> None: ... + def tick_left(self) -> None: ... + def get_ticks_position(self) -> Literal["left", "right", "default", "unknown"]: ... + def get_tick_space(self) -> int: ... diff --git a/infer_4_30_0/lib/python3.10/site-packages/matplotlib/backend_bases.pyi b/infer_4_30_0/lib/python3.10/site-packages/matplotlib/backend_bases.pyi new file mode 100644 index 0000000000000000000000000000000000000000..23a19b79d3be43f707ff02cf33540aa1102e06cc --- /dev/null +++ b/infer_4_30_0/lib/python3.10/site-packages/matplotlib/backend_bases.pyi @@ -0,0 +1,482 @@ +from enum import Enum, IntEnum +import os +from matplotlib import ( + cbook, + transforms, + widgets, + _api, +) +from matplotlib.artist import Artist +from matplotlib.axes import Axes +from matplotlib.backend_managers import ToolManager +from matplotlib.backend_tools import Cursors, ToolBase +from matplotlib.colorbar import Colorbar +from matplotlib.figure import Figure +from matplotlib.font_manager import FontProperties +from matplotlib.path import Path +from matplotlib.texmanager import TexManager +from matplotlib.text import Text +from matplotlib.transforms import Bbox, BboxBase, Transform, TransformedPath + +from collections.abc import Callable, Iterable, Sequence +from typing import Any, IO, Literal, NamedTuple, TypeVar +from numpy.typing import ArrayLike +from .typing import ColorType, LineStyleType, CapStyleType, JoinStyleType + +def register_backend( + format: str, backend: str | type[FigureCanvasBase], description: str | None = ... +) -> None: ... +def get_registered_canvas_class(format: str) -> type[FigureCanvasBase]: ... + +class RendererBase: + def __init__(self) -> None: ... + def open_group(self, s: str, gid: str | None = ...) -> None: ... + def close_group(self, s: str) -> None: ... + def draw_path( + self, + gc: GraphicsContextBase, + path: Path, + transform: Transform, + rgbFace: ColorType | None = ..., + ) -> None: ... + def draw_markers( + self, + gc: GraphicsContextBase, + marker_path: Path, + marker_trans: Transform, + path: Path, + trans: Transform, + rgbFace: ColorType | None = ..., + ) -> None: ... + def draw_path_collection( + self, + gc: GraphicsContextBase, + master_transform: Transform, + paths: Sequence[Path], + all_transforms: Sequence[ArrayLike], + offsets: ArrayLike | Sequence[ArrayLike], + offset_trans: Transform, + facecolors: ColorType | Sequence[ColorType], + edgecolors: ColorType | Sequence[ColorType], + linewidths: float | Sequence[float], + linestyles: LineStyleType | Sequence[LineStyleType], + antialiaseds: bool | Sequence[bool], + urls: str | Sequence[str], + offset_position: Any, + ) -> None: ... + def draw_quad_mesh( + self, + gc: GraphicsContextBase, + master_transform: Transform, + meshWidth, + meshHeight, + coordinates: ArrayLike, + offsets: ArrayLike | Sequence[ArrayLike], + offsetTrans: Transform, + facecolors: Sequence[ColorType], + antialiased: bool, + edgecolors: Sequence[ColorType] | ColorType | None, + ) -> None: ... + def draw_gouraud_triangles( + self, + gc: GraphicsContextBase, + triangles_array: ArrayLike, + colors_array: ArrayLike, + transform: Transform, + ) -> None: ... + def get_image_magnification(self) -> float: ... + def draw_image( + self, + gc: GraphicsContextBase, + x: float, + y: float, + im: ArrayLike, + transform: transforms.Affine2DBase | None = ..., + ) -> None: ... + def option_image_nocomposite(self) -> bool: ... + def option_scale_image(self) -> bool: ... + def draw_tex( + self, + gc: GraphicsContextBase, + x: float, + y: float, + s: str, + prop: FontProperties, + angle: float, + *, + mtext: Text | None = ... + ) -> None: ... + def draw_text( + self, + gc: GraphicsContextBase, + x: float, + y: float, + s: str, + prop: FontProperties, + angle: float, + ismath: bool | Literal["TeX"] = ..., + mtext: Text | None = ..., + ) -> None: ... + def get_text_width_height_descent( + self, s: str, prop: FontProperties, ismath: bool | Literal["TeX"] + ) -> tuple[float, float, float]: ... + def flipy(self) -> bool: ... + def get_canvas_width_height(self) -> tuple[float, float]: ... + def get_texmanager(self) -> TexManager: ... + def new_gc(self) -> GraphicsContextBase: ... + def points_to_pixels(self, points: ArrayLike) -> ArrayLike: ... + def start_rasterizing(self) -> None: ... + def stop_rasterizing(self) -> None: ... + def start_filter(self) -> None: ... + def stop_filter(self, filter_func) -> None: ... + +class GraphicsContextBase: + def __init__(self) -> None: ... + def copy_properties(self, gc: GraphicsContextBase) -> None: ... + def restore(self) -> None: ... + def get_alpha(self) -> float: ... + def get_antialiased(self) -> int: ... + def get_capstyle(self) -> Literal["butt", "projecting", "round"]: ... + def get_clip_rectangle(self) -> Bbox | None: ... + def get_clip_path( + self, + ) -> tuple[TransformedPath, Transform] | tuple[None, None]: ... + def get_dashes(self) -> tuple[float, ArrayLike | None]: ... + def get_forced_alpha(self) -> bool: ... + def get_joinstyle(self) -> Literal["miter", "round", "bevel"]: ... + def get_linewidth(self) -> float: ... + def get_rgb(self) -> tuple[float, float, float, float]: ... + def get_url(self) -> str | None: ... + def get_gid(self) -> int | None: ... + def get_snap(self) -> bool | None: ... + def set_alpha(self, alpha: float) -> None: ... + def set_antialiased(self, b: bool) -> None: ... + def set_capstyle(self, cs: CapStyleType) -> None: ... + def set_clip_rectangle(self, rectangle: Bbox | None) -> None: ... + def set_clip_path(self, path: TransformedPath | None) -> None: ... + def set_dashes(self, dash_offset: float, dash_list: ArrayLike | None) -> None: ... + def set_foreground(self, fg: ColorType, isRGBA: bool = ...) -> None: ... + def set_joinstyle(self, js: JoinStyleType) -> None: ... + def set_linewidth(self, w: float) -> None: ... + def set_url(self, url: str | None) -> None: ... + def set_gid(self, id: int | None) -> None: ... + def set_snap(self, snap: bool | None) -> None: ... + def set_hatch(self, hatch: str | None) -> None: ... + def get_hatch(self) -> str | None: ... + def get_hatch_path(self, density: float = ...) -> Path: ... + def get_hatch_color(self) -> ColorType: ... + def set_hatch_color(self, hatch_color: ColorType) -> None: ... + def get_hatch_linewidth(self) -> float: ... + def set_hatch_linewidth(self, hatch_linewidth: float) -> None: ... + def get_sketch_params(self) -> tuple[float, float, float] | None: ... + def set_sketch_params( + self, + scale: float | None = ..., + length: float | None = ..., + randomness: float | None = ..., + ) -> None: ... + +class TimerBase: + callbacks: list[tuple[Callable, tuple, dict[str, Any]]] + def __init__( + self, + interval: int | None = ..., + callbacks: list[tuple[Callable, tuple, dict[str, Any]]] | None = ..., + ) -> None: ... + def __del__(self) -> None: ... + def start(self, interval: int | None = ...) -> None: ... + def stop(self) -> None: ... + @property + def interval(self) -> int: ... + @interval.setter + def interval(self, interval: int) -> None: ... + @property + def single_shot(self) -> bool: ... + @single_shot.setter + def single_shot(self, ss: bool) -> None: ... + def add_callback(self, func: Callable, *args, **kwargs) -> Callable: ... + def remove_callback(self, func: Callable, *args, **kwargs) -> None: ... + +class Event: + name: str + canvas: FigureCanvasBase + guiEvent: Any + def __init__( + self, name: str, canvas: FigureCanvasBase, guiEvent: Any | None = ... + ) -> None: ... + +class DrawEvent(Event): + renderer: RendererBase + def __init__( + self, name: str, canvas: FigureCanvasBase, renderer: RendererBase + ) -> None: ... + +class ResizeEvent(Event): + width: int + height: int + def __init__(self, name: str, canvas: FigureCanvasBase) -> None: ... + +class CloseEvent(Event): ... + +class LocationEvent(Event): + x: int + y: int + inaxes: Axes | None + xdata: float | None + ydata: float | None + def __init__( + self, + name: str, + canvas: FigureCanvasBase, + x: int, + y: int, + guiEvent: Any | None = ..., + *, + modifiers: Iterable[str] | None = ..., + ) -> None: ... + +class MouseButton(IntEnum): + LEFT = 1 + MIDDLE = 2 + RIGHT = 3 + BACK = 8 + FORWARD = 9 + +class MouseEvent(LocationEvent): + button: MouseButton | Literal["up", "down"] | None + key: str | None + step: float + dblclick: bool + def __init__( + self, + name: str, + canvas: FigureCanvasBase, + x: int, + y: int, + button: MouseButton | Literal["up", "down"] | None = ..., + key: str | None = ..., + step: float = ..., + dblclick: bool = ..., + guiEvent: Any | None = ..., + *, + buttons: Iterable[MouseButton] | None = ..., + modifiers: Iterable[str] | None = ..., + ) -> None: ... + +class PickEvent(Event): + mouseevent: MouseEvent + artist: Artist + def __init__( + self, + name: str, + canvas: FigureCanvasBase, + mouseevent: MouseEvent, + artist: Artist, + guiEvent: Any | None = ..., + **kwargs + ) -> None: ... + +class KeyEvent(LocationEvent): + key: str | None + def __init__( + self, + name: str, + canvas: FigureCanvasBase, + key: str | None, + x: int = ..., + y: int = ..., + guiEvent: Any | None = ..., + ) -> None: ... + +class FigureCanvasBase: + required_interactive_framework: str | None + + @_api.classproperty + def manager_class(cls) -> type[FigureManagerBase]: ... + events: list[str] + fixed_dpi: None | float + filetypes: dict[str, str] + + @_api.classproperty + def supports_blit(cls) -> bool: ... + + figure: Figure + manager: None | FigureManagerBase + widgetlock: widgets.LockDraw + mouse_grabber: None | Axes + toolbar: None | NavigationToolbar2 + def __init__(self, figure: Figure | None = ...) -> None: ... + @property + def callbacks(self) -> cbook.CallbackRegistry: ... + @property + def button_pick_id(self) -> int: ... + @property + def scroll_pick_id(self) -> int: ... + @classmethod + def new_manager(cls, figure: Figure, num: int | str) -> FigureManagerBase: ... + def is_saving(self) -> bool: ... + def blit(self, bbox: BboxBase | None = ...) -> None: ... + def inaxes(self, xy: tuple[float, float]) -> Axes | None: ... + def grab_mouse(self, ax: Axes) -> None: ... + def release_mouse(self, ax: Axes) -> None: ... + def set_cursor(self, cursor: Cursors) -> None: ... + def draw(self, *args, **kwargs) -> None: ... + def draw_idle(self, *args, **kwargs) -> None: ... + @property + def device_pixel_ratio(self) -> float: ... + def get_width_height(self, *, physical: bool = ...) -> tuple[int, int]: ... + @classmethod + def get_supported_filetypes(cls) -> dict[str, str]: ... + @classmethod + def get_supported_filetypes_grouped(cls) -> dict[str, list[str]]: ... + def print_figure( + self, + filename: str | os.PathLike | IO, + dpi: float | None = ..., + facecolor: ColorType | Literal["auto"] | None = ..., + edgecolor: ColorType | Literal["auto"] | None = ..., + orientation: str = ..., + format: str | None = ..., + *, + bbox_inches: Literal["tight"] | Bbox | None = ..., + pad_inches: float | None = ..., + bbox_extra_artists: list[Artist] | None = ..., + backend: str | None = ..., + **kwargs + ) -> Any: ... + @classmethod + def get_default_filetype(cls) -> str: ... + def get_default_filename(self) -> str: ... + _T = TypeVar("_T", bound=FigureCanvasBase) + def mpl_connect(self, s: str, func: Callable[[Event], Any]) -> int: ... + def mpl_disconnect(self, cid: int) -> None: ... + def new_timer( + self, + interval: int | None = ..., + callbacks: list[tuple[Callable, tuple, dict[str, Any]]] | None = ..., + ) -> TimerBase: ... + def flush_events(self) -> None: ... + def start_event_loop(self, timeout: float = ...) -> None: ... + def stop_event_loop(self) -> None: ... + +def key_press_handler( + event: KeyEvent, + canvas: FigureCanvasBase | None = ..., + toolbar: NavigationToolbar2 | None = ..., +) -> None: ... +def button_press_handler( + event: MouseEvent, + canvas: FigureCanvasBase | None = ..., + toolbar: NavigationToolbar2 | None = ..., +) -> None: ... + +class NonGuiException(Exception): ... + +class FigureManagerBase: + canvas: FigureCanvasBase + num: int | str + key_press_handler_id: int | None + button_press_handler_id: int | None + toolmanager: ToolManager | None + toolbar: NavigationToolbar2 | ToolContainerBase | None + def __init__(self, canvas: FigureCanvasBase, num: int | str) -> None: ... + @classmethod + def create_with_canvas( + cls, canvas_class: type[FigureCanvasBase], figure: Figure, num: int | str + ) -> FigureManagerBase: ... + @classmethod + def start_main_loop(cls) -> None: ... + @classmethod + def pyplot_show(cls, *, block: bool | None = ...) -> None: ... + def show(self) -> None: ... + def destroy(self) -> None: ... + def full_screen_toggle(self) -> None: ... + def resize(self, w: int, h: int) -> None: ... + def get_window_title(self) -> str: ... + def set_window_title(self, title: str) -> None: ... + +cursors = Cursors + +class _Mode(str, Enum): + NONE = "" + PAN = "pan/zoom" + ZOOM = "zoom rect" + +class NavigationToolbar2: + toolitems: tuple[tuple[str, ...] | tuple[None, ...], ...] + UNKNOWN_SAVED_STATUS: object + canvas: FigureCanvasBase + mode: _Mode + def __init__(self, canvas: FigureCanvasBase) -> None: ... + def set_message(self, s: str) -> None: ... + def draw_rubberband( + self, event: Event, x0: float, y0: float, x1: float, y1: float + ) -> None: ... + def remove_rubberband(self) -> None: ... + def home(self, *args) -> None: ... + def back(self, *args) -> None: ... + def forward(self, *args) -> None: ... + def mouse_move(self, event: MouseEvent) -> None: ... + def pan(self, *args) -> None: ... + + class _PanInfo(NamedTuple): + button: MouseButton + axes: list[Axes] + cid: int + def press_pan(self, event: Event) -> None: ... + def drag_pan(self, event: Event) -> None: ... + def release_pan(self, event: Event) -> None: ... + def zoom(self, *args) -> None: ... + + class _ZoomInfo(NamedTuple): + direction: Literal["in", "out"] + start_xy: tuple[float, float] + axes: list[Axes] + cid: int + cbar: Colorbar + def press_zoom(self, event: Event) -> None: ... + def drag_zoom(self, event: Event) -> None: ... + def release_zoom(self, event: Event) -> None: ... + def push_current(self) -> None: ... + subplot_tool: widgets.SubplotTool + def configure_subplots(self, *args): ... + def save_figure(self, *args) -> str | None | object: ... + def update(self) -> None: ... + def set_history_buttons(self) -> None: ... + +class ToolContainerBase: + toolmanager: ToolManager + def __init__(self, toolmanager: ToolManager) -> None: ... + def add_tool(self, tool: ToolBase, group: str, position: int = ...) -> None: ... + def trigger_tool(self, name: str) -> None: ... + def add_toolitem( + self, + name: str, + group: str, + position: int, + image: str, + description: str, + toggle: bool, + ) -> None: ... + def toggle_toolitem(self, name: str, toggled: bool) -> None: ... + def remove_toolitem(self, name: str) -> None: ... + def set_message(self, s: str) -> None: ... + +class _Backend: + backend_version: str + FigureCanvas: type[FigureCanvasBase] | None + FigureManager: type[FigureManagerBase] + mainloop: None | Callable[[], Any] + @classmethod + def new_figure_manager(cls, num: int | str, *args, **kwargs) -> FigureManagerBase: ... + @classmethod + def new_figure_manager_given_figure(cls, num: int | str, figure: Figure) -> FigureManagerBase: ... + @classmethod + def draw_if_interactive(cls) -> None: ... + @classmethod + def show(cls, *, block: bool | None = ...) -> None: ... + @staticmethod + def export(cls) -> type[_Backend]: ... + +class ShowBase(_Backend): + def __call__(self, block: bool | None = ...) -> None: ... diff --git a/infer_4_30_0/lib/python3.10/site-packages/matplotlib/backend_managers.py b/infer_4_30_0/lib/python3.10/site-packages/matplotlib/backend_managers.py new file mode 100644 index 0000000000000000000000000000000000000000..76f15030bcc5e2c112b9aa72ca9cbf18334599e2 --- /dev/null +++ b/infer_4_30_0/lib/python3.10/site-packages/matplotlib/backend_managers.py @@ -0,0 +1,387 @@ +from matplotlib import _api, backend_tools, cbook, widgets + + +class ToolEvent: + """Event for tool manipulation (add/remove).""" + def __init__(self, name, sender, tool, data=None): + self.name = name + self.sender = sender + self.tool = tool + self.data = data + + +class ToolTriggerEvent(ToolEvent): + """Event to inform that a tool has been triggered.""" + def __init__(self, name, sender, tool, canvasevent=None, data=None): + super().__init__(name, sender, tool, data) + self.canvasevent = canvasevent + + +class ToolManagerMessageEvent: + """ + Event carrying messages from toolmanager. + + Messages usually get displayed to the user by the toolbar. + """ + def __init__(self, name, sender, message): + self.name = name + self.sender = sender + self.message = message + + +class ToolManager: + """ + Manager for actions triggered by user interactions (key press, toolbar + clicks, ...) on a Figure. + + Attributes + ---------- + figure : `.Figure` + keypresslock : `~matplotlib.widgets.LockDraw` + `.LockDraw` object to know if the `canvas` key_press_event is locked. + messagelock : `~matplotlib.widgets.LockDraw` + `.LockDraw` object to know if the message is available to write. + """ + + def __init__(self, figure=None): + + self._key_press_handler_id = None + + self._tools = {} + self._keys = {} + self._toggled = {} + self._callbacks = cbook.CallbackRegistry() + + # to process keypress event + self.keypresslock = widgets.LockDraw() + self.messagelock = widgets.LockDraw() + + self._figure = None + self.set_figure(figure) + + @property + def canvas(self): + """Canvas managed by FigureManager.""" + if not self._figure: + return None + return self._figure.canvas + + @property + def figure(self): + """Figure that holds the canvas.""" + return self._figure + + @figure.setter + def figure(self, figure): + self.set_figure(figure) + + def set_figure(self, figure, update_tools=True): + """ + Bind the given figure to the tools. + + Parameters + ---------- + figure : `.Figure` + update_tools : bool, default: True + Force tools to update figure. + """ + if self._key_press_handler_id: + self.canvas.mpl_disconnect(self._key_press_handler_id) + self._figure = figure + if figure: + self._key_press_handler_id = self.canvas.mpl_connect( + 'key_press_event', self._key_press) + if update_tools: + for tool in self._tools.values(): + tool.figure = figure + + def toolmanager_connect(self, s, func): + """ + Connect event with string *s* to *func*. + + Parameters + ---------- + s : str + The name of the event. The following events are recognized: + + - 'tool_message_event' + - 'tool_removed_event' + - 'tool_added_event' + + For every tool added a new event is created + + - 'tool_trigger_TOOLNAME', where TOOLNAME is the id of the tool. + + func : callable + Callback function for the toolmanager event with signature:: + + def func(event: ToolEvent) -> Any + + Returns + ------- + cid + The callback id for the connection. This can be used in + `.toolmanager_disconnect`. + """ + return self._callbacks.connect(s, func) + + def toolmanager_disconnect(self, cid): + """ + Disconnect callback id *cid*. + + Example usage:: + + cid = toolmanager.toolmanager_connect('tool_trigger_zoom', onpress) + #...later + toolmanager.toolmanager_disconnect(cid) + """ + return self._callbacks.disconnect(cid) + + def message_event(self, message, sender=None): + """Emit a `ToolManagerMessageEvent`.""" + if sender is None: + sender = self + + s = 'tool_message_event' + event = ToolManagerMessageEvent(s, sender, message) + self._callbacks.process(s, event) + + @property + def active_toggle(self): + """Currently toggled tools.""" + return self._toggled + + def get_tool_keymap(self, name): + """ + Return the keymap associated with the specified tool. + + Parameters + ---------- + name : str + Name of the Tool. + + Returns + ------- + list of str + List of keys associated with the tool. + """ + + keys = [k for k, i in self._keys.items() if i == name] + return keys + + def _remove_keys(self, name): + for k in self.get_tool_keymap(name): + del self._keys[k] + + def update_keymap(self, name, key): + """ + Set the keymap to associate with the specified tool. + + Parameters + ---------- + name : str + Name of the Tool. + key : str or list of str + Keys to associate with the tool. + """ + if name not in self._tools: + raise KeyError(f'{name!r} not in Tools') + self._remove_keys(name) + if isinstance(key, str): + key = [key] + for k in key: + if k in self._keys: + _api.warn_external( + f'Key {k} changed from {self._keys[k]} to {name}') + self._keys[k] = name + + def remove_tool(self, name): + """ + Remove tool named *name*. + + Parameters + ---------- + name : str + Name of the tool. + """ + tool = self.get_tool(name) + if getattr(tool, 'toggled', False): # If it's a toggled toggle tool, untoggle + self.trigger_tool(tool, 'toolmanager') + self._remove_keys(name) + event = ToolEvent('tool_removed_event', self, tool) + self._callbacks.process(event.name, event) + del self._tools[name] + + def add_tool(self, name, tool, *args, **kwargs): + """ + Add *tool* to `ToolManager`. + + If successful, adds a new event ``tool_trigger_{name}`` where + ``{name}`` is the *name* of the tool; the event is fired every time the + tool is triggered. + + Parameters + ---------- + name : str + Name of the tool, treated as the ID, has to be unique. + tool : type + Class of the tool to be added. A subclass will be used + instead if one was registered for the current canvas class. + *args, **kwargs + Passed to the *tool*'s constructor. + + See Also + -------- + matplotlib.backend_tools.ToolBase : The base class for tools. + """ + + tool_cls = backend_tools._find_tool_class(type(self.canvas), tool) + if not tool_cls: + raise ValueError('Impossible to find class for %s' % str(tool)) + + if name in self._tools: + _api.warn_external('A "Tool class" with the same name already ' + 'exists, not added') + return self._tools[name] + + tool_obj = tool_cls(self, name, *args, **kwargs) + self._tools[name] = tool_obj + + if tool_obj.default_keymap is not None: + self.update_keymap(name, tool_obj.default_keymap) + + # For toggle tools init the radio_group in self._toggled + if isinstance(tool_obj, backend_tools.ToolToggleBase): + # None group is not mutually exclusive, a set is used to keep track + # of all toggled tools in this group + if tool_obj.radio_group is None: + self._toggled.setdefault(None, set()) + else: + self._toggled.setdefault(tool_obj.radio_group, None) + + # If initially toggled + if tool_obj.toggled: + self._handle_toggle(tool_obj, None, None) + tool_obj.set_figure(self.figure) + + event = ToolEvent('tool_added_event', self, tool_obj) + self._callbacks.process(event.name, event) + + return tool_obj + + def _handle_toggle(self, tool, canvasevent, data): + """ + Toggle tools, need to untoggle prior to using other Toggle tool. + Called from trigger_tool. + + Parameters + ---------- + tool : `.ToolBase` + canvasevent : Event + Original Canvas event or None. + data : object + Extra data to pass to the tool when triggering. + """ + + radio_group = tool.radio_group + # radio_group None is not mutually exclusive + # just keep track of toggled tools in this group + if radio_group is None: + if tool.name in self._toggled[None]: + self._toggled[None].remove(tool.name) + else: + self._toggled[None].add(tool.name) + return + + # If the tool already has a toggled state, untoggle it + if self._toggled[radio_group] == tool.name: + toggled = None + # If no tool was toggled in the radio_group + # toggle it + elif self._toggled[radio_group] is None: + toggled = tool.name + # Other tool in the radio_group is toggled + else: + # Untoggle previously toggled tool + self.trigger_tool(self._toggled[radio_group], + self, + canvasevent, + data) + toggled = tool.name + + # Keep track of the toggled tool in the radio_group + self._toggled[radio_group] = toggled + + def trigger_tool(self, name, sender=None, canvasevent=None, data=None): + """ + Trigger a tool and emit the ``tool_trigger_{name}`` event. + + Parameters + ---------- + name : str + Name of the tool. + sender : object + Object that wishes to trigger the tool. + canvasevent : Event + Original Canvas event or None. + data : object + Extra data to pass to the tool when triggering. + """ + tool = self.get_tool(name) + if tool is None: + return + + if sender is None: + sender = self + + if isinstance(tool, backend_tools.ToolToggleBase): + self._handle_toggle(tool, canvasevent, data) + + tool.trigger(sender, canvasevent, data) # Actually trigger Tool. + + s = 'tool_trigger_%s' % name + event = ToolTriggerEvent(s, sender, tool, canvasevent, data) + self._callbacks.process(s, event) + + def _key_press(self, event): + if event.key is None or self.keypresslock.locked(): + return + + name = self._keys.get(event.key, None) + if name is None: + return + self.trigger_tool(name, canvasevent=event) + + @property + def tools(self): + """A dict mapping tool name -> controlled tool.""" + return self._tools + + def get_tool(self, name, warn=True): + """ + Return the tool object with the given name. + + For convenience, this passes tool objects through. + + Parameters + ---------- + name : str or `.ToolBase` + Name of the tool, or the tool itself. + warn : bool, default: True + Whether a warning should be emitted it no tool with the given name + exists. + + Returns + ------- + `.ToolBase` or None + The tool or None if no tool with the given name exists. + """ + if (isinstance(name, backend_tools.ToolBase) + and name.name in self._tools): + return name + if name not in self._tools: + if warn: + _api.warn_external( + f"ToolManager does not control tool {name!r}") + return None + return self._tools[name] diff --git a/infer_4_30_0/lib/python3.10/site-packages/matplotlib/backend_managers.pyi b/infer_4_30_0/lib/python3.10/site-packages/matplotlib/backend_managers.pyi new file mode 100644 index 0000000000000000000000000000000000000000..9e59acb14eda98b25e2dcb3f6e2004ca99d0ae5e --- /dev/null +++ b/infer_4_30_0/lib/python3.10/site-packages/matplotlib/backend_managers.pyi @@ -0,0 +1,64 @@ +from matplotlib import backend_tools, widgets +from matplotlib.backend_bases import FigureCanvasBase +from matplotlib.figure import Figure + +from collections.abc import Callable, Iterable +from typing import Any, TypeVar + +class ToolEvent: + name: str + sender: Any + tool: backend_tools.ToolBase + data: Any + def __init__(self, name, sender, tool, data: Any | None = ...) -> None: ... + +class ToolTriggerEvent(ToolEvent): + canvasevent: ToolEvent + def __init__( + self, + name, + sender, + tool, + canvasevent: ToolEvent | None = ..., + data: Any | None = ..., + ) -> None: ... + +class ToolManagerMessageEvent: + name: str + sender: Any + message: str + def __init__(self, name: str, sender: Any, message: str) -> None: ... + +class ToolManager: + keypresslock: widgets.LockDraw + messagelock: widgets.LockDraw + def __init__(self, figure: Figure | None = ...) -> None: ... + @property + def canvas(self) -> FigureCanvasBase | None: ... + @property + def figure(self) -> Figure | None: ... + @figure.setter + def figure(self, figure: Figure) -> None: ... + def set_figure(self, figure: Figure, update_tools: bool = ...) -> None: ... + def toolmanager_connect(self, s: str, func: Callable[[ToolEvent], Any]) -> int: ... + def toolmanager_disconnect(self, cid: int) -> None: ... + def message_event(self, message: str, sender: Any | None = ...) -> None: ... + @property + def active_toggle(self) -> dict[str | None, list[str] | str]: ... + def get_tool_keymap(self, name: str) -> list[str]: ... + def update_keymap(self, name: str, key: str | Iterable[str]) -> None: ... + def remove_tool(self, name: str) -> None: ... + _T = TypeVar("_T", bound=backend_tools.ToolBase) + def add_tool(self, name: str, tool: type[_T], *args, **kwargs) -> _T: ... + def trigger_tool( + self, + name: str | backend_tools.ToolBase, + sender: Any | None = ..., + canvasevent: ToolEvent | None = ..., + data: Any | None = ..., + ) -> None: ... + @property + def tools(self) -> dict[str, backend_tools.ToolBase]: ... + def get_tool( + self, name: str | backend_tools.ToolBase, warn: bool = ... + ) -> backend_tools.ToolBase | None: ... diff --git a/infer_4_30_0/lib/python3.10/site-packages/matplotlib/cbook.pyi b/infer_4_30_0/lib/python3.10/site-packages/matplotlib/cbook.pyi new file mode 100644 index 0000000000000000000000000000000000000000..cc6b4e8f4e1963922a75a140ff127d9bb5ead58c --- /dev/null +++ b/infer_4_30_0/lib/python3.10/site-packages/matplotlib/cbook.pyi @@ -0,0 +1,173 @@ +import collections.abc +from collections.abc import Callable, Collection, Generator, Iterable, Iterator +import contextlib +import os +from pathlib import Path + +from matplotlib.artist import Artist + +import numpy as np +from numpy.typing import ArrayLike + +from typing import ( + Any, + Generic, + IO, + Literal, + TypeVar, + overload, +) + +_T = TypeVar("_T") + +def _get_running_interactive_framework() -> str | None: ... + +class CallbackRegistry: + exception_handler: Callable[[Exception], Any] + callbacks: dict[Any, dict[int, Any]] + def __init__( + self, + exception_handler: Callable[[Exception], Any] | None = ..., + *, + signals: Iterable[Any] | None = ..., + ) -> None: ... + def connect(self, signal: Any, func: Callable) -> int: ... + def disconnect(self, cid: int) -> None: ... + def process(self, s: Any, *args, **kwargs) -> None: ... + def blocked( + self, *, signal: Any | None = ... + ) -> contextlib.AbstractContextManager[None]: ... + +class silent_list(list[_T]): + type: str | None + def __init__(self, type: str | None, seq: Iterable[_T] | None = ...) -> None: ... + +def strip_math(s: str) -> str: ... +def is_writable_file_like(obj: Any) -> bool: ... +def file_requires_unicode(x: Any) -> bool: ... +@overload +def to_filehandle( + fname: str | os.PathLike | IO, + flag: str = ..., + return_opened: Literal[False] = ..., + encoding: str | None = ..., +) -> IO: ... +@overload +def to_filehandle( + fname: str | os.PathLike | IO, + flag: str, + return_opened: Literal[True], + encoding: str | None = ..., +) -> tuple[IO, bool]: ... +@overload +def to_filehandle( + fname: str | os.PathLike | IO, + *, # if flag given, will match previous sig + return_opened: Literal[True], + encoding: str | None = ..., +) -> tuple[IO, bool]: ... +def open_file_cm( + path_or_file: str | os.PathLike | IO, + mode: str = ..., + encoding: str | None = ..., +) -> contextlib.AbstractContextManager[IO]: ... +def is_scalar_or_string(val: Any) -> bool: ... +@overload +def get_sample_data( + fname: str | os.PathLike, asfileobj: Literal[True] = ... +) -> np.ndarray | IO: ... +@overload +def get_sample_data(fname: str | os.PathLike, asfileobj: Literal[False]) -> str: ... +def _get_data_path(*args: Path | str) -> Path: ... +def flatten( + seq: Iterable[Any], scalarp: Callable[[Any], bool] = ... +) -> Generator[Any, None, None]: ... + +class _Stack(Generic[_T]): + def __init__(self) -> None: ... + def clear(self) -> None: ... + def __call__(self) -> _T: ... + def __len__(self) -> int: ... + def __getitem__(self, ind: int) -> _T: ... + def forward(self) -> _T: ... + def back(self) -> _T: ... + def push(self, o: _T) -> _T: ... + def home(self) -> _T: ... + +def safe_masked_invalid(x: ArrayLike, copy: bool = ...) -> np.ndarray: ... +def print_cycles( + objects: Iterable[Any], outstream: IO = ..., show_progress: bool = ... +) -> None: ... + +class Grouper(Generic[_T]): + def __init__(self, init: Iterable[_T] = ...) -> None: ... + def __contains__(self, item: _T) -> bool: ... + def join(self, a: _T, *args: _T) -> None: ... + def joined(self, a: _T, b: _T) -> bool: ... + def remove(self, a: _T) -> None: ... + def __iter__(self) -> Iterator[list[_T]]: ... + def get_siblings(self, a: _T) -> list[_T]: ... + +class GrouperView(Generic[_T]): + def __init__(self, grouper: Grouper[_T]) -> None: ... + def __contains__(self, item: _T) -> bool: ... + def __iter__(self) -> Iterator[list[_T]]: ... + def joined(self, a: _T, b: _T) -> bool: ... + def get_siblings(self, a: _T) -> list[_T]: ... + +def simple_linear_interpolation(a: ArrayLike, steps: int) -> np.ndarray: ... +def delete_masked_points(*args): ... +def _broadcast_with_masks(*args: ArrayLike, compress: bool = ...) -> list[ArrayLike]: ... +def boxplot_stats( + X: ArrayLike, + whis: float | tuple[float, float] = ..., + bootstrap: int | None = ..., + labels: ArrayLike | None = ..., + autorange: bool = ..., +) -> list[dict[str, Any]]: ... + +ls_mapper: dict[str, str] +ls_mapper_r: dict[str, str] + +def contiguous_regions(mask: ArrayLike) -> list[np.ndarray]: ... +def is_math_text(s: str) -> bool: ... +def violin_stats( + X: ArrayLike, method: Callable, points: int = ..., quantiles: ArrayLike | None = ... +) -> list[dict[str, Any]]: ... +def pts_to_prestep(x: ArrayLike, *args: ArrayLike) -> np.ndarray: ... +def pts_to_poststep(x: ArrayLike, *args: ArrayLike) -> np.ndarray: ... +def pts_to_midstep(x: np.ndarray, *args: np.ndarray) -> np.ndarray: ... + +STEP_LOOKUP_MAP: dict[str, Callable] + +def index_of(y: float | ArrayLike) -> tuple[np.ndarray, np.ndarray]: ... +def safe_first_element(obj: Collection[_T]) -> _T: ... +def sanitize_sequence(data): ... +def normalize_kwargs( + kw: dict[str, Any], + alias_mapping: dict[str, list[str]] | type[Artist] | Artist | None = ..., +) -> dict[str, Any]: ... +def _lock_path(path: str | os.PathLike) -> contextlib.AbstractContextManager[None]: ... +def _str_equal(obj: Any, s: str) -> bool: ... +def _str_lower_equal(obj: Any, s: str) -> bool: ... +def _array_perimeter(arr: np.ndarray) -> np.ndarray: ... +def _unfold(arr: np.ndarray, axis: int, size: int, step: int) -> np.ndarray: ... +def _array_patch_perimeters(x: np.ndarray, rstride: int, cstride: int) -> np.ndarray: ... +def _setattr_cm(obj: Any, **kwargs) -> contextlib.AbstractContextManager[None]: ... + +class _OrderedSet(collections.abc.MutableSet): + def __init__(self) -> None: ... + def __contains__(self, key) -> bool: ... + def __iter__(self): ... + def __len__(self) -> int: ... + def add(self, key) -> None: ... + def discard(self, key) -> None: ... + +def _setup_new_guiapp() -> None: ... +def _format_approx(number: float, precision: int) -> str: ... +def _g_sig_digits(value: float, delta: float) -> int: ... +def _unikey_or_keysym_to_mplkey(unikey: str, keysym: str) -> str: ... +def _is_torch_array(x: Any) -> bool: ... +def _is_jax_array(x: Any) -> bool: ... +def _unpack_to_numpy(x: Any) -> Any: ... +def _auto_format_str(fmt: str, value: Any) -> str: ... diff --git a/infer_4_30_0/lib/python3.10/site-packages/matplotlib/collections.pyi b/infer_4_30_0/lib/python3.10/site-packages/matplotlib/collections.pyi new file mode 100644 index 0000000000000000000000000000000000000000..0805adef42935aad06d51d3f3ed093923c02c16b --- /dev/null +++ b/infer_4_30_0/lib/python3.10/site-packages/matplotlib/collections.pyi @@ -0,0 +1,262 @@ +from collections.abc import Callable, Iterable, Sequence +from typing import Literal + +import numpy as np +from numpy.typing import ArrayLike, NDArray + +from . import colorizer, transforms +from .backend_bases import MouseEvent +from .artist import Artist +from .colors import Normalize, Colormap +from .lines import Line2D +from .path import Path +from .patches import Patch +from .ticker import Locator, Formatter +from .tri import Triangulation +from .typing import ColorType, LineStyleType, CapStyleType, JoinStyleType + +class Collection(colorizer.ColorizingArtist): + def __init__( + self, + *, + edgecolors: ColorType | Sequence[ColorType] | None = ..., + facecolors: ColorType | Sequence[ColorType] | None = ..., + linewidths: float | Sequence[float] | None = ..., + linestyles: LineStyleType | Sequence[LineStyleType] = ..., + capstyle: CapStyleType | None = ..., + joinstyle: JoinStyleType | None = ..., + antialiaseds: bool | Sequence[bool] | None = ..., + offsets: tuple[float, float] | Sequence[tuple[float, float]] | None = ..., + offset_transform: transforms.Transform | None = ..., + norm: Normalize | None = ..., + cmap: Colormap | None = ..., + colorizer: colorizer.Colorizer | None = ..., + pickradius: float = ..., + hatch: str | None = ..., + urls: Sequence[str] | None = ..., + zorder: float = ..., + **kwargs + ) -> None: ... + def get_paths(self) -> Sequence[Path]: ... + def set_paths(self, paths: Sequence[Path]) -> None: ... + def get_transforms(self) -> Sequence[transforms.Transform]: ... + def get_offset_transform(self) -> transforms.Transform: ... + def set_offset_transform(self, offset_transform: transforms.Transform) -> None: ... + def get_datalim(self, transData: transforms.Transform) -> transforms.Bbox: ... + def set_pickradius(self, pickradius: float) -> None: ... + def get_pickradius(self) -> float: ... + def set_urls(self, urls: Sequence[str | None]) -> None: ... + def get_urls(self) -> Sequence[str | None]: ... + def set_hatch(self, hatch: str) -> None: ... + def get_hatch(self) -> str: ... + def set_hatch_linewidth(self, lw: float) -> None: ... + def get_hatch_linewidth(self) -> float: ... + def set_offsets(self, offsets: ArrayLike) -> None: ... + def get_offsets(self) -> ArrayLike: ... + def set_linewidth(self, lw: float | Sequence[float]) -> None: ... + def set_linestyle(self, ls: LineStyleType | Sequence[LineStyleType]) -> None: ... + def set_capstyle(self, cs: CapStyleType) -> None: ... + def get_capstyle(self) -> Literal["butt", "projecting", "round"] | None: ... + def set_joinstyle(self, js: JoinStyleType) -> None: ... + def get_joinstyle(self) -> Literal["miter", "round", "bevel"] | None: ... + def set_antialiased(self, aa: bool | Sequence[bool]) -> None: ... + def get_antialiased(self) -> NDArray[np.bool_]: ... + def set_color(self, c: ColorType | Sequence[ColorType]) -> None: ... + def set_facecolor(self, c: ColorType | Sequence[ColorType]) -> None: ... + def get_facecolor(self) -> ColorType | Sequence[ColorType]: ... + def get_edgecolor(self) -> ColorType | Sequence[ColorType]: ... + def set_edgecolor(self, c: ColorType | Sequence[ColorType]) -> None: ... + def set_alpha(self, alpha: float | Sequence[float] | None) -> None: ... + def get_linewidth(self) -> float | Sequence[float]: ... + def get_linestyle(self) -> LineStyleType | Sequence[LineStyleType]: ... + def update_scalarmappable(self) -> None: ... + def get_fill(self) -> bool: ... + def update_from(self, other: Artist) -> None: ... + +class _CollectionWithSizes(Collection): + def get_sizes(self) -> np.ndarray: ... + def set_sizes(self, sizes: ArrayLike | None, dpi: float = ...) -> None: ... + +class PathCollection(_CollectionWithSizes): + def __init__( + self, paths: Sequence[Path], sizes: ArrayLike | None = ..., **kwargs + ) -> None: ... + def set_paths(self, paths: Sequence[Path]) -> None: ... + def get_paths(self) -> Sequence[Path]: ... + def legend_elements( + self, + prop: Literal["colors", "sizes"] = ..., + num: int | Literal["auto"] | ArrayLike | Locator = ..., + fmt: str | Formatter | None = ..., + func: Callable[[ArrayLike], ArrayLike] = ..., + **kwargs, + ) -> tuple[list[Line2D], list[str]]: ... + +class PolyCollection(_CollectionWithSizes): + def __init__( + self, + verts: Sequence[ArrayLike], + sizes: ArrayLike | None = ..., + *, + closed: bool = ..., + **kwargs + ) -> None: ... + def set_verts( + self, verts: Sequence[ArrayLike | Path], closed: bool = ... + ) -> None: ... + def set_paths(self, verts: Sequence[Path], closed: bool = ...) -> None: ... + def set_verts_and_codes( + self, verts: Sequence[ArrayLike | Path], codes: Sequence[int] + ) -> None: ... + +class FillBetweenPolyCollection(PolyCollection): + def __init__( + self, + t_direction: Literal["x", "y"], + t: ArrayLike, + f1: ArrayLike, + f2: ArrayLike, + *, + where: Sequence[bool] | None = ..., + interpolate: bool = ..., + step: Literal["pre", "post", "mid"] | None = ..., + **kwargs, + ) -> None: ... + def set_data( + self, + t: ArrayLike, + f1: ArrayLike, + f2: ArrayLike, + *, + where: Sequence[bool] | None = ..., + ) -> None: ... + def get_datalim(self, transData: transforms.Transform) -> transforms.Bbox: ... + +class RegularPolyCollection(_CollectionWithSizes): + def __init__( + self, numsides: int, *, rotation: float = ..., sizes: ArrayLike = ..., **kwargs + ) -> None: ... + def get_numsides(self) -> int: ... + def get_rotation(self) -> float: ... + +class StarPolygonCollection(RegularPolyCollection): ... +class AsteriskPolygonCollection(RegularPolyCollection): ... + +class LineCollection(Collection): + def __init__( + self, segments: Sequence[ArrayLike], *, zorder: float = ..., **kwargs + ) -> None: ... + def set_segments(self, segments: Sequence[ArrayLike] | None) -> None: ... + def set_verts(self, segments: Sequence[ArrayLike] | None) -> None: ... + def set_paths(self, segments: Sequence[ArrayLike] | None) -> None: ... # type: ignore[override] + def get_segments(self) -> list[np.ndarray]: ... + def set_color(self, c: ColorType | Sequence[ColorType]) -> None: ... + def set_colors(self, c: ColorType | Sequence[ColorType]) -> None: ... + def set_gapcolor(self, gapcolor: ColorType | Sequence[ColorType] | None) -> None: ... + def get_color(self) -> ColorType | Sequence[ColorType]: ... + def get_colors(self) -> ColorType | Sequence[ColorType]: ... + def get_gapcolor(self) -> ColorType | Sequence[ColorType] | None: ... + + +class EventCollection(LineCollection): + def __init__( + self, + positions: ArrayLike, + orientation: Literal["horizontal", "vertical"] = ..., + *, + lineoffset: float = ..., + linelength: float = ..., + linewidth: float | Sequence[float] | None = ..., + color: ColorType | Sequence[ColorType] | None = ..., + linestyle: LineStyleType | Sequence[LineStyleType] = ..., + antialiased: bool | Sequence[bool] | None = ..., + **kwargs + ) -> None: ... + def get_positions(self) -> list[float]: ... + def set_positions(self, positions: Sequence[float] | None) -> None: ... + def add_positions(self, position: Sequence[float] | None) -> None: ... + def extend_positions(self, position: Sequence[float] | None) -> None: ... + def append_positions(self, position: Sequence[float] | None) -> None: ... + def is_horizontal(self) -> bool: ... + def get_orientation(self) -> Literal["horizontal", "vertical"]: ... + def switch_orientation(self) -> None: ... + def set_orientation( + self, orientation: Literal["horizontal", "vertical"] + ) -> None: ... + def get_linelength(self) -> float | Sequence[float]: ... + def set_linelength(self, linelength: float | Sequence[float]) -> None: ... + def get_lineoffset(self) -> float: ... + def set_lineoffset(self, lineoffset: float) -> None: ... + def get_linewidth(self) -> float: ... + def get_linewidths(self) -> Sequence[float]: ... + def get_color(self) -> ColorType: ... + +class CircleCollection(_CollectionWithSizes): + def __init__(self, sizes: float | ArrayLike, **kwargs) -> None: ... + +class EllipseCollection(Collection): + def __init__( + self, + widths: ArrayLike, + heights: ArrayLike, + angles: ArrayLike, + *, + units: Literal[ + "points", "inches", "dots", "width", "height", "x", "y", "xy" + ] = ..., + **kwargs + ) -> None: ... + def set_widths(self, widths: ArrayLike) -> None: ... + def set_heights(self, heights: ArrayLike) -> None: ... + def set_angles(self, angles: ArrayLike) -> None: ... + def get_widths(self) -> ArrayLike: ... + def get_heights(self) -> ArrayLike: ... + def get_angles(self) -> ArrayLike: ... + +class PatchCollection(Collection): + def __init__( + self, patches: Iterable[Patch], *, match_original: bool = ..., **kwargs + ) -> None: ... + def set_paths(self, patches: Iterable[Patch]) -> None: ... # type: ignore[override] + +class TriMesh(Collection): + def __init__(self, triangulation: Triangulation, **kwargs) -> None: ... + def get_paths(self) -> list[Path]: ... + # Parent class has an argument, perhaps add a noop arg? + def set_paths(self) -> None: ... # type: ignore[override] + @staticmethod + def convert_mesh_to_paths(tri: Triangulation) -> list[Path]: ... + +class _MeshData: + def __init__( + self, + coordinates: ArrayLike, + *, + shading: Literal["flat", "gouraud"] = ..., + ) -> None: ... + def set_array(self, A: ArrayLike | None) -> None: ... + def get_coordinates(self) -> ArrayLike: ... + def get_facecolor(self) -> ColorType | Sequence[ColorType]: ... + def get_edgecolor(self) -> ColorType | Sequence[ColorType]: ... + +class QuadMesh(_MeshData, Collection): + def __init__( + self, + coordinates: ArrayLike, + *, + antialiased: bool = ..., + shading: Literal["flat", "gouraud"] = ..., + **kwargs + ) -> None: ... + def get_paths(self) -> list[Path]: ... + # Parent class has an argument, perhaps add a noop arg? + def set_paths(self) -> None: ... # type: ignore[override] + def get_datalim(self, transData: transforms.Transform) -> transforms.Bbox: ... + def get_cursor_data(self, event: MouseEvent) -> float: ... + +class PolyQuadMesh(_MeshData, PolyCollection): + def __init__( + self, + coordinates: ArrayLike, + **kwargs + ) -> None: ... diff --git a/infer_4_30_0/lib/python3.10/site-packages/matplotlib/colorbar.py b/infer_4_30_0/lib/python3.10/site-packages/matplotlib/colorbar.py new file mode 100644 index 0000000000000000000000000000000000000000..624e2250303ca3a269f7efd8fa56c9f0b547dd38 --- /dev/null +++ b/infer_4_30_0/lib/python3.10/site-packages/matplotlib/colorbar.py @@ -0,0 +1,1563 @@ +""" +Colorbars are a visualization of the mapping from scalar values to colors. +In Matplotlib they are drawn into a dedicated `~.axes.Axes`. + +.. note:: + Colorbars are typically created through `.Figure.colorbar` or its pyplot + wrapper `.pyplot.colorbar`, which internally use `.Colorbar` together with + `.make_axes_gridspec` (for `.GridSpec`-positioned Axes) or `.make_axes` (for + non-`.GridSpec`-positioned Axes). + + End-users most likely won't need to directly use this module's API. +""" + +import logging + +import numpy as np + +import matplotlib as mpl +from matplotlib import _api, cbook, collections, cm, colors, contour, ticker +import matplotlib.artist as martist +import matplotlib.patches as mpatches +import matplotlib.path as mpath +import matplotlib.spines as mspines +import matplotlib.transforms as mtransforms +from matplotlib import _docstring + +_log = logging.getLogger(__name__) + +_docstring.interpd.register( + _make_axes_kw_doc=""" +location : None or {'left', 'right', 'top', 'bottom'} + The location, relative to the parent Axes, where the colorbar Axes + is created. It also determines the *orientation* of the colorbar + (colorbars on the left and right are vertical, colorbars at the top + and bottom are horizontal). If None, the location will come from the + *orientation* if it is set (vertical colorbars on the right, horizontal + ones at the bottom), or default to 'right' if *orientation* is unset. + +orientation : None or {'vertical', 'horizontal'} + The orientation of the colorbar. It is preferable to set the *location* + of the colorbar, as that also determines the *orientation*; passing + incompatible values for *location* and *orientation* raises an exception. + +fraction : float, default: 0.15 + Fraction of original Axes to use for colorbar. + +shrink : float, default: 1.0 + Fraction by which to multiply the size of the colorbar. + +aspect : float, default: 20 + Ratio of long to short dimensions. + +pad : float, default: 0.05 if vertical, 0.15 if horizontal + Fraction of original Axes between colorbar and new image Axes. + +anchor : (float, float), optional + The anchor point of the colorbar Axes. + Defaults to (0.0, 0.5) if vertical; (0.5, 1.0) if horizontal. + +panchor : (float, float), or *False*, optional + The anchor point of the colorbar parent Axes. If *False*, the parent + axes' anchor will be unchanged. + Defaults to (1.0, 0.5) if vertical; (0.5, 0.0) if horizontal.""", + _colormap_kw_doc=""" +extend : {'neither', 'both', 'min', 'max'} + Make pointed end(s) for out-of-range values (unless 'neither'). These are + set for a given colormap using the colormap set_under and set_over methods. + +extendfrac : {*None*, 'auto', length, lengths} + If set to *None*, both the minimum and maximum triangular colorbar + extensions will have a length of 5% of the interior colorbar length (this + is the default setting). + + If set to 'auto', makes the triangular colorbar extensions the same lengths + as the interior boxes (when *spacing* is set to 'uniform') or the same + lengths as the respective adjacent interior boxes (when *spacing* is set to + 'proportional'). + + If a scalar, indicates the length of both the minimum and maximum + triangular colorbar extensions as a fraction of the interior colorbar + length. A two-element sequence of fractions may also be given, indicating + the lengths of the minimum and maximum colorbar extensions respectively as + a fraction of the interior colorbar length. + +extendrect : bool + If *False* the minimum and maximum colorbar extensions will be triangular + (the default). If *True* the extensions will be rectangular. + +ticks : None or list of ticks or Locator + If None, ticks are determined automatically from the input. + +format : None or str or Formatter + If None, `~.ticker.ScalarFormatter` is used. + Format strings, e.g., ``"%4.2e"`` or ``"{x:.2e}"``, are supported. + An alternative `~.ticker.Formatter` may be given instead. + +drawedges : bool + Whether to draw lines at color boundaries. + +label : str + The label on the colorbar's long axis. + +boundaries, values : None or a sequence + If unset, the colormap will be displayed on a 0-1 scale. + If sequences, *values* must have a length 1 less than *boundaries*. For + each region delimited by adjacent entries in *boundaries*, the color mapped + to the corresponding value in *values* will be used. The size of each + region is determined by the *spacing* parameter. + Normally only useful for indexed colors (i.e. ``norm=NoNorm()``) or other + unusual circumstances. + +spacing : {'uniform', 'proportional'} + For discrete colorbars (`.BoundaryNorm` or contours), 'uniform' gives each + color the same space; 'proportional' makes the space proportional to the + data interval.""") + + +def _set_ticks_on_axis_warn(*args, **kwargs): + # a top level function which gets put in at the axes' + # set_xticks and set_yticks by Colorbar.__init__. + _api.warn_external("Use the colorbar set_ticks() method instead.") + + +class _ColorbarSpine(mspines.Spine): + def __init__(self, axes): + self._ax = axes + super().__init__(axes, 'colorbar', mpath.Path(np.empty((0, 2)))) + mpatches.Patch.set_transform(self, axes.transAxes) + + def get_window_extent(self, renderer=None): + # This Spine has no Axis associated with it, and doesn't need to adjust + # its location, so we can directly get the window extent from the + # super-super-class. + return mpatches.Patch.get_window_extent(self, renderer=renderer) + + def set_xy(self, xy): + self._path = mpath.Path(xy, closed=True) + self._xy = xy + self.stale = True + + def draw(self, renderer): + ret = mpatches.Patch.draw(self, renderer) + self.stale = False + return ret + + +class _ColorbarAxesLocator: + """ + Shrink the Axes if there are triangular or rectangular extends. + """ + def __init__(self, cbar): + self._cbar = cbar + self._orig_locator = cbar.ax._axes_locator + + def __call__(self, ax, renderer): + if self._orig_locator is not None: + pos = self._orig_locator(ax, renderer) + else: + pos = ax.get_position(original=True) + if self._cbar.extend == 'neither': + return pos + + y, extendlen = self._cbar._proportional_y() + if not self._cbar._extend_lower(): + extendlen[0] = 0 + if not self._cbar._extend_upper(): + extendlen[1] = 0 + len = sum(extendlen) + 1 + shrink = 1 / len + offset = extendlen[0] / len + # we need to reset the aspect ratio of the axes to account + # of the extends... + if hasattr(ax, '_colorbar_info'): + aspect = ax._colorbar_info['aspect'] + else: + aspect = False + # now shrink and/or offset to take into account the + # extend tri/rectangles. + if self._cbar.orientation == 'vertical': + if aspect: + self._cbar.ax.set_box_aspect(aspect*shrink) + pos = pos.shrunk(1, shrink).translated(0, offset * pos.height) + else: + if aspect: + self._cbar.ax.set_box_aspect(1/(aspect * shrink)) + pos = pos.shrunk(shrink, 1).translated(offset * pos.width, 0) + return pos + + def get_subplotspec(self): + # make tight_layout happy.. + return ( + self._cbar.ax.get_subplotspec() + or getattr(self._orig_locator, "get_subplotspec", lambda: None)()) + + +@_docstring.interpd +class Colorbar: + r""" + Draw a colorbar in an existing Axes. + + Typically, colorbars are created using `.Figure.colorbar` or + `.pyplot.colorbar` and associated with `.ScalarMappable`\s (such as an + `.AxesImage` generated via `~.axes.Axes.imshow`). + + In order to draw a colorbar not associated with other elements in the + figure, e.g. when showing a colormap by itself, one can create an empty + `.ScalarMappable`, or directly pass *cmap* and *norm* instead of *mappable* + to `Colorbar`. + + Useful public methods are :meth:`set_label` and :meth:`add_lines`. + + Attributes + ---------- + ax : `~matplotlib.axes.Axes` + The `~.axes.Axes` instance in which the colorbar is drawn. + lines : list + A list of `.LineCollection` (empty if no lines were drawn). + dividers : `.LineCollection` + A LineCollection (empty if *drawedges* is ``False``). + """ + + n_rasterize = 50 # rasterize solids if number of colors >= n_rasterize + + def __init__( + self, ax, mappable=None, *, + alpha=None, + location=None, + extend=None, + extendfrac=None, + extendrect=False, + ticks=None, + format=None, + values=None, + boundaries=None, + spacing='uniform', + drawedges=False, + label='', + cmap=None, norm=None, # redundant with *mappable* + orientation=None, ticklocation='auto', # redundant with *location* + ): + """ + Parameters + ---------- + ax : `~matplotlib.axes.Axes` + The `~.axes.Axes` instance in which the colorbar is drawn. + + mappable : `.ScalarMappable` + The mappable whose colormap and norm will be used. + + To show the colors versus index instead of on a 0-1 scale, set the + mappable's norm to ``colors.NoNorm()``. + + alpha : float + The colorbar transparency between 0 (transparent) and 1 (opaque). + + location : None or {'left', 'right', 'top', 'bottom'} + Set the colorbar's *orientation* and *ticklocation*. Colorbars on + the left and right are vertical, colorbars at the top and bottom + are horizontal. The *ticklocation* is the same as *location*, so if + *location* is 'top', the ticks are on the top. *orientation* and/or + *ticklocation* can be provided as well and overrides the value set by + *location*, but there will be an error for incompatible combinations. + + .. versionadded:: 3.7 + + %(_colormap_kw_doc)s + + Other Parameters + ---------------- + cmap : `~matplotlib.colors.Colormap`, default: :rc:`image.cmap` + The colormap to use. This parameter is ignored, unless *mappable* is + None. + + norm : `~matplotlib.colors.Normalize` + The normalization to use. This parameter is ignored, unless *mappable* + is None. + + orientation : None or {'vertical', 'horizontal'} + If None, use the value determined by *location*. If both + *orientation* and *location* are None then defaults to 'vertical'. + + ticklocation : {'auto', 'left', 'right', 'top', 'bottom'} + The location of the colorbar ticks. The *ticklocation* must match + *orientation*. For example, a horizontal colorbar can only have ticks + at the top or the bottom. If 'auto', the ticks will be the same as + *location*, so a colorbar to the left will have ticks to the left. If + *location* is None, the ticks will be at the bottom for a horizontal + colorbar and at the right for a vertical. + """ + if mappable is None: + mappable = cm.ScalarMappable(norm=norm, cmap=cmap) + + self.mappable = mappable + cmap = mappable.cmap + norm = mappable.norm + + filled = True + if isinstance(mappable, contour.ContourSet): + cs = mappable + alpha = cs.get_alpha() + boundaries = cs._levels + values = cs.cvalues + extend = cs.extend + filled = cs.filled + if ticks is None: + ticks = ticker.FixedLocator(cs.levels, nbins=10) + elif isinstance(mappable, martist.Artist): + alpha = mappable.get_alpha() + + mappable.colorbar = self + mappable.colorbar_cid = mappable.callbacks.connect( + 'changed', self.update_normal) + + location_orientation = _get_orientation_from_location(location) + + _api.check_in_list( + [None, 'vertical', 'horizontal'], orientation=orientation) + _api.check_in_list( + ['auto', 'left', 'right', 'top', 'bottom'], + ticklocation=ticklocation) + _api.check_in_list( + ['uniform', 'proportional'], spacing=spacing) + + if location_orientation is not None and orientation is not None: + if location_orientation != orientation: + raise TypeError( + "location and orientation are mutually exclusive") + else: + orientation = orientation or location_orientation or "vertical" + + self.ax = ax + self.ax._axes_locator = _ColorbarAxesLocator(self) + + if extend is None: + if (not isinstance(mappable, contour.ContourSet) + and getattr(cmap, 'colorbar_extend', False) is not False): + extend = cmap.colorbar_extend + elif hasattr(norm, 'extend'): + extend = norm.extend + else: + extend = 'neither' + self.alpha = None + # Call set_alpha to handle array-like alphas properly + self.set_alpha(alpha) + self.cmap = cmap + self.norm = norm + self.values = values + self.boundaries = boundaries + self.extend = extend + self._inside = _api.check_getitem( + {'neither': slice(0, None), 'both': slice(1, -1), + 'min': slice(1, None), 'max': slice(0, -1)}, + extend=extend) + self.spacing = spacing + self.orientation = orientation + self.drawedges = drawedges + self._filled = filled + self.extendfrac = extendfrac + self.extendrect = extendrect + self._extend_patches = [] + self.solids = None + self.solids_patches = [] + self.lines = [] + + for spine in self.ax.spines.values(): + spine.set_visible(False) + self.outline = self.ax.spines['outline'] = _ColorbarSpine(self.ax) + + self.dividers = collections.LineCollection( + [], + colors=[mpl.rcParams['axes.edgecolor']], + linewidths=[0.5 * mpl.rcParams['axes.linewidth']], + clip_on=False) + self.ax.add_collection(self.dividers) + + self._locator = None + self._minorlocator = None + self._formatter = None + self._minorformatter = None + + if ticklocation == 'auto': + ticklocation = _get_ticklocation_from_orientation( + orientation) if location is None else location + self.ticklocation = ticklocation + + self.set_label(label) + self._reset_locator_formatter_scale() + + if np.iterable(ticks): + self._locator = ticker.FixedLocator(ticks, nbins=len(ticks)) + else: + self._locator = ticks + + if isinstance(format, str): + # Check format between FormatStrFormatter and StrMethodFormatter + try: + self._formatter = ticker.FormatStrFormatter(format) + _ = self._formatter(0) + except (TypeError, ValueError): + self._formatter = ticker.StrMethodFormatter(format) + else: + self._formatter = format # Assume it is a Formatter or None + self._draw_all() + + if isinstance(mappable, contour.ContourSet) and not mappable.filled: + self.add_lines(mappable) + + # Link the Axes and Colorbar for interactive use + self.ax._colorbar = self + # Don't navigate on any of these types of mappables + if (isinstance(self.norm, (colors.BoundaryNorm, colors.NoNorm)) or + isinstance(self.mappable, contour.ContourSet)): + self.ax.set_navigate(False) + + # These are the functions that set up interactivity on this colorbar + self._interactive_funcs = ["_get_view", "_set_view", + "_set_view_from_bbox", "drag_pan"] + for x in self._interactive_funcs: + setattr(self.ax, x, getattr(self, x)) + # Set the cla function to the cbar's method to override it + self.ax.cla = self._cbar_cla + # Callbacks for the extend calculations to handle inverting the axis + self._extend_cid1 = self.ax.callbacks.connect( + "xlim_changed", self._do_extends) + self._extend_cid2 = self.ax.callbacks.connect( + "ylim_changed", self._do_extends) + + @property + def long_axis(self): + """Axis that has decorations (ticks, etc) on it.""" + if self.orientation == 'vertical': + return self.ax.yaxis + return self.ax.xaxis + + @property + def locator(self): + """Major tick `.Locator` for the colorbar.""" + return self.long_axis.get_major_locator() + + @locator.setter + def locator(self, loc): + self.long_axis.set_major_locator(loc) + self._locator = loc + + @property + def minorlocator(self): + """Minor tick `.Locator` for the colorbar.""" + return self.long_axis.get_minor_locator() + + @minorlocator.setter + def minorlocator(self, loc): + self.long_axis.set_minor_locator(loc) + self._minorlocator = loc + + @property + def formatter(self): + """Major tick label `.Formatter` for the colorbar.""" + return self.long_axis.get_major_formatter() + + @formatter.setter + def formatter(self, fmt): + self.long_axis.set_major_formatter(fmt) + self._formatter = fmt + + @property + def minorformatter(self): + """Minor tick `.Formatter` for the colorbar.""" + return self.long_axis.get_minor_formatter() + + @minorformatter.setter + def minorformatter(self, fmt): + self.long_axis.set_minor_formatter(fmt) + self._minorformatter = fmt + + def _cbar_cla(self): + """Function to clear the interactive colorbar state.""" + for x in self._interactive_funcs: + delattr(self.ax, x) + # We now restore the old cla() back and can call it directly + del self.ax.cla + self.ax.cla() + + def update_normal(self, mappable=None): + """ + Update solid patches, lines, etc. + + This is meant to be called when the norm of the image or contour plot + to which this colorbar belongs changes. + + If the norm on the mappable is different than before, this resets the + locator and formatter for the axis, so if these have been customized, + they will need to be customized again. However, if the norm only + changes values of *vmin*, *vmax* or *cmap* then the old formatter + and locator will be preserved. + """ + if mappable: + # The mappable keyword argument exists because + # ScalarMappable.changed() emits self.callbacks.process('changed', self) + # in contrast, ColorizingArtist (and Colorizer) does not use this keyword. + # [ColorizingArtist.changed() emits self.callbacks.process('changed')] + # Also, there is no test where self.mappable == mappable is not True + # and possibly no use case. + # Therefore, the mappable keyword can be deprecated if cm.ScalarMappable + # is removed. + self.mappable = mappable + _log.debug('colorbar update normal %r %r', self.mappable.norm, self.norm) + self.set_alpha(self.mappable.get_alpha()) + self.cmap = self.mappable.cmap + if self.mappable.norm != self.norm: + self.norm = self.mappable.norm + self._reset_locator_formatter_scale() + + self._draw_all() + if isinstance(self.mappable, contour.ContourSet): + CS = self.mappable + if not CS.filled: + self.add_lines(CS) + self.stale = True + + def _draw_all(self): + """ + Calculate any free parameters based on the current cmap and norm, + and do all the drawing. + """ + if self.orientation == 'vertical': + if mpl.rcParams['ytick.minor.visible']: + self.minorticks_on() + else: + if mpl.rcParams['xtick.minor.visible']: + self.minorticks_on() + self.long_axis.set(label_position=self.ticklocation, + ticks_position=self.ticklocation) + self._short_axis().set_ticks([]) + self._short_axis().set_ticks([], minor=True) + + # Set self._boundaries and self._values, including extensions. + # self._boundaries are the edges of each square of color, and + # self._values are the value to map into the norm to get the + # color: + self._process_values() + # Set self.vmin and self.vmax to first and last boundary, excluding + # extensions: + self.vmin, self.vmax = self._boundaries[self._inside][[0, -1]] + # Compute the X/Y mesh. + X, Y = self._mesh() + # draw the extend triangles, and shrink the inner Axes to accommodate. + # also adds the outline path to self.outline spine: + self._do_extends() + lower, upper = self.vmin, self.vmax + if self.long_axis.get_inverted(): + # If the axis is inverted, we need to swap the vmin/vmax + lower, upper = upper, lower + if self.orientation == 'vertical': + self.ax.set_xlim(0, 1) + self.ax.set_ylim(lower, upper) + else: + self.ax.set_ylim(0, 1) + self.ax.set_xlim(lower, upper) + + # set up the tick locators and formatters. A bit complicated because + # boundary norms + uniform spacing requires a manual locator. + self.update_ticks() + + if self._filled: + ind = np.arange(len(self._values)) + if self._extend_lower(): + ind = ind[1:] + if self._extend_upper(): + ind = ind[:-1] + self._add_solids(X, Y, self._values[ind, np.newaxis]) + + def _add_solids(self, X, Y, C): + """Draw the colors; optionally add separators.""" + # Cleanup previously set artists. + if self.solids is not None: + self.solids.remove() + for solid in self.solids_patches: + solid.remove() + # Add new artist(s), based on mappable type. Use individual patches if + # hatching is needed, pcolormesh otherwise. + mappable = getattr(self, 'mappable', None) + if (isinstance(mappable, contour.ContourSet) + and any(hatch is not None for hatch in mappable.hatches)): + self._add_solids_patches(X, Y, C, mappable) + else: + self.solids = self.ax.pcolormesh( + X, Y, C, cmap=self.cmap, norm=self.norm, alpha=self.alpha, + edgecolors='none', shading='flat') + if not self.drawedges: + if len(self._y) >= self.n_rasterize: + self.solids.set_rasterized(True) + self._update_dividers() + + def _update_dividers(self): + if not self.drawedges: + self.dividers.set_segments([]) + return + # Place all *internal* dividers. + if self.orientation == 'vertical': + lims = self.ax.get_ylim() + bounds = (lims[0] < self._y) & (self._y < lims[1]) + else: + lims = self.ax.get_xlim() + bounds = (lims[0] < self._y) & (self._y < lims[1]) + y = self._y[bounds] + # And then add outer dividers if extensions are on. + if self._extend_lower(): + y = np.insert(y, 0, lims[0]) + if self._extend_upper(): + y = np.append(y, lims[1]) + X, Y = np.meshgrid([0, 1], y) + if self.orientation == 'vertical': + segments = np.dstack([X, Y]) + else: + segments = np.dstack([Y, X]) + self.dividers.set_segments(segments) + + def _add_solids_patches(self, X, Y, C, mappable): + hatches = mappable.hatches * (len(C) + 1) # Have enough hatches. + if self._extend_lower(): + # remove first hatch that goes into the extend patch + hatches = hatches[1:] + patches = [] + for i in range(len(X) - 1): + xy = np.array([[X[i, 0], Y[i, 1]], + [X[i, 1], Y[i, 0]], + [X[i + 1, 1], Y[i + 1, 0]], + [X[i + 1, 0], Y[i + 1, 1]]]) + patch = mpatches.PathPatch(mpath.Path(xy), + facecolor=self.cmap(self.norm(C[i][0])), + hatch=hatches[i], linewidth=0, + antialiased=False, alpha=self.alpha) + self.ax.add_patch(patch) + patches.append(patch) + self.solids_patches = patches + + def _do_extends(self, ax=None): + """ + Add the extend tri/rectangles on the outside of the Axes. + + ax is unused, but required due to the callbacks on xlim/ylim changed + """ + # Clean up any previous extend patches + for patch in self._extend_patches: + patch.remove() + self._extend_patches = [] + # extend lengths are fraction of the *inner* part of colorbar, + # not the total colorbar: + _, extendlen = self._proportional_y() + bot = 0 - (extendlen[0] if self._extend_lower() else 0) + top = 1 + (extendlen[1] if self._extend_upper() else 0) + + # xyout is the outline of the colorbar including the extend patches: + if not self.extendrect: + # triangle: + xyout = np.array([[0, 0], [0.5, bot], [1, 0], + [1, 1], [0.5, top], [0, 1], [0, 0]]) + else: + # rectangle: + xyout = np.array([[0, 0], [0, bot], [1, bot], [1, 0], + [1, 1], [1, top], [0, top], [0, 1], + [0, 0]]) + + if self.orientation == 'horizontal': + xyout = xyout[:, ::-1] + + # xyout is the path for the spine: + self.outline.set_xy(xyout) + if not self._filled: + return + + # Make extend triangles or rectangles filled patches. These are + # defined in the outer parent axes' coordinates: + mappable = getattr(self, 'mappable', None) + if (isinstance(mappable, contour.ContourSet) + and any(hatch is not None for hatch in mappable.hatches)): + hatches = mappable.hatches * (len(self._y) + 1) + else: + hatches = [None] * (len(self._y) + 1) + + if self._extend_lower(): + if not self.extendrect: + # triangle + xy = np.array([[0, 0], [0.5, bot], [1, 0]]) + else: + # rectangle + xy = np.array([[0, 0], [0, bot], [1., bot], [1, 0]]) + if self.orientation == 'horizontal': + xy = xy[:, ::-1] + # add the patch + val = -1 if self.long_axis.get_inverted() else 0 + color = self.cmap(self.norm(self._values[val])) + patch = mpatches.PathPatch( + mpath.Path(xy), facecolor=color, alpha=self.alpha, + linewidth=0, antialiased=False, + transform=self.ax.transAxes, + hatch=hatches[0], clip_on=False, + # Place it right behind the standard patches, which is + # needed if we updated the extends + zorder=np.nextafter(self.ax.patch.zorder, -np.inf)) + self.ax.add_patch(patch) + self._extend_patches.append(patch) + # remove first hatch that goes into the extend patch + hatches = hatches[1:] + if self._extend_upper(): + if not self.extendrect: + # triangle + xy = np.array([[0, 1], [0.5, top], [1, 1]]) + else: + # rectangle + xy = np.array([[0, 1], [0, top], [1, top], [1, 1]]) + if self.orientation == 'horizontal': + xy = xy[:, ::-1] + # add the patch + val = 0 if self.long_axis.get_inverted() else -1 + color = self.cmap(self.norm(self._values[val])) + hatch_idx = len(self._y) - 1 + patch = mpatches.PathPatch( + mpath.Path(xy), facecolor=color, alpha=self.alpha, + linewidth=0, antialiased=False, + transform=self.ax.transAxes, hatch=hatches[hatch_idx], + clip_on=False, + # Place it right behind the standard patches, which is + # needed if we updated the extends + zorder=np.nextafter(self.ax.patch.zorder, -np.inf)) + self.ax.add_patch(patch) + self._extend_patches.append(patch) + + self._update_dividers() + + def add_lines(self, *args, **kwargs): + """ + Draw lines on the colorbar. + + The lines are appended to the list :attr:`lines`. + + Parameters + ---------- + levels : array-like + The positions of the lines. + colors : :mpltype:`color` or list of :mpltype:`color` + Either a single color applying to all lines or one color value for + each line. + linewidths : float or array-like + Either a single linewidth applying to all lines or one linewidth + for each line. + erase : bool, default: True + Whether to remove any previously added lines. + + Notes + ----- + Alternatively, this method can also be called with the signature + ``colorbar.add_lines(contour_set, erase=True)``, in which case + *levels*, *colors*, and *linewidths* are taken from *contour_set*. + """ + params = _api.select_matching_signature( + [lambda self, CS, erase=True: locals(), + lambda self, levels, colors, linewidths, erase=True: locals()], + self, *args, **kwargs) + if "CS" in params: + self, cs, erase = params.values() + if not isinstance(cs, contour.ContourSet) or cs.filled: + raise ValueError("If a single artist is passed to add_lines, " + "it must be a ContourSet of lines") + # TODO: Make colorbar lines auto-follow changes in contour lines. + return self.add_lines( + cs.levels, + cs.to_rgba(cs.cvalues, cs.alpha), + cs.get_linewidths(), + erase=erase) + else: + self, levels, colors, linewidths, erase = params.values() + + y = self._locate(levels) + rtol = (self._y[-1] - self._y[0]) * 1e-10 + igood = (y < self._y[-1] + rtol) & (y > self._y[0] - rtol) + y = y[igood] + if np.iterable(colors): + colors = np.asarray(colors)[igood] + if np.iterable(linewidths): + linewidths = np.asarray(linewidths)[igood] + X, Y = np.meshgrid([0, 1], y) + if self.orientation == 'vertical': + xy = np.stack([X, Y], axis=-1) + else: + xy = np.stack([Y, X], axis=-1) + col = collections.LineCollection(xy, linewidths=linewidths, + colors=colors) + + if erase and self.lines: + for lc in self.lines: + lc.remove() + self.lines = [] + self.lines.append(col) + + # make a clip path that is just a linewidth bigger than the Axes... + fac = np.max(linewidths) / 72 + xy = np.array([[0, 0], [1, 0], [1, 1], [0, 1], [0, 0]]) + inches = self.ax.get_figure().dpi_scale_trans + # do in inches: + xy = inches.inverted().transform(self.ax.transAxes.transform(xy)) + xy[[0, 1, 4], 1] -= fac + xy[[2, 3], 1] += fac + # back to axes units... + xy = self.ax.transAxes.inverted().transform(inches.transform(xy)) + col.set_clip_path(mpath.Path(xy, closed=True), + self.ax.transAxes) + self.ax.add_collection(col) + self.stale = True + + def update_ticks(self): + """ + Set up the ticks and ticklabels. This should not be needed by users. + """ + # Get the locator and formatter; defaults to self._locator if not None. + self._get_ticker_locator_formatter() + self.long_axis.set_major_locator(self._locator) + self.long_axis.set_minor_locator(self._minorlocator) + self.long_axis.set_major_formatter(self._formatter) + + def _get_ticker_locator_formatter(self): + """ + Return the ``locator`` and ``formatter`` of the colorbar. + + If they have not been defined (i.e. are *None*), the formatter and + locator are retrieved from the axis, or from the value of the + boundaries for a boundary norm. + + Called by update_ticks... + """ + locator = self._locator + formatter = self._formatter + minorlocator = self._minorlocator + if isinstance(self.norm, colors.BoundaryNorm): + b = self.norm.boundaries + if locator is None: + locator = ticker.FixedLocator(b, nbins=10) + if minorlocator is None: + minorlocator = ticker.FixedLocator(b) + elif isinstance(self.norm, colors.NoNorm): + if locator is None: + # put ticks on integers between the boundaries of NoNorm + nv = len(self._values) + base = 1 + int(nv / 10) + locator = ticker.IndexLocator(base=base, offset=.5) + elif self.boundaries is not None: + b = self._boundaries[self._inside] + if locator is None: + locator = ticker.FixedLocator(b, nbins=10) + else: # most cases: + if locator is None: + # we haven't set the locator explicitly, so use the default + # for this axis: + locator = self.long_axis.get_major_locator() + if minorlocator is None: + minorlocator = self.long_axis.get_minor_locator() + + if minorlocator is None: + minorlocator = ticker.NullLocator() + + if formatter is None: + formatter = self.long_axis.get_major_formatter() + + self._locator = locator + self._formatter = formatter + self._minorlocator = minorlocator + _log.debug('locator: %r', locator) + + def set_ticks(self, ticks, *, labels=None, minor=False, **kwargs): + """ + Set tick locations. + + Parameters + ---------- + ticks : 1D array-like + List of tick locations. + labels : list of str, optional + List of tick labels. If not set, the labels show the data value. + minor : bool, default: False + If ``False``, set the major ticks; if ``True``, the minor ticks. + **kwargs + `.Text` properties for the labels. These take effect only if you + pass *labels*. In other cases, please use `~.Axes.tick_params`. + """ + if np.iterable(ticks): + self.long_axis.set_ticks(ticks, labels=labels, minor=minor, + **kwargs) + self._locator = self.long_axis.get_major_locator() + else: + self._locator = ticks + self.long_axis.set_major_locator(self._locator) + self.stale = True + + def get_ticks(self, minor=False): + """ + Return the ticks as a list of locations. + + Parameters + ---------- + minor : boolean, default: False + if True return the minor ticks. + """ + if minor: + return self.long_axis.get_minorticklocs() + else: + return self.long_axis.get_majorticklocs() + + def set_ticklabels(self, ticklabels, *, minor=False, **kwargs): + """ + [*Discouraged*] Set tick labels. + + .. admonition:: Discouraged + + The use of this method is discouraged, because of the dependency + on tick positions. In most cases, you'll want to use + ``set_ticks(positions, labels=labels)`` instead. + + If you are using this method, you should always fix the tick + positions before, e.g. by using `.Colorbar.set_ticks` or by + explicitly setting a `~.ticker.FixedLocator` on the long axis + of the colorbar. Otherwise, ticks are free to move and the + labels may end up in unexpected positions. + + Parameters + ---------- + ticklabels : sequence of str or of `.Text` + Texts for labeling each tick location in the sequence set by + `.Colorbar.set_ticks`; the number of labels must match the number + of locations. + + update_ticks : bool, default: True + This keyword argument is ignored and will be removed. + Deprecated + + minor : bool + If True, set minor ticks instead of major ticks. + + **kwargs + `.Text` properties for the labels. + """ + self.long_axis.set_ticklabels(ticklabels, minor=minor, **kwargs) + + def minorticks_on(self): + """ + Turn on colorbar minor ticks. + """ + self.ax.minorticks_on() + self._short_axis().set_minor_locator(ticker.NullLocator()) + + def minorticks_off(self): + """Turn the minor ticks of the colorbar off.""" + self._minorlocator = ticker.NullLocator() + self.long_axis.set_minor_locator(self._minorlocator) + + def set_label(self, label, *, loc=None, **kwargs): + """ + Add a label to the long axis of the colorbar. + + Parameters + ---------- + label : str + The label text. + loc : str, optional + The location of the label. + + - For horizontal orientation one of {'left', 'center', 'right'} + - For vertical orientation one of {'bottom', 'center', 'top'} + + Defaults to :rc:`xaxis.labellocation` or :rc:`yaxis.labellocation` + depending on the orientation. + **kwargs + Keyword arguments are passed to `~.Axes.set_xlabel` / + `~.Axes.set_ylabel`. + Supported keywords are *labelpad* and `.Text` properties. + """ + if self.orientation == "vertical": + self.ax.set_ylabel(label, loc=loc, **kwargs) + else: + self.ax.set_xlabel(label, loc=loc, **kwargs) + self.stale = True + + def set_alpha(self, alpha): + """ + Set the transparency between 0 (transparent) and 1 (opaque). + + If an array is provided, *alpha* will be set to None to use the + transparency values associated with the colormap. + """ + self.alpha = None if isinstance(alpha, np.ndarray) else alpha + + def _set_scale(self, scale, **kwargs): + """ + Set the colorbar long axis scale. + + Parameters + ---------- + scale : {"linear", "log", "symlog", "logit", ...} or `.ScaleBase` + The axis scale type to apply. + + **kwargs + Different keyword arguments are accepted, depending on the scale. + See the respective class keyword arguments: + + - `matplotlib.scale.LinearScale` + - `matplotlib.scale.LogScale` + - `matplotlib.scale.SymmetricalLogScale` + - `matplotlib.scale.LogitScale` + - `matplotlib.scale.FuncScale` + - `matplotlib.scale.AsinhScale` + + Notes + ----- + By default, Matplotlib supports the above-mentioned scales. + Additionally, custom scales may be registered using + `matplotlib.scale.register_scale`. These scales can then also + be used here. + """ + self.long_axis._set_axes_scale(scale, **kwargs) + + def remove(self): + """ + Remove this colorbar from the figure. + + If the colorbar was created with ``use_gridspec=True`` the previous + gridspec is restored. + """ + if hasattr(self.ax, '_colorbar_info'): + parents = self.ax._colorbar_info['parents'] + for a in parents: + if self.ax in a._colorbars: + a._colorbars.remove(self.ax) + + self.ax.remove() + + self.mappable.callbacks.disconnect(self.mappable.colorbar_cid) + self.mappable.colorbar = None + self.mappable.colorbar_cid = None + # Remove the extension callbacks + self.ax.callbacks.disconnect(self._extend_cid1) + self.ax.callbacks.disconnect(self._extend_cid2) + + try: + ax = self.mappable.axes + except AttributeError: + return + try: + subplotspec = self.ax.get_subplotspec().get_gridspec()._subplot_spec + except AttributeError: # use_gridspec was False + pos = ax.get_position(original=True) + ax._set_position(pos) + else: # use_gridspec was True + ax.set_subplotspec(subplotspec) + + def _process_values(self): + """ + Set `_boundaries` and `_values` based on the self.boundaries and + self.values if not None, or based on the size of the colormap and + the vmin/vmax of the norm. + """ + if self.values is not None: + # set self._boundaries from the values... + self._values = np.array(self.values) + if self.boundaries is None: + # bracket values by 1/2 dv: + b = np.zeros(len(self.values) + 1) + b[1:-1] = 0.5 * (self._values[:-1] + self._values[1:]) + b[0] = 2.0 * b[1] - b[2] + b[-1] = 2.0 * b[-2] - b[-3] + self._boundaries = b + return + self._boundaries = np.array(self.boundaries) + return + + # otherwise values are set from the boundaries + if isinstance(self.norm, colors.BoundaryNorm): + b = self.norm.boundaries + elif isinstance(self.norm, colors.NoNorm): + # NoNorm has N blocks, so N+1 boundaries, centered on integers: + b = np.arange(self.cmap.N + 1) - .5 + elif self.boundaries is not None: + b = self.boundaries + else: + # otherwise make the boundaries from the size of the cmap: + N = self.cmap.N + 1 + b, _ = self._uniform_y(N) + # add extra boundaries if needed: + if self._extend_lower(): + b = np.hstack((b[0] - 1, b)) + if self._extend_upper(): + b = np.hstack((b, b[-1] + 1)) + + # transform from 0-1 to vmin-vmax: + if self.mappable.get_array() is not None: + self.mappable.autoscale_None() + if not self.norm.scaled(): + # If we still aren't scaled after autoscaling, use 0, 1 as default + self.norm.vmin = 0 + self.norm.vmax = 1 + self.norm.vmin, self.norm.vmax = mtransforms.nonsingular( + self.norm.vmin, self.norm.vmax, expander=0.1) + if (not isinstance(self.norm, colors.BoundaryNorm) and + (self.boundaries is None)): + b = self.norm.inverse(b) + + self._boundaries = np.asarray(b, dtype=float) + self._values = 0.5 * (self._boundaries[:-1] + self._boundaries[1:]) + if isinstance(self.norm, colors.NoNorm): + self._values = (self._values + 0.00001).astype(np.int16) + + def _mesh(self): + """ + Return the coordinate arrays for the colorbar pcolormesh/patches. + + These are scaled between vmin and vmax, and already handle colorbar + orientation. + """ + y, _ = self._proportional_y() + # Use the vmin and vmax of the colorbar, which may not be the same + # as the norm. There are situations where the colormap has a + # narrower range than the colorbar and we want to accommodate the + # extra contours. + if (isinstance(self.norm, (colors.BoundaryNorm, colors.NoNorm)) + or self.boundaries is not None): + # not using a norm. + y = y * (self.vmax - self.vmin) + self.vmin + else: + # Update the norm values in a context manager as it is only + # a temporary change and we don't want to propagate any signals + # attached to the norm (callbacks.blocked). + with (self.norm.callbacks.blocked(), + cbook._setattr_cm(self.norm, vmin=self.vmin, vmax=self.vmax)): + y = self.norm.inverse(y) + self._y = y + X, Y = np.meshgrid([0., 1.], y) + if self.orientation == 'vertical': + return (X, Y) + else: + return (Y, X) + + def _forward_boundaries(self, x): + # map boundaries equally between 0 and 1... + b = self._boundaries + y = np.interp(x, b, np.linspace(0, 1, len(b))) + # the following avoids ticks in the extends: + eps = (b[-1] - b[0]) * 1e-6 + # map these _well_ out of bounds to keep any ticks out + # of the extends region... + y[x < b[0]-eps] = -1 + y[x > b[-1]+eps] = 2 + return y + + def _inverse_boundaries(self, x): + # invert the above... + b = self._boundaries + return np.interp(x, np.linspace(0, 1, len(b)), b) + + def _reset_locator_formatter_scale(self): + """ + Reset the locator et al to defaults. Any user-hardcoded changes + need to be re-entered if this gets called (either at init, or when + the mappable normal gets changed: Colorbar.update_normal) + """ + self._process_values() + self._locator = None + self._minorlocator = None + self._formatter = None + self._minorformatter = None + if (isinstance(self.mappable, contour.ContourSet) and + isinstance(self.norm, colors.LogNorm)): + # if contours have lognorm, give them a log scale... + self._set_scale('log') + elif (self.boundaries is not None or + isinstance(self.norm, colors.BoundaryNorm)): + if self.spacing == 'uniform': + funcs = (self._forward_boundaries, self._inverse_boundaries) + self._set_scale('function', functions=funcs) + elif self.spacing == 'proportional': + self._set_scale('linear') + elif getattr(self.norm, '_scale', None): + # use the norm's scale (if it exists and is not None): + self._set_scale(self.norm._scale) + elif type(self.norm) is colors.Normalize: + # plain Normalize: + self._set_scale('linear') + else: + # norm._scale is None or not an attr: derive the scale from + # the Norm: + funcs = (self.norm, self.norm.inverse) + self._set_scale('function', functions=funcs) + + def _locate(self, x): + """ + Given a set of color data values, return their + corresponding colorbar data coordinates. + """ + if isinstance(self.norm, (colors.NoNorm, colors.BoundaryNorm)): + b = self._boundaries + xn = x + else: + # Do calculations using normalized coordinates so + # as to make the interpolation more accurate. + b = self.norm(self._boundaries, clip=False).filled() + xn = self.norm(x, clip=False).filled() + + bunique = b[self._inside] + yunique = self._y + + z = np.interp(xn, bunique, yunique) + return z + + # trivial helpers + + def _uniform_y(self, N): + """ + Return colorbar data coordinates for *N* uniformly + spaced boundaries, plus extension lengths if required. + """ + automin = automax = 1. / (N - 1.) + extendlength = self._get_extension_lengths(self.extendfrac, + automin, automax, + default=0.05) + y = np.linspace(0, 1, N) + return y, extendlength + + def _proportional_y(self): + """ + Return colorbar data coordinates for the boundaries of + a proportional colorbar, plus extension lengths if required: + """ + if (isinstance(self.norm, colors.BoundaryNorm) or + self.boundaries is not None): + y = (self._boundaries - self._boundaries[self._inside][0]) + y = y / (self._boundaries[self._inside][-1] - + self._boundaries[self._inside][0]) + # need yscaled the same as the axes scale to get + # the extend lengths. + if self.spacing == 'uniform': + yscaled = self._forward_boundaries(self._boundaries) + else: + yscaled = y + else: + y = self.norm(self._boundaries.copy()) + y = np.ma.filled(y, np.nan) + # the norm and the scale should be the same... + yscaled = y + y = y[self._inside] + yscaled = yscaled[self._inside] + # normalize from 0..1: + norm = colors.Normalize(y[0], y[-1]) + y = np.ma.filled(norm(y), np.nan) + norm = colors.Normalize(yscaled[0], yscaled[-1]) + yscaled = np.ma.filled(norm(yscaled), np.nan) + # make the lower and upper extend lengths proportional to the lengths + # of the first and last boundary spacing (if extendfrac='auto'): + automin = yscaled[1] - yscaled[0] + automax = yscaled[-1] - yscaled[-2] + extendlength = [0, 0] + if self._extend_lower() or self._extend_upper(): + extendlength = self._get_extension_lengths( + self.extendfrac, automin, automax, default=0.05) + return y, extendlength + + def _get_extension_lengths(self, frac, automin, automax, default=0.05): + """ + Return the lengths of colorbar extensions. + + This is a helper method for _uniform_y and _proportional_y. + """ + # Set the default value. + extendlength = np.array([default, default]) + if isinstance(frac, str): + _api.check_in_list(['auto'], extendfrac=frac.lower()) + # Use the provided values when 'auto' is required. + extendlength[:] = [automin, automax] + elif frac is not None: + try: + # Try to set min and max extension fractions directly. + extendlength[:] = frac + # If frac is a sequence containing None then NaN may + # be encountered. This is an error. + if np.isnan(extendlength).any(): + raise ValueError() + except (TypeError, ValueError) as err: + # Raise an error on encountering an invalid value for frac. + raise ValueError('invalid value for extendfrac') from err + return extendlength + + def _extend_lower(self): + """Return whether the lower limit is open ended.""" + minmax = "max" if self.long_axis.get_inverted() else "min" + return self.extend in ('both', minmax) + + def _extend_upper(self): + """Return whether the upper limit is open ended.""" + minmax = "min" if self.long_axis.get_inverted() else "max" + return self.extend in ('both', minmax) + + def _short_axis(self): + """Return the short axis""" + if self.orientation == 'vertical': + return self.ax.xaxis + return self.ax.yaxis + + def _get_view(self): + # docstring inherited + # An interactive view for a colorbar is the norm's vmin/vmax + return self.norm.vmin, self.norm.vmax + + def _set_view(self, view): + # docstring inherited + # An interactive view for a colorbar is the norm's vmin/vmax + self.norm.vmin, self.norm.vmax = view + + def _set_view_from_bbox(self, bbox, direction='in', + mode=None, twinx=False, twiny=False): + # docstring inherited + # For colorbars, we use the zoom bbox to scale the norm's vmin/vmax + new_xbound, new_ybound = self.ax._prepare_view_from_bbox( + bbox, direction=direction, mode=mode, twinx=twinx, twiny=twiny) + if self.orientation == 'horizontal': + self.norm.vmin, self.norm.vmax = new_xbound + elif self.orientation == 'vertical': + self.norm.vmin, self.norm.vmax = new_ybound + + def drag_pan(self, button, key, x, y): + # docstring inherited + points = self.ax._get_pan_points(button, key, x, y) + if points is not None: + if self.orientation == 'horizontal': + self.norm.vmin, self.norm.vmax = points[:, 0] + elif self.orientation == 'vertical': + self.norm.vmin, self.norm.vmax = points[:, 1] + + +ColorbarBase = Colorbar # Backcompat API + + +def _normalize_location_orientation(location, orientation): + if location is None: + location = _get_ticklocation_from_orientation(orientation) + loc_settings = _api.check_getitem({ + "left": {"location": "left", "anchor": (1.0, 0.5), + "panchor": (0.0, 0.5), "pad": 0.10}, + "right": {"location": "right", "anchor": (0.0, 0.5), + "panchor": (1.0, 0.5), "pad": 0.05}, + "top": {"location": "top", "anchor": (0.5, 0.0), + "panchor": (0.5, 1.0), "pad": 0.05}, + "bottom": {"location": "bottom", "anchor": (0.5, 1.0), + "panchor": (0.5, 0.0), "pad": 0.15}, + }, location=location) + loc_settings["orientation"] = _get_orientation_from_location(location) + if orientation is not None and orientation != loc_settings["orientation"]: + # Allow the user to pass both if they are consistent. + raise TypeError("location and orientation are mutually exclusive") + return loc_settings + + +def _get_orientation_from_location(location): + return _api.check_getitem( + {None: None, "left": "vertical", "right": "vertical", + "top": "horizontal", "bottom": "horizontal"}, location=location) + + +def _get_ticklocation_from_orientation(orientation): + return _api.check_getitem( + {None: "right", "vertical": "right", "horizontal": "bottom"}, + orientation=orientation) + + +@_docstring.interpd +def make_axes(parents, location=None, orientation=None, fraction=0.15, + shrink=1.0, aspect=20, **kwargs): + """ + Create an `~.axes.Axes` suitable for a colorbar. + + The Axes is placed in the figure of the *parents* Axes, by resizing and + repositioning *parents*. + + Parameters + ---------- + parents : `~matplotlib.axes.Axes` or iterable or `numpy.ndarray` of `~.axes.Axes` + The Axes to use as parents for placing the colorbar. + %(_make_axes_kw_doc)s + + Returns + ------- + cax : `~matplotlib.axes.Axes` + The child Axes. + kwargs : dict + The reduced keyword dictionary to be passed when creating the colorbar + instance. + """ + loc_settings = _normalize_location_orientation(location, orientation) + # put appropriate values into the kwargs dict for passing back to + # the Colorbar class + kwargs['orientation'] = loc_settings['orientation'] + location = kwargs['ticklocation'] = loc_settings['location'] + + anchor = kwargs.pop('anchor', loc_settings['anchor']) + panchor = kwargs.pop('panchor', loc_settings['panchor']) + aspect0 = aspect + # turn parents into a list if it is not already. Note we cannot + # use .flatten or .ravel as these copy the references rather than + # reuse them, leading to a memory leak + if isinstance(parents, np.ndarray): + parents = list(parents.flat) + elif np.iterable(parents): + parents = list(parents) + else: + parents = [parents] + + fig = parents[0].get_figure() + + pad0 = 0.05 if fig.get_constrained_layout() else loc_settings['pad'] + pad = kwargs.pop('pad', pad0) + + if not all(fig is ax.get_figure() for ax in parents): + raise ValueError('Unable to create a colorbar Axes as not all ' + 'parents share the same figure.') + + # take a bounding box around all of the given Axes + parents_bbox = mtransforms.Bbox.union( + [ax.get_position(original=True).frozen() for ax in parents]) + + pb = parents_bbox + if location in ('left', 'right'): + if location == 'left': + pbcb, _, pb1 = pb.splitx(fraction, fraction + pad) + else: + pb1, _, pbcb = pb.splitx(1 - fraction - pad, 1 - fraction) + pbcb = pbcb.shrunk(1.0, shrink).anchored(anchor, pbcb) + else: + if location == 'bottom': + pbcb, _, pb1 = pb.splity(fraction, fraction + pad) + else: + pb1, _, pbcb = pb.splity(1 - fraction - pad, 1 - fraction) + pbcb = pbcb.shrunk(shrink, 1.0).anchored(anchor, pbcb) + + # define the aspect ratio in terms of y's per x rather than x's per y + aspect = 1.0 / aspect + + # define a transform which takes us from old axes coordinates to + # new axes coordinates + shrinking_trans = mtransforms.BboxTransform(parents_bbox, pb1) + + # transform each of the Axes in parents using the new transform + for ax in parents: + new_posn = shrinking_trans.transform(ax.get_position(original=True)) + new_posn = mtransforms.Bbox(new_posn) + ax._set_position(new_posn) + if panchor is not False: + ax.set_anchor(panchor) + + cax = fig.add_axes(pbcb, label="") + for a in parents: + # tell the parent it has a colorbar + a._colorbars += [cax] + cax._colorbar_info = dict( + parents=parents, + location=location, + shrink=shrink, + anchor=anchor, + panchor=panchor, + fraction=fraction, + aspect=aspect0, + pad=pad) + # and we need to set the aspect ratio by hand... + cax.set_anchor(anchor) + cax.set_box_aspect(aspect) + cax.set_aspect('auto') + + return cax, kwargs + + +@_docstring.interpd +def make_axes_gridspec(parent, *, location=None, orientation=None, + fraction=0.15, shrink=1.0, aspect=20, **kwargs): + """ + Create an `~.axes.Axes` suitable for a colorbar. + + The Axes is placed in the figure of the *parent* Axes, by resizing and + repositioning *parent*. + + This function is similar to `.make_axes` and mostly compatible with it. + Primary differences are + + - `.make_axes_gridspec` requires the *parent* to have a subplotspec. + - `.make_axes` positions the Axes in figure coordinates; + `.make_axes_gridspec` positions it using a subplotspec. + - `.make_axes` updates the position of the parent. `.make_axes_gridspec` + replaces the parent gridspec with a new one. + + Parameters + ---------- + parent : `~matplotlib.axes.Axes` + The Axes to use as parent for placing the colorbar. + %(_make_axes_kw_doc)s + + Returns + ------- + cax : `~matplotlib.axes.Axes` + The child Axes. + kwargs : dict + The reduced keyword dictionary to be passed when creating the colorbar + instance. + """ + + loc_settings = _normalize_location_orientation(location, orientation) + kwargs['orientation'] = loc_settings['orientation'] + location = kwargs['ticklocation'] = loc_settings['location'] + + aspect0 = aspect + anchor = kwargs.pop('anchor', loc_settings['anchor']) + panchor = kwargs.pop('panchor', loc_settings['panchor']) + pad = kwargs.pop('pad', loc_settings["pad"]) + wh_space = 2 * pad / (1 - pad) + + if location in ('left', 'right'): + gs = parent.get_subplotspec().subgridspec( + 3, 2, wspace=wh_space, hspace=0, + height_ratios=[(1-anchor[1])*(1-shrink), shrink, anchor[1]*(1-shrink)]) + if location == 'left': + gs.set_width_ratios([fraction, 1 - fraction - pad]) + ss_main = gs[:, 1] + ss_cb = gs[1, 0] + else: + gs.set_width_ratios([1 - fraction - pad, fraction]) + ss_main = gs[:, 0] + ss_cb = gs[1, 1] + else: + gs = parent.get_subplotspec().subgridspec( + 2, 3, hspace=wh_space, wspace=0, + width_ratios=[anchor[0]*(1-shrink), shrink, (1-anchor[0])*(1-shrink)]) + if location == 'top': + gs.set_height_ratios([fraction, 1 - fraction - pad]) + ss_main = gs[1, :] + ss_cb = gs[0, 1] + else: + gs.set_height_ratios([1 - fraction - pad, fraction]) + ss_main = gs[0, :] + ss_cb = gs[1, 1] + aspect = 1 / aspect + + parent.set_subplotspec(ss_main) + if panchor is not False: + parent.set_anchor(panchor) + + fig = parent.get_figure() + cax = fig.add_subplot(ss_cb, label="") + cax.set_anchor(anchor) + cax.set_box_aspect(aspect) + cax.set_aspect('auto') + cax._colorbar_info = dict( + location=location, + parents=[parent], + shrink=shrink, + anchor=anchor, + panchor=panchor, + fraction=fraction, + aspect=aspect0, + pad=pad) + + return cax, kwargs diff --git a/infer_4_30_0/lib/python3.10/site-packages/matplotlib/colorbar.pyi b/infer_4_30_0/lib/python3.10/site-packages/matplotlib/colorbar.pyi new file mode 100644 index 0000000000000000000000000000000000000000..07467ca74f3d5a528f8c1c0859fc25a2eb285664 --- /dev/null +++ b/infer_4_30_0/lib/python3.10/site-packages/matplotlib/colorbar.pyi @@ -0,0 +1,139 @@ +import matplotlib.spines as mspines +from matplotlib import cm, collections, colors, contour, colorizer +from matplotlib.axes import Axes +from matplotlib.axis import Axis +from matplotlib.backend_bases import RendererBase +from matplotlib.patches import Patch +from matplotlib.ticker import Locator, Formatter +from matplotlib.transforms import Bbox + +import numpy as np +from numpy.typing import ArrayLike +from collections.abc import Sequence +from typing import Any, Literal, overload +from .typing import ColorType + +class _ColorbarSpine(mspines.Spines): + def __init__(self, axes: Axes): ... + def get_window_extent(self, renderer: RendererBase | None = ...) -> Bbox:... + def set_xy(self, xy: ArrayLike) -> None: ... + def draw(self, renderer: RendererBase | None) -> None:... + + +class Colorbar: + n_rasterize: int + mappable: cm.ScalarMappable | colorizer.ColorizingArtist + ax: Axes + alpha: float | None + cmap: colors.Colormap + norm: colors.Normalize + values: Sequence[float] | None + boundaries: Sequence[float] | None + extend: Literal["neither", "both", "min", "max"] + spacing: Literal["uniform", "proportional"] + orientation: Literal["vertical", "horizontal"] + drawedges: bool + extendfrac: Literal["auto"] | float | Sequence[float] | None + extendrect: bool + solids: None | collections.QuadMesh + solids_patches: list[Patch] + lines: list[collections.LineCollection] + outline: _ColorbarSpine + dividers: collections.LineCollection + ticklocation: Literal["left", "right", "top", "bottom"] + def __init__( + self, + ax: Axes, + mappable: cm.ScalarMappable | colorizer.ColorizingArtist | None = ..., + *, + cmap: str | colors.Colormap | None = ..., + norm: colors.Normalize | None = ..., + alpha: float | None = ..., + values: Sequence[float] | None = ..., + boundaries: Sequence[float] | None = ..., + orientation: Literal["vertical", "horizontal"] | None = ..., + ticklocation: Literal["auto", "left", "right", "top", "bottom"] = ..., + extend: Literal["neither", "both", "min", "max"] | None = ..., + spacing: Literal["uniform", "proportional"] = ..., + ticks: Sequence[float] | Locator | None = ..., + format: str | Formatter | None = ..., + drawedges: bool = ..., + extendfrac: Literal["auto"] | float | Sequence[float] | None = ..., + extendrect: bool = ..., + label: str = ..., + location: Literal["left", "right", "top", "bottom"] | None = ... + ) -> None: ... + @property + def long_axis(self) -> Axis: ... + @property + def locator(self) -> Locator: ... + @locator.setter + def locator(self, loc: Locator) -> None: ... + @property + def minorlocator(self) -> Locator: ... + @minorlocator.setter + def minorlocator(self, loc: Locator) -> None: ... + @property + def formatter(self) -> Formatter: ... + @formatter.setter + def formatter(self, fmt: Formatter) -> None: ... + @property + def minorformatter(self) -> Formatter: ... + @minorformatter.setter + def minorformatter(self, fmt: Formatter) -> None: ... + def update_normal(self, mappable: cm.ScalarMappable | None = ...) -> None: ... + @overload + def add_lines(self, CS: contour.ContourSet, erase: bool = ...) -> None: ... + @overload + def add_lines( + self, + levels: ArrayLike, + colors: ColorType | Sequence[ColorType], + linewidths: float | ArrayLike, + erase: bool = ..., + ) -> None: ... + def update_ticks(self) -> None: ... + def set_ticks( + self, + ticks: Sequence[float] | Locator, + *, + labels: Sequence[str] | None = ..., + minor: bool = ..., + **kwargs + ) -> None: ... + def get_ticks(self, minor: bool = ...) -> np.ndarray: ... + def set_ticklabels( + self, + ticklabels: Sequence[str], + *, + minor: bool = ..., + **kwargs + ) -> None: ... + def minorticks_on(self) -> None: ... + def minorticks_off(self) -> None: ... + def set_label(self, label: str, *, loc: str | None = ..., **kwargs) -> None: ... + def set_alpha(self, alpha: float | np.ndarray) -> None: ... + def remove(self) -> None: ... + def drag_pan(self, button: Any, key: Any, x: float, y: float) -> None: ... + +ColorbarBase = Colorbar + +def make_axes( + parents: Axes | list[Axes] | np.ndarray, + location: Literal["left", "right", "top", "bottom"] | None = ..., + orientation: Literal["vertical", "horizontal"] | None = ..., + fraction: float = ..., + shrink: float = ..., + aspect: float = ..., + **kwargs +) -> tuple[Axes, dict[str, Any]]: ... +def make_axes_gridspec( + parent: Axes, + *, + location: Literal["left", "right", "top", "bottom"] | None = ..., + orientation: Literal["vertical", "horizontal"] | None = ..., + fraction: float = ..., + shrink: float = ..., + aspect: float = ..., + **kwargs +) -> tuple[Axes, dict[str, Any]]: ... diff --git a/infer_4_30_0/lib/python3.10/site-packages/matplotlib/colors.pyi b/infer_4_30_0/lib/python3.10/site-packages/matplotlib/colors.pyi new file mode 100644 index 0000000000000000000000000000000000000000..6941e3d5d176c39525c27e9a60d6926a18e31e8b --- /dev/null +++ b/infer_4_30_0/lib/python3.10/site-packages/matplotlib/colors.pyi @@ -0,0 +1,449 @@ +from collections.abc import Callable, Iterable, Iterator, Mapping, Sequence +from matplotlib import cbook, scale +import re + +from typing import Any, Literal, overload +from .typing import ColorType + +import numpy as np +from numpy.typing import ArrayLike + +# Explicitly export colors dictionaries which are imported in the impl +BASE_COLORS: dict[str, ColorType] +CSS4_COLORS: dict[str, ColorType] +TABLEAU_COLORS: dict[str, ColorType] +XKCD_COLORS: dict[str, ColorType] + +class _ColorMapping(dict[str, ColorType]): + cache: dict[tuple[ColorType, float | None], tuple[float, float, float, float]] + def __init__(self, mapping) -> None: ... + def __setitem__(self, key, value) -> None: ... + def __delitem__(self, key) -> None: ... + +def get_named_colors_mapping() -> _ColorMapping: ... + +class ColorSequenceRegistry(Mapping): + def __init__(self) -> None: ... + def __getitem__(self, item: str) -> list[ColorType]: ... + def __iter__(self) -> Iterator[str]: ... + def __len__(self) -> int: ... + def register(self, name: str, color_list: Iterable[ColorType]) -> None: ... + def unregister(self, name: str) -> None: ... + +_color_sequences: ColorSequenceRegistry = ... + +def is_color_like(c: Any) -> bool: ... +def same_color(c1: ColorType, c2: ColorType) -> bool: ... +def to_rgba( + c: ColorType, alpha: float | None = ... +) -> tuple[float, float, float, float]: ... +def to_rgba_array( + c: ColorType | ArrayLike, alpha: float | ArrayLike | None = ... +) -> np.ndarray: ... +def to_rgb(c: ColorType) -> tuple[float, float, float]: ... +def to_hex(c: ColorType, keep_alpha: bool = ...) -> str: ... + +cnames: dict[str, ColorType] +hexColorPattern: re.Pattern +rgb2hex = to_hex +hex2color = to_rgb + +class ColorConverter: + colors: _ColorMapping + cache: dict[tuple[ColorType, float | None], tuple[float, float, float, float]] + @staticmethod + def to_rgb(c: ColorType) -> tuple[float, float, float]: ... + @staticmethod + def to_rgba( + c: ColorType, alpha: float | None = ... + ) -> tuple[float, float, float, float]: ... + @staticmethod + def to_rgba_array( + c: ColorType | ArrayLike, alpha: float | ArrayLike | None = ... + ) -> np.ndarray: ... + +colorConverter: ColorConverter + +class Colormap: + name: str + N: int + colorbar_extend: bool + def __init__(self, name: str, N: int = ...) -> None: ... + @overload + def __call__( + self, X: Sequence[float] | np.ndarray, alpha: ArrayLike | None = ..., bytes: bool = ... + ) -> np.ndarray: ... + @overload + def __call__( + self, X: float, alpha: float | None = ..., bytes: bool = ... + ) -> tuple[float, float, float, float]: ... + @overload + def __call__( + self, X: ArrayLike, alpha: ArrayLike | None = ..., bytes: bool = ... + ) -> tuple[float, float, float, float] | np.ndarray: ... + def __copy__(self) -> Colormap: ... + def __eq__(self, other: object) -> bool: ... + def get_bad(self) -> np.ndarray: ... + def set_bad(self, color: ColorType = ..., alpha: float | None = ...) -> None: ... + def get_under(self) -> np.ndarray: ... + def set_under(self, color: ColorType = ..., alpha: float | None = ...) -> None: ... + def get_over(self) -> np.ndarray: ... + def set_over(self, color: ColorType = ..., alpha: float | None = ...) -> None: ... + def set_extremes( + self, + *, + bad: ColorType | None = ..., + under: ColorType | None = ..., + over: ColorType | None = ... + ) -> None: ... + def with_extremes( + self, + *, + bad: ColorType | None = ..., + under: ColorType | None = ..., + over: ColorType | None = ... + ) -> Colormap: ... + def is_gray(self) -> bool: ... + def resampled(self, lutsize: int) -> Colormap: ... + def reversed(self, name: str | None = ...) -> Colormap: ... + def _repr_html_(self) -> str: ... + def _repr_png_(self) -> bytes: ... + def copy(self) -> Colormap: ... + +class LinearSegmentedColormap(Colormap): + monochrome: bool + def __init__( + self, + name: str, + segmentdata: dict[ + Literal["red", "green", "blue", "alpha"], Sequence[tuple[float, ...]] + ], + N: int = ..., + gamma: float = ..., + ) -> None: ... + def set_gamma(self, gamma: float) -> None: ... + @staticmethod + def from_list( + name: str, colors: ArrayLike | Sequence[tuple[float, ColorType]], N: int = ..., gamma: float = ... + ) -> LinearSegmentedColormap: ... + def resampled(self, lutsize: int) -> LinearSegmentedColormap: ... + def reversed(self, name: str | None = ...) -> LinearSegmentedColormap: ... + +class ListedColormap(Colormap): + monochrome: bool + colors: ArrayLike | ColorType + def __init__( + self, colors: ArrayLike | ColorType, name: str = ..., N: int | None = ... + ) -> None: ... + def resampled(self, lutsize: int) -> ListedColormap: ... + def reversed(self, name: str | None = ...) -> ListedColormap: ... + +class MultivarColormap: + name: str + n_variates: int + def __init__(self, colormaps: list[Colormap], combination_mode: Literal['sRGB_add', 'sRGB_sub'], name: str = ...) -> None: ... + @overload + def __call__( + self, X: Sequence[Sequence[float]] | np.ndarray, alpha: ArrayLike | None = ..., bytes: bool = ..., clip: bool = ... + ) -> np.ndarray: ... + @overload + def __call__( + self, X: Sequence[float], alpha: float | None = ..., bytes: bool = ..., clip: bool = ... + ) -> tuple[float, float, float, float]: ... + @overload + def __call__( + self, X: ArrayLike, alpha: ArrayLike | None = ..., bytes: bool = ..., clip: bool = ... + ) -> tuple[float, float, float, float] | np.ndarray: ... + def copy(self) -> MultivarColormap: ... + def __copy__(self) -> MultivarColormap: ... + def __eq__(self, other: Any) -> bool: ... + def __getitem__(self, item: int) -> Colormap: ... + def __iter__(self) -> Iterator[Colormap]: ... + def __len__(self) -> int: ... + def get_bad(self) -> np.ndarray: ... + def resampled(self, lutshape: Sequence[int | None]) -> MultivarColormap: ... + def with_extremes( + self, + *, + bad: ColorType | None = ..., + under: Sequence[ColorType] | None = ..., + over: Sequence[ColorType] | None = ... + ) -> MultivarColormap: ... + @property + def combination_mode(self) -> str: ... + def _repr_html_(self) -> str: ... + def _repr_png_(self) -> bytes: ... + +class BivarColormap: + name: str + N: int + M: int + n_variates: int + def __init__( + self, N: int = ..., M: int | None = ..., shape: Literal['square', 'circle', 'ignore', 'circleignore'] = ..., + origin: Sequence[float] = ..., name: str = ... + ) -> None: ... + @overload + def __call__( + self, X: Sequence[Sequence[float]] | np.ndarray, alpha: ArrayLike | None = ..., bytes: bool = ... + ) -> np.ndarray: ... + @overload + def __call__( + self, X: Sequence[float], alpha: float | None = ..., bytes: bool = ... + ) -> tuple[float, float, float, float]: ... + @overload + def __call__( + self, X: ArrayLike, alpha: ArrayLike | None = ..., bytes: bool = ... + ) -> tuple[float, float, float, float] | np.ndarray: ... + @property + def lut(self) -> np.ndarray: ... + @property + def shape(self) -> str: ... + @property + def origin(self) -> tuple[float, float]: ... + def copy(self) -> BivarColormap: ... + def __copy__(self) -> BivarColormap: ... + def __getitem__(self, item: int) -> Colormap: ... + def __eq__(self, other: Any) -> bool: ... + def get_bad(self) -> np.ndarray: ... + def get_outside(self) -> np.ndarray: ... + def resampled(self, lutshape: Sequence[int | None], transposed: bool = ...) -> BivarColormap: ... + def transposed(self) -> BivarColormap: ... + def reversed(self, axis_0: bool = ..., axis_1: bool = ...) -> BivarColormap: ... + def with_extremes( + self, + *, + bad: ColorType | None = ..., + outside: ColorType | None = ..., + shape: str | None = ..., + origin: None | Sequence[float] = ..., + ) -> MultivarColormap: ... + def _repr_html_(self) -> str: ... + def _repr_png_(self) -> bytes: ... + +class SegmentedBivarColormap(BivarColormap): + def __init__( + self, patch: np.ndarray, N: int = ..., shape: Literal['square', 'circle', 'ignore', 'circleignore'] = ..., + origin: Sequence[float] = ..., name: str = ... + ) -> None: ... + +class BivarColormapFromImage(BivarColormap): + def __init__( + self, lut: np.ndarray, shape: Literal['square', 'circle', 'ignore', 'circleignore'] = ..., + origin: Sequence[float] = ..., name: str = ... + ) -> None: ... + +class Normalize: + callbacks: cbook.CallbackRegistry + def __init__( + self, vmin: float | None = ..., vmax: float | None = ..., clip: bool = ... + ) -> None: ... + @property + def vmin(self) -> float | None: ... + @vmin.setter + def vmin(self, value: float | None) -> None: ... + @property + def vmax(self) -> float | None: ... + @vmax.setter + def vmax(self, value: float | None) -> None: ... + @property + def clip(self) -> bool: ... + @clip.setter + def clip(self, value: bool) -> None: ... + @staticmethod + def process_value(value: ArrayLike) -> tuple[np.ma.MaskedArray, bool]: ... + @overload + def __call__(self, value: float, clip: bool | None = ...) -> float: ... + @overload + def __call__(self, value: np.ndarray, clip: bool | None = ...) -> np.ma.MaskedArray: ... + @overload + def __call__(self, value: ArrayLike, clip: bool | None = ...) -> ArrayLike: ... + @overload + def inverse(self, value: float) -> float: ... + @overload + def inverse(self, value: np.ndarray) -> np.ma.MaskedArray: ... + @overload + def inverse(self, value: ArrayLike) -> ArrayLike: ... + def autoscale(self, A: ArrayLike) -> None: ... + def autoscale_None(self, A: ArrayLike) -> None: ... + def scaled(self) -> bool: ... + +class TwoSlopeNorm(Normalize): + def __init__( + self, vcenter: float, vmin: float | None = ..., vmax: float | None = ... + ) -> None: ... + @property + def vcenter(self) -> float: ... + @vcenter.setter + def vcenter(self, value: float) -> None: ... + def autoscale_None(self, A: ArrayLike) -> None: ... + +class CenteredNorm(Normalize): + def __init__( + self, vcenter: float = ..., halfrange: float | None = ..., clip: bool = ... + ) -> None: ... + @property + def vcenter(self) -> float: ... + @vcenter.setter + def vcenter(self, vcenter: float) -> None: ... + @property + def halfrange(self) -> float: ... + @halfrange.setter + def halfrange(self, halfrange: float) -> None: ... + +@overload +def make_norm_from_scale( + scale_cls: type[scale.ScaleBase], + base_norm_cls: type[Normalize], + *, + init: Callable | None = ... +) -> type[Normalize]: ... +@overload +def make_norm_from_scale( + scale_cls: type[scale.ScaleBase], + base_norm_cls: None = ..., + *, + init: Callable | None = ... +) -> Callable[[type[Normalize]], type[Normalize]]: ... + +class FuncNorm(Normalize): + def __init__( + self, + functions: tuple[Callable, Callable], + vmin: float | None = ..., + vmax: float | None = ..., + clip: bool = ..., + ) -> None: ... +class LogNorm(Normalize): ... + +class SymLogNorm(Normalize): + def __init__( + self, + linthresh: float, + linscale: float = ..., + vmin: float | None = ..., + vmax: float | None = ..., + clip: bool = ..., + *, + base: float = ..., + ) -> None: ... + @property + def linthresh(self) -> float: ... + @linthresh.setter + def linthresh(self, value: float) -> None: ... + +class AsinhNorm(Normalize): + def __init__( + self, + linear_width: float = ..., + vmin: float | None = ..., + vmax: float | None = ..., + clip: bool = ..., + ) -> None: ... + @property + def linear_width(self) -> float: ... + @linear_width.setter + def linear_width(self, value: float) -> None: ... + +class PowerNorm(Normalize): + gamma: float + def __init__( + self, + gamma: float, + vmin: float | None = ..., + vmax: float | None = ..., + clip: bool = ..., + ) -> None: ... + +class BoundaryNorm(Normalize): + boundaries: np.ndarray + N: int + Ncmap: int + extend: Literal["neither", "both", "min", "max"] + def __init__( + self, + boundaries: ArrayLike, + ncolors: int, + clip: bool = ..., + *, + extend: Literal["neither", "both", "min", "max"] = ... + ) -> None: ... + +class NoNorm(Normalize): ... + +def rgb_to_hsv(arr: ArrayLike) -> np.ndarray: ... +def hsv_to_rgb(hsv: ArrayLike) -> np.ndarray: ... + +class LightSource: + azdeg: float + altdeg: float + hsv_min_val: float + hsv_max_val: float + hsv_min_sat: float + hsv_max_sat: float + def __init__( + self, + azdeg: float = ..., + altdeg: float = ..., + hsv_min_val: float = ..., + hsv_max_val: float = ..., + hsv_min_sat: float = ..., + hsv_max_sat: float = ..., + ) -> None: ... + @property + def direction(self) -> np.ndarray: ... + def hillshade( + self, + elevation: ArrayLike, + vert_exag: float = ..., + dx: float = ..., + dy: float = ..., + fraction: float = ..., + ) -> np.ndarray: ... + def shade_normals( + self, normals: np.ndarray, fraction: float = ... + ) -> np.ndarray: ... + def shade( + self, + data: ArrayLike, + cmap: Colormap, + norm: Normalize | None = ..., + blend_mode: Literal["hsv", "overlay", "soft"] | Callable = ..., + vmin: float | None = ..., + vmax: float | None = ..., + vert_exag: float = ..., + dx: float = ..., + dy: float = ..., + fraction: float = ..., + **kwargs + ) -> np.ndarray: ... + def shade_rgb( + self, + rgb: ArrayLike, + elevation: ArrayLike, + fraction: float = ..., + blend_mode: Literal["hsv", "overlay", "soft"] | Callable = ..., + vert_exag: float = ..., + dx: float = ..., + dy: float = ..., + **kwargs + ) -> np.ndarray: ... + def blend_hsv( + self, + rgb: ArrayLike, + intensity: ArrayLike, + hsv_max_sat: float | None = ..., + hsv_max_val: float | None = ..., + hsv_min_val: float | None = ..., + hsv_min_sat: float | None = ..., + ) -> ArrayLike: ... + def blend_soft_light( + self, rgb: np.ndarray, intensity: np.ndarray + ) -> np.ndarray: ... + def blend_overlay(self, rgb: np.ndarray, intensity: np.ndarray) -> np.ndarray: ... + +def from_levels_and_colors( + levels: Sequence[float], + colors: Sequence[ColorType], + extend: Literal["neither", "min", "max", "both"] = ..., +) -> tuple[ListedColormap, BoundaryNorm]: ... diff --git a/infer_4_30_0/lib/python3.10/site-packages/matplotlib/container.py b/infer_4_30_0/lib/python3.10/site-packages/matplotlib/container.py new file mode 100644 index 0000000000000000000000000000000000000000..b6dd43724f34b219a7d8864542af4dbec81d89ff --- /dev/null +++ b/infer_4_30_0/lib/python3.10/site-packages/matplotlib/container.py @@ -0,0 +1,141 @@ +from matplotlib import cbook +from matplotlib.artist import Artist + + +class Container(tuple): + """ + Base class for containers. + + Containers are classes that collect semantically related Artists such as + the bars of a bar plot. + """ + + def __repr__(self): + return f"<{type(self).__name__} object of {len(self)} artists>" + + def __new__(cls, *args, **kwargs): + return tuple.__new__(cls, args[0]) + + def __init__(self, kl, label=None): + self._callbacks = cbook.CallbackRegistry(signals=["pchanged"]) + self._remove_method = None + self._label = str(label) if label is not None else None + + def remove(self): + for c in cbook.flatten( + self, scalarp=lambda x: isinstance(x, Artist)): + if c is not None: + c.remove() + if self._remove_method: + self._remove_method(self) + + def get_children(self): + return [child for child in cbook.flatten(self) if child is not None] + + get_label = Artist.get_label + set_label = Artist.set_label + add_callback = Artist.add_callback + remove_callback = Artist.remove_callback + pchanged = Artist.pchanged + + +class BarContainer(Container): + """ + Container for the artists of bar plots (e.g. created by `.Axes.bar`). + + The container can be treated as a tuple of the *patches* themselves. + Additionally, you can access these and further parameters by the + attributes. + + Attributes + ---------- + patches : list of :class:`~matplotlib.patches.Rectangle` + The artists of the bars. + + errorbar : None or :class:`~matplotlib.container.ErrorbarContainer` + A container for the error bar artists if error bars are present. + *None* otherwise. + + datavalues : None or array-like + The underlying data values corresponding to the bars. + + orientation : {'vertical', 'horizontal'}, default: None + If 'vertical', the bars are assumed to be vertical. + If 'horizontal', the bars are assumed to be horizontal. + + """ + + def __init__(self, patches, errorbar=None, *, datavalues=None, + orientation=None, **kwargs): + self.patches = patches + self.errorbar = errorbar + self.datavalues = datavalues + self.orientation = orientation + super().__init__(patches, **kwargs) + + +class ErrorbarContainer(Container): + """ + Container for the artists of error bars (e.g. created by `.Axes.errorbar`). + + The container can be treated as the *lines* tuple itself. + Additionally, you can access these and further parameters by the + attributes. + + Attributes + ---------- + lines : tuple + Tuple of ``(data_line, caplines, barlinecols)``. + + - data_line : A `~matplotlib.lines.Line2D` instance of x, y plot markers + and/or line. + - caplines : A tuple of `~matplotlib.lines.Line2D` instances of the error + bar caps. + - barlinecols : A tuple of `~matplotlib.collections.LineCollection` with the + horizontal and vertical error ranges. + + has_xerr, has_yerr : bool + ``True`` if the errorbar has x/y errors. + + """ + + def __init__(self, lines, has_xerr=False, has_yerr=False, **kwargs): + self.lines = lines + self.has_xerr = has_xerr + self.has_yerr = has_yerr + super().__init__(lines, **kwargs) + + +class StemContainer(Container): + """ + Container for the artists created in a :meth:`.Axes.stem` plot. + + The container can be treated like a namedtuple ``(markerline, stemlines, + baseline)``. + + Attributes + ---------- + markerline : `~matplotlib.lines.Line2D` + The artist of the markers at the stem heads. + + stemlines : `~matplotlib.collections.LineCollection` + The artists of the vertical lines for all stems. + + baseline : `~matplotlib.lines.Line2D` + The artist of the horizontal baseline. + """ + def __init__(self, markerline_stemlines_baseline, **kwargs): + """ + Parameters + ---------- + markerline_stemlines_baseline : tuple + Tuple of ``(markerline, stemlines, baseline)``. + ``markerline`` contains the `.Line2D` of the markers, + ``stemlines`` is a `.LineCollection` of the main lines, + ``baseline`` is the `.Line2D` of the baseline. + """ + markerline, stemlines, baseline = markerline_stemlines_baseline + self.markerline = markerline + self.stemlines = stemlines + self.baseline = baseline + super().__init__(markerline_stemlines_baseline, **kwargs) diff --git a/infer_4_30_0/lib/python3.10/site-packages/matplotlib/dviread.py b/infer_4_30_0/lib/python3.10/site-packages/matplotlib/dviread.py new file mode 100644 index 0000000000000000000000000000000000000000..bd21367ce73dc39658ab3c671c2ec2ebba5341f3 --- /dev/null +++ b/infer_4_30_0/lib/python3.10/site-packages/matplotlib/dviread.py @@ -0,0 +1,1139 @@ +""" +A module for reading dvi files output by TeX. Several limitations make +this not (currently) useful as a general-purpose dvi preprocessor, but +it is currently used by the pdf backend for processing usetex text. + +Interface:: + + with Dvi(filename, 72) as dvi: + # iterate over pages: + for page in dvi: + w, h, d = page.width, page.height, page.descent + for x, y, font, glyph, width in page.text: + fontname = font.texname + pointsize = font.size + ... + for x, y, height, width in page.boxes: + ... +""" + +from collections import namedtuple +import enum +from functools import lru_cache, partial, wraps +import logging +import os +from pathlib import Path +import re +import struct +import subprocess +import sys + +import numpy as np + +from matplotlib import _api, cbook + +_log = logging.getLogger(__name__) + +# Many dvi related files are looked for by external processes, require +# additional parsing, and are used many times per rendering, which is why they +# are cached using lru_cache(). + +# Dvi is a bytecode format documented in +# https://ctan.org/pkg/dvitype +# https://texdoc.org/serve/dvitype.pdf/0 +# +# The file consists of a preamble, some number of pages, a postamble, +# and a finale. Different opcodes are allowed in different contexts, +# so the Dvi object has a parser state: +# +# pre: expecting the preamble +# outer: between pages (followed by a page or the postamble, +# also e.g. font definitions are allowed) +# page: processing a page +# post_post: state after the postamble (our current implementation +# just stops reading) +# finale: the finale (unimplemented in our current implementation) + +_dvistate = enum.Enum('DviState', 'pre outer inpage post_post finale') + +# The marks on a page consist of text and boxes. A page also has dimensions. +Page = namedtuple('Page', 'text boxes height width descent') +Box = namedtuple('Box', 'x y height width') + + +# Also a namedtuple, for backcompat. +class Text(namedtuple('Text', 'x y font glyph width')): + """ + A glyph in the dvi file. + + The *x* and *y* attributes directly position the glyph. The *font*, + *glyph*, and *width* attributes are kept public for back-compatibility, + but users wanting to draw the glyph themselves are encouraged to instead + load the font specified by `font_path` at `font_size`, warp it with the + effects specified by `font_effects`, and load the glyph specified by + `glyph_name_or_index`. + """ + + def _get_pdftexmap_entry(self): + return PsfontsMap(find_tex_file("pdftex.map"))[self.font.texname] + + @property + def font_path(self): + """The `~pathlib.Path` to the font for this glyph.""" + psfont = self._get_pdftexmap_entry() + if psfont.filename is None: + raise ValueError("No usable font file found for {} ({}); " + "the font may lack a Type-1 version" + .format(psfont.psname.decode("ascii"), + psfont.texname.decode("ascii"))) + return Path(psfont.filename) + + @property + def font_size(self): + """The font size.""" + return self.font.size + + @property + def font_effects(self): + """ + The "font effects" dict for this glyph. + + This dict contains the values for this glyph of SlantFont and + ExtendFont (if any), read off :file:`pdftex.map`. + """ + return self._get_pdftexmap_entry().effects + + @property + def glyph_name_or_index(self): + """ + Either the glyph name or the native charmap glyph index. + + If :file:`pdftex.map` specifies an encoding for this glyph's font, that + is a mapping of glyph indices to Adobe glyph names; use it to convert + dvi indices to glyph names. Callers can then convert glyph names to + glyph indices (with FT_Get_Name_Index/get_name_index), and load the + glyph using FT_Load_Glyph/load_glyph. + + If :file:`pdftex.map` specifies no encoding, the indices directly map + to the font's "native" charmap; glyphs should directly load using + FT_Load_Char/load_char after selecting the native charmap. + """ + entry = self._get_pdftexmap_entry() + return (_parse_enc(entry.encoding)[self.glyph] + if entry.encoding is not None else self.glyph) + + +# Opcode argument parsing +# +# Each of the following functions takes a Dvi object and delta, which is the +# difference between the opcode and the minimum opcode with the same meaning. +# Dvi opcodes often encode the number of argument bytes in this delta. +_arg_mapping = dict( + # raw: Return delta as is. + raw=lambda dvi, delta: delta, + # u1: Read 1 byte as an unsigned number. + u1=lambda dvi, delta: dvi._read_arg(1, signed=False), + # u4: Read 4 bytes as an unsigned number. + u4=lambda dvi, delta: dvi._read_arg(4, signed=False), + # s4: Read 4 bytes as a signed number. + s4=lambda dvi, delta: dvi._read_arg(4, signed=True), + # slen: Read delta bytes as a signed number, or None if delta is None. + slen=lambda dvi, delta: dvi._read_arg(delta, signed=True) if delta else None, + # slen1: Read (delta + 1) bytes as a signed number. + slen1=lambda dvi, delta: dvi._read_arg(delta + 1, signed=True), + # ulen1: Read (delta + 1) bytes as an unsigned number. + ulen1=lambda dvi, delta: dvi._read_arg(delta + 1, signed=False), + # olen1: Read (delta + 1) bytes as an unsigned number if less than 4 bytes, + # as a signed number if 4 bytes. + olen1=lambda dvi, delta: dvi._read_arg(delta + 1, signed=(delta == 3)), +) + + +def _dispatch(table, min, max=None, state=None, args=('raw',)): + """ + Decorator for dispatch by opcode. Sets the values in *table* + from *min* to *max* to this method, adds a check that the Dvi state + matches *state* if not None, reads arguments from the file according + to *args*. + + Parameters + ---------- + table : dict[int, callable] + The dispatch table to be filled in. + + min, max : int + Range of opcodes that calls the registered function; *max* defaults to + *min*. + + state : _dvistate, optional + State of the Dvi object in which these opcodes are allowed. + + args : list[str], default: ['raw'] + Sequence of argument specifications: + + - 'raw': opcode minus minimum + - 'u1': read one unsigned byte + - 'u4': read four bytes, treat as an unsigned number + - 's4': read four bytes, treat as a signed number + - 'slen': read (opcode - minimum) bytes, treat as signed + - 'slen1': read (opcode - minimum + 1) bytes, treat as signed + - 'ulen1': read (opcode - minimum + 1) bytes, treat as unsigned + - 'olen1': read (opcode - minimum + 1) bytes, treat as unsigned + if under four bytes, signed if four bytes + """ + def decorate(method): + get_args = [_arg_mapping[x] for x in args] + + @wraps(method) + def wrapper(self, byte): + if state is not None and self.state != state: + raise ValueError("state precondition failed") + return method(self, *[f(self, byte-min) for f in get_args]) + if max is None: + table[min] = wrapper + else: + for i in range(min, max+1): + assert table[i] is None + table[i] = wrapper + return wrapper + return decorate + + +class Dvi: + """ + A reader for a dvi ("device-independent") file, as produced by TeX. + + The current implementation can only iterate through pages in order, + and does not even attempt to verify the postamble. + + This class can be used as a context manager to close the underlying + file upon exit. Pages can be read via iteration. Here is an overly + simple way to extract text without trying to detect whitespace:: + + >>> with matplotlib.dviread.Dvi('input.dvi', 72) as dvi: + ... for page in dvi: + ... print(''.join(chr(t.glyph) for t in page.text)) + """ + # dispatch table + _dtable = [None] * 256 + _dispatch = partial(_dispatch, _dtable) + + def __init__(self, filename, dpi): + """ + Read the data from the file named *filename* and convert + TeX's internal units to units of *dpi* per inch. + *dpi* only sets the units and does not limit the resolution. + Use None to return TeX's internal units. + """ + _log.debug('Dvi: %s', filename) + self.file = open(filename, 'rb') + self.dpi = dpi + self.fonts = {} + self.state = _dvistate.pre + self._missing_font = None + + def __enter__(self): + """Context manager enter method, does nothing.""" + return self + + def __exit__(self, etype, evalue, etrace): + """ + Context manager exit method, closes the underlying file if it is open. + """ + self.close() + + def __iter__(self): + """ + Iterate through the pages of the file. + + Yields + ------ + Page + Details of all the text and box objects on the page. + The Page tuple contains lists of Text and Box tuples and + the page dimensions, and the Text and Box tuples contain + coordinates transformed into a standard Cartesian + coordinate system at the dpi value given when initializing. + The coordinates are floating point numbers, but otherwise + precision is not lost and coordinate values are not clipped to + integers. + """ + while self._read(): + yield self._output() + + def close(self): + """Close the underlying file if it is open.""" + if not self.file.closed: + self.file.close() + + def _output(self): + """ + Output the text and boxes belonging to the most recent page. + page = dvi._output() + """ + minx = miny = np.inf + maxx = maxy = -np.inf + maxy_pure = -np.inf + for elt in self.text + self.boxes: + if isinstance(elt, Box): + x, y, h, w = elt + e = 0 # zero depth + else: # glyph + x, y, font, g, w = elt + h, e = font._height_depth_of(g) + minx = min(minx, x) + miny = min(miny, y - h) + maxx = max(maxx, x + w) + maxy = max(maxy, y + e) + maxy_pure = max(maxy_pure, y) + if self._baseline_v is not None: + maxy_pure = self._baseline_v # This should normally be the case. + self._baseline_v = None + + if not self.text and not self.boxes: # Avoid infs/nans from inf+/-inf. + return Page(text=[], boxes=[], width=0, height=0, descent=0) + + if self.dpi is None: + # special case for ease of debugging: output raw dvi coordinates + return Page(text=self.text, boxes=self.boxes, + width=maxx-minx, height=maxy_pure-miny, + descent=maxy-maxy_pure) + + # convert from TeX's "scaled points" to dpi units + d = self.dpi / (72.27 * 2**16) + descent = (maxy - maxy_pure) * d + + text = [Text((x-minx)*d, (maxy-y)*d - descent, f, g, w*d) + for (x, y, f, g, w) in self.text] + boxes = [Box((x-minx)*d, (maxy-y)*d - descent, h*d, w*d) + for (x, y, h, w) in self.boxes] + + return Page(text=text, boxes=boxes, width=(maxx-minx)*d, + height=(maxy_pure-miny)*d, descent=descent) + + def _read(self): + """ + Read one page from the file. Return True if successful, + False if there were no more pages. + """ + # Pages appear to start with the sequence + # bop (begin of page) + # xxx comment + # # if using chemformula + # down + # push + # down + # # if using xcolor + # down + # push + # down (possibly multiple) + # push <= here, v is the baseline position. + # etc. + # (dviasm is useful to explore this structure.) + # Thus, we use the vertical position at the first time the stack depth + # reaches 3, while at least three "downs" have been executed (excluding + # those popped out (corresponding to the chemformula preamble)), as the + # baseline (the "down" count is necessary to handle xcolor). + down_stack = [0] + self._baseline_v = None + while True: + byte = self.file.read(1)[0] + self._dtable[byte](self, byte) + if self._missing_font: + raise self._missing_font.to_exception() + name = self._dtable[byte].__name__ + if name == "_push": + down_stack.append(down_stack[-1]) + elif name == "_pop": + down_stack.pop() + elif name == "_down": + down_stack[-1] += 1 + if (self._baseline_v is None + and len(getattr(self, "stack", [])) == 3 + and down_stack[-1] >= 4): + self._baseline_v = self.v + if byte == 140: # end of page + return True + if self.state is _dvistate.post_post: # end of file + self.close() + return False + + def _read_arg(self, nbytes, signed=False): + """ + Read and return a big-endian integer *nbytes* long. + Signedness is determined by the *signed* keyword. + """ + return int.from_bytes(self.file.read(nbytes), "big", signed=signed) + + @_dispatch(min=0, max=127, state=_dvistate.inpage) + def _set_char_immediate(self, char): + self._put_char_real(char) + if isinstance(self.fonts[self.f], cbook._ExceptionInfo): + return + self.h += self.fonts[self.f]._width_of(char) + + @_dispatch(min=128, max=131, state=_dvistate.inpage, args=('olen1',)) + def _set_char(self, char): + self._put_char_real(char) + if isinstance(self.fonts[self.f], cbook._ExceptionInfo): + return + self.h += self.fonts[self.f]._width_of(char) + + @_dispatch(132, state=_dvistate.inpage, args=('s4', 's4')) + def _set_rule(self, a, b): + self._put_rule_real(a, b) + self.h += b + + @_dispatch(min=133, max=136, state=_dvistate.inpage, args=('olen1',)) + def _put_char(self, char): + self._put_char_real(char) + + def _put_char_real(self, char): + font = self.fonts[self.f] + if isinstance(font, cbook._ExceptionInfo): + self._missing_font = font + elif font._vf is None: + self.text.append(Text(self.h, self.v, font, char, + font._width_of(char))) + else: + scale = font._scale + for x, y, f, g, w in font._vf[char].text: + newf = DviFont(scale=_mul2012(scale, f._scale), + tfm=f._tfm, texname=f.texname, vf=f._vf) + self.text.append(Text(self.h + _mul2012(x, scale), + self.v + _mul2012(y, scale), + newf, g, newf._width_of(g))) + self.boxes.extend([Box(self.h + _mul2012(x, scale), + self.v + _mul2012(y, scale), + _mul2012(a, scale), _mul2012(b, scale)) + for x, y, a, b in font._vf[char].boxes]) + + @_dispatch(137, state=_dvistate.inpage, args=('s4', 's4')) + def _put_rule(self, a, b): + self._put_rule_real(a, b) + + def _put_rule_real(self, a, b): + if a > 0 and b > 0: + self.boxes.append(Box(self.h, self.v, a, b)) + + @_dispatch(138) + def _nop(self, _): + pass + + @_dispatch(139, state=_dvistate.outer, args=('s4',)*11) + def _bop(self, c0, c1, c2, c3, c4, c5, c6, c7, c8, c9, p): + self.state = _dvistate.inpage + self.h = self.v = self.w = self.x = self.y = self.z = 0 + self.stack = [] + self.text = [] # list of Text objects + self.boxes = [] # list of Box objects + + @_dispatch(140, state=_dvistate.inpage) + def _eop(self, _): + self.state = _dvistate.outer + del self.h, self.v, self.w, self.x, self.y, self.z, self.stack + + @_dispatch(141, state=_dvistate.inpage) + def _push(self, _): + self.stack.append((self.h, self.v, self.w, self.x, self.y, self.z)) + + @_dispatch(142, state=_dvistate.inpage) + def _pop(self, _): + self.h, self.v, self.w, self.x, self.y, self.z = self.stack.pop() + + @_dispatch(min=143, max=146, state=_dvistate.inpage, args=('slen1',)) + def _right(self, b): + self.h += b + + @_dispatch(min=147, max=151, state=_dvistate.inpage, args=('slen',)) + def _right_w(self, new_w): + if new_w is not None: + self.w = new_w + self.h += self.w + + @_dispatch(min=152, max=156, state=_dvistate.inpage, args=('slen',)) + def _right_x(self, new_x): + if new_x is not None: + self.x = new_x + self.h += self.x + + @_dispatch(min=157, max=160, state=_dvistate.inpage, args=('slen1',)) + def _down(self, a): + self.v += a + + @_dispatch(min=161, max=165, state=_dvistate.inpage, args=('slen',)) + def _down_y(self, new_y): + if new_y is not None: + self.y = new_y + self.v += self.y + + @_dispatch(min=166, max=170, state=_dvistate.inpage, args=('slen',)) + def _down_z(self, new_z): + if new_z is not None: + self.z = new_z + self.v += self.z + + @_dispatch(min=171, max=234, state=_dvistate.inpage) + def _fnt_num_immediate(self, k): + self.f = k + + @_dispatch(min=235, max=238, state=_dvistate.inpage, args=('olen1',)) + def _fnt_num(self, new_f): + self.f = new_f + + @_dispatch(min=239, max=242, args=('ulen1',)) + def _xxx(self, datalen): + special = self.file.read(datalen) + _log.debug( + 'Dvi._xxx: encountered special: %s', + ''.join([chr(ch) if 32 <= ch < 127 else '<%02x>' % ch + for ch in special])) + + @_dispatch(min=243, max=246, args=('olen1', 'u4', 'u4', 'u4', 'u1', 'u1')) + def _fnt_def(self, k, c, s, d, a, l): + self._fnt_def_real(k, c, s, d, a, l) + + def _fnt_def_real(self, k, c, s, d, a, l): + n = self.file.read(a + l) + fontname = n[-l:].decode('ascii') + try: + tfm = _tfmfile(fontname) + except FileNotFoundError as exc: + # Explicitly allow defining missing fonts for Vf support; we only + # register an error when trying to load a glyph from a missing font + # and throw that error in Dvi._read. For Vf, _finalize_packet + # checks whether a missing glyph has been used, and in that case + # skips the glyph definition. + self.fonts[k] = cbook._ExceptionInfo.from_exception(exc) + return + if c != 0 and tfm.checksum != 0 and c != tfm.checksum: + raise ValueError(f'tfm checksum mismatch: {n}') + try: + vf = _vffile(fontname) + except FileNotFoundError: + vf = None + self.fonts[k] = DviFont(scale=s, tfm=tfm, texname=n, vf=vf) + + @_dispatch(247, state=_dvistate.pre, args=('u1', 'u4', 'u4', 'u4', 'u1')) + def _pre(self, i, num, den, mag, k): + self.file.read(k) # comment in the dvi file + if i != 2: + raise ValueError(f"Unknown dvi format {i}") + if num != 25400000 or den != 7227 * 2**16: + raise ValueError("Nonstandard units in dvi file") + # meaning: TeX always uses those exact values, so it + # should be enough for us to support those + # (There are 72.27 pt to an inch so 7227 pt = + # 7227 * 2**16 sp to 100 in. The numerator is multiplied + # by 10^5 to get units of 10**-7 meters.) + if mag != 1000: + raise ValueError("Nonstandard magnification in dvi file") + # meaning: LaTeX seems to frown on setting \mag, so + # I think we can assume this is constant + self.state = _dvistate.outer + + @_dispatch(248, state=_dvistate.outer) + def _post(self, _): + self.state = _dvistate.post_post + # TODO: actually read the postamble and finale? + # currently post_post just triggers closing the file + + @_dispatch(249) + def _post_post(self, _): + raise NotImplementedError + + @_dispatch(min=250, max=255) + def _malformed(self, offset): + raise ValueError(f"unknown command: byte {250 + offset}") + + +class DviFont: + """ + Encapsulation of a font that a DVI file can refer to. + + This class holds a font's texname and size, supports comparison, + and knows the widths of glyphs in the same units as the AFM file. + There are also internal attributes (for use by dviread.py) that + are *not* used for comparison. + + The size is in Adobe points (converted from TeX points). + + Parameters + ---------- + scale : float + Factor by which the font is scaled from its natural size. + tfm : Tfm + TeX font metrics for this font + texname : bytes + Name of the font as used internally by TeX and friends, as an ASCII + bytestring. This is usually very different from any external font + names; `PsfontsMap` can be used to find the external name of the font. + vf : Vf + A TeX "virtual font" file, or None if this font is not virtual. + + Attributes + ---------- + texname : bytes + size : float + Size of the font in Adobe points, converted from the slightly + smaller TeX points. + widths : list + Widths of glyphs in glyph-space units, typically 1/1000ths of + the point size. + + """ + __slots__ = ('texname', 'size', 'widths', '_scale', '_vf', '_tfm') + + def __init__(self, scale, tfm, texname, vf): + _api.check_isinstance(bytes, texname=texname) + self._scale = scale + self._tfm = tfm + self.texname = texname + self._vf = vf + self.size = scale * (72.0 / (72.27 * 2**16)) + try: + nchars = max(tfm.width) + 1 + except ValueError: + nchars = 0 + self.widths = [(1000*tfm.width.get(char, 0)) >> 20 + for char in range(nchars)] + + def __eq__(self, other): + return (type(self) is type(other) + and self.texname == other.texname and self.size == other.size) + + def __ne__(self, other): + return not self.__eq__(other) + + def __repr__(self): + return f"<{type(self).__name__}: {self.texname}>" + + def _width_of(self, char): + """Width of char in dvi units.""" + width = self._tfm.width.get(char, None) + if width is not None: + return _mul2012(width, self._scale) + _log.debug('No width for char %d in font %s.', char, self.texname) + return 0 + + def _height_depth_of(self, char): + """Height and depth of char in dvi units.""" + result = [] + for metric, name in ((self._tfm.height, "height"), + (self._tfm.depth, "depth")): + value = metric.get(char, None) + if value is None: + _log.debug('No %s for char %d in font %s', + name, char, self.texname) + result.append(0) + else: + result.append(_mul2012(value, self._scale)) + # cmsyXX (symbols font) glyph 0 ("minus") has a nonzero descent + # so that TeX aligns equations properly + # (https://tex.stackexchange.com/q/526103/) + # but we actually care about the rasterization depth to align + # the dvipng-generated images. + if re.match(br'^cmsy\d+$', self.texname) and char == 0: + result[-1] = 0 + return result + + +class Vf(Dvi): + r""" + A virtual font (\*.vf file) containing subroutines for dvi files. + + Parameters + ---------- + filename : str or path-like + + Notes + ----- + The virtual font format is a derivative of dvi: + http://mirrors.ctan.org/info/knuth/virtual-fonts + This class reuses some of the machinery of `Dvi` + but replaces the `_read` loop and dispatch mechanism. + + Examples + -------- + :: + + vf = Vf(filename) + glyph = vf[code] + glyph.text, glyph.boxes, glyph.width + """ + + def __init__(self, filename): + super().__init__(filename, 0) + try: + self._first_font = None + self._chars = {} + self._read() + finally: + self.close() + + def __getitem__(self, code): + return self._chars[code] + + def _read(self): + """ + Read one page from the file. Return True if successful, + False if there were no more pages. + """ + packet_char = packet_ends = None + packet_len = packet_width = None + while True: + byte = self.file.read(1)[0] + # If we are in a packet, execute the dvi instructions + if self.state is _dvistate.inpage: + byte_at = self.file.tell()-1 + if byte_at == packet_ends: + self._finalize_packet(packet_char, packet_width) + packet_len = packet_char = packet_width = None + # fall through to out-of-packet code + elif byte_at > packet_ends: + raise ValueError("Packet length mismatch in vf file") + else: + if byte in (139, 140) or byte >= 243: + raise ValueError(f"Inappropriate opcode {byte} in vf file") + Dvi._dtable[byte](self, byte) + continue + + # We are outside a packet + if byte < 242: # a short packet (length given by byte) + packet_len = byte + packet_char = self._read_arg(1) + packet_width = self._read_arg(3) + packet_ends = self._init_packet(byte) + self.state = _dvistate.inpage + elif byte == 242: # a long packet + packet_len = self._read_arg(4) + packet_char = self._read_arg(4) + packet_width = self._read_arg(4) + self._init_packet(packet_len) + elif 243 <= byte <= 246: + k = self._read_arg(byte - 242, byte == 246) + c = self._read_arg(4) + s = self._read_arg(4) + d = self._read_arg(4) + a = self._read_arg(1) + l = self._read_arg(1) + self._fnt_def_real(k, c, s, d, a, l) + if self._first_font is None: + self._first_font = k + elif byte == 247: # preamble + i = self._read_arg(1) + k = self._read_arg(1) + x = self.file.read(k) + cs = self._read_arg(4) + ds = self._read_arg(4) + self._pre(i, x, cs, ds) + elif byte == 248: # postamble (just some number of 248s) + break + else: + raise ValueError(f"Unknown vf opcode {byte}") + + def _init_packet(self, pl): + if self.state != _dvistate.outer: + raise ValueError("Misplaced packet in vf file") + self.h = self.v = self.w = self.x = self.y = self.z = 0 + self.stack = [] + self.text = [] + self.boxes = [] + self.f = self._first_font + self._missing_font = None + return self.file.tell() + pl + + def _finalize_packet(self, packet_char, packet_width): + if not self._missing_font: # Otherwise we don't have full glyph definition. + self._chars[packet_char] = Page( + text=self.text, boxes=self.boxes, width=packet_width, + height=None, descent=None) + self.state = _dvistate.outer + + def _pre(self, i, x, cs, ds): + if self.state is not _dvistate.pre: + raise ValueError("pre command in middle of vf file") + if i != 202: + raise ValueError(f"Unknown vf format {i}") + if len(x): + _log.debug('vf file comment: %s', x) + self.state = _dvistate.outer + # cs = checksum, ds = design size + + +def _mul2012(num1, num2): + """Multiply two numbers in 20.12 fixed point format.""" + # Separated into a function because >> has surprising precedence + return (num1*num2) >> 20 + + +class Tfm: + """ + A TeX Font Metric file. + + This implementation covers only the bare minimum needed by the Dvi class. + + Parameters + ---------- + filename : str or path-like + + Attributes + ---------- + checksum : int + Used for verifying against the dvi file. + design_size : int + Design size of the font (unknown units) + width, height, depth : dict + Dimensions of each character, need to be scaled by the factor + specified in the dvi file. These are dicts because indexing may + not start from 0. + """ + __slots__ = ('checksum', 'design_size', 'width', 'height', 'depth') + + def __init__(self, filename): + _log.debug('opening tfm file %s', filename) + with open(filename, 'rb') as file: + header1 = file.read(24) + lh, bc, ec, nw, nh, nd = struct.unpack('!6H', header1[2:14]) + _log.debug('lh=%d, bc=%d, ec=%d, nw=%d, nh=%d, nd=%d', + lh, bc, ec, nw, nh, nd) + header2 = file.read(4*lh) + self.checksum, self.design_size = struct.unpack('!2I', header2[:8]) + # there is also encoding information etc. + char_info = file.read(4*(ec-bc+1)) + widths = struct.unpack(f'!{nw}i', file.read(4*nw)) + heights = struct.unpack(f'!{nh}i', file.read(4*nh)) + depths = struct.unpack(f'!{nd}i', file.read(4*nd)) + self.width = {} + self.height = {} + self.depth = {} + for idx, char in enumerate(range(bc, ec+1)): + byte0 = char_info[4*idx] + byte1 = char_info[4*idx+1] + self.width[char] = widths[byte0] + self.height[char] = heights[byte1 >> 4] + self.depth[char] = depths[byte1 & 0xf] + + +PsFont = namedtuple('PsFont', 'texname psname effects encoding filename') + + +class PsfontsMap: + """ + A psfonts.map formatted file, mapping TeX fonts to PS fonts. + + Parameters + ---------- + filename : str or path-like + + Notes + ----- + For historical reasons, TeX knows many Type-1 fonts by different + names than the outside world. (For one thing, the names have to + fit in eight characters.) Also, TeX's native fonts are not Type-1 + but Metafont, which is nontrivial to convert to PostScript except + as a bitmap. While high-quality conversions to Type-1 format exist + and are shipped with modern TeX distributions, we need to know + which Type-1 fonts are the counterparts of which native fonts. For + these reasons a mapping is needed from internal font names to font + file names. + + A texmf tree typically includes mapping files called e.g. + :file:`psfonts.map`, :file:`pdftex.map`, or :file:`dvipdfm.map`. + The file :file:`psfonts.map` is used by :program:`dvips`, + :file:`pdftex.map` by :program:`pdfTeX`, and :file:`dvipdfm.map` + by :program:`dvipdfm`. :file:`psfonts.map` might avoid embedding + the 35 PostScript fonts (i.e., have no filename for them, as in + the Times-Bold example above), while the pdf-related files perhaps + only avoid the "Base 14" pdf fonts. But the user may have + configured these files differently. + + Examples + -------- + >>> map = PsfontsMap(find_tex_file('pdftex.map')) + >>> entry = map[b'ptmbo8r'] + >>> entry.texname + b'ptmbo8r' + >>> entry.psname + b'Times-Bold' + >>> entry.encoding + '/usr/local/texlive/2008/texmf-dist/fonts/enc/dvips/base/8r.enc' + >>> entry.effects + {'slant': 0.16700000000000001} + >>> entry.filename + """ + __slots__ = ('_filename', '_unparsed', '_parsed') + + # Create a filename -> PsfontsMap cache, so that calling + # `PsfontsMap(filename)` with the same filename a second time immediately + # returns the same object. + @lru_cache + def __new__(cls, filename): + self = object.__new__(cls) + self._filename = os.fsdecode(filename) + # Some TeX distributions have enormous pdftex.map files which would + # take hundreds of milliseconds to parse, but it is easy enough to just + # store the unparsed lines (keyed by the first word, which is the + # texname) and parse them on-demand. + with open(filename, 'rb') as file: + self._unparsed = {} + for line in file: + tfmname = line.split(b' ', 1)[0] + self._unparsed.setdefault(tfmname, []).append(line) + self._parsed = {} + return self + + def __getitem__(self, texname): + assert isinstance(texname, bytes) + if texname in self._unparsed: + for line in self._unparsed.pop(texname): + if self._parse_and_cache_line(line): + break + try: + return self._parsed[texname] + except KeyError: + raise LookupError( + f"An associated PostScript font (required by Matplotlib) " + f"could not be found for TeX font {texname.decode('ascii')!r} " + f"in {self._filename!r}; this problem can often be solved by " + f"installing a suitable PostScript font package in your TeX " + f"package manager") from None + + def _parse_and_cache_line(self, line): + """ + Parse a line in the font mapping file. + + The format is (partially) documented at + http://mirrors.ctan.org/systems/doc/pdftex/manual/pdftex-a.pdf + https://tug.org/texinfohtml/dvips.html#psfonts_002emap + Each line can have the following fields: + + - tfmname (first, only required field), + - psname (defaults to tfmname, must come immediately after tfmname if + present), + - fontflags (integer, must come immediately after psname if present, + ignored by us), + - special (SlantFont and ExtendFont, only field that is double-quoted), + - fontfile, encodingfile (optional, prefixed by <, <<, or <[; << always + precedes a font, <[ always precedes an encoding, < can precede either + but then an encoding file must have extension .enc; < and << also + request different font subsetting behaviors but we ignore that; < can + be separated from the filename by whitespace). + + special, fontfile, and encodingfile can appear in any order. + """ + # If the map file specifies multiple encodings for a font, we + # follow pdfTeX in choosing the last one specified. Such + # entries are probably mistakes but they have occurred. + # https://tex.stackexchange.com/q/10826/ + + if not line or line.startswith((b" ", b"%", b"*", b";", b"#")): + return + tfmname = basename = special = encodingfile = fontfile = None + is_subsetted = is_t1 = is_truetype = False + matches = re.finditer(br'"([^"]*)(?:"|$)|(\S+)', line) + for match in matches: + quoted, unquoted = match.groups() + if unquoted: + if unquoted.startswith(b"<<"): # font + fontfile = unquoted[2:] + elif unquoted.startswith(b"<["): # encoding + encodingfile = unquoted[2:] + elif unquoted.startswith(b"<"): # font or encoding + word = ( + # foo + unquoted[1:] + # < by itself => read the next word + or next(filter(None, next(matches).groups()))) + if word.endswith(b".enc"): + encodingfile = word + else: + fontfile = word + is_subsetted = True + elif tfmname is None: + tfmname = unquoted + elif basename is None: + basename = unquoted + elif quoted: + special = quoted + effects = {} + if special: + words = reversed(special.split()) + for word in words: + if word == b"SlantFont": + effects["slant"] = float(next(words)) + elif word == b"ExtendFont": + effects["extend"] = float(next(words)) + + # Verify some properties of the line that would cause it to be ignored + # otherwise. + if fontfile is not None: + if fontfile.endswith((b".ttf", b".ttc")): + is_truetype = True + elif not fontfile.endswith(b".otf"): + is_t1 = True + elif basename is not None: + is_t1 = True + if is_truetype and is_subsetted and encodingfile is None: + return + if not is_t1 and ("slant" in effects or "extend" in effects): + return + if abs(effects.get("slant", 0)) > 1: + return + if abs(effects.get("extend", 0)) > 2: + return + + if basename is None: + basename = tfmname + if encodingfile is not None: + encodingfile = find_tex_file(encodingfile) + if fontfile is not None: + fontfile = find_tex_file(fontfile) + self._parsed[tfmname] = PsFont( + texname=tfmname, psname=basename, effects=effects, + encoding=encodingfile, filename=fontfile) + return True + + +def _parse_enc(path): + r""" + Parse a \*.enc file referenced from a psfonts.map style file. + + The format supported by this function is a tiny subset of PostScript. + + Parameters + ---------- + path : `os.PathLike` + + Returns + ------- + list + The nth entry of the list is the PostScript glyph name of the nth + glyph. + """ + no_comments = re.sub("%.*", "", Path(path).read_text(encoding="ascii")) + array = re.search(r"(?s)\[(.*)\]", no_comments).group(1) + lines = [line for line in array.split() if line] + if all(line.startswith("/") for line in lines): + return [line[1:] for line in lines] + else: + raise ValueError(f"Failed to parse {path} as Postscript encoding") + + +class _LuatexKpsewhich: + @lru_cache # A singleton. + def __new__(cls): + self = object.__new__(cls) + self._proc = self._new_proc() + return self + + def _new_proc(self): + return subprocess.Popen( + ["luatex", "--luaonly", + str(cbook._get_data_path("kpsewhich.lua"))], + stdin=subprocess.PIPE, stdout=subprocess.PIPE) + + def search(self, filename): + if self._proc.poll() is not None: # Dead, restart it. + self._proc = self._new_proc() + self._proc.stdin.write(os.fsencode(filename) + b"\n") + self._proc.stdin.flush() + out = self._proc.stdout.readline().rstrip() + return None if out == b"nil" else os.fsdecode(out) + + +@lru_cache +def find_tex_file(filename): + """ + Find a file in the texmf tree using kpathsea_. + + The kpathsea library, provided by most existing TeX distributions, both + on Unix-like systems and on Windows (MikTeX), is invoked via a long-lived + luatex process if luatex is installed, or via kpsewhich otherwise. + + .. _kpathsea: https://www.tug.org/kpathsea/ + + Parameters + ---------- + filename : str or path-like + + Raises + ------ + FileNotFoundError + If the file is not found. + """ + + # we expect these to always be ascii encoded, but use utf-8 + # out of caution + if isinstance(filename, bytes): + filename = filename.decode('utf-8', errors='replace') + + try: + lk = _LuatexKpsewhich() + except FileNotFoundError: + lk = None # Fallback to directly calling kpsewhich, as below. + + if lk: + path = lk.search(filename) + else: + if sys.platform == 'win32': + # On Windows only, kpathsea can use utf-8 for cmd args and output. + # The `command_line_encoding` environment variable is set to force + # it to always use utf-8 encoding. See Matplotlib issue #11848. + kwargs = {'env': {**os.environ, 'command_line_encoding': 'utf-8'}, + 'encoding': 'utf-8'} + else: # On POSIX, run through the equivalent of os.fsdecode(). + kwargs = {'encoding': sys.getfilesystemencoding(), + 'errors': 'surrogateescape'} + + try: + path = (cbook._check_and_log_subprocess(['kpsewhich', filename], + _log, **kwargs) + .rstrip('\n')) + except (FileNotFoundError, RuntimeError): + path = None + + if path: + return path + else: + raise FileNotFoundError( + f"Matplotlib's TeX implementation searched for a file named " + f"{filename!r} in your texmf tree, but could not find it") + + +@lru_cache +def _fontfile(cls, suffix, texname): + return cls(find_tex_file(texname + suffix)) + + +_tfmfile = partial(_fontfile, Tfm, ".tfm") +_vffile = partial(_fontfile, Vf, ".vf") + + +if __name__ == '__main__': + from argparse import ArgumentParser + import itertools + + parser = ArgumentParser() + parser.add_argument("filename") + parser.add_argument("dpi", nargs="?", type=float, default=None) + args = parser.parse_args() + with Dvi(args.filename, args.dpi) as dvi: + fontmap = PsfontsMap(find_tex_file('pdftex.map')) + for page in dvi: + print(f"=== new page === " + f"(w: {page.width}, h: {page.height}, d: {page.descent})") + for font, group in itertools.groupby( + page.text, lambda text: text.font): + print(f"font: {font.texname.decode('latin-1')!r}\t" + f"scale: {font._scale / 2 ** 20}") + print("x", "y", "glyph", "chr", "w", "(glyphs)", sep="\t") + for text in group: + print(text.x, text.y, text.glyph, + chr(text.glyph) if chr(text.glyph).isprintable() + else ".", + text.width, sep="\t") + if page.boxes: + print("x", "y", "h", "w", "", "(boxes)", sep="\t") + for box in page.boxes: + print(box.x, box.y, box.height, box.width, sep="\t") diff --git a/infer_4_30_0/lib/python3.10/site-packages/matplotlib/figure.py b/infer_4_30_0/lib/python3.10/site-packages/matplotlib/figure.py new file mode 100644 index 0000000000000000000000000000000000000000..3d6f9a7f4c1617aa8af106bc0123128ec77cb448 --- /dev/null +++ b/infer_4_30_0/lib/python3.10/site-packages/matplotlib/figure.py @@ -0,0 +1,3726 @@ +""" +`matplotlib.figure` implements the following classes: + +`Figure` + Top level `~matplotlib.artist.Artist`, which holds all plot elements. + Many methods are implemented in `FigureBase`. + +`SubFigure` + A logical figure inside a figure, usually added to a figure (or parent `SubFigure`) + with `Figure.add_subfigure` or `Figure.subfigures` methods. + +Figures are typically created using pyplot methods `~.pyplot.figure`, +`~.pyplot.subplots`, and `~.pyplot.subplot_mosaic`. + +.. plot:: + :include-source: + + fig, ax = plt.subplots(figsize=(2, 2), facecolor='lightskyblue', + layout='constrained') + fig.suptitle('Figure') + ax.set_title('Axes', loc='left', fontstyle='oblique', fontsize='medium') + +Some situations call for directly instantiating a `~.figure.Figure` class, +usually inside an application of some sort (see :ref:`user_interfaces` for a +list of examples) . More information about Figures can be found at +:ref:`figure-intro`. +""" + +from contextlib import ExitStack +import inspect +import itertools +import functools +import logging +from numbers import Integral +import threading + +import numpy as np + +import matplotlib as mpl +from matplotlib import _blocking_input, backend_bases, _docstring, projections +from matplotlib.artist import ( + Artist, allow_rasterization, _finalize_rasterization) +from matplotlib.backend_bases import ( + DrawEvent, FigureCanvasBase, NonGuiException, MouseButton, _get_renderer) +import matplotlib._api as _api +import matplotlib.cbook as cbook +import matplotlib.colorbar as cbar +import matplotlib.image as mimage + +from matplotlib.axes import Axes +from matplotlib.gridspec import GridSpec, SubplotParams +from matplotlib.layout_engine import ( + ConstrainedLayoutEngine, TightLayoutEngine, LayoutEngine, + PlaceHolderLayoutEngine +) +import matplotlib.legend as mlegend +from matplotlib.patches import Rectangle +from matplotlib.text import Text +from matplotlib.transforms import (Affine2D, Bbox, BboxTransformTo, + TransformedBbox) + +_log = logging.getLogger(__name__) + + +def _stale_figure_callback(self, val): + if (fig := self.get_figure(root=False)) is not None: + fig.stale = val + + +class _AxesStack: + """ + Helper class to track Axes in a figure. + + Axes are tracked both in the order in which they have been added + (``self._axes`` insertion/iteration order) and in the separate "gca" stack + (which is the index to which they map in the ``self._axes`` dict). + """ + + def __init__(self): + self._axes = {} # Mapping of Axes to "gca" order. + self._counter = itertools.count() + + def as_list(self): + """List the Axes that have been added to the figure.""" + return [*self._axes] # This relies on dict preserving order. + + def remove(self, a): + """Remove the Axes from the stack.""" + self._axes.pop(a) + + def bubble(self, a): + """Move an Axes, which must already exist in the stack, to the top.""" + if a not in self._axes: + raise ValueError("Axes has not been added yet") + self._axes[a] = next(self._counter) + + def add(self, a): + """Add an Axes to the stack, ignoring it if already present.""" + if a not in self._axes: + self._axes[a] = next(self._counter) + + def current(self): + """Return the active Axes, or None if the stack is empty.""" + return max(self._axes, key=self._axes.__getitem__, default=None) + + def __getstate__(self): + return { + **vars(self), + "_counter": max(self._axes.values(), default=0) + } + + def __setstate__(self, state): + next_counter = state.pop('_counter') + vars(self).update(state) + self._counter = itertools.count(next_counter) + + +class FigureBase(Artist): + """ + Base class for `.Figure` and `.SubFigure` containing the methods that add + artists to the figure or subfigure, create Axes, etc. + """ + def __init__(self, **kwargs): + super().__init__() + # remove the non-figure artist _axes property + # as it makes no sense for a figure to be _in_ an Axes + # this is used by the property methods in the artist base class + # which are over-ridden in this class + del self._axes + + self._suptitle = None + self._supxlabel = None + self._supylabel = None + + # groupers to keep track of x, y labels and title we want to align. + # see self.align_xlabels, self.align_ylabels, + # self.align_titles, and axis._get_tick_boxes_siblings + self._align_label_groups = { + "x": cbook.Grouper(), + "y": cbook.Grouper(), + "title": cbook.Grouper() + } + + self._localaxes = [] # track all Axes + self.artists = [] + self.lines = [] + self.patches = [] + self.texts = [] + self.images = [] + self.legends = [] + self.subfigs = [] + self.stale = True + self.suppressComposite = None + self.set(**kwargs) + + def _get_draw_artists(self, renderer): + """Also runs apply_aspect""" + artists = self.get_children() + + artists.remove(self.patch) + artists = sorted( + (artist for artist in artists if not artist.get_animated()), + key=lambda artist: artist.get_zorder()) + for ax in self._localaxes: + locator = ax.get_axes_locator() + ax.apply_aspect(locator(ax, renderer) if locator else None) + + for child in ax.get_children(): + if hasattr(child, 'apply_aspect'): + locator = child.get_axes_locator() + child.apply_aspect( + locator(child, renderer) if locator else None) + return artists + + def autofmt_xdate( + self, bottom=0.2, rotation=30, ha='right', which='major'): + """ + Date ticklabels often overlap, so it is useful to rotate them + and right align them. Also, a common use case is a number of + subplots with shared x-axis where the x-axis is date data. The + ticklabels are often long, and it helps to rotate them on the + bottom subplot and turn them off on other subplots, as well as + turn off xlabels. + + Parameters + ---------- + bottom : float, default: 0.2 + The bottom of the subplots for `subplots_adjust`. + rotation : float, default: 30 degrees + The rotation angle of the xtick labels in degrees. + ha : {'left', 'center', 'right'}, default: 'right' + The horizontal alignment of the xticklabels. + which : {'major', 'minor', 'both'}, default: 'major' + Selects which ticklabels to rotate. + """ + _api.check_in_list(['major', 'minor', 'both'], which=which) + axes = [ax for ax in self.axes if ax._label != ''] + allsubplots = all(ax.get_subplotspec() for ax in axes) + if len(axes) == 1: + for label in self.axes[0].get_xticklabels(which=which): + label.set_ha(ha) + label.set_rotation(rotation) + else: + if allsubplots: + for ax in axes: + if ax.get_subplotspec().is_last_row(): + for label in ax.get_xticklabels(which=which): + label.set_ha(ha) + label.set_rotation(rotation) + else: + for label in ax.get_xticklabels(which=which): + label.set_visible(False) + ax.set_xlabel('') + + engine = self.get_layout_engine() + if allsubplots and (engine is None or engine.adjust_compatible): + self.subplots_adjust(bottom=bottom) + self.stale = True + + def get_children(self): + """Get a list of artists contained in the figure.""" + return [self.patch, + *self.artists, + *self._localaxes, + *self.lines, + *self.patches, + *self.texts, + *self.images, + *self.legends, + *self.subfigs] + + def get_figure(self, root=None): + """ + Return the `.Figure` or `.SubFigure` instance the (Sub)Figure belongs to. + + Parameters + ---------- + root : bool, default=True + If False, return the (Sub)Figure this artist is on. If True, + return the root Figure for a nested tree of SubFigures. + + .. deprecated:: 3.10 + + From version 3.12 *root* will default to False. + """ + if self._root_figure is self: + # Top level Figure + return self + + if self._parent is self._root_figure: + # Return early to prevent the deprecation warning when *root* does not + # matter + return self._parent + + if root is None: + # When deprecation expires, consider removing the docstring and just + # inheriting the one from Artist. + message = ('From Matplotlib 3.12 SubFigure.get_figure will by default ' + 'return the direct parent figure, which may be a SubFigure. ' + 'To suppress this warning, pass the root parameter. Pass ' + '`True` to maintain the old behavior and `False` to opt-in to ' + 'the future behavior.') + _api.warn_deprecated('3.10', message=message) + root = True + + if root: + return self._root_figure + + return self._parent + + def set_figure(self, fig): + """ + .. deprecated:: 3.10 + Currently this method will raise an exception if *fig* is anything other + than the root `.Figure` this (Sub)Figure is on. In future it will always + raise an exception. + """ + no_switch = ("The parent and root figures of a (Sub)Figure are set at " + "instantiation and cannot be changed.") + if fig is self._root_figure: + _api.warn_deprecated( + "3.10", + message=(f"{no_switch} From Matplotlib 3.12 this operation will raise " + "an exception.")) + return + + raise ValueError(no_switch) + + figure = property(functools.partial(get_figure, root=True), set_figure, + doc=("The root `Figure`. To get the parent of a `SubFigure`, " + "use the `get_figure` method.")) + + def contains(self, mouseevent): + """ + Test whether the mouse event occurred on the figure. + + Returns + ------- + bool, {} + """ + if self._different_canvas(mouseevent): + return False, {} + inside = self.bbox.contains(mouseevent.x, mouseevent.y) + return inside, {} + + def get_window_extent(self, renderer=None): + # docstring inherited + return self.bbox + + def _suplabels(self, t, info, **kwargs): + """ + Add a centered %(name)s to the figure. + + Parameters + ---------- + t : str + The %(name)s text. + x : float, default: %(x0)s + The x location of the text in figure coordinates. + y : float, default: %(y0)s + The y location of the text in figure coordinates. + horizontalalignment, ha : {'center', 'left', 'right'}, default: %(ha)s + The horizontal alignment of the text relative to (*x*, *y*). + verticalalignment, va : {'top', 'center', 'bottom', 'baseline'}, \ +default: %(va)s + The vertical alignment of the text relative to (*x*, *y*). + fontsize, size : default: :rc:`figure.%(rc)ssize` + The font size of the text. See `.Text.set_size` for possible + values. + fontweight, weight : default: :rc:`figure.%(rc)sweight` + The font weight of the text. See `.Text.set_weight` for possible + values. + + Returns + ------- + text + The `.Text` instance of the %(name)s. + + Other Parameters + ---------------- + fontproperties : None or dict, optional + A dict of font properties. If *fontproperties* is given the + default values for font size and weight are taken from the + `.FontProperties` defaults. :rc:`figure.%(rc)ssize` and + :rc:`figure.%(rc)sweight` are ignored in this case. + + **kwargs + Additional kwargs are `matplotlib.text.Text` properties. + """ + + x = kwargs.pop('x', None) + y = kwargs.pop('y', None) + if info['name'] in ['_supxlabel', '_suptitle']: + autopos = y is None + elif info['name'] == '_supylabel': + autopos = x is None + if x is None: + x = info['x0'] + if y is None: + y = info['y0'] + + kwargs = cbook.normalize_kwargs(kwargs, Text) + kwargs.setdefault('horizontalalignment', info['ha']) + kwargs.setdefault('verticalalignment', info['va']) + kwargs.setdefault('rotation', info['rotation']) + + if 'fontproperties' not in kwargs: + kwargs.setdefault('fontsize', mpl.rcParams[info['size']]) + kwargs.setdefault('fontweight', mpl.rcParams[info['weight']]) + + suplab = getattr(self, info['name']) + if suplab is not None: + suplab.set_text(t) + suplab.set_position((x, y)) + suplab.set(**kwargs) + else: + suplab = self.text(x, y, t, **kwargs) + setattr(self, info['name'], suplab) + suplab._autopos = autopos + self.stale = True + return suplab + + @_docstring.Substitution(x0=0.5, y0=0.98, name='super title', ha='center', + va='top', rc='title') + @_docstring.copy(_suplabels) + def suptitle(self, t, **kwargs): + # docstring from _suplabels... + info = {'name': '_suptitle', 'x0': 0.5, 'y0': 0.98, + 'ha': 'center', 'va': 'top', 'rotation': 0, + 'size': 'figure.titlesize', 'weight': 'figure.titleweight'} + return self._suplabels(t, info, **kwargs) + + def get_suptitle(self): + """Return the suptitle as string or an empty string if not set.""" + text_obj = self._suptitle + return "" if text_obj is None else text_obj.get_text() + + @_docstring.Substitution(x0=0.5, y0=0.01, name='super xlabel', ha='center', + va='bottom', rc='label') + @_docstring.copy(_suplabels) + def supxlabel(self, t, **kwargs): + # docstring from _suplabels... + info = {'name': '_supxlabel', 'x0': 0.5, 'y0': 0.01, + 'ha': 'center', 'va': 'bottom', 'rotation': 0, + 'size': 'figure.labelsize', 'weight': 'figure.labelweight'} + return self._suplabels(t, info, **kwargs) + + def get_supxlabel(self): + """Return the supxlabel as string or an empty string if not set.""" + text_obj = self._supxlabel + return "" if text_obj is None else text_obj.get_text() + + @_docstring.Substitution(x0=0.02, y0=0.5, name='super ylabel', ha='left', + va='center', rc='label') + @_docstring.copy(_suplabels) + def supylabel(self, t, **kwargs): + # docstring from _suplabels... + info = {'name': '_supylabel', 'x0': 0.02, 'y0': 0.5, + 'ha': 'left', 'va': 'center', 'rotation': 'vertical', + 'rotation_mode': 'anchor', 'size': 'figure.labelsize', + 'weight': 'figure.labelweight'} + return self._suplabels(t, info, **kwargs) + + def get_supylabel(self): + """Return the supylabel as string or an empty string if not set.""" + text_obj = self._supylabel + return "" if text_obj is None else text_obj.get_text() + + def get_edgecolor(self): + """Get the edge color of the Figure rectangle.""" + return self.patch.get_edgecolor() + + def get_facecolor(self): + """Get the face color of the Figure rectangle.""" + return self.patch.get_facecolor() + + def get_frameon(self): + """ + Return the figure's background patch visibility, i.e. + whether the figure background will be drawn. Equivalent to + ``Figure.patch.get_visible()``. + """ + return self.patch.get_visible() + + def set_linewidth(self, linewidth): + """ + Set the line width of the Figure rectangle. + + Parameters + ---------- + linewidth : number + """ + self.patch.set_linewidth(linewidth) + + def get_linewidth(self): + """ + Get the line width of the Figure rectangle. + """ + return self.patch.get_linewidth() + + def set_edgecolor(self, color): + """ + Set the edge color of the Figure rectangle. + + Parameters + ---------- + color : :mpltype:`color` + """ + self.patch.set_edgecolor(color) + + def set_facecolor(self, color): + """ + Set the face color of the Figure rectangle. + + Parameters + ---------- + color : :mpltype:`color` + """ + self.patch.set_facecolor(color) + + def set_frameon(self, b): + """ + Set the figure's background patch visibility, i.e. + whether the figure background will be drawn. Equivalent to + ``Figure.patch.set_visible()``. + + Parameters + ---------- + b : bool + """ + self.patch.set_visible(b) + self.stale = True + + frameon = property(get_frameon, set_frameon) + + def add_artist(self, artist, clip=False): + """ + Add an `.Artist` to the figure. + + Usually artists are added to `~.axes.Axes` objects using + `.Axes.add_artist`; this method can be used in the rare cases where + one needs to add artists directly to the figure instead. + + Parameters + ---------- + artist : `~matplotlib.artist.Artist` + The artist to add to the figure. If the added artist has no + transform previously set, its transform will be set to + ``figure.transSubfigure``. + clip : bool, default: False + Whether the added artist should be clipped by the figure patch. + + Returns + ------- + `~matplotlib.artist.Artist` + The added artist. + """ + artist.set_figure(self) + self.artists.append(artist) + artist._remove_method = self.artists.remove + + if not artist.is_transform_set(): + artist.set_transform(self.transSubfigure) + + if clip and artist.get_clip_path() is None: + artist.set_clip_path(self.patch) + + self.stale = True + return artist + + @_docstring.interpd + def add_axes(self, *args, **kwargs): + """ + Add an `~.axes.Axes` to the figure. + + Call signatures:: + + add_axes(rect, projection=None, polar=False, **kwargs) + add_axes(ax) + + Parameters + ---------- + rect : tuple (left, bottom, width, height) + The dimensions (left, bottom, width, height) of the new + `~.axes.Axes`. All quantities are in fractions of figure width and + height. + + projection : {None, 'aitoff', 'hammer', 'lambert', 'mollweide', \ +'polar', 'rectilinear', str}, optional + The projection type of the `~.axes.Axes`. *str* is the name of + a custom projection, see `~matplotlib.projections`. The default + None results in a 'rectilinear' projection. + + polar : bool, default: False + If True, equivalent to projection='polar'. + + axes_class : subclass type of `~.axes.Axes`, optional + The `.axes.Axes` subclass that is instantiated. This parameter + is incompatible with *projection* and *polar*. See + :ref:`axisartist_users-guide-index` for examples. + + sharex, sharey : `~matplotlib.axes.Axes`, optional + Share the x or y `~matplotlib.axis` with sharex and/or sharey. + The axis will have the same limits, ticks, and scale as the axis + of the shared Axes. + + label : str + A label for the returned Axes. + + Returns + ------- + `~.axes.Axes`, or a subclass of `~.axes.Axes` + The returned Axes class depends on the projection used. It is + `~.axes.Axes` if rectilinear projection is used and + `.projections.polar.PolarAxes` if polar projection is used. + + Other Parameters + ---------------- + **kwargs + This method also takes the keyword arguments for + the returned Axes class. The keyword arguments for the + rectilinear Axes class `~.axes.Axes` can be found in + the following table but there might also be other keyword + arguments if another projection is used, see the actual Axes + class. + + %(Axes:kwdoc)s + + Notes + ----- + In rare circumstances, `.add_axes` may be called with a single + argument, an Axes instance already created in the present figure but + not in the figure's list of Axes. + + See Also + -------- + .Figure.add_subplot + .pyplot.subplot + .pyplot.axes + .Figure.subplots + .pyplot.subplots + + Examples + -------- + Some simple examples:: + + rect = l, b, w, h + fig = plt.figure() + fig.add_axes(rect) + fig.add_axes(rect, frameon=False, facecolor='g') + fig.add_axes(rect, polar=True) + ax = fig.add_axes(rect, projection='polar') + fig.delaxes(ax) + fig.add_axes(ax) + """ + + if not len(args) and 'rect' not in kwargs: + raise TypeError("add_axes() missing 1 required positional argument: 'rect'") + elif 'rect' in kwargs: + if len(args): + raise TypeError("add_axes() got multiple values for argument 'rect'") + args = (kwargs.pop('rect'), ) + if len(args) != 1: + raise _api.nargs_error("add_axes", 1, len(args)) + + if isinstance(args[0], Axes): + a, = args + key = a._projection_init + if a.get_figure(root=False) is not self: + raise ValueError( + "The Axes must have been created in the present figure") + else: + rect, = args + if not np.isfinite(rect).all(): + raise ValueError(f'all entries in rect must be finite not {rect}') + projection_class, pkw = self._process_projection_requirements(**kwargs) + + # create the new Axes using the Axes class given + a = projection_class(self, rect, **pkw) + key = (projection_class, pkw) + + return self._add_axes_internal(a, key) + + @_docstring.interpd + def add_subplot(self, *args, **kwargs): + """ + Add an `~.axes.Axes` to the figure as part of a subplot arrangement. + + Call signatures:: + + add_subplot(nrows, ncols, index, **kwargs) + add_subplot(pos, **kwargs) + add_subplot(ax) + add_subplot() + + Parameters + ---------- + *args : int, (int, int, *index*), or `.SubplotSpec`, default: (1, 1, 1) + The position of the subplot described by one of + + - Three integers (*nrows*, *ncols*, *index*). The subplot will + take the *index* position on a grid with *nrows* rows and + *ncols* columns. *index* starts at 1 in the upper left corner + and increases to the right. *index* can also be a two-tuple + specifying the (*first*, *last*) indices (1-based, and including + *last*) of the subplot, e.g., ``fig.add_subplot(3, 1, (1, 2))`` + makes a subplot that spans the upper 2/3 of the figure. + - A 3-digit integer. The digits are interpreted as if given + separately as three single-digit integers, i.e. + ``fig.add_subplot(235)`` is the same as + ``fig.add_subplot(2, 3, 5)``. Note that this can only be used + if there are no more than 9 subplots. + - A `.SubplotSpec`. + + In rare circumstances, `.add_subplot` may be called with a single + argument, a subplot Axes instance already created in the + present figure but not in the figure's list of Axes. + + projection : {None, 'aitoff', 'hammer', 'lambert', 'mollweide', \ +'polar', 'rectilinear', str}, optional + The projection type of the subplot (`~.axes.Axes`). *str* is the + name of a custom projection, see `~matplotlib.projections`. The + default None results in a 'rectilinear' projection. + + polar : bool, default: False + If True, equivalent to projection='polar'. + + axes_class : subclass type of `~.axes.Axes`, optional + The `.axes.Axes` subclass that is instantiated. This parameter + is incompatible with *projection* and *polar*. See + :ref:`axisartist_users-guide-index` for examples. + + sharex, sharey : `~matplotlib.axes.Axes`, optional + Share the x or y `~matplotlib.axis` with sharex and/or sharey. + The axis will have the same limits, ticks, and scale as the axis + of the shared Axes. + + label : str + A label for the returned Axes. + + Returns + ------- + `~.axes.Axes` + + The Axes of the subplot. The returned Axes can actually be an + instance of a subclass, such as `.projections.polar.PolarAxes` for + polar projections. + + Other Parameters + ---------------- + **kwargs + This method also takes the keyword arguments for the returned Axes + base class; except for the *figure* argument. The keyword arguments + for the rectilinear base class `~.axes.Axes` can be found in + the following table but there might also be other keyword + arguments if another projection is used. + + %(Axes:kwdoc)s + + See Also + -------- + .Figure.add_axes + .pyplot.subplot + .pyplot.axes + .Figure.subplots + .pyplot.subplots + + Examples + -------- + :: + + fig = plt.figure() + + fig.add_subplot(231) + ax1 = fig.add_subplot(2, 3, 1) # equivalent but more general + + fig.add_subplot(232, frameon=False) # subplot with no frame + fig.add_subplot(233, projection='polar') # polar subplot + fig.add_subplot(234, sharex=ax1) # subplot sharing x-axis with ax1 + fig.add_subplot(235, facecolor="red") # red subplot + + ax1.remove() # delete ax1 from the figure + fig.add_subplot(ax1) # add ax1 back to the figure + """ + if 'figure' in kwargs: + # Axes itself allows for a 'figure' kwarg, but since we want to + # bind the created Axes to self, it is not allowed here. + raise _api.kwarg_error("add_subplot", "figure") + + if (len(args) == 1 + and isinstance(args[0], mpl.axes._base._AxesBase) + and args[0].get_subplotspec()): + ax = args[0] + key = ax._projection_init + if ax.get_figure(root=False) is not self: + raise ValueError("The Axes must have been created in " + "the present figure") + else: + if not args: + args = (1, 1, 1) + # Normalize correct ijk values to (i, j, k) here so that + # add_subplot(211) == add_subplot(2, 1, 1). Invalid values will + # trigger errors later (via SubplotSpec._from_subplot_args). + if (len(args) == 1 and isinstance(args[0], Integral) + and 100 <= args[0] <= 999): + args = tuple(map(int, str(args[0]))) + projection_class, pkw = self._process_projection_requirements(**kwargs) + ax = projection_class(self, *args, **pkw) + key = (projection_class, pkw) + return self._add_axes_internal(ax, key) + + def _add_axes_internal(self, ax, key): + """Private helper for `add_axes` and `add_subplot`.""" + self._axstack.add(ax) + if ax not in self._localaxes: + self._localaxes.append(ax) + self.sca(ax) + ax._remove_method = self.delaxes + # this is to support plt.subplot's re-selection logic + ax._projection_init = key + self.stale = True + ax.stale_callback = _stale_figure_callback + return ax + + def subplots(self, nrows=1, ncols=1, *, sharex=False, sharey=False, + squeeze=True, width_ratios=None, height_ratios=None, + subplot_kw=None, gridspec_kw=None): + """ + Add a set of subplots to this figure. + + This utility wrapper makes it convenient to create common layouts of + subplots in a single call. + + Parameters + ---------- + nrows, ncols : int, default: 1 + Number of rows/columns of the subplot grid. + + sharex, sharey : bool or {'none', 'all', 'row', 'col'}, default: False + Controls sharing of x-axis (*sharex*) or y-axis (*sharey*): + + - True or 'all': x- or y-axis will be shared among all subplots. + - False or 'none': each subplot x- or y-axis will be independent. + - 'row': each subplot row will share an x- or y-axis. + - 'col': each subplot column will share an x- or y-axis. + + When subplots have a shared x-axis along a column, only the x tick + labels of the bottom subplot are created. Similarly, when subplots + have a shared y-axis along a row, only the y tick labels of the + first column subplot are created. To later turn other subplots' + ticklabels on, use `~matplotlib.axes.Axes.tick_params`. + + When subplots have a shared axis that has units, calling + `.Axis.set_units` will update each axis with the new units. + + Note that it is not possible to unshare axes. + + squeeze : bool, default: True + - If True, extra dimensions are squeezed out from the returned + array of Axes: + + - if only one subplot is constructed (nrows=ncols=1), the + resulting single Axes object is returned as a scalar. + - for Nx1 or 1xM subplots, the returned object is a 1D numpy + object array of Axes objects. + - for NxM, subplots with N>1 and M>1 are returned as a 2D array. + + - If False, no squeezing at all is done: the returned Axes object + is always a 2D array containing Axes instances, even if it ends + up being 1x1. + + width_ratios : array-like of length *ncols*, optional + Defines the relative widths of the columns. Each column gets a + relative width of ``width_ratios[i] / sum(width_ratios)``. + If not given, all columns will have the same width. Equivalent + to ``gridspec_kw={'width_ratios': [...]}``. + + height_ratios : array-like of length *nrows*, optional + Defines the relative heights of the rows. Each row gets a + relative height of ``height_ratios[i] / sum(height_ratios)``. + If not given, all rows will have the same height. Equivalent + to ``gridspec_kw={'height_ratios': [...]}``. + + subplot_kw : dict, optional + Dict with keywords passed to the `.Figure.add_subplot` call used to + create each subplot. + + gridspec_kw : dict, optional + Dict with keywords passed to the + `~matplotlib.gridspec.GridSpec` constructor used to create + the grid the subplots are placed on. + + Returns + ------- + `~.axes.Axes` or array of Axes + Either a single `~matplotlib.axes.Axes` object or an array of Axes + objects if more than one subplot was created. The dimensions of the + resulting array can be controlled with the *squeeze* keyword, see + above. + + See Also + -------- + .pyplot.subplots + .Figure.add_subplot + .pyplot.subplot + + Examples + -------- + :: + + # First create some toy data: + x = np.linspace(0, 2*np.pi, 400) + y = np.sin(x**2) + + # Create a figure + fig = plt.figure() + + # Create a subplot + ax = fig.subplots() + ax.plot(x, y) + ax.set_title('Simple plot') + + # Create two subplots and unpack the output array immediately + ax1, ax2 = fig.subplots(1, 2, sharey=True) + ax1.plot(x, y) + ax1.set_title('Sharing Y axis') + ax2.scatter(x, y) + + # Create four polar Axes and access them through the returned array + axes = fig.subplots(2, 2, subplot_kw=dict(projection='polar')) + axes[0, 0].plot(x, y) + axes[1, 1].scatter(x, y) + + # Share an X-axis with each column of subplots + fig.subplots(2, 2, sharex='col') + + # Share a Y-axis with each row of subplots + fig.subplots(2, 2, sharey='row') + + # Share both X- and Y-axes with all subplots + fig.subplots(2, 2, sharex='all', sharey='all') + + # Note that this is the same as + fig.subplots(2, 2, sharex=True, sharey=True) + """ + gridspec_kw = dict(gridspec_kw or {}) + if height_ratios is not None: + if 'height_ratios' in gridspec_kw: + raise ValueError("'height_ratios' must not be defined both as " + "parameter and as key in 'gridspec_kw'") + gridspec_kw['height_ratios'] = height_ratios + if width_ratios is not None: + if 'width_ratios' in gridspec_kw: + raise ValueError("'width_ratios' must not be defined both as " + "parameter and as key in 'gridspec_kw'") + gridspec_kw['width_ratios'] = width_ratios + + gs = self.add_gridspec(nrows, ncols, figure=self, **gridspec_kw) + axs = gs.subplots(sharex=sharex, sharey=sharey, squeeze=squeeze, + subplot_kw=subplot_kw) + return axs + + def delaxes(self, ax): + """ + Remove the `~.axes.Axes` *ax* from the figure; update the current Axes. + """ + self._remove_axes(ax, owners=[self._axstack, self._localaxes]) + + def _remove_axes(self, ax, owners): + """ + Common helper for removal of standard Axes (via delaxes) and of child Axes. + + Parameters + ---------- + ax : `~.AxesBase` + The Axes to remove. + owners + List of objects (list or _AxesStack) "owning" the Axes, from which the Axes + will be remove()d. + """ + for owner in owners: + owner.remove(ax) + + self._axobservers.process("_axes_change_event", self) + self.stale = True + self._root_figure.canvas.release_mouse(ax) + + for name in ax._axis_names: # Break link between any shared Axes + grouper = ax._shared_axes[name] + siblings = [other for other in grouper.get_siblings(ax) if other is not ax] + if not siblings: # Axes was not shared along this axis; we're done. + continue + grouper.remove(ax) + # Formatters and locators may previously have been associated with the now + # removed axis. Update them to point to an axis still there (we can pick + # any of them, and use the first sibling). + remaining_axis = siblings[0]._axis_map[name] + remaining_axis.get_major_formatter().set_axis(remaining_axis) + remaining_axis.get_major_locator().set_axis(remaining_axis) + remaining_axis.get_minor_formatter().set_axis(remaining_axis) + remaining_axis.get_minor_locator().set_axis(remaining_axis) + + ax._twinned_axes.remove(ax) # Break link between any twinned Axes. + + def clear(self, keep_observers=False): + """ + Clear the figure. + + Parameters + ---------- + keep_observers : bool, default: False + Set *keep_observers* to True if, for example, + a gui widget is tracking the Axes in the figure. + """ + self.suppressComposite = None + + # first clear the Axes in any subfigures + for subfig in self.subfigs: + subfig.clear(keep_observers=keep_observers) + self.subfigs = [] + + for ax in tuple(self.axes): # Iterate over the copy. + ax.clear() + self.delaxes(ax) # Remove ax from self._axstack. + + self.artists = [] + self.lines = [] + self.patches = [] + self.texts = [] + self.images = [] + self.legends = [] + if not keep_observers: + self._axobservers = cbook.CallbackRegistry() + self._suptitle = None + self._supxlabel = None + self._supylabel = None + + self.stale = True + + # synonym for `clear`. + def clf(self, keep_observers=False): + """ + [*Discouraged*] Alias for the `clear()` method. + + .. admonition:: Discouraged + + The use of ``clf()`` is discouraged. Use ``clear()`` instead. + + Parameters + ---------- + keep_observers : bool, default: False + Set *keep_observers* to True if, for example, + a gui widget is tracking the Axes in the figure. + """ + return self.clear(keep_observers=keep_observers) + + # Note: the docstring below is modified with replace for the pyplot + # version of this function because the method name differs (plt.figlegend) + # the replacements are: + # " legend(" -> " figlegend(" for the signatures + # "fig.legend(" -> "plt.figlegend" for the code examples + # "ax.plot" -> "plt.plot" for consistency in using pyplot when able + @_docstring.interpd + def legend(self, *args, **kwargs): + """ + Place a legend on the figure. + + Call signatures:: + + legend() + legend(handles, labels) + legend(handles=handles) + legend(labels) + + The call signatures correspond to the following different ways to use + this method: + + **1. Automatic detection of elements to be shown in the legend** + + The elements to be added to the legend are automatically determined, + when you do not pass in any extra arguments. + + In this case, the labels are taken from the artist. You can specify + them either at artist creation or by calling the + :meth:`~.Artist.set_label` method on the artist:: + + ax.plot([1, 2, 3], label='Inline label') + fig.legend() + + or:: + + line, = ax.plot([1, 2, 3]) + line.set_label('Label via method') + fig.legend() + + Specific lines can be excluded from the automatic legend element + selection by defining a label starting with an underscore. + This is default for all artists, so calling `.Figure.legend` without + any arguments and without setting the labels manually will result in + no legend being drawn. + + + **2. Explicitly listing the artists and labels in the legend** + + For full control of which artists have a legend entry, it is possible + to pass an iterable of legend artists followed by an iterable of + legend labels respectively:: + + fig.legend([line1, line2, line3], ['label1', 'label2', 'label3']) + + + **3. Explicitly listing the artists in the legend** + + This is similar to 2, but the labels are taken from the artists' + label properties. Example:: + + line1, = ax1.plot([1, 2, 3], label='label1') + line2, = ax2.plot([1, 2, 3], label='label2') + fig.legend(handles=[line1, line2]) + + + **4. Labeling existing plot elements** + + .. admonition:: Discouraged + + This call signature is discouraged, because the relation between + plot elements and labels is only implicit by their order and can + easily be mixed up. + + To make a legend for all artists on all Axes, call this function with + an iterable of strings, one for each legend item. For example:: + + fig, (ax1, ax2) = plt.subplots(1, 2) + ax1.plot([1, 3, 5], color='blue') + ax2.plot([2, 4, 6], color='red') + fig.legend(['the blues', 'the reds']) + + + Parameters + ---------- + handles : list of `.Artist`, optional + A list of Artists (lines, patches) to be added to the legend. + Use this together with *labels*, if you need full control on what + is shown in the legend and the automatic mechanism described above + is not sufficient. + + The length of handles and labels should be the same in this + case. If they are not, they are truncated to the smaller length. + + labels : list of str, optional + A list of labels to show next to the artists. + Use this together with *handles*, if you need full control on what + is shown in the legend and the automatic mechanism described above + is not sufficient. + + Returns + ------- + `~matplotlib.legend.Legend` + + Other Parameters + ---------------- + %(_legend_kw_figure)s + + See Also + -------- + .Axes.legend + + Notes + ----- + Some artists are not supported by this function. See + :ref:`legend_guide` for details. + """ + + handles, labels, kwargs = mlegend._parse_legend_args(self.axes, *args, **kwargs) + # explicitly set the bbox transform if the user hasn't. + kwargs.setdefault("bbox_transform", self.transSubfigure) + l = mlegend.Legend(self, handles, labels, **kwargs) + self.legends.append(l) + l._remove_method = self.legends.remove + self.stale = True + return l + + @_docstring.interpd + def text(self, x, y, s, fontdict=None, **kwargs): + """ + Add text to figure. + + Parameters + ---------- + x, y : float + The position to place the text. By default, this is in figure + coordinates, floats in [0, 1]. The coordinate system can be changed + using the *transform* keyword. + + s : str + The text string. + + fontdict : dict, optional + A dictionary to override the default text properties. If not given, + the defaults are determined by :rc:`font.*`. Properties passed as + *kwargs* override the corresponding ones given in *fontdict*. + + Returns + ------- + `~.text.Text` + + Other Parameters + ---------------- + **kwargs : `~matplotlib.text.Text` properties + Other miscellaneous text parameters. + + %(Text:kwdoc)s + + See Also + -------- + .Axes.text + .pyplot.text + """ + effective_kwargs = { + 'transform': self.transSubfigure, + **(fontdict if fontdict is not None else {}), + **kwargs, + } + text = Text(x=x, y=y, text=s, **effective_kwargs) + text.set_figure(self) + text.stale_callback = _stale_figure_callback + + self.texts.append(text) + text._remove_method = self.texts.remove + self.stale = True + return text + + @_docstring.interpd + def colorbar( + self, mappable, cax=None, ax=None, use_gridspec=True, **kwargs): + """ + Add a colorbar to a plot. + + Parameters + ---------- + mappable + The `matplotlib.cm.ScalarMappable` (i.e., `.AxesImage`, + `.ContourSet`, etc.) described by this colorbar. This argument is + mandatory for the `.Figure.colorbar` method but optional for the + `.pyplot.colorbar` function, which sets the default to the current + image. + + Note that one can create a `.ScalarMappable` "on-the-fly" to + generate colorbars not attached to a previously drawn artist, e.g. + :: + + fig.colorbar(cm.ScalarMappable(norm=norm, cmap=cmap), ax=ax) + + cax : `~matplotlib.axes.Axes`, optional + Axes into which the colorbar will be drawn. If `None`, then a new + Axes is created and the space for it will be stolen from the Axes(s) + specified in *ax*. + + ax : `~matplotlib.axes.Axes` or iterable or `numpy.ndarray` of Axes, optional + The one or more parent Axes from which space for a new colorbar Axes + will be stolen. This parameter is only used if *cax* is not set. + + Defaults to the Axes that contains the mappable used to create the + colorbar. + + use_gridspec : bool, optional + If *cax* is ``None``, a new *cax* is created as an instance of + Axes. If *ax* is positioned with a subplotspec and *use_gridspec* + is ``True``, then *cax* is also positioned with a subplotspec. + + Returns + ------- + colorbar : `~matplotlib.colorbar.Colorbar` + + Other Parameters + ---------------- + %(_make_axes_kw_doc)s + %(_colormap_kw_doc)s + + Notes + ----- + If *mappable* is a `~.contour.ContourSet`, its *extend* kwarg is + included automatically. + + The *shrink* kwarg provides a simple way to scale the colorbar with + respect to the Axes. Note that if *cax* is specified, it determines the + size of the colorbar, and *shrink* and *aspect* are ignored. + + For more precise control, you can manually specify the positions of the + axes objects in which the mappable and the colorbar are drawn. In this + case, do not use any of the Axes properties kwargs. + + It is known that some vector graphics viewers (svg and pdf) render + white gaps between segments of the colorbar. This is due to bugs in + the viewers, not Matplotlib. As a workaround, the colorbar can be + rendered with overlapping segments:: + + cbar = colorbar() + cbar.solids.set_edgecolor("face") + draw() + + However, this has negative consequences in other circumstances, e.g. + with semi-transparent images (alpha < 1) and colorbar extensions; + therefore, this workaround is not used by default (see issue #1188). + + """ + + if ax is None: + ax = getattr(mappable, "axes", None) + + if cax is None: + if ax is None: + raise ValueError( + 'Unable to determine Axes to steal space for Colorbar. ' + 'Either provide the *cax* argument to use as the Axes for ' + 'the Colorbar, provide the *ax* argument to steal space ' + 'from it, or add *mappable* to an Axes.') + fig = ( # Figure of first Axes; logic copied from make_axes. + [*ax.flat] if isinstance(ax, np.ndarray) + else [*ax] if np.iterable(ax) + else [ax])[0].get_figure(root=False) + current_ax = fig.gca() + if (fig.get_layout_engine() is not None and + not fig.get_layout_engine().colorbar_gridspec): + use_gridspec = False + if (use_gridspec + and isinstance(ax, mpl.axes._base._AxesBase) + and ax.get_subplotspec()): + cax, kwargs = cbar.make_axes_gridspec(ax, **kwargs) + else: + cax, kwargs = cbar.make_axes(ax, **kwargs) + # make_axes calls add_{axes,subplot} which changes gca; undo that. + fig.sca(current_ax) + cax.grid(visible=False, which='both', axis='both') + + if (hasattr(mappable, "get_figure") and + (mappable_host_fig := mappable.get_figure(root=True)) is not None): + # Warn in case of mismatch + if mappable_host_fig is not self._root_figure: + _api.warn_external( + f'Adding colorbar to a different Figure ' + f'{repr(mappable_host_fig)} than ' + f'{repr(self._root_figure)} which ' + f'fig.colorbar is called on.') + + NON_COLORBAR_KEYS = [ # remove kws that cannot be passed to Colorbar + 'fraction', 'pad', 'shrink', 'aspect', 'anchor', 'panchor'] + cb = cbar.Colorbar(cax, mappable, **{ + k: v for k, v in kwargs.items() if k not in NON_COLORBAR_KEYS}) + cax.get_figure(root=False).stale = True + return cb + + def subplots_adjust(self, left=None, bottom=None, right=None, top=None, + wspace=None, hspace=None): + """ + Adjust the subplot layout parameters. + + Unset parameters are left unmodified; initial values are given by + :rc:`figure.subplot.[name]`. + + .. plot:: _embedded_plots/figure_subplots_adjust.py + + Parameters + ---------- + left : float, optional + The position of the left edge of the subplots, + as a fraction of the figure width. + right : float, optional + The position of the right edge of the subplots, + as a fraction of the figure width. + bottom : float, optional + The position of the bottom edge of the subplots, + as a fraction of the figure height. + top : float, optional + The position of the top edge of the subplots, + as a fraction of the figure height. + wspace : float, optional + The width of the padding between subplots, + as a fraction of the average Axes width. + hspace : float, optional + The height of the padding between subplots, + as a fraction of the average Axes height. + """ + if (self.get_layout_engine() is not None and + not self.get_layout_engine().adjust_compatible): + _api.warn_external( + "This figure was using a layout engine that is " + "incompatible with subplots_adjust and/or tight_layout; " + "not calling subplots_adjust.") + return + self.subplotpars.update(left, bottom, right, top, wspace, hspace) + for ax in self.axes: + if ax.get_subplotspec() is not None: + ax._set_position(ax.get_subplotspec().get_position(self)) + self.stale = True + + def align_xlabels(self, axs=None): + """ + Align the xlabels of subplots in the same subplot row if label + alignment is being done automatically (i.e. the label position is + not manually set). + + Alignment persists for draw events after this is called. + + If a label is on the bottom, it is aligned with labels on Axes that + also have their label on the bottom and that have the same + bottom-most subplot row. If the label is on the top, + it is aligned with labels on Axes with the same top-most row. + + Parameters + ---------- + axs : list of `~matplotlib.axes.Axes` + Optional list of (or `~numpy.ndarray`) `~matplotlib.axes.Axes` + to align the xlabels. + Default is to align all Axes on the figure. + + See Also + -------- + matplotlib.figure.Figure.align_ylabels + matplotlib.figure.Figure.align_titles + matplotlib.figure.Figure.align_labels + + Notes + ----- + This assumes that all Axes in ``axs`` are from the same `.GridSpec`, + so that their `.SubplotSpec` positions correspond to figure positions. + + Examples + -------- + Example with rotated xtick labels:: + + fig, axs = plt.subplots(1, 2) + for tick in axs[0].get_xticklabels(): + tick.set_rotation(55) + axs[0].set_xlabel('XLabel 0') + axs[1].set_xlabel('XLabel 1') + fig.align_xlabels() + """ + if axs is None: + axs = self.axes + axs = [ax for ax in np.ravel(axs) if ax.get_subplotspec() is not None] + for ax in axs: + _log.debug(' Working on: %s', ax.get_xlabel()) + rowspan = ax.get_subplotspec().rowspan + pos = ax.xaxis.get_label_position() # top or bottom + # Search through other Axes for label positions that are same as + # this one and that share the appropriate row number. + # Add to a grouper associated with each Axes of siblings. + # This list is inspected in `axis.draw` by + # `axis._update_label_position`. + for axc in axs: + if axc.xaxis.get_label_position() == pos: + rowspanc = axc.get_subplotspec().rowspan + if (pos == 'top' and rowspan.start == rowspanc.start or + pos == 'bottom' and rowspan.stop == rowspanc.stop): + # grouper for groups of xlabels to align + self._align_label_groups['x'].join(ax, axc) + + def align_ylabels(self, axs=None): + """ + Align the ylabels of subplots in the same subplot column if label + alignment is being done automatically (i.e. the label position is + not manually set). + + Alignment persists for draw events after this is called. + + If a label is on the left, it is aligned with labels on Axes that + also have their label on the left and that have the same + left-most subplot column. If the label is on the right, + it is aligned with labels on Axes with the same right-most column. + + Parameters + ---------- + axs : list of `~matplotlib.axes.Axes` + Optional list (or `~numpy.ndarray`) of `~matplotlib.axes.Axes` + to align the ylabels. + Default is to align all Axes on the figure. + + See Also + -------- + matplotlib.figure.Figure.align_xlabels + matplotlib.figure.Figure.align_titles + matplotlib.figure.Figure.align_labels + + Notes + ----- + This assumes that all Axes in ``axs`` are from the same `.GridSpec`, + so that their `.SubplotSpec` positions correspond to figure positions. + + Examples + -------- + Example with large yticks labels:: + + fig, axs = plt.subplots(2, 1) + axs[0].plot(np.arange(0, 1000, 50)) + axs[0].set_ylabel('YLabel 0') + axs[1].set_ylabel('YLabel 1') + fig.align_ylabels() + """ + if axs is None: + axs = self.axes + axs = [ax for ax in np.ravel(axs) if ax.get_subplotspec() is not None] + for ax in axs: + _log.debug(' Working on: %s', ax.get_ylabel()) + colspan = ax.get_subplotspec().colspan + pos = ax.yaxis.get_label_position() # left or right + # Search through other Axes for label positions that are same as + # this one and that share the appropriate column number. + # Add to a list associated with each Axes of siblings. + # This list is inspected in `axis.draw` by + # `axis._update_label_position`. + for axc in axs: + if axc.yaxis.get_label_position() == pos: + colspanc = axc.get_subplotspec().colspan + if (pos == 'left' and colspan.start == colspanc.start or + pos == 'right' and colspan.stop == colspanc.stop): + # grouper for groups of ylabels to align + self._align_label_groups['y'].join(ax, axc) + + def align_titles(self, axs=None): + """ + Align the titles of subplots in the same subplot row if title + alignment is being done automatically (i.e. the title position is + not manually set). + + Alignment persists for draw events after this is called. + + Parameters + ---------- + axs : list of `~matplotlib.axes.Axes` + Optional list of (or ndarray) `~matplotlib.axes.Axes` + to align the titles. + Default is to align all Axes on the figure. + + See Also + -------- + matplotlib.figure.Figure.align_xlabels + matplotlib.figure.Figure.align_ylabels + matplotlib.figure.Figure.align_labels + + Notes + ----- + This assumes that all Axes in ``axs`` are from the same `.GridSpec`, + so that their `.SubplotSpec` positions correspond to figure positions. + + Examples + -------- + Example with titles:: + + fig, axs = plt.subplots(1, 2) + axs[0].set_aspect('equal') + axs[0].set_title('Title 0') + axs[1].set_title('Title 1') + fig.align_titles() + """ + if axs is None: + axs = self.axes + axs = [ax for ax in np.ravel(axs) if ax.get_subplotspec() is not None] + for ax in axs: + _log.debug(' Working on: %s', ax.get_title()) + rowspan = ax.get_subplotspec().rowspan + for axc in axs: + rowspanc = axc.get_subplotspec().rowspan + if (rowspan.start == rowspanc.start): + self._align_label_groups['title'].join(ax, axc) + + def align_labels(self, axs=None): + """ + Align the xlabels and ylabels of subplots with the same subplots + row or column (respectively) if label alignment is being + done automatically (i.e. the label position is not manually set). + + Alignment persists for draw events after this is called. + + Parameters + ---------- + axs : list of `~matplotlib.axes.Axes` + Optional list (or `~numpy.ndarray`) of `~matplotlib.axes.Axes` + to align the labels. + Default is to align all Axes on the figure. + + See Also + -------- + matplotlib.figure.Figure.align_xlabels + matplotlib.figure.Figure.align_ylabels + matplotlib.figure.Figure.align_titles + + Notes + ----- + This assumes that all Axes in ``axs`` are from the same `.GridSpec`, + so that their `.SubplotSpec` positions correspond to figure positions. + """ + self.align_xlabels(axs=axs) + self.align_ylabels(axs=axs) + + def add_gridspec(self, nrows=1, ncols=1, **kwargs): + """ + Low-level API for creating a `.GridSpec` that has this figure as a parent. + + This is a low-level API, allowing you to create a gridspec and + subsequently add subplots based on the gridspec. Most users do + not need that freedom and should use the higher-level methods + `~.Figure.subplots` or `~.Figure.subplot_mosaic`. + + Parameters + ---------- + nrows : int, default: 1 + Number of rows in grid. + + ncols : int, default: 1 + Number of columns in grid. + + Returns + ------- + `.GridSpec` + + Other Parameters + ---------------- + **kwargs + Keyword arguments are passed to `.GridSpec`. + + See Also + -------- + matplotlib.pyplot.subplots + + Examples + -------- + Adding a subplot that spans two rows:: + + fig = plt.figure() + gs = fig.add_gridspec(2, 2) + ax1 = fig.add_subplot(gs[0, 0]) + ax2 = fig.add_subplot(gs[1, 0]) + # spans two rows: + ax3 = fig.add_subplot(gs[:, 1]) + + """ + + _ = kwargs.pop('figure', None) # pop in case user has added this... + gs = GridSpec(nrows=nrows, ncols=ncols, figure=self, **kwargs) + return gs + + def subfigures(self, nrows=1, ncols=1, squeeze=True, + wspace=None, hspace=None, + width_ratios=None, height_ratios=None, + **kwargs): + """ + Add a set of subfigures to this figure or subfigure. + + A subfigure has the same artist methods as a figure, and is logically + the same as a figure, but cannot print itself. + See :doc:`/gallery/subplots_axes_and_figures/subfigures`. + + .. versionchanged:: 3.10 + subfigures are now added in row-major order. + + Parameters + ---------- + nrows, ncols : int, default: 1 + Number of rows/columns of the subfigure grid. + + squeeze : bool, default: True + If True, extra dimensions are squeezed out from the returned + array of subfigures. + + wspace, hspace : float, default: None + The amount of width/height reserved for space between subfigures, + expressed as a fraction of the average subfigure width/height. + If not given, the values will be inferred from rcParams if using + constrained layout (see `~.ConstrainedLayoutEngine`), or zero if + not using a layout engine. + + width_ratios : array-like of length *ncols*, optional + Defines the relative widths of the columns. Each column gets a + relative width of ``width_ratios[i] / sum(width_ratios)``. + If not given, all columns will have the same width. + + height_ratios : array-like of length *nrows*, optional + Defines the relative heights of the rows. Each row gets a + relative height of ``height_ratios[i] / sum(height_ratios)``. + If not given, all rows will have the same height. + """ + gs = GridSpec(nrows=nrows, ncols=ncols, figure=self, + wspace=wspace, hspace=hspace, + width_ratios=width_ratios, + height_ratios=height_ratios, + left=0, right=1, bottom=0, top=1) + + sfarr = np.empty((nrows, ncols), dtype=object) + for i in range(nrows): + for j in range(ncols): + sfarr[i, j] = self.add_subfigure(gs[i, j], **kwargs) + + if self.get_layout_engine() is None and (wspace is not None or + hspace is not None): + # Gridspec wspace and hspace is ignored on subfigure instantiation, + # and no space is left. So need to account for it here if required. + bottoms, tops, lefts, rights = gs.get_grid_positions(self) + for sfrow, bottom, top in zip(sfarr, bottoms, tops): + for sf, left, right in zip(sfrow, lefts, rights): + bbox = Bbox.from_extents(left, bottom, right, top) + sf._redo_transform_rel_fig(bbox=bbox) + + if squeeze: + # Discarding unneeded dimensions that equal 1. If we only have one + # subfigure, just return it instead of a 1-element array. + return sfarr.item() if sfarr.size == 1 else sfarr.squeeze() + else: + # Returned axis array will be always 2-d, even if nrows=ncols=1. + return sfarr + + def add_subfigure(self, subplotspec, **kwargs): + """ + Add a `.SubFigure` to the figure as part of a subplot arrangement. + + Parameters + ---------- + subplotspec : `.gridspec.SubplotSpec` + Defines the region in a parent gridspec where the subfigure will + be placed. + + Returns + ------- + `.SubFigure` + + Other Parameters + ---------------- + **kwargs + Are passed to the `.SubFigure` object. + + See Also + -------- + .Figure.subfigures + """ + sf = SubFigure(self, subplotspec, **kwargs) + self.subfigs += [sf] + sf._remove_method = self.subfigs.remove + sf.stale_callback = _stale_figure_callback + self.stale = True + return sf + + def sca(self, a): + """Set the current Axes to be *a* and return *a*.""" + self._axstack.bubble(a) + self._axobservers.process("_axes_change_event", self) + return a + + def gca(self): + """ + Get the current Axes. + + If there is currently no Axes on this Figure, a new one is created + using `.Figure.add_subplot`. (To test whether there is currently an + Axes on a Figure, check whether ``figure.axes`` is empty. To test + whether there is currently a Figure on the pyplot figure stack, check + whether `.pyplot.get_fignums()` is empty.) + """ + ax = self._axstack.current() + return ax if ax is not None else self.add_subplot() + + def _gci(self): + # Helper for `~matplotlib.pyplot.gci`. Do not use elsewhere. + """ + Get the current colorable artist. + + Specifically, returns the current `.ScalarMappable` instance (`.Image` + created by `imshow` or `figimage`, `.Collection` created by `pcolor` or + `scatter`, etc.), or *None* if no such instance has been defined. + + The current image is an attribute of the current Axes, or the nearest + earlier Axes in the current figure that contains an image. + + Notes + ----- + Historically, the only colorable artists were images; hence the name + ``gci`` (get current image). + """ + # Look first for an image in the current Axes. + ax = self._axstack.current() + if ax is None: + return None + im = ax._gci() + if im is not None: + return im + # If there is no image in the current Axes, search for + # one in a previously created Axes. Whether this makes + # sense is debatable, but it is the documented behavior. + for ax in reversed(self.axes): + im = ax._gci() + if im is not None: + return im + return None + + def _process_projection_requirements(self, *, axes_class=None, polar=False, + projection=None, **kwargs): + """ + Handle the args/kwargs to add_axes/add_subplot/gca, returning:: + + (axes_proj_class, proj_class_kwargs) + + which can be used for new Axes initialization/identification. + """ + if axes_class is not None: + if polar or projection is not None: + raise ValueError( + "Cannot combine 'axes_class' and 'projection' or 'polar'") + projection_class = axes_class + else: + + if polar: + if projection is not None and projection != 'polar': + raise ValueError( + f"polar={polar}, yet projection={projection!r}. " + "Only one of these arguments should be supplied." + ) + projection = 'polar' + + if isinstance(projection, str) or projection is None: + projection_class = projections.get_projection_class(projection) + elif hasattr(projection, '_as_mpl_axes'): + projection_class, extra_kwargs = projection._as_mpl_axes() + kwargs.update(**extra_kwargs) + else: + raise TypeError( + f"projection must be a string, None or implement a " + f"_as_mpl_axes method, not {projection!r}") + return projection_class, kwargs + + def get_default_bbox_extra_artists(self): + """ + Return a list of Artists typically used in `.Figure.get_tightbbox`. + """ + bbox_artists = [artist for artist in self.get_children() + if (artist.get_visible() and artist.get_in_layout())] + for ax in self.axes: + if ax.get_visible(): + bbox_artists.extend(ax.get_default_bbox_extra_artists()) + return bbox_artists + + def get_tightbbox(self, renderer=None, *, bbox_extra_artists=None): + """ + Return a (tight) bounding box of the figure *in inches*. + + Note that `.FigureBase` differs from all other artists, which return + their `.Bbox` in pixels. + + Artists that have ``artist.set_in_layout(False)`` are not included + in the bbox. + + Parameters + ---------- + renderer : `.RendererBase` subclass + Renderer that will be used to draw the figures (i.e. + ``fig.canvas.get_renderer()``) + + bbox_extra_artists : list of `.Artist` or ``None`` + List of artists to include in the tight bounding box. If + ``None`` (default), then all artist children of each Axes are + included in the tight bounding box. + + Returns + ------- + `.BboxBase` + containing the bounding box (in figure inches). + """ + + if renderer is None: + renderer = self.get_figure(root=True)._get_renderer() + + bb = [] + if bbox_extra_artists is None: + artists = [artist for artist in self.get_children() + if (artist not in self.axes and artist.get_visible() + and artist.get_in_layout())] + else: + artists = bbox_extra_artists + + for a in artists: + bbox = a.get_tightbbox(renderer) + if bbox is not None: + bb.append(bbox) + + for ax in self.axes: + if ax.get_visible(): + # some Axes don't take the bbox_extra_artists kwarg so we + # need this conditional.... + try: + bbox = ax.get_tightbbox( + renderer, bbox_extra_artists=bbox_extra_artists) + except TypeError: + bbox = ax.get_tightbbox(renderer) + bb.append(bbox) + bb = [b for b in bb + if (np.isfinite(b.width) and np.isfinite(b.height) + and (b.width != 0 or b.height != 0))] + + isfigure = hasattr(self, 'bbox_inches') + if len(bb) == 0: + if isfigure: + return self.bbox_inches + else: + # subfigures do not have bbox_inches, but do have a bbox + bb = [self.bbox] + + _bbox = Bbox.union(bb) + + if isfigure: + # transform from pixels to inches... + _bbox = TransformedBbox(_bbox, self.dpi_scale_trans.inverted()) + + return _bbox + + @staticmethod + def _norm_per_subplot_kw(per_subplot_kw): + expanded = {} + for k, v in per_subplot_kw.items(): + if isinstance(k, tuple): + for sub_key in k: + if sub_key in expanded: + raise ValueError(f'The key {sub_key!r} appears multiple times.') + expanded[sub_key] = v + else: + if k in expanded: + raise ValueError(f'The key {k!r} appears multiple times.') + expanded[k] = v + return expanded + + @staticmethod + def _normalize_grid_string(layout): + if '\n' not in layout: + # single-line string + return [list(ln) for ln in layout.split(';')] + else: + # multi-line string + layout = inspect.cleandoc(layout) + return [list(ln) for ln in layout.strip('\n').split('\n')] + + def subplot_mosaic(self, mosaic, *, sharex=False, sharey=False, + width_ratios=None, height_ratios=None, + empty_sentinel='.', + subplot_kw=None, per_subplot_kw=None, gridspec_kw=None): + """ + Build a layout of Axes based on ASCII art or nested lists. + + This is a helper function to build complex GridSpec layouts visually. + + See :ref:`mosaic` + for an example and full API documentation + + Parameters + ---------- + mosaic : list of list of {hashable or nested} or str + + A visual layout of how you want your Axes to be arranged + labeled as strings. For example :: + + x = [['A panel', 'A panel', 'edge'], + ['C panel', '.', 'edge']] + + produces 4 Axes: + + - 'A panel' which is 1 row high and spans the first two columns + - 'edge' which is 2 rows high and is on the right edge + - 'C panel' which in 1 row and 1 column wide in the bottom left + - a blank space 1 row and 1 column wide in the bottom center + + Any of the entries in the layout can be a list of lists + of the same form to create nested layouts. + + If input is a str, then it can either be a multi-line string of + the form :: + + ''' + AAE + C.E + ''' + + where each character is a column and each line is a row. Or it + can be a single-line string where rows are separated by ``;``:: + + 'AB;CC' + + The string notation allows only single character Axes labels and + does not support nesting but is very terse. + + The Axes identifiers may be `str` or a non-iterable hashable + object (e.g. `tuple` s may not be used). + + sharex, sharey : bool, default: False + If True, the x-axis (*sharex*) or y-axis (*sharey*) will be shared + among all subplots. In that case, tick label visibility and axis + units behave as for `subplots`. If False, each subplot's x- or + y-axis will be independent. + + width_ratios : array-like of length *ncols*, optional + Defines the relative widths of the columns. Each column gets a + relative width of ``width_ratios[i] / sum(width_ratios)``. + If not given, all columns will have the same width. Equivalent + to ``gridspec_kw={'width_ratios': [...]}``. In the case of nested + layouts, this argument applies only to the outer layout. + + height_ratios : array-like of length *nrows*, optional + Defines the relative heights of the rows. Each row gets a + relative height of ``height_ratios[i] / sum(height_ratios)``. + If not given, all rows will have the same height. Equivalent + to ``gridspec_kw={'height_ratios': [...]}``. In the case of nested + layouts, this argument applies only to the outer layout. + + subplot_kw : dict, optional + Dictionary with keywords passed to the `.Figure.add_subplot` call + used to create each subplot. These values may be overridden by + values in *per_subplot_kw*. + + per_subplot_kw : dict, optional + A dictionary mapping the Axes identifiers or tuples of identifiers + to a dictionary of keyword arguments to be passed to the + `.Figure.add_subplot` call used to create each subplot. The values + in these dictionaries have precedence over the values in + *subplot_kw*. + + If *mosaic* is a string, and thus all keys are single characters, + it is possible to use a single string instead of a tuple as keys; + i.e. ``"AB"`` is equivalent to ``("A", "B")``. + + .. versionadded:: 3.7 + + gridspec_kw : dict, optional + Dictionary with keywords passed to the `.GridSpec` constructor used + to create the grid the subplots are placed on. In the case of + nested layouts, this argument applies only to the outer layout. + For more complex layouts, users should use `.Figure.subfigures` + to create the nesting. + + empty_sentinel : object, optional + Entry in the layout to mean "leave this space empty". Defaults + to ``'.'``. Note, if *layout* is a string, it is processed via + `inspect.cleandoc` to remove leading white space, which may + interfere with using white-space as the empty sentinel. + + Returns + ------- + dict[label, Axes] + A dictionary mapping the labels to the Axes objects. The order of + the Axes is left-to-right and top-to-bottom of their position in the + total layout. + + """ + subplot_kw = subplot_kw or {} + gridspec_kw = dict(gridspec_kw or {}) + per_subplot_kw = per_subplot_kw or {} + + if height_ratios is not None: + if 'height_ratios' in gridspec_kw: + raise ValueError("'height_ratios' must not be defined both as " + "parameter and as key in 'gridspec_kw'") + gridspec_kw['height_ratios'] = height_ratios + if width_ratios is not None: + if 'width_ratios' in gridspec_kw: + raise ValueError("'width_ratios' must not be defined both as " + "parameter and as key in 'gridspec_kw'") + gridspec_kw['width_ratios'] = width_ratios + + # special-case string input + if isinstance(mosaic, str): + mosaic = self._normalize_grid_string(mosaic) + per_subplot_kw = { + tuple(k): v for k, v in per_subplot_kw.items() + } + + per_subplot_kw = self._norm_per_subplot_kw(per_subplot_kw) + + # Only accept strict bools to allow a possible future API expansion. + _api.check_isinstance(bool, sharex=sharex, sharey=sharey) + + def _make_array(inp): + """ + Convert input into 2D array + + We need to have this internal function rather than + ``np.asarray(..., dtype=object)`` so that a list of lists + of lists does not get converted to an array of dimension > 2. + + Returns + ------- + 2D object array + """ + r0, *rest = inp + if isinstance(r0, str): + raise ValueError('List mosaic specification must be 2D') + for j, r in enumerate(rest, start=1): + if isinstance(r, str): + raise ValueError('List mosaic specification must be 2D') + if len(r0) != len(r): + raise ValueError( + "All of the rows must be the same length, however " + f"the first row ({r0!r}) has length {len(r0)} " + f"and row {j} ({r!r}) has length {len(r)}." + ) + out = np.zeros((len(inp), len(r0)), dtype=object) + for j, r in enumerate(inp): + for k, v in enumerate(r): + out[j, k] = v + return out + + def _identify_keys_and_nested(mosaic): + """ + Given a 2D object array, identify unique IDs and nested mosaics + + Parameters + ---------- + mosaic : 2D object array + + Returns + ------- + unique_ids : tuple + The unique non-sub mosaic entries in this mosaic + nested : dict[tuple[int, int], 2D object array] + """ + # make sure we preserve the user supplied order + unique_ids = cbook._OrderedSet() + nested = {} + for j, row in enumerate(mosaic): + for k, v in enumerate(row): + if v == empty_sentinel: + continue + elif not cbook.is_scalar_or_string(v): + nested[(j, k)] = _make_array(v) + else: + unique_ids.add(v) + + return tuple(unique_ids), nested + + def _do_layout(gs, mosaic, unique_ids, nested): + """ + Recursively do the mosaic. + + Parameters + ---------- + gs : GridSpec + mosaic : 2D object array + The input converted to a 2D array for this level. + unique_ids : tuple + The identified scalar labels at this level of nesting. + nested : dict[tuple[int, int]], 2D object array + The identified nested mosaics, if any. + + Returns + ------- + dict[label, Axes] + A flat dict of all of the Axes created. + """ + output = dict() + + # we need to merge together the Axes at this level and the Axes + # in the (recursively) nested sub-mosaics so that we can add + # them to the figure in the "natural" order if you were to + # ravel in c-order all of the Axes that will be created + # + # This will stash the upper left index of each object (axes or + # nested mosaic) at this level + this_level = dict() + + # go through the unique keys, + for name in unique_ids: + # sort out where each axes starts/ends + indx = np.argwhere(mosaic == name) + start_row, start_col = np.min(indx, axis=0) + end_row, end_col = np.max(indx, axis=0) + 1 + # and construct the slice object + slc = (slice(start_row, end_row), slice(start_col, end_col)) + # some light error checking + if (mosaic[slc] != name).any(): + raise ValueError( + f"While trying to layout\n{mosaic!r}\n" + f"we found that the label {name!r} specifies a " + "non-rectangular or non-contiguous area.") + # and stash this slice for later + this_level[(start_row, start_col)] = (name, slc, 'axes') + + # do the same thing for the nested mosaics (simpler because these + # cannot be spans yet!) + for (j, k), nested_mosaic in nested.items(): + this_level[(j, k)] = (None, nested_mosaic, 'nested') + + # now go through the things in this level and add them + # in order left-to-right top-to-bottom + for key in sorted(this_level): + name, arg, method = this_level[key] + # we are doing some hokey function dispatch here based + # on the 'method' string stashed above to sort out if this + # element is an Axes or a nested mosaic. + if method == 'axes': + slc = arg + # add a single Axes + if name in output: + raise ValueError(f"There are duplicate keys {name} " + f"in the layout\n{mosaic!r}") + ax = self.add_subplot( + gs[slc], **{ + 'label': str(name), + **subplot_kw, + **per_subplot_kw.get(name, {}) + } + ) + output[name] = ax + elif method == 'nested': + nested_mosaic = arg + j, k = key + # recursively add the nested mosaic + rows, cols = nested_mosaic.shape + nested_output = _do_layout( + gs[j, k].subgridspec(rows, cols), + nested_mosaic, + *_identify_keys_and_nested(nested_mosaic) + ) + overlap = set(output) & set(nested_output) + if overlap: + raise ValueError( + f"There are duplicate keys {overlap} " + f"between the outer layout\n{mosaic!r}\n" + f"and the nested layout\n{nested_mosaic}" + ) + output.update(nested_output) + else: + raise RuntimeError("This should never happen") + return output + + mosaic = _make_array(mosaic) + rows, cols = mosaic.shape + gs = self.add_gridspec(rows, cols, **gridspec_kw) + ret = _do_layout(gs, mosaic, *_identify_keys_and_nested(mosaic)) + ax0 = next(iter(ret.values())) + for ax in ret.values(): + if sharex: + ax.sharex(ax0) + ax._label_outer_xaxis(skip_non_rectangular_axes=True) + if sharey: + ax.sharey(ax0) + ax._label_outer_yaxis(skip_non_rectangular_axes=True) + if extra := set(per_subplot_kw) - set(ret): + raise ValueError( + f"The keys {extra} are in *per_subplot_kw* " + "but not in the mosaic." + ) + return ret + + def _set_artist_props(self, a): + if a != self: + a.set_figure(self) + a.stale_callback = _stale_figure_callback + a.set_transform(self.transSubfigure) + + +@_docstring.interpd +class SubFigure(FigureBase): + """ + Logical figure that can be placed inside a figure. + + See :ref:`figure-api-subfigure` for an index of methods on this class. + Typically instantiated using `.Figure.add_subfigure` or + `.SubFigure.add_subfigure`, or `.SubFigure.subfigures`. A subfigure has + the same methods as a figure except for those particularly tied to the size + or dpi of the figure, and is confined to a prescribed region of the figure. + For example the following puts two subfigures side-by-side:: + + fig = plt.figure() + sfigs = fig.subfigures(1, 2) + axsL = sfigs[0].subplots(1, 2) + axsR = sfigs[1].subplots(2, 1) + + See :doc:`/gallery/subplots_axes_and_figures/subfigures` + """ + + def __init__(self, parent, subplotspec, *, + facecolor=None, + edgecolor=None, + linewidth=0.0, + frameon=None, + **kwargs): + """ + Parameters + ---------- + parent : `.Figure` or `.SubFigure` + Figure or subfigure that contains the SubFigure. SubFigures + can be nested. + + subplotspec : `.gridspec.SubplotSpec` + Defines the region in a parent gridspec where the subfigure will + be placed. + + facecolor : default: ``"none"`` + The figure patch face color; transparent by default. + + edgecolor : default: :rc:`figure.edgecolor` + The figure patch edge color. + + linewidth : float + The linewidth of the frame (i.e. the edge linewidth of the figure + patch). + + frameon : bool, default: :rc:`figure.frameon` + If ``False``, suppress drawing the figure background patch. + + Other Parameters + ---------------- + **kwargs : `.SubFigure` properties, optional + + %(SubFigure:kwdoc)s + """ + super().__init__(**kwargs) + if facecolor is None: + facecolor = "none" + if edgecolor is None: + edgecolor = mpl.rcParams['figure.edgecolor'] + if frameon is None: + frameon = mpl.rcParams['figure.frameon'] + + self._subplotspec = subplotspec + self._parent = parent + self._root_figure = parent._root_figure + + # subfigures use the parent axstack + self._axstack = parent._axstack + self.subplotpars = parent.subplotpars + self.dpi_scale_trans = parent.dpi_scale_trans + self._axobservers = parent._axobservers + self.transFigure = parent.transFigure + self.bbox_relative = Bbox.null() + self._redo_transform_rel_fig() + self.figbbox = self._parent.figbbox + self.bbox = TransformedBbox(self.bbox_relative, + self._parent.transSubfigure) + self.transSubfigure = BboxTransformTo(self.bbox) + + self.patch = Rectangle( + xy=(0, 0), width=1, height=1, visible=frameon, + facecolor=facecolor, edgecolor=edgecolor, linewidth=linewidth, + # Don't let the figure patch influence bbox calculation. + in_layout=False, transform=self.transSubfigure) + self._set_artist_props(self.patch) + self.patch.set_antialiased(False) + + @property + def canvas(self): + return self._parent.canvas + + @property + def dpi(self): + return self._parent.dpi + + @dpi.setter + def dpi(self, value): + self._parent.dpi = value + + def get_dpi(self): + """ + Return the resolution of the parent figure in dots-per-inch as a float. + """ + return self._parent.dpi + + def set_dpi(self, val): + """ + Set the resolution of parent figure in dots-per-inch. + + Parameters + ---------- + val : float + """ + self._parent.dpi = val + self.stale = True + + def _get_renderer(self): + return self._parent._get_renderer() + + def _redo_transform_rel_fig(self, bbox=None): + """ + Make the transSubfigure bbox relative to Figure transform. + + Parameters + ---------- + bbox : bbox or None + If not None, then the bbox is used for relative bounding box. + Otherwise, it is calculated from the subplotspec. + """ + if bbox is not None: + self.bbox_relative.p0 = bbox.p0 + self.bbox_relative.p1 = bbox.p1 + return + # need to figure out *where* this subplotspec is. + gs = self._subplotspec.get_gridspec() + wr = np.asarray(gs.get_width_ratios()) + hr = np.asarray(gs.get_height_ratios()) + dx = wr[self._subplotspec.colspan].sum() / wr.sum() + dy = hr[self._subplotspec.rowspan].sum() / hr.sum() + x0 = wr[:self._subplotspec.colspan.start].sum() / wr.sum() + y0 = 1 - hr[:self._subplotspec.rowspan.stop].sum() / hr.sum() + self.bbox_relative.p0 = (x0, y0) + self.bbox_relative.p1 = (x0 + dx, y0 + dy) + + def get_constrained_layout(self): + """ + Return whether constrained layout is being used. + + See :ref:`constrainedlayout_guide`. + """ + return self._parent.get_constrained_layout() + + def get_constrained_layout_pads(self, relative=False): + """ + Get padding for ``constrained_layout``. + + Returns a list of ``w_pad, h_pad`` in inches and + ``wspace`` and ``hspace`` as fractions of the subplot. + + See :ref:`constrainedlayout_guide`. + + Parameters + ---------- + relative : bool + If `True`, then convert from inches to figure relative. + """ + return self._parent.get_constrained_layout_pads(relative=relative) + + def get_layout_engine(self): + return self._parent.get_layout_engine() + + @property + def axes(self): + """ + List of Axes in the SubFigure. You can access and modify the Axes + in the SubFigure through this list. + + Modifying this list has no effect. Instead, use `~.SubFigure.add_axes`, + `~.SubFigure.add_subplot` or `~.SubFigure.delaxes` to add or remove an + Axes. + + Note: The `.SubFigure.axes` property and `~.SubFigure.get_axes` method + are equivalent. + """ + return self._localaxes[:] + + get_axes = axes.fget + + def draw(self, renderer): + # docstring inherited + + # draw the figure bounding box, perhaps none for white figure + if not self.get_visible(): + return + + artists = self._get_draw_artists(renderer) + + try: + renderer.open_group('subfigure', gid=self.get_gid()) + self.patch.draw(renderer) + mimage._draw_list_compositing_images( + renderer, self, artists, self.get_figure(root=True).suppressComposite) + renderer.close_group('subfigure') + + finally: + self.stale = False + + +@_docstring.interpd +class Figure(FigureBase): + """ + The top level container for all the plot elements. + + See `matplotlib.figure` for an index of class methods. + + Attributes + ---------- + patch + The `.Rectangle` instance representing the figure background patch. + + suppressComposite + For multiple images, the figure will make composite images + depending on the renderer option_image_nocomposite function. If + *suppressComposite* is a boolean, this will override the renderer. + """ + + # we want to cache the fonts and mathtext at a global level so that when + # multiple figures are created we can reuse them. This helps with a bug on + # windows where the creation of too many figures leads to too many open + # file handles and improves the performance of parsing mathtext. However, + # these global caches are not thread safe. The solution here is to let the + # Figure acquire a shared lock at the start of the draw, and release it when it + # is done. This allows multiple renderers to share the cached fonts and + # parsed text, but only one figure can draw at a time and so the font cache + # and mathtext cache are used by only one renderer at a time. + + _render_lock = threading.RLock() + + def __str__(self): + return "Figure(%gx%g)" % tuple(self.bbox.size) + + def __repr__(self): + return "<{clsname} size {h:g}x{w:g} with {naxes} Axes>".format( + clsname=self.__class__.__name__, + h=self.bbox.size[0], w=self.bbox.size[1], + naxes=len(self.axes), + ) + + def __init__(self, + figsize=None, + dpi=None, + *, + facecolor=None, + edgecolor=None, + linewidth=0.0, + frameon=None, + subplotpars=None, # rc figure.subplot.* + tight_layout=None, # rc figure.autolayout + constrained_layout=None, # rc figure.constrained_layout.use + layout=None, + **kwargs + ): + """ + Parameters + ---------- + figsize : 2-tuple of floats, default: :rc:`figure.figsize` + Figure dimension ``(width, height)`` in inches. + + dpi : float, default: :rc:`figure.dpi` + Dots per inch. + + facecolor : default: :rc:`figure.facecolor` + The figure patch facecolor. + + edgecolor : default: :rc:`figure.edgecolor` + The figure patch edge color. + + linewidth : float + The linewidth of the frame (i.e. the edge linewidth of the figure + patch). + + frameon : bool, default: :rc:`figure.frameon` + If ``False``, suppress drawing the figure background patch. + + subplotpars : `~matplotlib.gridspec.SubplotParams` + Subplot parameters. If not given, the default subplot + parameters :rc:`figure.subplot.*` are used. + + tight_layout : bool or dict, default: :rc:`figure.autolayout` + Whether to use the tight layout mechanism. See `.set_tight_layout`. + + .. admonition:: Discouraged + + The use of this parameter is discouraged. Please use + ``layout='tight'`` instead for the common case of + ``tight_layout=True`` and use `.set_tight_layout` otherwise. + + constrained_layout : bool, default: :rc:`figure.constrained_layout.use` + This is equal to ``layout='constrained'``. + + .. admonition:: Discouraged + + The use of this parameter is discouraged. Please use + ``layout='constrained'`` instead. + + layout : {'constrained', 'compressed', 'tight', 'none', `.LayoutEngine`, \ +None}, default: None + The layout mechanism for positioning of plot elements to avoid + overlapping Axes decorations (labels, ticks, etc). Note that + layout managers can have significant performance penalties. + + - 'constrained': The constrained layout solver adjusts Axes sizes + to avoid overlapping Axes decorations. Can handle complex plot + layouts and colorbars, and is thus recommended. + + See :ref:`constrainedlayout_guide` for examples. + + - 'compressed': uses the same algorithm as 'constrained', but + removes extra space between fixed-aspect-ratio Axes. Best for + simple grids of Axes. + + - 'tight': Use the tight layout mechanism. This is a relatively + simple algorithm that adjusts the subplot parameters so that + decorations do not overlap. + + See :ref:`tight_layout_guide` for examples. + + - 'none': Do not use a layout engine. + + - A `.LayoutEngine` instance. Builtin layout classes are + `.ConstrainedLayoutEngine` and `.TightLayoutEngine`, more easily + accessible by 'constrained' and 'tight'. Passing an instance + allows third parties to provide their own layout engine. + + If not given, fall back to using the parameters *tight_layout* and + *constrained_layout*, including their config defaults + :rc:`figure.autolayout` and :rc:`figure.constrained_layout.use`. + + Other Parameters + ---------------- + **kwargs : `.Figure` properties, optional + + %(Figure:kwdoc)s + """ + super().__init__(**kwargs) + self._root_figure = self + self._layout_engine = None + + if layout is not None: + if (tight_layout is not None): + _api.warn_external( + "The Figure parameters 'layout' and 'tight_layout' cannot " + "be used together. Please use 'layout' only.") + if (constrained_layout is not None): + _api.warn_external( + "The Figure parameters 'layout' and 'constrained_layout' " + "cannot be used together. Please use 'layout' only.") + self.set_layout_engine(layout=layout) + elif tight_layout is not None: + if constrained_layout is not None: + _api.warn_external( + "The Figure parameters 'tight_layout' and " + "'constrained_layout' cannot be used together. Please use " + "'layout' parameter") + self.set_layout_engine(layout='tight') + if isinstance(tight_layout, dict): + self.get_layout_engine().set(**tight_layout) + elif constrained_layout is not None: + if isinstance(constrained_layout, dict): + self.set_layout_engine(layout='constrained') + self.get_layout_engine().set(**constrained_layout) + elif constrained_layout: + self.set_layout_engine(layout='constrained') + + else: + # everything is None, so use default: + self.set_layout_engine(layout=layout) + + # Callbacks traditionally associated with the canvas (and exposed with + # a proxy property), but that actually need to be on the figure for + # pickling. + self._canvas_callbacks = cbook.CallbackRegistry( + signals=FigureCanvasBase.events) + connect = self._canvas_callbacks._connect_picklable + self._mouse_key_ids = [ + connect('key_press_event', backend_bases._key_handler), + connect('key_release_event', backend_bases._key_handler), + connect('key_release_event', backend_bases._key_handler), + connect('button_press_event', backend_bases._mouse_handler), + connect('button_release_event', backend_bases._mouse_handler), + connect('scroll_event', backend_bases._mouse_handler), + connect('motion_notify_event', backend_bases._mouse_handler), + ] + self._button_pick_id = connect('button_press_event', self.pick) + self._scroll_pick_id = connect('scroll_event', self.pick) + + if figsize is None: + figsize = mpl.rcParams['figure.figsize'] + if dpi is None: + dpi = mpl.rcParams['figure.dpi'] + if facecolor is None: + facecolor = mpl.rcParams['figure.facecolor'] + if edgecolor is None: + edgecolor = mpl.rcParams['figure.edgecolor'] + if frameon is None: + frameon = mpl.rcParams['figure.frameon'] + + if not np.isfinite(figsize).all() or (np.array(figsize) < 0).any(): + raise ValueError('figure size must be positive finite not ' + f'{figsize}') + self.bbox_inches = Bbox.from_bounds(0, 0, *figsize) + + self.dpi_scale_trans = Affine2D().scale(dpi) + # do not use property as it will trigger + self._dpi = dpi + self.bbox = TransformedBbox(self.bbox_inches, self.dpi_scale_trans) + self.figbbox = self.bbox + self.transFigure = BboxTransformTo(self.bbox) + self.transSubfigure = self.transFigure + + self.patch = Rectangle( + xy=(0, 0), width=1, height=1, visible=frameon, + facecolor=facecolor, edgecolor=edgecolor, linewidth=linewidth, + # Don't let the figure patch influence bbox calculation. + in_layout=False) + self._set_artist_props(self.patch) + self.patch.set_antialiased(False) + + FigureCanvasBase(self) # Set self.canvas. + + if subplotpars is None: + subplotpars = SubplotParams() + + self.subplotpars = subplotpars + + self._axstack = _AxesStack() # track all figure Axes and current Axes + self.clear() + + def pick(self, mouseevent): + if not self.canvas.widgetlock.locked(): + super().pick(mouseevent) + + def _check_layout_engines_compat(self, old, new): + """ + Helper for set_layout engine + + If the figure has used the old engine and added a colorbar then the + value of colorbar_gridspec must be the same on the new engine. + """ + if old is None or new is None: + return True + if old.colorbar_gridspec == new.colorbar_gridspec: + return True + # colorbar layout different, so check if any colorbars are on the + # figure... + for ax in self.axes: + if hasattr(ax, '_colorbar'): + # colorbars list themselves as a colorbar. + return False + return True + + def set_layout_engine(self, layout=None, **kwargs): + """ + Set the layout engine for this figure. + + Parameters + ---------- + layout : {'constrained', 'compressed', 'tight', 'none', `.LayoutEngine`, None} + + - 'constrained' will use `~.ConstrainedLayoutEngine` + - 'compressed' will also use `~.ConstrainedLayoutEngine`, but with + a correction that attempts to make a good layout for fixed-aspect + ratio Axes. + - 'tight' uses `~.TightLayoutEngine` + - 'none' removes layout engine. + + If a `.LayoutEngine` instance, that instance will be used. + + If `None`, the behavior is controlled by :rc:`figure.autolayout` + (which if `True` behaves as if 'tight' was passed) and + :rc:`figure.constrained_layout.use` (which if `True` behaves as if + 'constrained' was passed). If both are `True`, + :rc:`figure.autolayout` takes priority. + + Users and libraries can define their own layout engines and pass + the instance directly as well. + + **kwargs + The keyword arguments are passed to the layout engine to set things + like padding and margin sizes. Only used if *layout* is a string. + + """ + if layout is None: + if mpl.rcParams['figure.autolayout']: + layout = 'tight' + elif mpl.rcParams['figure.constrained_layout.use']: + layout = 'constrained' + else: + self._layout_engine = None + return + if layout == 'tight': + new_layout_engine = TightLayoutEngine(**kwargs) + elif layout == 'constrained': + new_layout_engine = ConstrainedLayoutEngine(**kwargs) + elif layout == 'compressed': + new_layout_engine = ConstrainedLayoutEngine(compress=True, + **kwargs) + elif layout == 'none': + if self._layout_engine is not None: + new_layout_engine = PlaceHolderLayoutEngine( + self._layout_engine.adjust_compatible, + self._layout_engine.colorbar_gridspec + ) + else: + new_layout_engine = None + elif isinstance(layout, LayoutEngine): + new_layout_engine = layout + else: + raise ValueError(f"Invalid value for 'layout': {layout!r}") + + if self._check_layout_engines_compat(self._layout_engine, + new_layout_engine): + self._layout_engine = new_layout_engine + else: + raise RuntimeError('Colorbar layout of new layout engine not ' + 'compatible with old engine, and a colorbar ' + 'has been created. Engine not changed.') + + def get_layout_engine(self): + return self._layout_engine + + # TODO: I'd like to dynamically add the _repr_html_ method + # to the figure in the right context, but then IPython doesn't + # use it, for some reason. + + def _repr_html_(self): + # We can't use "isinstance" here, because then we'd end up importing + # webagg unconditionally. + if 'WebAgg' in type(self.canvas).__name__: + from matplotlib.backends import backend_webagg + return backend_webagg.ipython_inline_display(self) + + def show(self, warn=True): + """ + If using a GUI backend with pyplot, display the figure window. + + If the figure was not created using `~.pyplot.figure`, it will lack + a `~.backend_bases.FigureManagerBase`, and this method will raise an + AttributeError. + + .. warning:: + + This does not manage an GUI event loop. Consequently, the figure + may only be shown briefly or not shown at all if you or your + environment are not managing an event loop. + + Use cases for `.Figure.show` include running this from a GUI + application (where there is persistently an event loop running) or + from a shell, like IPython, that install an input hook to allow the + interactive shell to accept input while the figure is also being + shown and interactive. Some, but not all, GUI toolkits will + register an input hook on import. See :ref:`cp_integration` for + more details. + + If you're in a shell without input hook integration or executing a + python script, you should use `matplotlib.pyplot.show` with + ``block=True`` instead, which takes care of starting and running + the event loop for you. + + Parameters + ---------- + warn : bool, default: True + If ``True`` and we are not running headless (i.e. on Linux with an + unset DISPLAY), issue warning when called on a non-GUI backend. + + """ + if self.canvas.manager is None: + raise AttributeError( + "Figure.show works only for figures managed by pyplot, " + "normally created by pyplot.figure()") + try: + self.canvas.manager.show() + except NonGuiException as exc: + if warn: + _api.warn_external(str(exc)) + + @property + def axes(self): + """ + List of Axes in the Figure. You can access and modify the Axes in the + Figure through this list. + + Do not modify the list itself. Instead, use `~Figure.add_axes`, + `~.Figure.add_subplot` or `~.Figure.delaxes` to add or remove an Axes. + + Note: The `.Figure.axes` property and `~.Figure.get_axes` method are + equivalent. + """ + return self._axstack.as_list() + + get_axes = axes.fget + + @property + def number(self): + """The figure id, used to identify figures in `.pyplot`.""" + # Historically, pyplot dynamically added a number attribute to figure. + # However, this number must stay in sync with the figure manager. + # AFAICS overwriting the number attribute does not have the desired + # effect for pyplot. But there are some repos in GitHub that do change + # number. So let's take it slow and properly migrate away from writing. + # + # Making the dynamic attribute private and wrapping it in a property + # allows to maintain current behavior and deprecate write-access. + # + # When the deprecation expires, there's no need for duplicate state + # anymore and the private _number attribute can be replaced by + # `self.canvas.manager.num` if that exists and None otherwise. + if hasattr(self, '_number'): + return self._number + else: + raise AttributeError( + "'Figure' object has no attribute 'number'. In the future this" + "will change to returning 'None' instead.") + + @number.setter + def number(self, num): + _api.warn_deprecated( + "3.10", + message="Changing 'Figure.number' is deprecated since %(since)s and " + "will raise an error starting %(removal)s") + self._number = num + + def _get_renderer(self): + if hasattr(self.canvas, 'get_renderer'): + return self.canvas.get_renderer() + else: + return _get_renderer(self) + + def _get_dpi(self): + return self._dpi + + def _set_dpi(self, dpi, forward=True): + """ + Parameters + ---------- + dpi : float + + forward : bool + Passed on to `~.Figure.set_size_inches` + """ + if dpi == self._dpi: + # We don't want to cause undue events in backends. + return + self._dpi = dpi + self.dpi_scale_trans.clear().scale(dpi) + w, h = self.get_size_inches() + self.set_size_inches(w, h, forward=forward) + + dpi = property(_get_dpi, _set_dpi, doc="The resolution in dots per inch.") + + def get_tight_layout(self): + """Return whether `.Figure.tight_layout` is called when drawing.""" + return isinstance(self.get_layout_engine(), TightLayoutEngine) + + @_api.deprecated("3.6", alternative="set_layout_engine", + pending=True) + def set_tight_layout(self, tight): + """ + Set whether and how `.Figure.tight_layout` is called when drawing. + + Parameters + ---------- + tight : bool or dict with keys "pad", "w_pad", "h_pad", "rect" or None + If a bool, sets whether to call `.Figure.tight_layout` upon drawing. + If ``None``, use :rc:`figure.autolayout` instead. + If a dict, pass it as kwargs to `.Figure.tight_layout`, overriding the + default paddings. + """ + if tight is None: + tight = mpl.rcParams['figure.autolayout'] + _tight = 'tight' if bool(tight) else 'none' + _tight_parameters = tight if isinstance(tight, dict) else {} + self.set_layout_engine(_tight, **_tight_parameters) + self.stale = True + + def get_constrained_layout(self): + """ + Return whether constrained layout is being used. + + See :ref:`constrainedlayout_guide`. + """ + return isinstance(self.get_layout_engine(), ConstrainedLayoutEngine) + + @_api.deprecated("3.6", alternative="set_layout_engine('constrained')", + pending=True) + def set_constrained_layout(self, constrained): + """ + Set whether ``constrained_layout`` is used upon drawing. + + If None, :rc:`figure.constrained_layout.use` value will be used. + + When providing a dict containing the keys ``w_pad``, ``h_pad`` + the default ``constrained_layout`` paddings will be + overridden. These pads are in inches and default to 3.0/72.0. + ``w_pad`` is the width padding and ``h_pad`` is the height padding. + + Parameters + ---------- + constrained : bool or dict or None + """ + if constrained is None: + constrained = mpl.rcParams['figure.constrained_layout.use'] + _constrained = 'constrained' if bool(constrained) else 'none' + _parameters = constrained if isinstance(constrained, dict) else {} + self.set_layout_engine(_constrained, **_parameters) + self.stale = True + + @_api.deprecated( + "3.6", alternative="figure.get_layout_engine().set()", + pending=True) + def set_constrained_layout_pads(self, **kwargs): + """ + Set padding for ``constrained_layout``. + + Tip: The parameters can be passed from a dictionary by using + ``fig.set_constrained_layout(**pad_dict)``. + + See :ref:`constrainedlayout_guide`. + + Parameters + ---------- + w_pad : float, default: :rc:`figure.constrained_layout.w_pad` + Width padding in inches. This is the pad around Axes + and is meant to make sure there is enough room for fonts to + look good. Defaults to 3 pts = 0.04167 inches + + h_pad : float, default: :rc:`figure.constrained_layout.h_pad` + Height padding in inches. Defaults to 3 pts. + + wspace : float, default: :rc:`figure.constrained_layout.wspace` + Width padding between subplots, expressed as a fraction of the + subplot width. The total padding ends up being w_pad + wspace. + + hspace : float, default: :rc:`figure.constrained_layout.hspace` + Height padding between subplots, expressed as a fraction of the + subplot width. The total padding ends up being h_pad + hspace. + + """ + if isinstance(self.get_layout_engine(), ConstrainedLayoutEngine): + self.get_layout_engine().set(**kwargs) + + @_api.deprecated("3.6", alternative="fig.get_layout_engine().get()", + pending=True) + def get_constrained_layout_pads(self, relative=False): + """ + Get padding for ``constrained_layout``. + + Returns a list of ``w_pad, h_pad`` in inches and + ``wspace`` and ``hspace`` as fractions of the subplot. + All values are None if ``constrained_layout`` is not used. + + See :ref:`constrainedlayout_guide`. + + Parameters + ---------- + relative : bool + If `True`, then convert from inches to figure relative. + """ + if not isinstance(self.get_layout_engine(), ConstrainedLayoutEngine): + return None, None, None, None + info = self.get_layout_engine().get() + w_pad = info['w_pad'] + h_pad = info['h_pad'] + wspace = info['wspace'] + hspace = info['hspace'] + + if relative and (w_pad is not None or h_pad is not None): + renderer = self._get_renderer() + dpi = renderer.dpi + w_pad = w_pad * dpi / renderer.width + h_pad = h_pad * dpi / renderer.height + + return w_pad, h_pad, wspace, hspace + + def set_canvas(self, canvas): + """ + Set the canvas that contains the figure + + Parameters + ---------- + canvas : FigureCanvas + """ + self.canvas = canvas + + @_docstring.interpd + def figimage(self, X, xo=0, yo=0, alpha=None, norm=None, cmap=None, + vmin=None, vmax=None, origin=None, resize=False, *, + colorizer=None, **kwargs): + """ + Add a non-resampled image to the figure. + + The image is attached to the lower or upper left corner depending on + *origin*. + + Parameters + ---------- + X + The image data. This is an array of one of the following shapes: + + - (M, N): an image with scalar data. Color-mapping is controlled + by *cmap*, *norm*, *vmin*, and *vmax*. + - (M, N, 3): an image with RGB values (0-1 float or 0-255 int). + - (M, N, 4): an image with RGBA values (0-1 float or 0-255 int), + i.e. including transparency. + + xo, yo : int + The *x*/*y* image offset in pixels. + + alpha : None or float + The alpha blending value. + + %(cmap_doc)s + + This parameter is ignored if *X* is RGB(A). + + %(norm_doc)s + + This parameter is ignored if *X* is RGB(A). + + %(vmin_vmax_doc)s + + This parameter is ignored if *X* is RGB(A). + + origin : {'upper', 'lower'}, default: :rc:`image.origin` + Indicates where the [0, 0] index of the array is in the upper left + or lower left corner of the Axes. + + resize : bool + If *True*, resize the figure to match the given image size. + + %(colorizer_doc)s + + This parameter is ignored if *X* is RGB(A). + + Returns + ------- + `matplotlib.image.FigureImage` + + Other Parameters + ---------------- + **kwargs + Additional kwargs are `.Artist` kwargs passed on to `.FigureImage`. + + Notes + ----- + figimage complements the Axes image (`~matplotlib.axes.Axes.imshow`) + which will be resampled to fit the current Axes. If you want + a resampled image to fill the entire figure, you can define an + `~matplotlib.axes.Axes` with extent [0, 0, 1, 1]. + + Examples + -------- + :: + + f = plt.figure() + nx = int(f.get_figwidth() * f.dpi) + ny = int(f.get_figheight() * f.dpi) + data = np.random.random((ny, nx)) + f.figimage(data) + plt.show() + """ + if resize: + dpi = self.get_dpi() + figsize = [x / dpi for x in (X.shape[1], X.shape[0])] + self.set_size_inches(figsize, forward=True) + + im = mimage.FigureImage(self, cmap=cmap, norm=norm, + colorizer=colorizer, + offsetx=xo, offsety=yo, + origin=origin, **kwargs) + im.stale_callback = _stale_figure_callback + + im.set_array(X) + im.set_alpha(alpha) + if norm is None: + im._check_exclusionary_keywords(colorizer, vmin=vmin, vmax=vmax) + im.set_clim(vmin, vmax) + self.images.append(im) + im._remove_method = self.images.remove + self.stale = True + return im + + def set_size_inches(self, w, h=None, forward=True): + """ + Set the figure size in inches. + + Call signatures:: + + fig.set_size_inches(w, h) # OR + fig.set_size_inches((w, h)) + + Parameters + ---------- + w : (float, float) or float + Width and height in inches (if height not specified as a separate + argument) or width. + h : float + Height in inches. + forward : bool, default: True + If ``True``, the canvas size is automatically updated, e.g., + you can resize the figure window from the shell. + + See Also + -------- + matplotlib.figure.Figure.get_size_inches + matplotlib.figure.Figure.set_figwidth + matplotlib.figure.Figure.set_figheight + + Notes + ----- + To transform from pixels to inches divide by `Figure.dpi`. + """ + if h is None: # Got called with a single pair as argument. + w, h = w + size = np.array([w, h]) + if not np.isfinite(size).all() or (size < 0).any(): + raise ValueError(f'figure size must be positive finite not {size}') + self.bbox_inches.p1 = size + if forward: + manager = self.canvas.manager + if manager is not None: + manager.resize(*(size * self.dpi).astype(int)) + self.stale = True + + def get_size_inches(self): + """ + Return the current size of the figure in inches. + + Returns + ------- + ndarray + The size (width, height) of the figure in inches. + + See Also + -------- + matplotlib.figure.Figure.set_size_inches + matplotlib.figure.Figure.get_figwidth + matplotlib.figure.Figure.get_figheight + + Notes + ----- + The size in pixels can be obtained by multiplying with `Figure.dpi`. + """ + return np.array(self.bbox_inches.p1) + + def get_figwidth(self): + """Return the figure width in inches.""" + return self.bbox_inches.width + + def get_figheight(self): + """Return the figure height in inches.""" + return self.bbox_inches.height + + def get_dpi(self): + """Return the resolution in dots per inch as a float.""" + return self.dpi + + def set_dpi(self, val): + """ + Set the resolution of the figure in dots-per-inch. + + Parameters + ---------- + val : float + """ + self.dpi = val + self.stale = True + + def set_figwidth(self, val, forward=True): + """ + Set the width of the figure in inches. + + Parameters + ---------- + val : float + forward : bool + See `set_size_inches`. + + See Also + -------- + matplotlib.figure.Figure.set_figheight + matplotlib.figure.Figure.set_size_inches + """ + self.set_size_inches(val, self.get_figheight(), forward=forward) + + def set_figheight(self, val, forward=True): + """ + Set the height of the figure in inches. + + Parameters + ---------- + val : float + forward : bool + See `set_size_inches`. + + See Also + -------- + matplotlib.figure.Figure.set_figwidth + matplotlib.figure.Figure.set_size_inches + """ + self.set_size_inches(self.get_figwidth(), val, forward=forward) + + def clear(self, keep_observers=False): + # docstring inherited + super().clear(keep_observers=keep_observers) + # FigureBase.clear does not clear toolbars, as + # only Figure can have toolbars + toolbar = self.canvas.toolbar + if toolbar is not None: + toolbar.update() + + @_finalize_rasterization + @allow_rasterization + def draw(self, renderer): + # docstring inherited + if not self.get_visible(): + return + + with self._render_lock: + + artists = self._get_draw_artists(renderer) + try: + renderer.open_group('figure', gid=self.get_gid()) + if self.axes and self.get_layout_engine() is not None: + try: + self.get_layout_engine().execute(self) + except ValueError: + pass + # ValueError can occur when resizing a window. + + self.patch.draw(renderer) + mimage._draw_list_compositing_images( + renderer, self, artists, self.suppressComposite) + + renderer.close_group('figure') + finally: + self.stale = False + + DrawEvent("draw_event", self.canvas, renderer)._process() + + def draw_without_rendering(self): + """ + Draw the figure with no output. Useful to get the final size of + artists that require a draw before their size is known (e.g. text). + """ + renderer = _get_renderer(self) + with renderer._draw_disabled(): + self.draw(renderer) + + def draw_artist(self, a): + """ + Draw `.Artist` *a* only. + """ + a.draw(self.canvas.get_renderer()) + + def __getstate__(self): + state = super().__getstate__() + + # The canvas cannot currently be pickled, but this has the benefit + # of meaning that a figure can be detached from one canvas, and + # re-attached to another. + state.pop("canvas") + + # discard any changes to the dpi due to pixel ratio changes + state["_dpi"] = state.get('_original_dpi', state['_dpi']) + + # add version information to the state + state['__mpl_version__'] = mpl.__version__ + + # check whether the figure manager (if any) is registered with pyplot + from matplotlib import _pylab_helpers + if self.canvas.manager in _pylab_helpers.Gcf.figs.values(): + state['_restore_to_pylab'] = True + return state + + def __setstate__(self, state): + version = state.pop('__mpl_version__') + restore_to_pylab = state.pop('_restore_to_pylab', False) + + if version != mpl.__version__: + _api.warn_external( + f"This figure was saved with matplotlib version {version} and " + f"loaded with {mpl.__version__} so may not function correctly." + ) + self.__dict__ = state + + # re-initialise some of the unstored state information + FigureCanvasBase(self) # Set self.canvas. + + if restore_to_pylab: + # lazy import to avoid circularity + import matplotlib.pyplot as plt + import matplotlib._pylab_helpers as pylab_helpers + allnums = plt.get_fignums() + num = max(allnums) + 1 if allnums else 1 + backend = plt._get_backend_mod() + mgr = backend.new_figure_manager_given_figure(num, self) + pylab_helpers.Gcf._set_new_active_manager(mgr) + plt.draw_if_interactive() + + self.stale = True + + def add_axobserver(self, func): + """Whenever the Axes state change, ``func(self)`` will be called.""" + # Connect a wrapper lambda and not func itself, to avoid it being + # weakref-collected. + self._axobservers.connect("_axes_change_event", lambda arg: func(arg)) + + def savefig(self, fname, *, transparent=None, **kwargs): + """ + Save the current figure as an image or vector graphic to a file. + + Call signature:: + + savefig(fname, *, transparent=None, dpi='figure', format=None, + metadata=None, bbox_inches=None, pad_inches=0.1, + facecolor='auto', edgecolor='auto', backend=None, + **kwargs + ) + + The available output formats depend on the backend being used. + + Parameters + ---------- + fname : str or path-like or binary file-like + A path, or a Python file-like object, or + possibly some backend-dependent object such as + `matplotlib.backends.backend_pdf.PdfPages`. + + If *format* is set, it determines the output format, and the file + is saved as *fname*. Note that *fname* is used verbatim, and there + is no attempt to make the extension, if any, of *fname* match + *format*, and no extension is appended. + + If *format* is not set, then the format is inferred from the + extension of *fname*, if there is one. If *format* is not + set and *fname* has no extension, then the file is saved with + :rc:`savefig.format` and the appropriate extension is appended to + *fname*. + + Other Parameters + ---------------- + transparent : bool, default: :rc:`savefig.transparent` + If *True*, the Axes patches will all be transparent; the + Figure patch will also be transparent unless *facecolor* + and/or *edgecolor* are specified via kwargs. + + If *False* has no effect and the color of the Axes and + Figure patches are unchanged (unless the Figure patch + is specified via the *facecolor* and/or *edgecolor* keyword + arguments in which case those colors are used). + + The transparency of these patches will be restored to their + original values upon exit of this function. + + This is useful, for example, for displaying + a plot on top of a colored background on a web page. + + dpi : float or 'figure', default: :rc:`savefig.dpi` + The resolution in dots per inch. If 'figure', use the figure's + dpi value. + + format : str + The file format, e.g. 'png', 'pdf', 'svg', ... The behavior when + this is unset is documented under *fname*. + + metadata : dict, optional + Key/value pairs to store in the image metadata. The supported keys + and defaults depend on the image format and backend: + + - 'png' with Agg backend: See the parameter ``metadata`` of + `~.FigureCanvasAgg.print_png`. + - 'pdf' with pdf backend: See the parameter ``metadata`` of + `~.backend_pdf.PdfPages`. + - 'svg' with svg backend: See the parameter ``metadata`` of + `~.FigureCanvasSVG.print_svg`. + - 'eps' and 'ps' with PS backend: Only 'Creator' is supported. + + Not supported for 'pgf', 'raw', and 'rgba' as those formats do not support + embedding metadata. + Does not currently support 'jpg', 'tiff', or 'webp', but may include + embedding EXIF metadata in the future. + + bbox_inches : str or `.Bbox`, default: :rc:`savefig.bbox` + Bounding box in inches: only the given portion of the figure is + saved. If 'tight', try to figure out the tight bbox of the figure. + + pad_inches : float or 'layout', default: :rc:`savefig.pad_inches` + Amount of padding in inches around the figure when bbox_inches is + 'tight'. If 'layout' use the padding from the constrained or + compressed layout engine; ignored if one of those engines is not in + use. + + facecolor : :mpltype:`color` or 'auto', default: :rc:`savefig.facecolor` + The facecolor of the figure. If 'auto', use the current figure + facecolor. + + edgecolor : :mpltype:`color` or 'auto', default: :rc:`savefig.edgecolor` + The edgecolor of the figure. If 'auto', use the current figure + edgecolor. + + backend : str, optional + Use a non-default backend to render the file, e.g. to render a + png file with the "cairo" backend rather than the default "agg", + or a pdf file with the "pgf" backend rather than the default + "pdf". Note that the default backend is normally sufficient. See + :ref:`the-builtin-backends` for a list of valid backends for each + file format. Custom backends can be referenced as "module://...". + + orientation : {'landscape', 'portrait'} + Currently only supported by the postscript backend. + + papertype : str + One of 'letter', 'legal', 'executive', 'ledger', 'a0' through + 'a10', 'b0' through 'b10'. Only supported for postscript + output. + + bbox_extra_artists : list of `~matplotlib.artist.Artist`, optional + A list of extra artists that will be considered when the + tight bbox is calculated. + + pil_kwargs : dict, optional + Additional keyword arguments that are passed to + `PIL.Image.Image.save` when saving the figure. + + """ + + kwargs.setdefault('dpi', mpl.rcParams['savefig.dpi']) + if transparent is None: + transparent = mpl.rcParams['savefig.transparent'] + + with ExitStack() as stack: + if transparent: + def _recursively_make_subfig_transparent(exit_stack, subfig): + exit_stack.enter_context( + subfig.patch._cm_set( + facecolor="none", edgecolor="none")) + for ax in subfig.axes: + exit_stack.enter_context( + ax.patch._cm_set( + facecolor="none", edgecolor="none")) + for sub_subfig in subfig.subfigs: + _recursively_make_subfig_transparent( + exit_stack, sub_subfig) + + def _recursively_make_axes_transparent(exit_stack, ax): + exit_stack.enter_context( + ax.patch._cm_set(facecolor="none", edgecolor="none")) + for child_ax in ax.child_axes: + exit_stack.enter_context( + child_ax.patch._cm_set( + facecolor="none", edgecolor="none")) + for child_childax in ax.child_axes: + _recursively_make_axes_transparent( + exit_stack, child_childax) + + kwargs.setdefault('facecolor', 'none') + kwargs.setdefault('edgecolor', 'none') + # set subfigure to appear transparent in printed image + for subfig in self.subfigs: + _recursively_make_subfig_transparent(stack, subfig) + # set Axes to be transparent + for ax in self.axes: + _recursively_make_axes_transparent(stack, ax) + self.canvas.print_figure(fname, **kwargs) + + def ginput(self, n=1, timeout=30, show_clicks=True, + mouse_add=MouseButton.LEFT, + mouse_pop=MouseButton.RIGHT, + mouse_stop=MouseButton.MIDDLE): + """ + Blocking call to interact with a figure. + + Wait until the user clicks *n* times on the figure, and return the + coordinates of each click in a list. + + There are three possible interactions: + + - Add a point. + - Remove the most recently added point. + - Stop the interaction and return the points added so far. + + The actions are assigned to mouse buttons via the arguments + *mouse_add*, *mouse_pop* and *mouse_stop*. + + Parameters + ---------- + n : int, default: 1 + Number of mouse clicks to accumulate. If negative, accumulate + clicks until the input is terminated manually. + timeout : float, default: 30 seconds + Number of seconds to wait before timing out. If zero or negative + will never time out. + show_clicks : bool, default: True + If True, show a red cross at the location of each click. + mouse_add : `.MouseButton` or None, default: `.MouseButton.LEFT` + Mouse button used to add points. + mouse_pop : `.MouseButton` or None, default: `.MouseButton.RIGHT` + Mouse button used to remove the most recently added point. + mouse_stop : `.MouseButton` or None, default: `.MouseButton.MIDDLE` + Mouse button used to stop input. + + Returns + ------- + list of tuples + A list of the clicked (x, y) coordinates. + + Notes + ----- + The keyboard can also be used to select points in case your mouse + does not have one or more of the buttons. The delete and backspace + keys act like right-clicking (i.e., remove last point), the enter key + terminates input and any other key (not already used by the window + manager) selects a point. + """ + clicks = [] + marks = [] + + def handler(event): + is_button = event.name == "button_press_event" + is_key = event.name == "key_press_event" + # Quit (even if not in infinite mode; this is consistent with + # MATLAB and sometimes quite useful, but will require the user to + # test how many points were actually returned before using data). + if (is_button and event.button == mouse_stop + or is_key and event.key in ["escape", "enter"]): + self.canvas.stop_event_loop() + # Pop last click. + elif (is_button and event.button == mouse_pop + or is_key and event.key in ["backspace", "delete"]): + if clicks: + clicks.pop() + if show_clicks: + marks.pop().remove() + self.canvas.draw() + # Add new click. + elif (is_button and event.button == mouse_add + # On macOS/gtk, some keys return None. + or is_key and event.key is not None): + if event.inaxes: + clicks.append((event.xdata, event.ydata)) + _log.info("input %i: %f, %f", + len(clicks), event.xdata, event.ydata) + if show_clicks: + line = mpl.lines.Line2D([event.xdata], [event.ydata], + marker="+", color="r") + event.inaxes.add_line(line) + marks.append(line) + self.canvas.draw() + if len(clicks) == n and n > 0: + self.canvas.stop_event_loop() + + _blocking_input.blocking_input_loop( + self, ["button_press_event", "key_press_event"], timeout, handler) + + # Cleanup. + for mark in marks: + mark.remove() + self.canvas.draw() + + return clicks + + def waitforbuttonpress(self, timeout=-1): + """ + Blocking call to interact with the figure. + + Wait for user input and return True if a key was pressed, False if a + mouse button was pressed and None if no input was given within + *timeout* seconds. Negative values deactivate *timeout*. + """ + event = None + + def handler(ev): + nonlocal event + event = ev + self.canvas.stop_event_loop() + + _blocking_input.blocking_input_loop( + self, ["button_press_event", "key_press_event"], timeout, handler) + + return None if event is None else event.name == "key_press_event" + + def tight_layout(self, *, pad=1.08, h_pad=None, w_pad=None, rect=None): + """ + Adjust the padding between and around subplots. + + To exclude an artist on the Axes from the bounding box calculation + that determines the subplot parameters (i.e. legend, or annotation), + set ``a.set_in_layout(False)`` for that artist. + + Parameters + ---------- + pad : float, default: 1.08 + Padding between the figure edge and the edges of subplots, + as a fraction of the font size. + h_pad, w_pad : float, default: *pad* + Padding (height/width) between edges of adjacent subplots, + as a fraction of the font size. + rect : tuple (left, bottom, right, top), default: (0, 0, 1, 1) + A rectangle in normalized figure coordinates into which the whole + subplots area (including labels) will fit. + + See Also + -------- + .Figure.set_layout_engine + .pyplot.tight_layout + """ + # note that here we do not permanently set the figures engine to + # tight_layout but rather just perform the layout in place and remove + # any previous engines. + engine = TightLayoutEngine(pad=pad, h_pad=h_pad, w_pad=w_pad, rect=rect) + try: + previous_engine = self.get_layout_engine() + self.set_layout_engine(engine) + engine.execute(self) + if previous_engine is not None and not isinstance( + previous_engine, (TightLayoutEngine, PlaceHolderLayoutEngine) + ): + _api.warn_external('The figure layout has changed to tight') + finally: + self.set_layout_engine('none') + + +def figaspect(arg): + """ + Calculate the width and height for a figure with a specified aspect ratio. + + While the height is taken from :rc:`figure.figsize`, the width is + adjusted to match the desired aspect ratio. Additionally, it is ensured + that the width is in the range [4., 16.] and the height is in the range + [2., 16.]. If necessary, the default height is adjusted to ensure this. + + Parameters + ---------- + arg : float or 2D array + If a float, this defines the aspect ratio (i.e. the ratio height / + width). + In case of an array the aspect ratio is number of rows / number of + columns, so that the array could be fitted in the figure undistorted. + + Returns + ------- + width, height : float + The figure size in inches. + + Notes + ----- + If you want to create an Axes within the figure, that still preserves the + aspect ratio, be sure to create it with equal width and height. See + examples below. + + Thanks to Fernando Perez for this function. + + Examples + -------- + Make a figure twice as tall as it is wide:: + + w, h = figaspect(2.) + fig = Figure(figsize=(w, h)) + ax = fig.add_axes([0.1, 0.1, 0.8, 0.8]) + ax.imshow(A, **kwargs) + + Make a figure with the proper aspect for an array:: + + A = rand(5, 3) + w, h = figaspect(A) + fig = Figure(figsize=(w, h)) + ax = fig.add_axes([0.1, 0.1, 0.8, 0.8]) + ax.imshow(A, **kwargs) + """ + + isarray = hasattr(arg, 'shape') and not np.isscalar(arg) + + # min/max sizes to respect when autoscaling. If John likes the idea, they + # could become rc parameters, for now they're hardwired. + figsize_min = np.array((4.0, 2.0)) # min length for width/height + figsize_max = np.array((16.0, 16.0)) # max length for width/height + + # Extract the aspect ratio of the array + if isarray: + nr, nc = arg.shape[:2] + arr_ratio = nr / nc + else: + arr_ratio = arg + + # Height of user figure defaults + fig_height = mpl.rcParams['figure.figsize'][1] + + # New size for the figure, keeping the aspect ratio of the caller + newsize = np.array((fig_height / arr_ratio, fig_height)) + + # Sanity checks, don't drop either dimension below figsize_min + newsize /= min(1.0, *(newsize / figsize_min)) + + # Avoid humongous windows as well + newsize /= max(1.0, *(newsize / figsize_max)) + + # Finally, if we have a really funky aspect ratio, break it but respect + # the min/max dimensions (we don't want figures 10 feet tall!) + newsize = np.clip(newsize, figsize_min, figsize_max) + return newsize diff --git a/infer_4_30_0/lib/python3.10/site-packages/matplotlib/ft2font.pyi b/infer_4_30_0/lib/python3.10/site-packages/matplotlib/ft2font.pyi new file mode 100644 index 0000000000000000000000000000000000000000..37281afeaafa751790af911a422aedebece7133e --- /dev/null +++ b/infer_4_30_0/lib/python3.10/site-packages/matplotlib/ft2font.pyi @@ -0,0 +1,312 @@ +from enum import Enum, Flag +import sys +from typing import BinaryIO, Literal, TypedDict, final, overload, cast +from typing_extensions import Buffer # < Py 3.12 + +import numpy as np +from numpy.typing import NDArray + +__freetype_build_type__: str +__freetype_version__: str + +class FaceFlags(Flag): + SCALABLE = cast(int, ...) + FIXED_SIZES = cast(int, ...) + FIXED_WIDTH = cast(int, ...) + SFNT = cast(int, ...) + HORIZONTAL = cast(int, ...) + VERTICAL = cast(int, ...) + KERNING = cast(int, ...) + FAST_GLYPHS = cast(int, ...) + MULTIPLE_MASTERS = cast(int, ...) + GLYPH_NAMES = cast(int, ...) + EXTERNAL_STREAM = cast(int, ...) + HINTER = cast(int, ...) + CID_KEYED = cast(int, ...) + TRICKY = cast(int, ...) + COLOR = cast(int, ...) + # VARIATION = cast(int, ...) # FT 2.9 + # SVG = cast(int, ...) # FT 2.12 + # SBIX = cast(int, ...) # FT 2.12 + # SBIX_OVERLAY = cast(int, ...) # FT 2.12 + +class Kerning(Enum): + DEFAULT = cast(int, ...) + UNFITTED = cast(int, ...) + UNSCALED = cast(int, ...) + +class LoadFlags(Flag): + DEFAULT = cast(int, ...) + NO_SCALE = cast(int, ...) + NO_HINTING = cast(int, ...) + RENDER = cast(int, ...) + NO_BITMAP = cast(int, ...) + VERTICAL_LAYOUT = cast(int, ...) + FORCE_AUTOHINT = cast(int, ...) + CROP_BITMAP = cast(int, ...) + PEDANTIC = cast(int, ...) + IGNORE_GLOBAL_ADVANCE_WIDTH = cast(int, ...) + NO_RECURSE = cast(int, ...) + IGNORE_TRANSFORM = cast(int, ...) + MONOCHROME = cast(int, ...) + LINEAR_DESIGN = cast(int, ...) + NO_AUTOHINT = cast(int, ...) + COLOR = cast(int, ...) + COMPUTE_METRICS = cast(int, ...) # FT 2.6.1 + # BITMAP_METRICS_ONLY = cast(int, ...) # FT 2.7.1 + # NO_SVG = cast(int, ...) # FT 2.13.1 + # The following should be unique, but the above can be OR'd together. + TARGET_NORMAL = cast(int, ...) + TARGET_LIGHT = cast(int, ...) + TARGET_MONO = cast(int, ...) + TARGET_LCD = cast(int, ...) + TARGET_LCD_V = cast(int, ...) + +class StyleFlags(Flag): + NORMAL = cast(int, ...) + ITALIC = cast(int, ...) + BOLD = cast(int, ...) + +class _SfntHeadDict(TypedDict): + version: tuple[int, int] + fontRevision: tuple[int, int] + checkSumAdjustment: int + magicNumber: int + flags: int + unitsPerEm: int + created: tuple[int, int] + modified: tuple[int, int] + xMin: int + yMin: int + xMax: int + yMax: int + macStyle: int + lowestRecPPEM: int + fontDirectionHint: int + indexToLocFormat: int + glyphDataFormat: int + +class _SfntMaxpDict(TypedDict): + version: tuple[int, int] + numGlyphs: int + maxPoints: int + maxContours: int + maxComponentPoints: int + maxComponentContours: int + maxZones: int + maxTwilightPoints: int + maxStorage: int + maxFunctionDefs: int + maxInstructionDefs: int + maxStackElements: int + maxSizeOfInstructions: int + maxComponentElements: int + maxComponentDepth: int + +class _SfntOs2Dict(TypedDict): + version: int + xAvgCharWidth: int + usWeightClass: int + usWidthClass: int + fsType: int + ySubscriptXSize: int + ySubscriptYSize: int + ySubscriptXOffset: int + ySubscriptYOffset: int + ySuperscriptXSize: int + ySuperscriptYSize: int + ySuperscriptXOffset: int + ySuperscriptYOffset: int + yStrikeoutSize: int + yStrikeoutPosition: int + sFamilyClass: int + panose: bytes + ulCharRange: tuple[int, int, int, int] + achVendID: bytes + fsSelection: int + fsFirstCharIndex: int + fsLastCharIndex: int + +class _SfntHheaDict(TypedDict): + version: tuple[int, int] + ascent: int + descent: int + lineGap: int + advanceWidthMax: int + minLeftBearing: int + minRightBearing: int + xMaxExtent: int + caretSlopeRise: int + caretSlopeRun: int + caretOffset: int + metricDataFormat: int + numOfLongHorMetrics: int + +class _SfntVheaDict(TypedDict): + version: tuple[int, int] + vertTypoAscender: int + vertTypoDescender: int + vertTypoLineGap: int + advanceHeightMax: int + minTopSideBearing: int + minBottomSizeBearing: int + yMaxExtent: int + caretSlopeRise: int + caretSlopeRun: int + caretOffset: int + metricDataFormat: int + numOfLongVerMetrics: int + +class _SfntPostDict(TypedDict): + format: tuple[int, int] + italicAngle: tuple[int, int] + underlinePosition: int + underlineThickness: int + isFixedPitch: int + minMemType42: int + maxMemType42: int + minMemType1: int + maxMemType1: int + +class _SfntPcltDict(TypedDict): + version: tuple[int, int] + fontNumber: int + pitch: int + xHeight: int + style: int + typeFamily: int + capHeight: int + symbolSet: int + typeFace: bytes + characterComplement: bytes + strokeWeight: int + widthType: int + serifStyle: int + +@final +class FT2Font(Buffer): + def __init__( + self, + filename: str | BinaryIO, + hinting_factor: int = ..., + *, + _fallback_list: list[FT2Font] | None = ..., + _kerning_factor: int = ... + ) -> None: ... + if sys.version_info[:2] >= (3, 12): + def __buffer__(self, flags: int) -> memoryview: ... + def _get_fontmap(self, string: str) -> dict[str, FT2Font]: ... + def clear(self) -> None: ... + def draw_glyph_to_bitmap( + self, image: FT2Image, x: int, y: int, glyph: Glyph, antialiased: bool = ... + ) -> None: ... + def draw_glyphs_to_bitmap(self, antialiased: bool = ...) -> None: ... + def get_bitmap_offset(self) -> tuple[int, int]: ... + def get_char_index(self, codepoint: int) -> int: ... + def get_charmap(self) -> dict[int, int]: ... + def get_descent(self) -> int: ... + def get_glyph_name(self, index: int) -> str: ... + def get_image(self) -> NDArray[np.uint8]: ... + def get_kerning(self, left: int, right: int, mode: Kerning) -> int: ... + def get_name_index(self, name: str) -> int: ... + def get_num_glyphs(self) -> int: ... + def get_path(self) -> tuple[NDArray[np.float64], NDArray[np.int8]]: ... + def get_ps_font_info( + self, + ) -> tuple[str, str, str, str, str, int, int, int, int]: ... + def get_sfnt(self) -> dict[tuple[int, int, int, int], bytes]: ... + @overload + def get_sfnt_table(self, name: Literal["head"]) -> _SfntHeadDict | None: ... + @overload + def get_sfnt_table(self, name: Literal["maxp"]) -> _SfntMaxpDict | None: ... + @overload + def get_sfnt_table(self, name: Literal["OS/2"]) -> _SfntOs2Dict | None: ... + @overload + def get_sfnt_table(self, name: Literal["hhea"]) -> _SfntHheaDict | None: ... + @overload + def get_sfnt_table(self, name: Literal["vhea"]) -> _SfntVheaDict | None: ... + @overload + def get_sfnt_table(self, name: Literal["post"]) -> _SfntPostDict | None: ... + @overload + def get_sfnt_table(self, name: Literal["pclt"]) -> _SfntPcltDict | None: ... + def get_width_height(self) -> tuple[int, int]: ... + def load_char(self, charcode: int, flags: LoadFlags = ...) -> Glyph: ... + def load_glyph(self, glyphindex: int, flags: LoadFlags = ...) -> Glyph: ... + def select_charmap(self, i: int) -> None: ... + def set_charmap(self, i: int) -> None: ... + def set_size(self, ptsize: float, dpi: float) -> None: ... + def set_text( + self, string: str, angle: float = ..., flags: LoadFlags = ... + ) -> NDArray[np.float64]: ... + @property + def ascender(self) -> int: ... + @property + def bbox(self) -> tuple[int, int, int, int]: ... + @property + def descender(self) -> int: ... + @property + def face_flags(self) -> FaceFlags: ... + @property + def family_name(self) -> str: ... + @property + def fname(self) -> str: ... + @property + def height(self) -> int: ... + @property + def max_advance_height(self) -> int: ... + @property + def max_advance_width(self) -> int: ... + @property + def num_charmaps(self) -> int: ... + @property + def num_faces(self) -> int: ... + @property + def num_fixed_sizes(self) -> int: ... + @property + def num_glyphs(self) -> int: ... + @property + def num_named_instances(self) -> int: ... + @property + def postscript_name(self) -> str: ... + @property + def scalable(self) -> bool: ... + @property + def style_flags(self) -> StyleFlags: ... + @property + def style_name(self) -> str: ... + @property + def underline_position(self) -> int: ... + @property + def underline_thickness(self) -> int: ... + @property + def units_per_EM(self) -> int: ... + +@final +class FT2Image(Buffer): + def __init__(self, width: int, height: int) -> None: ... + def draw_rect_filled(self, x0: int, y0: int, x1: int, y1: int) -> None: ... + if sys.version_info[:2] >= (3, 12): + def __buffer__(self, flags: int) -> memoryview: ... + +@final +class Glyph: + @property + def width(self) -> int: ... + @property + def height(self) -> int: ... + @property + def horiBearingX(self) -> int: ... + @property + def horiBearingY(self) -> int: ... + @property + def horiAdvance(self) -> int: ... + @property + def linearHoriAdvance(self) -> int: ... + @property + def vertBearingX(self) -> int: ... + @property + def vertBearingY(self) -> int: ... + @property + def vertAdvance(self) -> int: ... + @property + def bbox(self) -> tuple[int, int, int, int]: ... diff --git a/infer_4_30_0/lib/python3.10/site-packages/matplotlib/gridspec.py b/infer_4_30_0/lib/python3.10/site-packages/matplotlib/gridspec.py new file mode 100644 index 0000000000000000000000000000000000000000..06f0b2f7f781d291ca6159fd7ad8333d75dc6abb --- /dev/null +++ b/infer_4_30_0/lib/python3.10/site-packages/matplotlib/gridspec.py @@ -0,0 +1,788 @@ +r""" +:mod:`~matplotlib.gridspec` contains classes that help to layout multiple +`~.axes.Axes` in a grid-like pattern within a figure. + +The `GridSpec` specifies the overall grid structure. Individual cells within +the grid are referenced by `SubplotSpec`\s. + +Often, users need not access this module directly, and can use higher-level +methods like `~.pyplot.subplots`, `~.pyplot.subplot_mosaic` and +`~.Figure.subfigures`. See the tutorial :ref:`arranging_axes` for a guide. +""" + +import copy +import logging +from numbers import Integral + +import numpy as np + +import matplotlib as mpl +from matplotlib import _api, _pylab_helpers, _tight_layout +from matplotlib.transforms import Bbox + +_log = logging.getLogger(__name__) + + +class GridSpecBase: + """ + A base class of GridSpec that specifies the geometry of the grid + that a subplot will be placed. + """ + + def __init__(self, nrows, ncols, height_ratios=None, width_ratios=None): + """ + Parameters + ---------- + nrows, ncols : int + The number of rows and columns of the grid. + width_ratios : array-like of length *ncols*, optional + Defines the relative widths of the columns. Each column gets a + relative width of ``width_ratios[i] / sum(width_ratios)``. + If not given, all columns will have the same width. + height_ratios : array-like of length *nrows*, optional + Defines the relative heights of the rows. Each row gets a + relative height of ``height_ratios[i] / sum(height_ratios)``. + If not given, all rows will have the same height. + """ + if not isinstance(nrows, Integral) or nrows <= 0: + raise ValueError( + f"Number of rows must be a positive integer, not {nrows!r}") + if not isinstance(ncols, Integral) or ncols <= 0: + raise ValueError( + f"Number of columns must be a positive integer, not {ncols!r}") + self._nrows, self._ncols = nrows, ncols + self.set_height_ratios(height_ratios) + self.set_width_ratios(width_ratios) + + def __repr__(self): + height_arg = (f', height_ratios={self._row_height_ratios!r}' + if len(set(self._row_height_ratios)) != 1 else '') + width_arg = (f', width_ratios={self._col_width_ratios!r}' + if len(set(self._col_width_ratios)) != 1 else '') + return '{clsname}({nrows}, {ncols}{optionals})'.format( + clsname=self.__class__.__name__, + nrows=self._nrows, + ncols=self._ncols, + optionals=height_arg + width_arg, + ) + + nrows = property(lambda self: self._nrows, + doc="The number of rows in the grid.") + ncols = property(lambda self: self._ncols, + doc="The number of columns in the grid.") + + def get_geometry(self): + """ + Return a tuple containing the number of rows and columns in the grid. + """ + return self._nrows, self._ncols + + def get_subplot_params(self, figure=None): + # Must be implemented in subclasses + pass + + def new_subplotspec(self, loc, rowspan=1, colspan=1): + """ + Create and return a `.SubplotSpec` instance. + + Parameters + ---------- + loc : (int, int) + The position of the subplot in the grid as + ``(row_index, column_index)``. + rowspan, colspan : int, default: 1 + The number of rows and columns the subplot should span in the grid. + """ + loc1, loc2 = loc + subplotspec = self[loc1:loc1+rowspan, loc2:loc2+colspan] + return subplotspec + + def set_width_ratios(self, width_ratios): + """ + Set the relative widths of the columns. + + *width_ratios* must be of length *ncols*. Each column gets a relative + width of ``width_ratios[i] / sum(width_ratios)``. + """ + if width_ratios is None: + width_ratios = [1] * self._ncols + elif len(width_ratios) != self._ncols: + raise ValueError('Expected the given number of width ratios to ' + 'match the number of columns of the grid') + self._col_width_ratios = width_ratios + + def get_width_ratios(self): + """ + Return the width ratios. + + This is *None* if no width ratios have been set explicitly. + """ + return self._col_width_ratios + + def set_height_ratios(self, height_ratios): + """ + Set the relative heights of the rows. + + *height_ratios* must be of length *nrows*. Each row gets a relative + height of ``height_ratios[i] / sum(height_ratios)``. + """ + if height_ratios is None: + height_ratios = [1] * self._nrows + elif len(height_ratios) != self._nrows: + raise ValueError('Expected the given number of height ratios to ' + 'match the number of rows of the grid') + self._row_height_ratios = height_ratios + + def get_height_ratios(self): + """ + Return the height ratios. + + This is *None* if no height ratios have been set explicitly. + """ + return self._row_height_ratios + + def get_grid_positions(self, fig): + """ + Return the positions of the grid cells in figure coordinates. + + Parameters + ---------- + fig : `~matplotlib.figure.Figure` + The figure the grid should be applied to. The subplot parameters + (margins and spacing between subplots) are taken from *fig*. + + Returns + ------- + bottoms, tops, lefts, rights : array + The bottom, top, left, right positions of the grid cells in + figure coordinates. + """ + nrows, ncols = self.get_geometry() + subplot_params = self.get_subplot_params(fig) + left = subplot_params.left + right = subplot_params.right + bottom = subplot_params.bottom + top = subplot_params.top + wspace = subplot_params.wspace + hspace = subplot_params.hspace + tot_width = right - left + tot_height = top - bottom + + # calculate accumulated heights of columns + cell_h = tot_height / (nrows + hspace*(nrows-1)) + sep_h = hspace * cell_h + norm = cell_h * nrows / sum(self._row_height_ratios) + cell_heights = [r * norm for r in self._row_height_ratios] + sep_heights = [0] + ([sep_h] * (nrows-1)) + cell_hs = np.cumsum(np.column_stack([sep_heights, cell_heights]).flat) + + # calculate accumulated widths of rows + cell_w = tot_width / (ncols + wspace*(ncols-1)) + sep_w = wspace * cell_w + norm = cell_w * ncols / sum(self._col_width_ratios) + cell_widths = [r * norm for r in self._col_width_ratios] + sep_widths = [0] + ([sep_w] * (ncols-1)) + cell_ws = np.cumsum(np.column_stack([sep_widths, cell_widths]).flat) + + fig_tops, fig_bottoms = (top - cell_hs).reshape((-1, 2)).T + fig_lefts, fig_rights = (left + cell_ws).reshape((-1, 2)).T + return fig_bottoms, fig_tops, fig_lefts, fig_rights + + @staticmethod + def _check_gridspec_exists(figure, nrows, ncols): + """ + Check if the figure already has a gridspec with these dimensions, + or create a new one + """ + for ax in figure.get_axes(): + gs = ax.get_gridspec() + if gs is not None: + if hasattr(gs, 'get_topmost_subplotspec'): + # This is needed for colorbar gridspec layouts. + # This is probably OK because this whole logic tree + # is for when the user is doing simple things with the + # add_subplot command. For complicated layouts + # like subgridspecs the proper gridspec is passed in... + gs = gs.get_topmost_subplotspec().get_gridspec() + if gs.get_geometry() == (nrows, ncols): + return gs + # else gridspec not found: + return GridSpec(nrows, ncols, figure=figure) + + def __getitem__(self, key): + """Create and return a `.SubplotSpec` instance.""" + nrows, ncols = self.get_geometry() + + def _normalize(key, size, axis): # Includes last index. + orig_key = key + if isinstance(key, slice): + start, stop, _ = key.indices(size) + if stop > start: + return start, stop - 1 + raise IndexError("GridSpec slice would result in no space " + "allocated for subplot") + else: + if key < 0: + key = key + size + if 0 <= key < size: + return key, key + elif axis is not None: + raise IndexError(f"index {orig_key} is out of bounds for " + f"axis {axis} with size {size}") + else: # flat index + raise IndexError(f"index {orig_key} is out of bounds for " + f"GridSpec with size {size}") + + if isinstance(key, tuple): + try: + k1, k2 = key + except ValueError as err: + raise ValueError("Unrecognized subplot spec") from err + num1, num2 = np.ravel_multi_index( + [_normalize(k1, nrows, 0), _normalize(k2, ncols, 1)], + (nrows, ncols)) + else: # Single key + num1, num2 = _normalize(key, nrows * ncols, None) + + return SubplotSpec(self, num1, num2) + + def subplots(self, *, sharex=False, sharey=False, squeeze=True, + subplot_kw=None): + """ + Add all subplots specified by this `GridSpec` to its parent figure. + + See `.Figure.subplots` for detailed documentation. + """ + + figure = self.figure + + if figure is None: + raise ValueError("GridSpec.subplots() only works for GridSpecs " + "created with a parent figure") + + if not isinstance(sharex, str): + sharex = "all" if sharex else "none" + if not isinstance(sharey, str): + sharey = "all" if sharey else "none" + + _api.check_in_list(["all", "row", "col", "none", False, True], + sharex=sharex, sharey=sharey) + if subplot_kw is None: + subplot_kw = {} + # don't mutate kwargs passed by user... + subplot_kw = subplot_kw.copy() + + # Create array to hold all Axes. + axarr = np.empty((self._nrows, self._ncols), dtype=object) + for row in range(self._nrows): + for col in range(self._ncols): + shared_with = {"none": None, "all": axarr[0, 0], + "row": axarr[row, 0], "col": axarr[0, col]} + subplot_kw["sharex"] = shared_with[sharex] + subplot_kw["sharey"] = shared_with[sharey] + axarr[row, col] = figure.add_subplot( + self[row, col], **subplot_kw) + + # turn off redundant tick labeling + if sharex in ["col", "all"]: + for ax in axarr.flat: + ax._label_outer_xaxis(skip_non_rectangular_axes=True) + if sharey in ["row", "all"]: + for ax in axarr.flat: + ax._label_outer_yaxis(skip_non_rectangular_axes=True) + + if squeeze: + # Discarding unneeded dimensions that equal 1. If we only have one + # subplot, just return it instead of a 1-element array. + return axarr.item() if axarr.size == 1 else axarr.squeeze() + else: + # Returned axis array will be always 2-d, even if nrows=ncols=1. + return axarr + + +class GridSpec(GridSpecBase): + """ + A grid layout to place subplots within a figure. + + The location of the grid cells is determined in a similar way to + `.SubplotParams` using *left*, *right*, *top*, *bottom*, *wspace* + and *hspace*. + + Indexing a GridSpec instance returns a `.SubplotSpec`. + """ + def __init__(self, nrows, ncols, figure=None, + left=None, bottom=None, right=None, top=None, + wspace=None, hspace=None, + width_ratios=None, height_ratios=None): + """ + Parameters + ---------- + nrows, ncols : int + The number of rows and columns of the grid. + + figure : `.Figure`, optional + Only used for constrained layout to create a proper layoutgrid. + + left, right, top, bottom : float, optional + Extent of the subplots as a fraction of figure width or height. + Left cannot be larger than right, and bottom cannot be larger than + top. If not given, the values will be inferred from a figure or + rcParams at draw time. See also `GridSpec.get_subplot_params`. + + wspace : float, optional + The amount of width reserved for space between subplots, + expressed as a fraction of the average axis width. + If not given, the values will be inferred from a figure or + rcParams when necessary. See also `GridSpec.get_subplot_params`. + + hspace : float, optional + The amount of height reserved for space between subplots, + expressed as a fraction of the average axis height. + If not given, the values will be inferred from a figure or + rcParams when necessary. See also `GridSpec.get_subplot_params`. + + width_ratios : array-like of length *ncols*, optional + Defines the relative widths of the columns. Each column gets a + relative width of ``width_ratios[i] / sum(width_ratios)``. + If not given, all columns will have the same width. + + height_ratios : array-like of length *nrows*, optional + Defines the relative heights of the rows. Each row gets a + relative height of ``height_ratios[i] / sum(height_ratios)``. + If not given, all rows will have the same height. + + """ + self.left = left + self.bottom = bottom + self.right = right + self.top = top + self.wspace = wspace + self.hspace = hspace + self.figure = figure + + super().__init__(nrows, ncols, + width_ratios=width_ratios, + height_ratios=height_ratios) + + _AllowedKeys = ["left", "bottom", "right", "top", "wspace", "hspace"] + + def update(self, **kwargs): + """ + Update the subplot parameters of the grid. + + Parameters that are not explicitly given are not changed. Setting a + parameter to *None* resets it to :rc:`figure.subplot.*`. + + Parameters + ---------- + left, right, top, bottom : float or None, optional + Extent of the subplots as a fraction of figure width or height. + wspace, hspace : float, optional + Spacing between the subplots as a fraction of the average subplot + width / height. + """ + for k, v in kwargs.items(): + if k in self._AllowedKeys: + setattr(self, k, v) + else: + raise AttributeError(f"{k} is an unknown keyword") + for figmanager in _pylab_helpers.Gcf.figs.values(): + for ax in figmanager.canvas.figure.axes: + if ax.get_subplotspec() is not None: + ss = ax.get_subplotspec().get_topmost_subplotspec() + if ss.get_gridspec() == self: + fig = ax.get_figure(root=False) + ax._set_position(ax.get_subplotspec().get_position(fig)) + + def get_subplot_params(self, figure=None): + """ + Return the `.SubplotParams` for the GridSpec. + + In order of precedence the values are taken from + + - non-*None* attributes of the GridSpec + - the provided *figure* + - :rc:`figure.subplot.*` + + Note that the ``figure`` attribute of the GridSpec is always ignored. + """ + if figure is None: + kw = {k: mpl.rcParams["figure.subplot."+k] + for k in self._AllowedKeys} + subplotpars = SubplotParams(**kw) + else: + subplotpars = copy.copy(figure.subplotpars) + + subplotpars.update(**{k: getattr(self, k) for k in self._AllowedKeys}) + + return subplotpars + + def locally_modified_subplot_params(self): + """ + Return a list of the names of the subplot parameters explicitly set + in the GridSpec. + + This is a subset of the attributes of `.SubplotParams`. + """ + return [k for k in self._AllowedKeys if getattr(self, k)] + + def tight_layout(self, figure, renderer=None, + pad=1.08, h_pad=None, w_pad=None, rect=None): + """ + Adjust subplot parameters to give specified padding. + + Parameters + ---------- + figure : `.Figure` + The figure. + renderer : `.RendererBase` subclass, optional + The renderer to be used. + pad : float + Padding between the figure edge and the edges of subplots, as a + fraction of the font-size. + h_pad, w_pad : float, optional + Padding (height/width) between edges of adjacent subplots. + Defaults to *pad*. + rect : tuple (left, bottom, right, top), default: None + (left, bottom, right, top) rectangle in normalized figure + coordinates that the whole subplots area (including labels) will + fit into. Default (None) is the whole figure. + """ + if renderer is None: + renderer = figure._get_renderer() + kwargs = _tight_layout.get_tight_layout_figure( + figure, figure.axes, + _tight_layout.get_subplotspec_list(figure.axes, grid_spec=self), + renderer, pad=pad, h_pad=h_pad, w_pad=w_pad, rect=rect) + if kwargs: + self.update(**kwargs) + + +class GridSpecFromSubplotSpec(GridSpecBase): + """ + GridSpec whose subplot layout parameters are inherited from the + location specified by a given SubplotSpec. + """ + def __init__(self, nrows, ncols, + subplot_spec, + wspace=None, hspace=None, + height_ratios=None, width_ratios=None): + """ + Parameters + ---------- + nrows, ncols : int + Number of rows and number of columns of the grid. + subplot_spec : SubplotSpec + Spec from which the layout parameters are inherited. + wspace, hspace : float, optional + See `GridSpec` for more details. If not specified default values + (from the figure or rcParams) are used. + height_ratios : array-like of length *nrows*, optional + See `GridSpecBase` for details. + width_ratios : array-like of length *ncols*, optional + See `GridSpecBase` for details. + """ + self._wspace = wspace + self._hspace = hspace + if isinstance(subplot_spec, SubplotSpec): + self._subplot_spec = subplot_spec + else: + raise TypeError( + "subplot_spec must be type SubplotSpec, " + "usually from GridSpec, or axes.get_subplotspec.") + self.figure = self._subplot_spec.get_gridspec().figure + super().__init__(nrows, ncols, + width_ratios=width_ratios, + height_ratios=height_ratios) + + def get_subplot_params(self, figure=None): + """Return a dictionary of subplot layout parameters.""" + hspace = (self._hspace if self._hspace is not None + else figure.subplotpars.hspace if figure is not None + else mpl.rcParams["figure.subplot.hspace"]) + wspace = (self._wspace if self._wspace is not None + else figure.subplotpars.wspace if figure is not None + else mpl.rcParams["figure.subplot.wspace"]) + + figbox = self._subplot_spec.get_position(figure) + left, bottom, right, top = figbox.extents + + return SubplotParams(left=left, right=right, + bottom=bottom, top=top, + wspace=wspace, hspace=hspace) + + def get_topmost_subplotspec(self): + """ + Return the topmost `.SubplotSpec` instance associated with the subplot. + """ + return self._subplot_spec.get_topmost_subplotspec() + + +class SubplotSpec: + """ + The location of a subplot in a `GridSpec`. + + .. note:: + + Likely, you will never instantiate a `SubplotSpec` yourself. Instead, + you will typically obtain one from a `GridSpec` using item-access. + + Parameters + ---------- + gridspec : `~matplotlib.gridspec.GridSpec` + The GridSpec, which the subplot is referencing. + num1, num2 : int + The subplot will occupy the *num1*-th cell of the given + *gridspec*. If *num2* is provided, the subplot will span between + *num1*-th cell and *num2*-th cell **inclusive**. + + The index starts from 0. + """ + def __init__(self, gridspec, num1, num2=None): + self._gridspec = gridspec + self.num1 = num1 + self.num2 = num2 + + def __repr__(self): + return (f"{self.get_gridspec()}[" + f"{self.rowspan.start}:{self.rowspan.stop}, " + f"{self.colspan.start}:{self.colspan.stop}]") + + @staticmethod + def _from_subplot_args(figure, args): + """ + Construct a `.SubplotSpec` from a parent `.Figure` and either + + - a `.SubplotSpec` -- returned as is; + - one or three numbers -- a MATLAB-style subplot specifier. + """ + if len(args) == 1: + arg, = args + if isinstance(arg, SubplotSpec): + return arg + elif not isinstance(arg, Integral): + raise ValueError( + f"Single argument to subplot must be a three-digit " + f"integer, not {arg!r}") + try: + rows, cols, num = map(int, str(arg)) + except ValueError: + raise ValueError( + f"Single argument to subplot must be a three-digit " + f"integer, not {arg!r}") from None + elif len(args) == 3: + rows, cols, num = args + else: + raise _api.nargs_error("subplot", takes="1 or 3", given=len(args)) + + gs = GridSpec._check_gridspec_exists(figure, rows, cols) + if gs is None: + gs = GridSpec(rows, cols, figure=figure) + if isinstance(num, tuple) and len(num) == 2: + if not all(isinstance(n, Integral) for n in num): + raise ValueError( + f"Subplot specifier tuple must contain integers, not {num}" + ) + i, j = num + else: + if not isinstance(num, Integral) or num < 1 or num > rows*cols: + raise ValueError( + f"num must be an integer with 1 <= num <= {rows*cols}, " + f"not {num!r}" + ) + i = j = num + return gs[i-1:j] + + # num2 is a property only to handle the case where it is None and someone + # mutates num1. + + @property + def num2(self): + return self.num1 if self._num2 is None else self._num2 + + @num2.setter + def num2(self, value): + self._num2 = value + + def get_gridspec(self): + return self._gridspec + + def get_geometry(self): + """ + Return the subplot geometry as tuple ``(n_rows, n_cols, start, stop)``. + + The indices *start* and *stop* define the range of the subplot within + the `GridSpec`. *stop* is inclusive (i.e. for a single cell + ``start == stop``). + """ + rows, cols = self.get_gridspec().get_geometry() + return rows, cols, self.num1, self.num2 + + @property + def rowspan(self): + """The rows spanned by this subplot, as a `range` object.""" + ncols = self.get_gridspec().ncols + return range(self.num1 // ncols, self.num2 // ncols + 1) + + @property + def colspan(self): + """The columns spanned by this subplot, as a `range` object.""" + ncols = self.get_gridspec().ncols + # We explicitly support num2 referring to a column on num1's *left*, so + # we must sort the column indices here so that the range makes sense. + c1, c2 = sorted([self.num1 % ncols, self.num2 % ncols]) + return range(c1, c2 + 1) + + def is_first_row(self): + return self.rowspan.start == 0 + + def is_last_row(self): + return self.rowspan.stop == self.get_gridspec().nrows + + def is_first_col(self): + return self.colspan.start == 0 + + def is_last_col(self): + return self.colspan.stop == self.get_gridspec().ncols + + def get_position(self, figure): + """ + Update the subplot position from ``figure.subplotpars``. + """ + gridspec = self.get_gridspec() + nrows, ncols = gridspec.get_geometry() + rows, cols = np.unravel_index([self.num1, self.num2], (nrows, ncols)) + fig_bottoms, fig_tops, fig_lefts, fig_rights = \ + gridspec.get_grid_positions(figure) + + fig_bottom = fig_bottoms[rows].min() + fig_top = fig_tops[rows].max() + fig_left = fig_lefts[cols].min() + fig_right = fig_rights[cols].max() + return Bbox.from_extents(fig_left, fig_bottom, fig_right, fig_top) + + def get_topmost_subplotspec(self): + """ + Return the topmost `SubplotSpec` instance associated with the subplot. + """ + gridspec = self.get_gridspec() + if hasattr(gridspec, "get_topmost_subplotspec"): + return gridspec.get_topmost_subplotspec() + else: + return self + + def __eq__(self, other): + """ + Two SubplotSpecs are considered equal if they refer to the same + position(s) in the same `GridSpec`. + """ + # other may not even have the attributes we are checking. + return ((self._gridspec, self.num1, self.num2) + == (getattr(other, "_gridspec", object()), + getattr(other, "num1", object()), + getattr(other, "num2", object()))) + + def __hash__(self): + return hash((self._gridspec, self.num1, self.num2)) + + def subgridspec(self, nrows, ncols, **kwargs): + """ + Create a GridSpec within this subplot. + + The created `.GridSpecFromSubplotSpec` will have this `SubplotSpec` as + a parent. + + Parameters + ---------- + nrows : int + Number of rows in grid. + + ncols : int + Number of columns in grid. + + Returns + ------- + `.GridSpecFromSubplotSpec` + + Other Parameters + ---------------- + **kwargs + All other parameters are passed to `.GridSpecFromSubplotSpec`. + + See Also + -------- + matplotlib.pyplot.subplots + + Examples + -------- + Adding three subplots in the space occupied by a single subplot:: + + fig = plt.figure() + gs0 = fig.add_gridspec(3, 1) + ax1 = fig.add_subplot(gs0[0]) + ax2 = fig.add_subplot(gs0[1]) + gssub = gs0[2].subgridspec(1, 3) + for i in range(3): + fig.add_subplot(gssub[0, i]) + """ + return GridSpecFromSubplotSpec(nrows, ncols, self, **kwargs) + + +class SubplotParams: + """ + Parameters defining the positioning of a subplots grid in a figure. + """ + + def __init__(self, left=None, bottom=None, right=None, top=None, + wspace=None, hspace=None): + """ + Defaults are given by :rc:`figure.subplot.[name]`. + + Parameters + ---------- + left : float + The position of the left edge of the subplots, + as a fraction of the figure width. + right : float + The position of the right edge of the subplots, + as a fraction of the figure width. + bottom : float + The position of the bottom edge of the subplots, + as a fraction of the figure height. + top : float + The position of the top edge of the subplots, + as a fraction of the figure height. + wspace : float + The width of the padding between subplots, + as a fraction of the average Axes width. + hspace : float + The height of the padding between subplots, + as a fraction of the average Axes height. + """ + for key in ["left", "bottom", "right", "top", "wspace", "hspace"]: + setattr(self, key, mpl.rcParams[f"figure.subplot.{key}"]) + self.update(left, bottom, right, top, wspace, hspace) + + def update(self, left=None, bottom=None, right=None, top=None, + wspace=None, hspace=None): + """ + Update the dimensions of the passed parameters. *None* means unchanged. + """ + if ((left if left is not None else self.left) + >= (right if right is not None else self.right)): + raise ValueError('left cannot be >= right') + if ((bottom if bottom is not None else self.bottom) + >= (top if top is not None else self.top)): + raise ValueError('bottom cannot be >= top') + if left is not None: + self.left = left + if right is not None: + self.right = right + if bottom is not None: + self.bottom = bottom + if top is not None: + self.top = top + if wspace is not None: + self.wspace = wspace + if hspace is not None: + self.hspace = hspace diff --git a/infer_4_30_0/lib/python3.10/site-packages/matplotlib/gridspec.pyi b/infer_4_30_0/lib/python3.10/site-packages/matplotlib/gridspec.pyi new file mode 100644 index 0000000000000000000000000000000000000000..08c4dd7f4e4918a259b86c2201db7055602a4000 --- /dev/null +++ b/infer_4_30_0/lib/python3.10/site-packages/matplotlib/gridspec.pyi @@ -0,0 +1,160 @@ +from typing import Any, Literal, overload + +from numpy.typing import ArrayLike +import numpy as np + +from matplotlib.axes import Axes +from matplotlib.backend_bases import RendererBase +from matplotlib.figure import Figure +from matplotlib.transforms import Bbox + +class GridSpecBase: + def __init__( + self, + nrows: int, + ncols: int, + height_ratios: ArrayLike | None = ..., + width_ratios: ArrayLike | None = ..., + ) -> None: ... + @property + def nrows(self) -> int: ... + @property + def ncols(self) -> int: ... + def get_geometry(self) -> tuple[int, int]: ... + def get_subplot_params(self, figure: Figure | None = ...) -> SubplotParams: ... + def new_subplotspec( + self, loc: tuple[int, int], rowspan: int = ..., colspan: int = ... + ) -> SubplotSpec: ... + def set_width_ratios(self, width_ratios: ArrayLike | None) -> None: ... + def get_width_ratios(self) -> ArrayLike: ... + def set_height_ratios(self, height_ratios: ArrayLike | None) -> None: ... + def get_height_ratios(self) -> ArrayLike: ... + def get_grid_positions( + self, fig: Figure + ) -> tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray]: ... + @staticmethod + def _check_gridspec_exists(figure: Figure, nrows: int, ncols: int) -> GridSpec: ... + def __getitem__( + self, key: tuple[int | slice, int | slice] | slice | int + ) -> SubplotSpec: ... + @overload + def subplots( + self, + *, + sharex: bool | Literal["all", "row", "col", "none"] = ..., + sharey: bool | Literal["all", "row", "col", "none"] = ..., + squeeze: Literal[False], + subplot_kw: dict[str, Any] | None = ... + ) -> np.ndarray: ... + @overload + def subplots( + self, + *, + sharex: bool | Literal["all", "row", "col", "none"] = ..., + sharey: bool | Literal["all", "row", "col", "none"] = ..., + squeeze: Literal[True] = ..., + subplot_kw: dict[str, Any] | None = ... + ) -> np.ndarray | Axes: ... + +class GridSpec(GridSpecBase): + left: float | None + bottom: float | None + right: float | None + top: float | None + wspace: float | None + hspace: float | None + figure: Figure | None + def __init__( + self, + nrows: int, + ncols: int, + figure: Figure | None = ..., + left: float | None = ..., + bottom: float | None = ..., + right: float | None = ..., + top: float | None = ..., + wspace: float | None = ..., + hspace: float | None = ..., + width_ratios: ArrayLike | None = ..., + height_ratios: ArrayLike | None = ..., + ) -> None: ... + def update(self, **kwargs: float | None) -> None: ... + def locally_modified_subplot_params(self) -> list[str]: ... + def tight_layout( + self, + figure: Figure, + renderer: RendererBase | None = ..., + pad: float = ..., + h_pad: float | None = ..., + w_pad: float | None = ..., + rect: tuple[float, float, float, float] | None = ..., + ) -> None: ... + +class GridSpecFromSubplotSpec(GridSpecBase): + figure: Figure | None + def __init__( + self, + nrows: int, + ncols: int, + subplot_spec: SubplotSpec, + wspace: float | None = ..., + hspace: float | None = ..., + height_ratios: ArrayLike | None = ..., + width_ratios: ArrayLike | None = ..., + ) -> None: ... + def get_topmost_subplotspec(self) -> SubplotSpec: ... + +class SubplotSpec: + num1: int + def __init__( + self, gridspec: GridSpecBase, num1: int, num2: int | None = ... + ) -> None: ... + @staticmethod + def _from_subplot_args(figure, args): ... + @property + def num2(self) -> int: ... + @num2.setter + def num2(self, value: int) -> None: ... + def get_gridspec(self) -> GridSpec: ... + def get_geometry(self) -> tuple[int, int, int, int]: ... + @property + def rowspan(self) -> range: ... + @property + def colspan(self) -> range: ... + def is_first_row(self) -> bool: ... + def is_last_row(self) -> bool: ... + def is_first_col(self) -> bool: ... + def is_last_col(self) -> bool: ... + def get_position(self, figure: Figure) -> Bbox: ... + def get_topmost_subplotspec(self) -> SubplotSpec: ... + def __eq__(self, other: object) -> bool: ... + def __hash__(self) -> int: ... + def subgridspec( + self, nrows: int, ncols: int, **kwargs + ) -> GridSpecFromSubplotSpec: ... + +class SubplotParams: + def __init__( + self, + left: float | None = ..., + bottom: float | None = ..., + right: float | None = ..., + top: float | None = ..., + wspace: float | None = ..., + hspace: float | None = ..., + ) -> None: ... + left: float + right: float + bottom: float + top: float + wspace: float + hspace: float + def update( + self, + left: float | None = ..., + bottom: float | None = ..., + right: float | None = ..., + top: float | None = ..., + wspace: float | None = ..., + hspace: float | None = ..., + ) -> None: ... diff --git a/infer_4_30_0/lib/python3.10/site-packages/matplotlib/inset.py b/infer_4_30_0/lib/python3.10/site-packages/matplotlib/inset.py new file mode 100644 index 0000000000000000000000000000000000000000..bab69491303e698ff6ec05a7d95ae88d1d213ac3 --- /dev/null +++ b/infer_4_30_0/lib/python3.10/site-packages/matplotlib/inset.py @@ -0,0 +1,269 @@ +""" +The inset module defines the InsetIndicator class, which draws the rectangle and +connectors required for `.Axes.indicate_inset` and `.Axes.indicate_inset_zoom`. +""" + +from . import _api, artist, transforms +from matplotlib.patches import ConnectionPatch, PathPatch, Rectangle +from matplotlib.path import Path + + +_shared_properties = ('alpha', 'edgecolor', 'linestyle', 'linewidth') + + +class InsetIndicator(artist.Artist): + """ + An artist to highlight an area of interest. + + An inset indicator is a rectangle on the plot at the position indicated by + *bounds* that optionally has lines that connect the rectangle to an inset + Axes (`.Axes.inset_axes`). + + .. versionadded:: 3.10 + """ + zorder = 4.99 + + def __init__(self, bounds=None, inset_ax=None, zorder=None, **kwargs): + """ + Parameters + ---------- + bounds : [x0, y0, width, height], optional + Lower-left corner of rectangle to be marked, and its width + and height. If not set, the bounds will be calculated from the + data limits of inset_ax, which must be supplied. + + inset_ax : `~.axes.Axes`, optional + An optional inset Axes to draw connecting lines to. Two lines are + drawn connecting the indicator box to the inset Axes on corners + chosen so as to not overlap with the indicator box. + + zorder : float, default: 4.99 + Drawing order of the rectangle and connector lines. The default, + 4.99, is just below the default level of inset Axes. + + **kwargs + Other keyword arguments are passed on to the `.Rectangle` patch. + """ + if bounds is None and inset_ax is None: + raise ValueError("At least one of bounds or inset_ax must be supplied") + + self._inset_ax = inset_ax + + if bounds is None: + # Work out bounds from inset_ax + self._auto_update_bounds = True + bounds = self._bounds_from_inset_ax() + else: + self._auto_update_bounds = False + + x, y, width, height = bounds + + self._rectangle = Rectangle((x, y), width, height, clip_on=False, **kwargs) + + # Connector positions cannot be calculated till the artist has been added + # to an axes, so just make an empty list for now. + self._connectors = [] + + super().__init__() + self.set_zorder(zorder) + + # Initial style properties for the artist should match the rectangle. + for prop in _shared_properties: + setattr(self, f'_{prop}', artist.getp(self._rectangle, prop)) + + def _shared_setter(self, prop, val): + """ + Helper function to set the same style property on the artist and its children. + """ + setattr(self, f'_{prop}', val) + + artist.setp([self._rectangle, *self._connectors], prop, val) + + def set_alpha(self, alpha): + # docstring inherited + self._shared_setter('alpha', alpha) + + def set_edgecolor(self, color): + """ + Set the edge color of the rectangle and the connectors. + + Parameters + ---------- + color : :mpltype:`color` or None + """ + self._shared_setter('edgecolor', color) + + def set_color(self, c): + """ + Set the edgecolor of the rectangle and the connectors, and the + facecolor for the rectangle. + + Parameters + ---------- + c : :mpltype:`color` + """ + self._shared_setter('edgecolor', c) + self._shared_setter('facecolor', c) + + def set_linewidth(self, w): + """ + Set the linewidth in points of the rectangle and the connectors. + + Parameters + ---------- + w : float or None + """ + self._shared_setter('linewidth', w) + + def set_linestyle(self, ls): + """ + Set the linestyle of the rectangle and the connectors. + + ========================================== ================= + linestyle description + ========================================== ================= + ``'-'`` or ``'solid'`` solid line + ``'--'`` or ``'dashed'`` dashed line + ``'-.'`` or ``'dashdot'`` dash-dotted line + ``':'`` or ``'dotted'`` dotted line + ``'none'``, ``'None'``, ``' '``, or ``''`` draw nothing + ========================================== ================= + + Alternatively a dash tuple of the following form can be provided:: + + (offset, onoffseq) + + where ``onoffseq`` is an even length tuple of on and off ink in points. + + Parameters + ---------- + ls : {'-', '--', '-.', ':', '', (offset, on-off-seq), ...} + The line style. + """ + self._shared_setter('linestyle', ls) + + def _bounds_from_inset_ax(self): + xlim = self._inset_ax.get_xlim() + ylim = self._inset_ax.get_ylim() + return (xlim[0], ylim[0], xlim[1] - xlim[0], ylim[1] - ylim[0]) + + def _update_connectors(self): + (x, y) = self._rectangle.get_xy() + width = self._rectangle.get_width() + height = self._rectangle.get_height() + + existing_connectors = self._connectors or [None] * 4 + + # connect the inset_axes to the rectangle + for xy_inset_ax, existing in zip([(0, 0), (0, 1), (1, 0), (1, 1)], + existing_connectors): + # inset_ax positions are in axes coordinates + # The 0, 1 values define the four edges if the inset_ax + # lower_left, upper_left, lower_right upper_right. + ex, ey = xy_inset_ax + if self.axes.xaxis.get_inverted(): + ex = 1 - ex + if self.axes.yaxis.get_inverted(): + ey = 1 - ey + xy_data = x + ex * width, y + ey * height + if existing is None: + # Create new connection patch with styles inherited from the + # parent artist. + p = ConnectionPatch( + xyA=xy_inset_ax, coordsA=self._inset_ax.transAxes, + xyB=xy_data, coordsB=self.axes.transData, + arrowstyle="-", + edgecolor=self._edgecolor, alpha=self.get_alpha(), + linestyle=self._linestyle, linewidth=self._linewidth) + self._connectors.append(p) + else: + # Only update positioning of existing connection patch. We + # do not want to override any style settings made by the user. + existing.xy1 = xy_inset_ax + existing.xy2 = xy_data + existing.coords1 = self._inset_ax.transAxes + existing.coords2 = self.axes.transData + + if existing is None: + # decide which two of the lines to keep visible.... + pos = self._inset_ax.get_position() + bboxins = pos.transformed(self.get_figure(root=False).transSubfigure) + rectbbox = transforms.Bbox.from_bounds(x, y, width, height).transformed( + self._rectangle.get_transform()) + x0 = rectbbox.x0 < bboxins.x0 + x1 = rectbbox.x1 < bboxins.x1 + y0 = rectbbox.y0 < bboxins.y0 + y1 = rectbbox.y1 < bboxins.y1 + self._connectors[0].set_visible(x0 ^ y0) + self._connectors[1].set_visible(x0 == y1) + self._connectors[2].set_visible(x1 == y0) + self._connectors[3].set_visible(x1 ^ y1) + + @property + def rectangle(self): + """`.Rectangle`: the indicator frame.""" + return self._rectangle + + @property + def connectors(self): + """ + 4-tuple of `.patches.ConnectionPatch` or None + The four connector lines connecting to (lower_left, upper_left, + lower_right upper_right) corners of *inset_ax*. Two lines are + set with visibility to *False*, but the user can set the + visibility to True if the automatic choice is not deemed correct. + """ + if self._inset_ax is None: + return + + if self._auto_update_bounds: + self._rectangle.set_bounds(self._bounds_from_inset_ax()) + self._update_connectors() + return tuple(self._connectors) + + def draw(self, renderer): + # docstring inherited + conn_same_style = [] + + # Figure out which connectors have the same style as the box, so should + # be drawn as a single path. + for conn in self.connectors or []: + if conn.get_visible(): + drawn = False + for s in _shared_properties: + if artist.getp(self._rectangle, s) != artist.getp(conn, s): + # Draw this connector by itself + conn.draw(renderer) + drawn = True + break + + if not drawn: + # Connector has same style as box. + conn_same_style.append(conn) + + if conn_same_style: + # Since at least one connector has the same style as the rectangle, draw + # them as a compound path. + artists = [self._rectangle] + conn_same_style + paths = [a.get_transform().transform_path(a.get_path()) for a in artists] + path = Path.make_compound_path(*paths) + + # Create a temporary patch to draw the path. + p = PathPatch(path) + p.update_from(self._rectangle) + p.set_transform(transforms.IdentityTransform()) + p.draw(renderer) + + return + + # Just draw the rectangle + self._rectangle.draw(renderer) + + @_api.deprecated( + '3.10', + message=('Since Matplotlib 3.10 indicate_inset_[zoom] returns a single ' + 'InsetIndicator artist with a rectangle property and a connectors ' + 'property. From 3.12 it will no longer be possible to unpack the ' + 'return value into two elements.')) + def __getitem__(self, key): + return [self._rectangle, self.connectors][key] diff --git a/infer_4_30_0/lib/python3.10/site-packages/matplotlib/layout_engine.pyi b/infer_4_30_0/lib/python3.10/site-packages/matplotlib/layout_engine.pyi new file mode 100644 index 0000000000000000000000000000000000000000..5b8c812ff47f53913ff2812b58fcaf3652985a86 --- /dev/null +++ b/infer_4_30_0/lib/python3.10/site-packages/matplotlib/layout_engine.pyi @@ -0,0 +1,62 @@ +from matplotlib.figure import Figure + +from typing import Any + +class LayoutEngine: + def __init__(self, **kwargs: Any) -> None: ... + def set(self) -> None: ... + @property + def colorbar_gridspec(self) -> bool: ... + @property + def adjust_compatible(self) -> bool: ... + def get(self) -> dict[str, Any]: ... + def execute(self, fig: Figure) -> None: ... + +class PlaceHolderLayoutEngine(LayoutEngine): + def __init__( + self, adjust_compatible: bool, colorbar_gridspec: bool, **kwargs: Any + ) -> None: ... + def execute(self, fig: Figure) -> None: ... + +class TightLayoutEngine(LayoutEngine): + def __init__( + self, + *, + pad: float = ..., + h_pad: float | None = ..., + w_pad: float | None = ..., + rect: tuple[float, float, float, float] = ..., + **kwargs: Any + ) -> None: ... + def execute(self, fig: Figure) -> None: ... + def set( + self, + *, + pad: float | None = ..., + w_pad: float | None = ..., + h_pad: float | None = ..., + rect: tuple[float, float, float, float] | None = ... + ) -> None: ... + +class ConstrainedLayoutEngine(LayoutEngine): + def __init__( + self, + *, + h_pad: float | None = ..., + w_pad: float | None = ..., + hspace: float | None = ..., + wspace: float | None = ..., + rect: tuple[float, float, float, float] = ..., + compress: bool = ..., + **kwargs: Any + ) -> None: ... + def execute(self, fig: Figure) -> Any: ... + def set( + self, + *, + h_pad: float | None = ..., + w_pad: float | None = ..., + hspace: float | None = ..., + wspace: float | None = ..., + rect: tuple[float, float, float, float] | None = ... + ) -> None: ... diff --git a/infer_4_30_0/lib/python3.10/site-packages/matplotlib/legend.py b/infer_4_30_0/lib/python3.10/site-packages/matplotlib/legend.py new file mode 100644 index 0000000000000000000000000000000000000000..0c2dfc19705ca03fa7887413f3c1c9d643e3b1a0 --- /dev/null +++ b/infer_4_30_0/lib/python3.10/site-packages/matplotlib/legend.py @@ -0,0 +1,1370 @@ +""" +The legend module defines the Legend class, which is responsible for +drawing legends associated with Axes and/or figures. + +.. important:: + + It is unlikely that you would ever create a Legend instance manually. + Most users would normally create a legend via the `~.Axes.legend` + function. For more details on legends there is also a :ref:`legend guide + `. + +The `Legend` class is a container of legend handles and legend texts. + +The legend handler map specifies how to create legend handles from artists +(lines, patches, etc.) in the Axes or figures. Default legend handlers are +defined in the :mod:`~matplotlib.legend_handler` module. While not all artist +types are covered by the default legend handlers, custom legend handlers can be +defined to support arbitrary objects. + +See the :ref`` for more +information. +""" + +import itertools +import logging +import numbers +import time + +import numpy as np + +import matplotlib as mpl +from matplotlib import _api, _docstring, cbook, colors, offsetbox +from matplotlib.artist import Artist, allow_rasterization +from matplotlib.cbook import silent_list +from matplotlib.font_manager import FontProperties +from matplotlib.lines import Line2D +from matplotlib.patches import (Patch, Rectangle, Shadow, FancyBboxPatch, + StepPatch) +from matplotlib.collections import ( + Collection, CircleCollection, LineCollection, PathCollection, + PolyCollection, RegularPolyCollection) +from matplotlib.text import Text +from matplotlib.transforms import Bbox, BboxBase, TransformedBbox +from matplotlib.transforms import BboxTransformTo, BboxTransformFrom +from matplotlib.offsetbox import ( + AnchoredOffsetbox, DraggableOffsetBox, + HPacker, VPacker, + DrawingArea, TextArea, +) +from matplotlib.container import ErrorbarContainer, BarContainer, StemContainer +from . import legend_handler + + +class DraggableLegend(DraggableOffsetBox): + def __init__(self, legend, use_blit=False, update="loc"): + """ + Wrapper around a `.Legend` to support mouse dragging. + + Parameters + ---------- + legend : `.Legend` + The `.Legend` instance to wrap. + use_blit : bool, optional + Use blitting for faster image composition. For details see + :ref:`func-animation`. + update : {'loc', 'bbox'}, optional + If "loc", update the *loc* parameter of the legend upon finalizing. + If "bbox", update the *bbox_to_anchor* parameter. + """ + self.legend = legend + + _api.check_in_list(["loc", "bbox"], update=update) + self._update = update + + super().__init__(legend, legend._legend_box, use_blit=use_blit) + + def finalize_offset(self): + if self._update == "loc": + self._update_loc(self.get_loc_in_canvas()) + elif self._update == "bbox": + self._update_bbox_to_anchor(self.get_loc_in_canvas()) + + def _update_loc(self, loc_in_canvas): + bbox = self.legend.get_bbox_to_anchor() + # if bbox has zero width or height, the transformation is + # ill-defined. Fall back to the default bbox_to_anchor. + if bbox.width == 0 or bbox.height == 0: + self.legend.set_bbox_to_anchor(None) + bbox = self.legend.get_bbox_to_anchor() + _bbox_transform = BboxTransformFrom(bbox) + self.legend._loc = tuple(_bbox_transform.transform(loc_in_canvas)) + + def _update_bbox_to_anchor(self, loc_in_canvas): + loc_in_bbox = self.legend.axes.transAxes.transform(loc_in_canvas) + self.legend.set_bbox_to_anchor(loc_in_bbox) + + +_legend_kw_doc_base = """ +bbox_to_anchor : `.BboxBase`, 2-tuple, or 4-tuple of floats + Box that is used to position the legend in conjunction with *loc*. + Defaults to ``axes.bbox`` (if called as a method to `.Axes.legend`) or + ``figure.bbox`` (if ``figure.legend``). This argument allows arbitrary + placement of the legend. + + Bbox coordinates are interpreted in the coordinate system given by + *bbox_transform*, with the default transform + Axes or Figure coordinates, depending on which ``legend`` is called. + + If a 4-tuple or `.BboxBase` is given, then it specifies the bbox + ``(x, y, width, height)`` that the legend is placed in. + To put the legend in the best location in the bottom right + quadrant of the Axes (or figure):: + + loc='best', bbox_to_anchor=(0.5, 0., 0.5, 0.5) + + A 2-tuple ``(x, y)`` places the corner of the legend specified by *loc* at + x, y. For example, to put the legend's upper right-hand corner in the + center of the Axes (or figure) the following keywords can be used:: + + loc='upper right', bbox_to_anchor=(0.5, 0.5) + +ncols : int, default: 1 + The number of columns that the legend has. + + For backward compatibility, the spelling *ncol* is also supported + but it is discouraged. If both are given, *ncols* takes precedence. + +prop : None or `~matplotlib.font_manager.FontProperties` or dict + The font properties of the legend. If None (default), the current + :data:`matplotlib.rcParams` will be used. + +fontsize : int or {'xx-small', 'x-small', 'small', 'medium', 'large', \ +'x-large', 'xx-large'} + The font size of the legend. If the value is numeric the size will be the + absolute font size in points. String values are relative to the current + default font size. This argument is only used if *prop* is not specified. + +labelcolor : str or list, default: :rc:`legend.labelcolor` + The color of the text in the legend. Either a valid color string + (for example, 'red'), or a list of color strings. The labelcolor can + also be made to match the color of the line or marker using 'linecolor', + 'markerfacecolor' (or 'mfc'), or 'markeredgecolor' (or 'mec'). + + Labelcolor can be set globally using :rc:`legend.labelcolor`. If None, + use :rc:`text.color`. + +numpoints : int, default: :rc:`legend.numpoints` + The number of marker points in the legend when creating a legend + entry for a `.Line2D` (line). + +scatterpoints : int, default: :rc:`legend.scatterpoints` + The number of marker points in the legend when creating + a legend entry for a `.PathCollection` (scatter plot). + +scatteryoffsets : iterable of floats, default: ``[0.375, 0.5, 0.3125]`` + The vertical offset (relative to the font size) for the markers + created for a scatter plot legend entry. 0.0 is at the base the + legend text, and 1.0 is at the top. To draw all markers at the + same height, set to ``[0.5]``. + +markerscale : float, default: :rc:`legend.markerscale` + The relative size of legend markers compared to the originally drawn ones. + +markerfirst : bool, default: True + If *True*, legend marker is placed to the left of the legend label. + If *False*, legend marker is placed to the right of the legend label. + +reverse : bool, default: False + If *True*, the legend labels are displayed in reverse order from the input. + If *False*, the legend labels are displayed in the same order as the input. + + .. versionadded:: 3.7 + +frameon : bool, default: :rc:`legend.frameon` + Whether the legend should be drawn on a patch (frame). + +fancybox : bool, default: :rc:`legend.fancybox` + Whether round edges should be enabled around the `.FancyBboxPatch` which + makes up the legend's background. + +shadow : None, bool or dict, default: :rc:`legend.shadow` + Whether to draw a shadow behind the legend. + The shadow can be configured using `.Patch` keywords. + Customization via :rc:`legend.shadow` is currently not supported. + +framealpha : float, default: :rc:`legend.framealpha` + The alpha transparency of the legend's background. + If *shadow* is activated and *framealpha* is ``None``, the default value is + ignored. + +facecolor : "inherit" or color, default: :rc:`legend.facecolor` + The legend's background color. + If ``"inherit"``, use :rc:`axes.facecolor`. + +edgecolor : "inherit" or color, default: :rc:`legend.edgecolor` + The legend's background patch edge color. + If ``"inherit"``, use :rc:`axes.edgecolor`. + +mode : {"expand", None} + If *mode* is set to ``"expand"`` the legend will be horizontally + expanded to fill the Axes area (or *bbox_to_anchor* if defines + the legend's size). + +bbox_transform : None or `~matplotlib.transforms.Transform` + The transform for the bounding box (*bbox_to_anchor*). For a value + of ``None`` (default) the Axes' + :data:`~matplotlib.axes.Axes.transAxes` transform will be used. + +title : str or None + The legend's title. Default is no title (``None``). + +title_fontproperties : None or `~matplotlib.font_manager.FontProperties` or dict + The font properties of the legend's title. If None (default), the + *title_fontsize* argument will be used if present; if *title_fontsize* is + also None, the current :rc:`legend.title_fontsize` will be used. + +title_fontsize : int or {'xx-small', 'x-small', 'small', 'medium', 'large', \ +'x-large', 'xx-large'}, default: :rc:`legend.title_fontsize` + The font size of the legend's title. + Note: This cannot be combined with *title_fontproperties*. If you want + to set the fontsize alongside other font properties, use the *size* + parameter in *title_fontproperties*. + +alignment : {'center', 'left', 'right'}, default: 'center' + The alignment of the legend title and the box of entries. The entries + are aligned as a single block, so that markers always lined up. + +borderpad : float, default: :rc:`legend.borderpad` + The fractional whitespace inside the legend border, in font-size units. + +labelspacing : float, default: :rc:`legend.labelspacing` + The vertical space between the legend entries, in font-size units. + +handlelength : float, default: :rc:`legend.handlelength` + The length of the legend handles, in font-size units. + +handleheight : float, default: :rc:`legend.handleheight` + The height of the legend handles, in font-size units. + +handletextpad : float, default: :rc:`legend.handletextpad` + The pad between the legend handle and text, in font-size units. + +borderaxespad : float, default: :rc:`legend.borderaxespad` + The pad between the Axes and legend border, in font-size units. + +columnspacing : float, default: :rc:`legend.columnspacing` + The spacing between columns, in font-size units. + +handler_map : dict or None + The custom dictionary mapping instances or types to a legend + handler. This *handler_map* updates the default handler map + found at `matplotlib.legend.Legend.get_legend_handler_map`. + +draggable : bool, default: False + Whether the legend can be dragged with the mouse. +""" + +_loc_doc_base = """ +loc : str or pair of floats, default: {default} + The location of the legend. + + The strings ``'upper left'``, ``'upper right'``, ``'lower left'``, + ``'lower right'`` place the legend at the corresponding corner of the + {parent}. + + The strings ``'upper center'``, ``'lower center'``, ``'center left'``, + ``'center right'`` place the legend at the center of the corresponding edge + of the {parent}. + + The string ``'center'`` places the legend at the center of the {parent}. +{best} + The location can also be a 2-tuple giving the coordinates of the lower-left + corner of the legend in {parent} coordinates (in which case *bbox_to_anchor* + will be ignored). + + For back-compatibility, ``'center right'`` (but no other location) can also + be spelled ``'right'``, and each "string" location can also be given as a + numeric value: + + ================== ============= + Location String Location Code + ================== ============= + 'best' (Axes only) 0 + 'upper right' 1 + 'upper left' 2 + 'lower left' 3 + 'lower right' 4 + 'right' 5 + 'center left' 6 + 'center right' 7 + 'lower center' 8 + 'upper center' 9 + 'center' 10 + ================== ============= + {outside}""" + +_loc_doc_best = """ + The string ``'best'`` places the legend at the location, among the nine + locations defined so far, with the minimum overlap with other drawn + artists. This option can be quite slow for plots with large amounts of + data; your plotting speed may benefit from providing a specific location. +""" + +_legend_kw_axes_st = ( + _loc_doc_base.format(parent='axes', default=':rc:`legend.loc`', + best=_loc_doc_best, outside='') + + _legend_kw_doc_base) +_docstring.interpd.register(_legend_kw_axes=_legend_kw_axes_st) + +_outside_doc = """ + If a figure is using the constrained layout manager, the string codes + of the *loc* keyword argument can get better layout behaviour using the + prefix 'outside'. There is ambiguity at the corners, so 'outside + upper right' will make space for the legend above the rest of the + axes in the layout, and 'outside right upper' will make space on the + right side of the layout. In addition to the values of *loc* + listed above, we have 'outside right upper', 'outside right lower', + 'outside left upper', and 'outside left lower'. See + :ref:`legend_guide` for more details. +""" + +_legend_kw_figure_st = ( + _loc_doc_base.format(parent='figure', default="'upper right'", + best='', outside=_outside_doc) + + _legend_kw_doc_base) +_docstring.interpd.register(_legend_kw_figure=_legend_kw_figure_st) + +_legend_kw_both_st = ( + _loc_doc_base.format(parent='axes/figure', + default=":rc:`legend.loc` for Axes, 'upper right' for Figure", + best=_loc_doc_best, outside=_outside_doc) + + _legend_kw_doc_base) +_docstring.interpd.register(_legend_kw_doc=_legend_kw_both_st) + +_legend_kw_set_loc_st = ( + _loc_doc_base.format(parent='axes/figure', + default=":rc:`legend.loc` for Axes, 'upper right' for Figure", + best=_loc_doc_best, outside=_outside_doc)) +_docstring.interpd.register(_legend_kw_set_loc_doc=_legend_kw_set_loc_st) + + +class Legend(Artist): + """ + Place a legend on the figure/axes. + """ + + # 'best' is only implemented for Axes legends + codes = {'best': 0, **AnchoredOffsetbox.codes} + zorder = 5 + + def __str__(self): + return "Legend" + + @_docstring.interpd + def __init__( + self, parent, handles, labels, + *, + loc=None, + numpoints=None, # number of points in the legend line + markerscale=None, # relative size of legend markers vs. original + markerfirst=True, # left/right ordering of legend marker and label + reverse=False, # reverse ordering of legend marker and label + scatterpoints=None, # number of scatter points + scatteryoffsets=None, + prop=None, # properties for the legend texts + fontsize=None, # keyword to set font size directly + labelcolor=None, # keyword to set the text color + + # spacing & pad defined as a fraction of the font-size + borderpad=None, # whitespace inside the legend border + labelspacing=None, # vertical space between the legend entries + handlelength=None, # length of the legend handles + handleheight=None, # height of the legend handles + handletextpad=None, # pad between the legend handle and text + borderaxespad=None, # pad between the Axes and legend border + columnspacing=None, # spacing between columns + + ncols=1, # number of columns + mode=None, # horizontal distribution of columns: None or "expand" + + fancybox=None, # True: fancy box, False: rounded box, None: rcParam + shadow=None, + title=None, # legend title + title_fontsize=None, # legend title font size + framealpha=None, # set frame alpha + edgecolor=None, # frame patch edgecolor + facecolor=None, # frame patch facecolor + + bbox_to_anchor=None, # bbox to which the legend will be anchored + bbox_transform=None, # transform for the bbox + frameon=None, # draw frame + handler_map=None, + title_fontproperties=None, # properties for the legend title + alignment="center", # control the alignment within the legend box + ncol=1, # synonym for ncols (backward compatibility) + draggable=False # whether the legend can be dragged with the mouse + ): + """ + Parameters + ---------- + parent : `~matplotlib.axes.Axes` or `.Figure` + The artist that contains the legend. + + handles : list of (`.Artist` or tuple of `.Artist`) + A list of Artists (lines, patches) to be added to the legend. + + labels : list of str + A list of labels to show next to the artists. The length of handles + and labels should be the same. If they are not, they are truncated + to the length of the shorter list. + + Other Parameters + ---------------- + %(_legend_kw_doc)s + + Attributes + ---------- + legend_handles + List of `.Artist` objects added as legend entries. + + .. versionadded:: 3.7 + """ + # local import only to avoid circularity + from matplotlib.axes import Axes + from matplotlib.figure import FigureBase + + super().__init__() + + if prop is None: + self.prop = FontProperties(size=mpl._val_or_rc(fontsize, "legend.fontsize")) + else: + self.prop = FontProperties._from_any(prop) + if isinstance(prop, dict) and "size" not in prop: + self.prop.set_size(mpl.rcParams["legend.fontsize"]) + + self._fontsize = self.prop.get_size_in_points() + + self.texts = [] + self.legend_handles = [] + self._legend_title_box = None + + #: A dictionary with the extra handler mappings for this Legend + #: instance. + self._custom_handler_map = handler_map + + self.numpoints = mpl._val_or_rc(numpoints, 'legend.numpoints') + self.markerscale = mpl._val_or_rc(markerscale, 'legend.markerscale') + self.scatterpoints = mpl._val_or_rc(scatterpoints, 'legend.scatterpoints') + self.borderpad = mpl._val_or_rc(borderpad, 'legend.borderpad') + self.labelspacing = mpl._val_or_rc(labelspacing, 'legend.labelspacing') + self.handlelength = mpl._val_or_rc(handlelength, 'legend.handlelength') + self.handleheight = mpl._val_or_rc(handleheight, 'legend.handleheight') + self.handletextpad = mpl._val_or_rc(handletextpad, 'legend.handletextpad') + self.borderaxespad = mpl._val_or_rc(borderaxespad, 'legend.borderaxespad') + self.columnspacing = mpl._val_or_rc(columnspacing, 'legend.columnspacing') + self.shadow = mpl._val_or_rc(shadow, 'legend.shadow') + + if reverse: + labels = [*reversed(labels)] + handles = [*reversed(handles)] + + if len(handles) < 2: + ncols = 1 + self._ncols = ncols if ncols != 1 else ncol + + if self.numpoints <= 0: + raise ValueError("numpoints must be > 0; it was %d" % numpoints) + + # introduce y-offset for handles of the scatter plot + if scatteryoffsets is None: + self._scatteryoffsets = np.array([3. / 8., 4. / 8., 2.5 / 8.]) + else: + self._scatteryoffsets = np.asarray(scatteryoffsets) + reps = self.scatterpoints // len(self._scatteryoffsets) + 1 + self._scatteryoffsets = np.tile(self._scatteryoffsets, + reps)[:self.scatterpoints] + + # _legend_box is a VPacker instance that contains all + # legend items and will be initialized from _init_legend_box() + # method. + self._legend_box = None + + if isinstance(parent, Axes): + self.isaxes = True + self.axes = parent + self.set_figure(parent.get_figure(root=False)) + elif isinstance(parent, FigureBase): + self.isaxes = False + self.set_figure(parent) + else: + raise TypeError( + "Legend needs either Axes or FigureBase as parent" + ) + self.parent = parent + + self._mode = mode + self.set_bbox_to_anchor(bbox_to_anchor, bbox_transform) + + # Figure out if self.shadow is valid + # If shadow was None, rcParams loads False + # So it shouldn't be None here + + self._shadow_props = {'ox': 2, 'oy': -2} # default location offsets + if isinstance(self.shadow, dict): + self._shadow_props.update(self.shadow) + self.shadow = True + elif self.shadow in (0, 1, True, False): + self.shadow = bool(self.shadow) + else: + raise ValueError( + 'Legend shadow must be a dict or bool, not ' + f'{self.shadow!r} of type {type(self.shadow)}.' + ) + + # We use FancyBboxPatch to draw a legend frame. The location + # and size of the box will be updated during the drawing time. + + facecolor = mpl._val_or_rc(facecolor, "legend.facecolor") + if facecolor == 'inherit': + facecolor = mpl.rcParams["axes.facecolor"] + + edgecolor = mpl._val_or_rc(edgecolor, "legend.edgecolor") + if edgecolor == 'inherit': + edgecolor = mpl.rcParams["axes.edgecolor"] + + fancybox = mpl._val_or_rc(fancybox, "legend.fancybox") + + self.legendPatch = FancyBboxPatch( + xy=(0, 0), width=1, height=1, + facecolor=facecolor, edgecolor=edgecolor, + # If shadow is used, default to alpha=1 (#8943). + alpha=(framealpha if framealpha is not None + else 1 if shadow + else mpl.rcParams["legend.framealpha"]), + # The width and height of the legendPatch will be set (in draw()) + # to the length that includes the padding. Thus we set pad=0 here. + boxstyle=("round,pad=0,rounding_size=0.2" if fancybox + else "square,pad=0"), + mutation_scale=self._fontsize, + snap=True, + visible=mpl._val_or_rc(frameon, "legend.frameon") + ) + self._set_artist_props(self.legendPatch) + + _api.check_in_list(["center", "left", "right"], alignment=alignment) + self._alignment = alignment + + # init with null renderer + self._init_legend_box(handles, labels, markerfirst) + + # Set legend location + self.set_loc(loc) + + # figure out title font properties: + if title_fontsize is not None and title_fontproperties is not None: + raise ValueError( + "title_fontsize and title_fontproperties can't be specified " + "at the same time. Only use one of them. ") + title_prop_fp = FontProperties._from_any(title_fontproperties) + if isinstance(title_fontproperties, dict): + if "size" not in title_fontproperties: + title_fontsize = mpl.rcParams["legend.title_fontsize"] + title_prop_fp.set_size(title_fontsize) + elif title_fontsize is not None: + title_prop_fp.set_size(title_fontsize) + elif not isinstance(title_fontproperties, FontProperties): + title_fontsize = mpl.rcParams["legend.title_fontsize"] + title_prop_fp.set_size(title_fontsize) + + self.set_title(title, prop=title_prop_fp) + + self._draggable = None + self.set_draggable(state=draggable) + + # set the text color + + color_getters = { # getter function depends on line or patch + 'linecolor': ['get_color', 'get_facecolor'], + 'markerfacecolor': ['get_markerfacecolor', 'get_facecolor'], + 'mfc': ['get_markerfacecolor', 'get_facecolor'], + 'markeredgecolor': ['get_markeredgecolor', 'get_edgecolor'], + 'mec': ['get_markeredgecolor', 'get_edgecolor'], + } + labelcolor = mpl._val_or_rc(labelcolor, 'legend.labelcolor') + if labelcolor is None: + labelcolor = mpl.rcParams['text.color'] + if isinstance(labelcolor, str) and labelcolor in color_getters: + getter_names = color_getters[labelcolor] + for handle, text in zip(self.legend_handles, self.texts): + try: + if handle.get_array() is not None: + continue + except AttributeError: + pass + for getter_name in getter_names: + try: + color = getattr(handle, getter_name)() + if isinstance(color, np.ndarray): + if ( + color.shape[0] == 1 + or np.isclose(color, color[0]).all() + ): + text.set_color(color[0]) + else: + pass + else: + text.set_color(color) + break + except AttributeError: + pass + elif cbook._str_equal(labelcolor, 'none'): + for text in self.texts: + text.set_color(labelcolor) + elif np.iterable(labelcolor): + for text, color in zip(self.texts, + itertools.cycle( + colors.to_rgba_array(labelcolor))): + text.set_color(color) + else: + raise ValueError(f"Invalid labelcolor: {labelcolor!r}") + + def _set_artist_props(self, a): + """ + Set the boilerplate props for artists added to Axes. + """ + a.set_figure(self.get_figure(root=False)) + if self.isaxes: + a.axes = self.axes + + a.set_transform(self.get_transform()) + + @_docstring.interpd + def set_loc(self, loc=None): + """ + Set the location of the legend. + + .. versionadded:: 3.8 + + Parameters + ---------- + %(_legend_kw_set_loc_doc)s + """ + loc0 = loc + self._loc_used_default = loc is None + if loc is None: + loc = mpl.rcParams["legend.loc"] + if not self.isaxes and loc in [0, 'best']: + loc = 'upper right' + + type_err_message = ("loc must be string, coordinate tuple, or" + f" an integer 0-10, not {loc!r}") + + # handle outside legends: + self._outside_loc = None + if isinstance(loc, str): + if loc.split()[0] == 'outside': + # strip outside: + loc = loc.split('outside ')[1] + # strip "center" at the beginning + self._outside_loc = loc.replace('center ', '') + # strip first + self._outside_loc = self._outside_loc.split()[0] + locs = loc.split() + if len(locs) > 1 and locs[0] in ('right', 'left'): + # locs doesn't accept "left upper", etc, so swap + if locs[0] != 'center': + locs = locs[::-1] + loc = locs[0] + ' ' + locs[1] + # check that loc is in acceptable strings + loc = _api.check_getitem(self.codes, loc=loc) + elif np.iterable(loc): + # coerce iterable into tuple + loc = tuple(loc) + # validate the tuple represents Real coordinates + if len(loc) != 2 or not all(isinstance(e, numbers.Real) for e in loc): + raise ValueError(type_err_message) + elif isinstance(loc, int): + # validate the integer represents a string numeric value + if loc < 0 or loc > 10: + raise ValueError(type_err_message) + else: + # all other cases are invalid values of loc + raise ValueError(type_err_message) + + if self.isaxes and self._outside_loc: + raise ValueError( + f"'outside' option for loc='{loc0}' keyword argument only " + "works for figure legends") + + if not self.isaxes and loc == 0: + raise ValueError( + "Automatic legend placement (loc='best') not implemented for " + "figure legend") + + tmp = self._loc_used_default + self._set_loc(loc) + self._loc_used_default = tmp # ignore changes done by _set_loc + + def _set_loc(self, loc): + # find_offset function will be provided to _legend_box and + # _legend_box will draw itself at the location of the return + # value of the find_offset. + self._loc_used_default = False + self._loc_real = loc + self.stale = True + self._legend_box.set_offset(self._findoffset) + + def set_ncols(self, ncols): + """Set the number of columns.""" + self._ncols = ncols + + def _get_loc(self): + return self._loc_real + + _loc = property(_get_loc, _set_loc) + + def _findoffset(self, width, height, xdescent, ydescent, renderer): + """Helper function to locate the legend.""" + + if self._loc == 0: # "best". + x, y = self._find_best_position(width, height, renderer) + elif self._loc in Legend.codes.values(): # Fixed location. + bbox = Bbox.from_bounds(0, 0, width, height) + x, y = self._get_anchored_bbox(self._loc, bbox, + self.get_bbox_to_anchor(), + renderer) + else: # Axes or figure coordinates. + fx, fy = self._loc + bbox = self.get_bbox_to_anchor() + x, y = bbox.x0 + bbox.width * fx, bbox.y0 + bbox.height * fy + + return x + xdescent, y + ydescent + + @allow_rasterization + def draw(self, renderer): + # docstring inherited + if not self.get_visible(): + return + + renderer.open_group('legend', gid=self.get_gid()) + + fontsize = renderer.points_to_pixels(self._fontsize) + + # if mode == fill, set the width of the legend_box to the + # width of the parent (minus pads) + if self._mode in ["expand"]: + pad = 2 * (self.borderaxespad + self.borderpad) * fontsize + self._legend_box.set_width(self.get_bbox_to_anchor().width - pad) + + # update the location and size of the legend. This needs to + # be done in any case to clip the figure right. + bbox = self._legend_box.get_window_extent(renderer) + self.legendPatch.set_bounds(bbox.bounds) + self.legendPatch.set_mutation_scale(fontsize) + + # self.shadow is validated in __init__ + # So by here it is a bool and self._shadow_props contains any configs + + if self.shadow: + Shadow(self.legendPatch, **self._shadow_props).draw(renderer) + + self.legendPatch.draw(renderer) + self._legend_box.draw(renderer) + + renderer.close_group('legend') + self.stale = False + + # _default_handler_map defines the default mapping between plot + # elements and the legend handlers. + + _default_handler_map = { + StemContainer: legend_handler.HandlerStem(), + ErrorbarContainer: legend_handler.HandlerErrorbar(), + Line2D: legend_handler.HandlerLine2D(), + Patch: legend_handler.HandlerPatch(), + StepPatch: legend_handler.HandlerStepPatch(), + LineCollection: legend_handler.HandlerLineCollection(), + RegularPolyCollection: legend_handler.HandlerRegularPolyCollection(), + CircleCollection: legend_handler.HandlerCircleCollection(), + BarContainer: legend_handler.HandlerPatch( + update_func=legend_handler.update_from_first_child), + tuple: legend_handler.HandlerTuple(), + PathCollection: legend_handler.HandlerPathCollection(), + PolyCollection: legend_handler.HandlerPolyCollection() + } + + # (get|set|update)_default_handler_maps are public interfaces to + # modify the default handler map. + + @classmethod + def get_default_handler_map(cls): + """Return the global default handler map, shared by all legends.""" + return cls._default_handler_map + + @classmethod + def set_default_handler_map(cls, handler_map): + """Set the global default handler map, shared by all legends.""" + cls._default_handler_map = handler_map + + @classmethod + def update_default_handler_map(cls, handler_map): + """Update the global default handler map, shared by all legends.""" + cls._default_handler_map.update(handler_map) + + def get_legend_handler_map(self): + """Return this legend instance's handler map.""" + default_handler_map = self.get_default_handler_map() + return ({**default_handler_map, **self._custom_handler_map} + if self._custom_handler_map else default_handler_map) + + @staticmethod + def get_legend_handler(legend_handler_map, orig_handle): + """ + Return a legend handler from *legend_handler_map* that + corresponds to *orig_handler*. + + *legend_handler_map* should be a dictionary object (that is + returned by the get_legend_handler_map method). + + It first checks if the *orig_handle* itself is a key in the + *legend_handler_map* and return the associated value. + Otherwise, it checks for each of the classes in its + method-resolution-order. If no matching key is found, it + returns ``None``. + """ + try: + return legend_handler_map[orig_handle] + except (TypeError, KeyError): # TypeError if unhashable. + pass + for handle_type in type(orig_handle).mro(): + try: + return legend_handler_map[handle_type] + except KeyError: + pass + return None + + def _init_legend_box(self, handles, labels, markerfirst=True): + """ + Initialize the legend_box. The legend_box is an instance of + the OffsetBox, which is packed with legend handles and + texts. Once packed, their location is calculated during the + drawing time. + """ + + fontsize = self._fontsize + + # legend_box is a HPacker, horizontally packed with columns. + # Each column is a VPacker, vertically packed with legend items. + # Each legend item is a HPacker packed with: + # - handlebox: a DrawingArea which contains the legend handle. + # - labelbox: a TextArea which contains the legend text. + + text_list = [] # the list of text instances + handle_list = [] # the list of handle instances + handles_and_labels = [] + + # The approximate height and descent of text. These values are + # only used for plotting the legend handle. + descent = 0.35 * fontsize * (self.handleheight - 0.7) # heuristic. + height = fontsize * self.handleheight - descent + # each handle needs to be drawn inside a box of (x, y, w, h) = + # (0, -descent, width, height). And their coordinates should + # be given in the display coordinates. + + # The transformation of each handle will be automatically set + # to self.get_transform(). If the artist does not use its + # default transform (e.g., Collections), you need to + # manually set their transform to the self.get_transform(). + legend_handler_map = self.get_legend_handler_map() + + for orig_handle, label in zip(handles, labels): + handler = self.get_legend_handler(legend_handler_map, orig_handle) + if handler is None: + _api.warn_external( + "Legend does not support handles for " + f"{type(orig_handle).__name__} " + "instances.\nA proxy artist may be used " + "instead.\nSee: https://matplotlib.org/" + "stable/users/explain/axes/legend_guide.html" + "#controlling-the-legend-entries") + # No handle for this artist, so we just defer to None. + handle_list.append(None) + else: + textbox = TextArea(label, multilinebaseline=True, + textprops=dict( + verticalalignment='baseline', + horizontalalignment='left', + fontproperties=self.prop)) + handlebox = DrawingArea(width=self.handlelength * fontsize, + height=height, + xdescent=0., ydescent=descent) + + text_list.append(textbox._text) + # Create the artist for the legend which represents the + # original artist/handle. + handle_list.append(handler.legend_artist(self, orig_handle, + fontsize, handlebox)) + handles_and_labels.append((handlebox, textbox)) + + columnbox = [] + # array_split splits n handles_and_labels into ncols columns, with the + # first n%ncols columns having an extra entry. filter(len, ...) + # handles the case where n < ncols: the last ncols-n columns are empty + # and get filtered out. + for handles_and_labels_column in filter( + len, np.array_split(handles_and_labels, self._ncols)): + # pack handlebox and labelbox into itembox + itemboxes = [HPacker(pad=0, + sep=self.handletextpad * fontsize, + children=[h, t] if markerfirst else [t, h], + align="baseline") + for h, t in handles_and_labels_column] + # pack columnbox + alignment = "baseline" if markerfirst else "right" + columnbox.append(VPacker(pad=0, + sep=self.labelspacing * fontsize, + align=alignment, + children=itemboxes)) + + mode = "expand" if self._mode == "expand" else "fixed" + sep = self.columnspacing * fontsize + self._legend_handle_box = HPacker(pad=0, + sep=sep, align="baseline", + mode=mode, + children=columnbox) + self._legend_title_box = TextArea("") + self._legend_box = VPacker(pad=self.borderpad * fontsize, + sep=self.labelspacing * fontsize, + align=self._alignment, + children=[self._legend_title_box, + self._legend_handle_box]) + self._legend_box.set_figure(self.get_figure(root=False)) + self._legend_box.axes = self.axes + self.texts = text_list + self.legend_handles = handle_list + + def _auto_legend_data(self, renderer): + """ + Return display coordinates for hit testing for "best" positioning. + + Returns + ------- + bboxes + List of bounding boxes of all patches. + lines + List of `.Path` corresponding to each line. + offsets + List of (x, y) offsets of all collection. + """ + assert self.isaxes # always holds, as this is only called internally + bboxes = [] + lines = [] + offsets = [] + for artist in self.parent._children: + if isinstance(artist, Line2D): + lines.append( + artist.get_transform().transform_path(artist.get_path())) + elif isinstance(artist, Rectangle): + bboxes.append( + artist.get_bbox().transformed(artist.get_data_transform())) + elif isinstance(artist, Patch): + lines.append( + artist.get_transform().transform_path(artist.get_path())) + elif isinstance(artist, PolyCollection): + lines.extend(artist.get_transform().transform_path(path) + for path in artist.get_paths()) + elif isinstance(artist, Collection): + transform, transOffset, hoffsets, _ = artist._prepare_points() + if len(hoffsets): + offsets.extend(transOffset.transform(hoffsets)) + elif isinstance(artist, Text): + bboxes.append(artist.get_window_extent(renderer)) + + return bboxes, lines, offsets + + def get_children(self): + # docstring inherited + return [self._legend_box, self.get_frame()] + + def get_frame(self): + """Return the `~.patches.Rectangle` used to frame the legend.""" + return self.legendPatch + + def get_lines(self): + r"""Return the list of `~.lines.Line2D`\s in the legend.""" + return [h for h in self.legend_handles if isinstance(h, Line2D)] + + def get_patches(self): + r"""Return the list of `~.patches.Patch`\s in the legend.""" + return silent_list('Patch', + [h for h in self.legend_handles + if isinstance(h, Patch)]) + + def get_texts(self): + r"""Return the list of `~.text.Text`\s in the legend.""" + return silent_list('Text', self.texts) + + def set_alignment(self, alignment): + """ + Set the alignment of the legend title and the box of entries. + + The entries are aligned as a single block, so that markers always + lined up. + + Parameters + ---------- + alignment : {'center', 'left', 'right'}. + + """ + _api.check_in_list(["center", "left", "right"], alignment=alignment) + self._alignment = alignment + self._legend_box.align = alignment + + def get_alignment(self): + """Get the alignment value of the legend box""" + return self._legend_box.align + + def set_title(self, title, prop=None): + """ + Set legend title and title style. + + Parameters + ---------- + title : str + The legend title. + + prop : `.font_manager.FontProperties` or `str` or `pathlib.Path` + The font properties of the legend title. + If a `str`, it is interpreted as a fontconfig pattern parsed by + `.FontProperties`. If a `pathlib.Path`, it is interpreted as the + absolute path to a font file. + + """ + self._legend_title_box._text.set_text(title) + if title: + self._legend_title_box._text.set_visible(True) + self._legend_title_box.set_visible(True) + else: + self._legend_title_box._text.set_visible(False) + self._legend_title_box.set_visible(False) + + if prop is not None: + self._legend_title_box._text.set_fontproperties(prop) + + self.stale = True + + def get_title(self): + """Return the `.Text` instance for the legend title.""" + return self._legend_title_box._text + + def get_window_extent(self, renderer=None): + # docstring inherited + if renderer is None: + renderer = self.get_figure(root=True)._get_renderer() + return self._legend_box.get_window_extent(renderer=renderer) + + def get_tightbbox(self, renderer=None): + # docstring inherited + return self._legend_box.get_window_extent(renderer) + + def get_frame_on(self): + """Get whether the legend box patch is drawn.""" + return self.legendPatch.get_visible() + + def set_frame_on(self, b): + """ + Set whether the legend box patch is drawn. + + Parameters + ---------- + b : bool + """ + self.legendPatch.set_visible(b) + self.stale = True + + draw_frame = set_frame_on # Backcompat alias. + + def get_bbox_to_anchor(self): + """Return the bbox that the legend will be anchored to.""" + if self._bbox_to_anchor is None: + return self.parent.bbox + else: + return self._bbox_to_anchor + + def set_bbox_to_anchor(self, bbox, transform=None): + """ + Set the bbox that the legend will be anchored to. + + Parameters + ---------- + bbox : `~matplotlib.transforms.BboxBase` or tuple + The bounding box can be specified in the following ways: + + - A `.BboxBase` instance + - A tuple of ``(left, bottom, width, height)`` in the given + transform (normalized axes coordinate if None) + - A tuple of ``(left, bottom)`` where the width and height will be + assumed to be zero. + - *None*, to remove the bbox anchoring, and use the parent bbox. + + transform : `~matplotlib.transforms.Transform`, optional + A transform to apply to the bounding box. If not specified, this + will use a transform to the bounding box of the parent. + """ + if bbox is None: + self._bbox_to_anchor = None + return + elif isinstance(bbox, BboxBase): + self._bbox_to_anchor = bbox + else: + try: + l = len(bbox) + except TypeError as err: + raise ValueError(f"Invalid bbox: {bbox}") from err + + if l == 2: + bbox = [bbox[0], bbox[1], 0, 0] + + self._bbox_to_anchor = Bbox.from_bounds(*bbox) + + if transform is None: + transform = BboxTransformTo(self.parent.bbox) + + self._bbox_to_anchor = TransformedBbox(self._bbox_to_anchor, + transform) + self.stale = True + + def _get_anchored_bbox(self, loc, bbox, parentbbox, renderer): + """ + Place the *bbox* inside the *parentbbox* according to a given + location code. Return the (x, y) coordinate of the bbox. + + Parameters + ---------- + loc : int + A location code in range(1, 11). This corresponds to the possible + values for ``self._loc``, excluding "best". + bbox : `~matplotlib.transforms.Bbox` + bbox to be placed, in display coordinates. + parentbbox : `~matplotlib.transforms.Bbox` + A parent box which will contain the bbox, in display coordinates. + """ + return offsetbox._get_anchored_bbox( + loc, bbox, parentbbox, + self.borderaxespad * renderer.points_to_pixels(self._fontsize)) + + def _find_best_position(self, width, height, renderer): + """Determine the best location to place the legend.""" + assert self.isaxes # always holds, as this is only called internally + + start_time = time.perf_counter() + + bboxes, lines, offsets = self._auto_legend_data(renderer) + + bbox = Bbox.from_bounds(0, 0, width, height) + + candidates = [] + for idx in range(1, len(self.codes)): + l, b = self._get_anchored_bbox(idx, bbox, + self.get_bbox_to_anchor(), + renderer) + legendBox = Bbox.from_bounds(l, b, width, height) + # XXX TODO: If markers are present, it would be good to take them + # into account when checking vertex overlaps in the next line. + badness = (sum(legendBox.count_contains(line.vertices) + for line in lines) + + legendBox.count_contains(offsets) + + legendBox.count_overlaps(bboxes) + + sum(line.intersects_bbox(legendBox, filled=False) + for line in lines)) + # Include the index to favor lower codes in case of a tie. + candidates.append((badness, idx, (l, b))) + if badness == 0: + break + + _, _, (l, b) = min(candidates) + + if self._loc_used_default and time.perf_counter() - start_time > 1: + _api.warn_external( + 'Creating legend with loc="best" can be slow with large ' + 'amounts of data.') + + return l, b + + def contains(self, mouseevent): + return self.legendPatch.contains(mouseevent) + + def set_draggable(self, state, use_blit=False, update='loc'): + """ + Enable or disable mouse dragging support of the legend. + + Parameters + ---------- + state : bool + Whether mouse dragging is enabled. + use_blit : bool, optional + Use blitting for faster image composition. For details see + :ref:`func-animation`. + update : {'loc', 'bbox'}, optional + The legend parameter to be changed when dragged: + + - 'loc': update the *loc* parameter of the legend + - 'bbox': update the *bbox_to_anchor* parameter of the legend + + Returns + ------- + `.DraggableLegend` or *None* + If *state* is ``True`` this returns the `.DraggableLegend` helper + instance. Otherwise this returns *None*. + """ + if state: + if self._draggable is None: + self._draggable = DraggableLegend(self, + use_blit, + update=update) + else: + if self._draggable is not None: + self._draggable.disconnect() + self._draggable = None + return self._draggable + + def get_draggable(self): + """Return ``True`` if the legend is draggable, ``False`` otherwise.""" + return self._draggable is not None + + +# Helper functions to parse legend arguments for both `figure.legend` and +# `axes.legend`: +def _get_legend_handles(axs, legend_handler_map=None): + """Yield artists that can be used as handles in a legend.""" + handles_original = [] + for ax in axs: + handles_original += [ + *(a for a in ax._children + if isinstance(a, (Line2D, Patch, Collection, Text))), + *ax.containers] + # support parasite Axes: + if hasattr(ax, 'parasites'): + for axx in ax.parasites: + handles_original += [ + *(a for a in axx._children + if isinstance(a, (Line2D, Patch, Collection, Text))), + *axx.containers] + + handler_map = {**Legend.get_default_handler_map(), + **(legend_handler_map or {})} + has_handler = Legend.get_legend_handler + for handle in handles_original: + label = handle.get_label() + if label != '_nolegend_' and has_handler(handler_map, handle): + yield handle + elif (label and not label.startswith('_') and + not has_handler(handler_map, handle)): + _api.warn_external( + "Legend does not support handles for " + f"{type(handle).__name__} " + "instances.\nSee: https://matplotlib.org/stable/" + "tutorials/intermediate/legend_guide.html" + "#implementing-a-custom-legend-handler") + continue + + +def _get_legend_handles_labels(axs, legend_handler_map=None): + """Return handles and labels for legend.""" + handles = [] + labels = [] + for handle in _get_legend_handles(axs, legend_handler_map): + label = handle.get_label() + if label and not label.startswith('_'): + handles.append(handle) + labels.append(label) + return handles, labels + + +def _parse_legend_args(axs, *args, handles=None, labels=None, **kwargs): + """ + Get the handles and labels from the calls to either ``figure.legend`` + or ``axes.legend``. + + The parser is a bit involved because we support:: + + legend() + legend(labels) + legend(handles, labels) + legend(labels=labels) + legend(handles=handles) + legend(handles=handles, labels=labels) + + The behavior for a mixture of positional and keyword handles and labels + is undefined and issues a warning; it will be an error in the future. + + Parameters + ---------- + axs : list of `.Axes` + If handles are not given explicitly, the artists in these Axes are + used as handles. + *args : tuple + Positional parameters passed to ``legend()``. + handles + The value of the keyword argument ``legend(handles=...)``, or *None* + if that keyword argument was not used. + labels + The value of the keyword argument ``legend(labels=...)``, or *None* + if that keyword argument was not used. + **kwargs + All other keyword arguments passed to ``legend()``. + + Returns + ------- + handles : list of (`.Artist` or tuple of `.Artist`) + The legend handles. + labels : list of str + The legend labels. + kwargs : dict + *kwargs* with keywords handles and labels removed. + + """ + log = logging.getLogger(__name__) + + handlers = kwargs.get('handler_map') + + if (handles is not None or labels is not None) and args: + _api.warn_deprecated("3.9", message=( + "You have mixed positional and keyword arguments, some input may " + "be discarded. This is deprecated since %(since)s and will " + "become an error in %(removal)s.")) + + if (hasattr(handles, "__len__") and + hasattr(labels, "__len__") and + len(handles) != len(labels)): + _api.warn_external(f"Mismatched number of handles and labels: " + f"len(handles) = {len(handles)} " + f"len(labels) = {len(labels)}") + # if got both handles and labels as kwargs, make same length + if handles and labels: + handles, labels = zip(*zip(handles, labels)) + + elif handles is not None and labels is None: + labels = [handle.get_label() for handle in handles] + + elif labels is not None and handles is None: + # Get as many handles as there are labels. + handles = [handle for handle, label + in zip(_get_legend_handles(axs, handlers), labels)] + + elif len(args) == 0: # 0 args: automatically detect labels and handles. + handles, labels = _get_legend_handles_labels(axs, handlers) + if not handles: + _api.warn_external( + "No artists with labels found to put in legend. Note that " + "artists whose label start with an underscore are ignored " + "when legend() is called with no argument.") + + elif len(args) == 1: # 1 arg: user defined labels, automatic handle detection. + labels, = args + if any(isinstance(l, Artist) for l in labels): + raise TypeError("A single argument passed to legend() must be a " + "list of labels, but found an Artist in there.") + + # Get as many handles as there are labels. + handles = [handle for handle, label + in zip(_get_legend_handles(axs, handlers), labels)] + + elif len(args) == 2: # 2 args: user defined handles and labels. + handles, labels = args[:2] + + else: + raise _api.nargs_error('legend', '0-2', len(args)) + + return handles, labels, kwargs diff --git a/infer_4_30_0/lib/python3.10/site-packages/matplotlib/legend_handler.pyi b/infer_4_30_0/lib/python3.10/site-packages/matplotlib/legend_handler.pyi new file mode 100644 index 0000000000000000000000000000000000000000..db028a136a48ed5fe58f80b56854288564316851 --- /dev/null +++ b/infer_4_30_0/lib/python3.10/site-packages/matplotlib/legend_handler.pyi @@ -0,0 +1,294 @@ +from collections.abc import Callable, Sequence +from matplotlib.artist import Artist +from matplotlib.legend import Legend +from matplotlib.offsetbox import OffsetBox +from matplotlib.transforms import Transform + +from typing import TypeVar + +from numpy.typing import ArrayLike + +def update_from_first_child(tgt: Artist, src: Artist) -> None: ... + +class HandlerBase: + def __init__( + self, + xpad: float = ..., + ypad: float = ..., + update_func: Callable[[Artist, Artist], None] | None = ..., + ) -> None: ... + def update_prop( + self, legend_handle: Artist, orig_handle: Artist, legend: Legend + ) -> None: ... + def adjust_drawing_area( + self, + legend: Legend, + orig_handle: Artist, + xdescent: float, + ydescent: float, + width: float, + height: float, + fontsize: float, + ) -> tuple[float, float, float, float]: ... + def legend_artist( + self, legend: Legend, orig_handle: Artist, fontsize: float, handlebox: OffsetBox + ) -> Artist: ... + def create_artists( + self, + legend: Legend, + orig_handle: Artist, + xdescent: float, + ydescent: float, + width: float, + height: float, + fontsize: float, + trans: Transform, + ) -> Sequence[Artist]: ... + +class HandlerNpoints(HandlerBase): + def __init__( + self, marker_pad: float = ..., numpoints: int | None = ..., **kwargs + ) -> None: ... + def get_numpoints(self, legend: Legend) -> int | None: ... + def get_xdata( + self, + legend: Legend, + xdescent: float, + ydescent: float, + width: float, + height: float, + fontsize: float, + ) -> tuple[ArrayLike, ArrayLike]: ... + +class HandlerNpointsYoffsets(HandlerNpoints): + def __init__( + self, + numpoints: int | None = ..., + yoffsets: Sequence[float] | None = ..., + **kwargs + ) -> None: ... + def get_ydata( + self, + legend: Legend, + xdescent: float, + ydescent: float, + width: float, + height: float, + fontsize: float, + ) -> ArrayLike: ... + +class HandlerLine2DCompound(HandlerNpoints): + def create_artists( + self, + legend: Legend, + orig_handle: Artist, + xdescent: float, + ydescent: float, + width: float, + height: float, + fontsize: float, + trans: Transform, + ) -> Sequence[Artist]: ... + +class HandlerLine2D(HandlerNpoints): + def create_artists( + self, + legend: Legend, + orig_handle: Artist, + xdescent: float, + ydescent: float, + width: float, + height: float, + fontsize: float, + trans: Transform, + ) -> Sequence[Artist]: ... + +class HandlerPatch(HandlerBase): + def __init__(self, patch_func: Callable | None = ..., **kwargs) -> None: ... + def create_artists( + self, + legend: Legend, + orig_handle: Artist, + xdescent: float, + ydescent: float, + width: float, + height: float, + fontsize: float, + trans: Transform, + ) -> Sequence[Artist]: ... + +class HandlerStepPatch(HandlerBase): + def create_artists( + self, + legend: Legend, + orig_handle: Artist, + xdescent: float, + ydescent: float, + width: float, + height: float, + fontsize: float, + trans: Transform, + ) -> Sequence[Artist]: ... + +class HandlerLineCollection(HandlerLine2D): + def get_numpoints(self, legend: Legend) -> int: ... + def create_artists( + self, + legend: Legend, + orig_handle: Artist, + xdescent: float, + ydescent: float, + width: float, + height: float, + fontsize: float, + trans: Transform, + ) -> Sequence[Artist]: ... + +_T = TypeVar("_T", bound=Artist) + +class HandlerRegularPolyCollection(HandlerNpointsYoffsets): + def __init__( + self, + yoffsets: Sequence[float] | None = ..., + sizes: Sequence[float] | None = ..., + **kwargs + ) -> None: ... + def get_numpoints(self, legend: Legend) -> int: ... + def get_sizes( + self, + legend: Legend, + orig_handle: Artist, + xdescent: float, + ydescent: float, + width: float, + height: float, + fontsize: float, + ) -> Sequence[float]: ... + def update_prop( + self, legend_handle, orig_handle: Artist, legend: Legend + ) -> None: ... + def create_collection( + self, + orig_handle: _T, + sizes: Sequence[float] | None, + offsets: Sequence[float] | None, + offset_transform: Transform, + ) -> _T: ... + def create_artists( + self, + legend: Legend, + orig_handle: Artist, + xdescent: float, + ydescent: float, + width: float, + height: float, + fontsize: float, + trans: Transform, + ) -> Sequence[Artist]: ... + +class HandlerPathCollection(HandlerRegularPolyCollection): + def create_collection( + self, + orig_handle: _T, + sizes: Sequence[float] | None, + offsets: Sequence[float] | None, + offset_transform: Transform, + ) -> _T: ... + +class HandlerCircleCollection(HandlerRegularPolyCollection): + def create_collection( + self, + orig_handle: _T, + sizes: Sequence[float] | None, + offsets: Sequence[float] | None, + offset_transform: Transform, + ) -> _T: ... + +class HandlerErrorbar(HandlerLine2D): + def __init__( + self, + xerr_size: float = ..., + yerr_size: float | None = ..., + marker_pad: float = ..., + numpoints: int | None = ..., + **kwargs + ) -> None: ... + def get_err_size( + self, + legend: Legend, + xdescent: float, + ydescent: float, + width: float, + height: float, + fontsize: float, + ) -> tuple[float, float]: ... + def create_artists( + self, + legend: Legend, + orig_handle: Artist, + xdescent: float, + ydescent: float, + width: float, + height: float, + fontsize: float, + trans: Transform, + ) -> Sequence[Artist]: ... + +class HandlerStem(HandlerNpointsYoffsets): + def __init__( + self, + marker_pad: float = ..., + numpoints: int | None = ..., + bottom: float | None = ..., + yoffsets: Sequence[float] | None = ..., + **kwargs + ) -> None: ... + def get_ydata( + self, + legend: Legend, + xdescent: float, + ydescent: float, + width: float, + height: float, + fontsize: float, + ) -> ArrayLike: ... + def create_artists( + self, + legend: Legend, + orig_handle: Artist, + xdescent: float, + ydescent: float, + width: float, + height: float, + fontsize: float, + trans: Transform, + ) -> Sequence[Artist]: ... + +class HandlerTuple(HandlerBase): + def __init__( + self, ndivide: int | None = ..., pad: float | None = ..., **kwargs + ) -> None: ... + def create_artists( + self, + legend: Legend, + orig_handle: Artist, + xdescent: float, + ydescent: float, + width: float, + height: float, + fontsize: float, + trans: Transform, + ) -> Sequence[Artist]: ... + +class HandlerPolyCollection(HandlerBase): + def create_artists( + self, + legend: Legend, + orig_handle: Artist, + xdescent: float, + ydescent: float, + width: float, + height: float, + fontsize: float, + trans: Transform, + ) -> Sequence[Artist]: ... diff --git a/infer_4_30_0/lib/python3.10/site-packages/matplotlib/lines.py b/infer_4_30_0/lib/python3.10/site-packages/matplotlib/lines.py new file mode 100644 index 0000000000000000000000000000000000000000..65a4ccb6d950d92340e965599be244d71ebe029b --- /dev/null +++ b/infer_4_30_0/lib/python3.10/site-packages/matplotlib/lines.py @@ -0,0 +1,1706 @@ +""" +2D lines with support for a variety of line styles, markers, colors, etc. +""" + +import copy + +from numbers import Integral, Number, Real +import logging + +import numpy as np + +import matplotlib as mpl +from . import _api, cbook, colors as mcolors, _docstring +from .artist import Artist, allow_rasterization +from .cbook import ( + _to_unmasked_float_array, ls_mapper, ls_mapper_r, STEP_LOOKUP_MAP) +from .markers import MarkerStyle +from .path import Path +from .transforms import Bbox, BboxTransformTo, TransformedPath +from ._enums import JoinStyle, CapStyle + +# Imported here for backward compatibility, even though they don't +# really belong. +from . import _path +from .markers import ( # noqa + CARETLEFT, CARETRIGHT, CARETUP, CARETDOWN, + CARETLEFTBASE, CARETRIGHTBASE, CARETUPBASE, CARETDOWNBASE, + TICKLEFT, TICKRIGHT, TICKUP, TICKDOWN) + +_log = logging.getLogger(__name__) + + +def _get_dash_pattern(style): + """Convert linestyle to dash pattern.""" + # go from short hand -> full strings + if isinstance(style, str): + style = ls_mapper.get(style, style) + # un-dashed styles + if style in ['solid', 'None']: + offset = 0 + dashes = None + # dashed styles + elif style in ['dashed', 'dashdot', 'dotted']: + offset = 0 + dashes = tuple(mpl.rcParams[f'lines.{style}_pattern']) + # + elif isinstance(style, tuple): + offset, dashes = style + if offset is None: + raise ValueError(f'Unrecognized linestyle: {style!r}') + else: + raise ValueError(f'Unrecognized linestyle: {style!r}') + + # normalize offset to be positive and shorter than the dash cycle + if dashes is not None: + dsum = sum(dashes) + if dsum: + offset %= dsum + + return offset, dashes + + +def _get_inverse_dash_pattern(offset, dashes): + """Return the inverse of the given dash pattern, for filling the gaps.""" + # Define the inverse pattern by moving the last gap to the start of the + # sequence. + gaps = dashes[-1:] + dashes[:-1] + # Set the offset so that this new first segment is skipped + # (see backend_bases.GraphicsContextBase.set_dashes for offset definition). + offset_gaps = offset + dashes[-1] + + return offset_gaps, gaps + + +def _scale_dashes(offset, dashes, lw): + if not mpl.rcParams['lines.scale_dashes']: + return offset, dashes + scaled_offset = offset * lw + scaled_dashes = ([x * lw if x is not None else None for x in dashes] + if dashes is not None else None) + return scaled_offset, scaled_dashes + + +def segment_hits(cx, cy, x, y, radius): + """ + Return the indices of the segments in the polyline with coordinates (*cx*, + *cy*) that are within a distance *radius* of the point (*x*, *y*). + """ + # Process single points specially + if len(x) <= 1: + res, = np.nonzero((cx - x) ** 2 + (cy - y) ** 2 <= radius ** 2) + return res + + # We need to lop the last element off a lot. + xr, yr = x[:-1], y[:-1] + + # Only look at line segments whose nearest point to C on the line + # lies within the segment. + dx, dy = x[1:] - xr, y[1:] - yr + Lnorm_sq = dx ** 2 + dy ** 2 # Possibly want to eliminate Lnorm==0 + u = ((cx - xr) * dx + (cy - yr) * dy) / Lnorm_sq + candidates = (u >= 0) & (u <= 1) + + # Note that there is a little area near one side of each point + # which will be near neither segment, and another which will + # be near both, depending on the angle of the lines. The + # following radius test eliminates these ambiguities. + point_hits = (cx - x) ** 2 + (cy - y) ** 2 <= radius ** 2 + candidates = candidates & ~(point_hits[:-1] | point_hits[1:]) + + # For those candidates which remain, determine how far they lie away + # from the line. + px, py = xr + u * dx, yr + u * dy + line_hits = (cx - px) ** 2 + (cy - py) ** 2 <= radius ** 2 + line_hits = line_hits & candidates + points, = point_hits.ravel().nonzero() + lines, = line_hits.ravel().nonzero() + return np.concatenate((points, lines)) + + +def _mark_every_path(markevery, tpath, affine, ax): + """ + Helper function that sorts out how to deal the input + `markevery` and returns the points where markers should be drawn. + + Takes in the `markevery` value and the line path and returns the + sub-sampled path. + """ + # pull out the two bits of data we want from the path + codes, verts = tpath.codes, tpath.vertices + + def _slice_or_none(in_v, slc): + """Helper function to cope with `codes` being an ndarray or `None`.""" + if in_v is None: + return None + return in_v[slc] + + # if just an int, assume starting at 0 and make a tuple + if isinstance(markevery, Integral): + markevery = (0, markevery) + # if just a float, assume starting at 0.0 and make a tuple + elif isinstance(markevery, Real): + markevery = (0.0, markevery) + + if isinstance(markevery, tuple): + if len(markevery) != 2: + raise ValueError('`markevery` is a tuple but its len is not 2; ' + f'markevery={markevery}') + start, step = markevery + # if step is an int, old behavior + if isinstance(step, Integral): + # tuple of 2 int is for backwards compatibility, + if not isinstance(start, Integral): + raise ValueError( + '`markevery` is a tuple with len 2 and second element is ' + 'an int, but the first element is not an int; ' + f'markevery={markevery}') + # just return, we are done here + + return Path(verts[slice(start, None, step)], + _slice_or_none(codes, slice(start, None, step))) + + elif isinstance(step, Real): + if not isinstance(start, Real): + raise ValueError( + '`markevery` is a tuple with len 2 and second element is ' + 'a float, but the first element is not a float or an int; ' + f'markevery={markevery}') + if ax is None: + raise ValueError( + "markevery is specified relative to the Axes size, but " + "the line does not have a Axes as parent") + + # calc cumulative distance along path (in display coords): + fin = np.isfinite(verts).all(axis=1) + fverts = verts[fin] + disp_coords = affine.transform(fverts) + + delta = np.empty((len(disp_coords), 2)) + delta[0, :] = 0 + delta[1:, :] = disp_coords[1:, :] - disp_coords[:-1, :] + delta = np.hypot(*delta.T).cumsum() + # calc distance between markers along path based on the Axes + # bounding box diagonal being a distance of unity: + (x0, y0), (x1, y1) = ax.transAxes.transform([[0, 0], [1, 1]]) + scale = np.hypot(x1 - x0, y1 - y0) + marker_delta = np.arange(start * scale, delta[-1], step * scale) + # find closest actual data point that is closest to + # the theoretical distance along the path: + inds = np.abs(delta[np.newaxis, :] - marker_delta[:, np.newaxis]) + inds = inds.argmin(axis=1) + inds = np.unique(inds) + # return, we are done here + return Path(fverts[inds], _slice_or_none(codes, inds)) + else: + raise ValueError( + f"markevery={markevery!r} is a tuple with len 2, but its " + f"second element is not an int or a float") + + elif isinstance(markevery, slice): + # mazol tov, it's already a slice, just return + return Path(verts[markevery], _slice_or_none(codes, markevery)) + + elif np.iterable(markevery): + # fancy indexing + try: + return Path(verts[markevery], _slice_or_none(codes, markevery)) + except (ValueError, IndexError) as err: + raise ValueError( + f"markevery={markevery!r} is iterable but not a valid numpy " + f"fancy index") from err + else: + raise ValueError(f"markevery={markevery!r} is not a recognized value") + + +@_docstring.interpd +@_api.define_aliases({ + "antialiased": ["aa"], + "color": ["c"], + "drawstyle": ["ds"], + "linestyle": ["ls"], + "linewidth": ["lw"], + "markeredgecolor": ["mec"], + "markeredgewidth": ["mew"], + "markerfacecolor": ["mfc"], + "markerfacecoloralt": ["mfcalt"], + "markersize": ["ms"], +}) +class Line2D(Artist): + """ + A line - the line can have both a solid linestyle connecting all + the vertices, and a marker at each vertex. Additionally, the + drawing of the solid line is influenced by the drawstyle, e.g., one + can create "stepped" lines in various styles. + """ + + lineStyles = _lineStyles = { # hidden names deprecated + '-': '_draw_solid', + '--': '_draw_dashed', + '-.': '_draw_dash_dot', + ':': '_draw_dotted', + 'None': '_draw_nothing', + ' ': '_draw_nothing', + '': '_draw_nothing', + } + + _drawStyles_l = { + 'default': '_draw_lines', + 'steps-mid': '_draw_steps_mid', + 'steps-pre': '_draw_steps_pre', + 'steps-post': '_draw_steps_post', + } + + _drawStyles_s = { + 'steps': '_draw_steps_pre', + } + + # drawStyles should now be deprecated. + drawStyles = {**_drawStyles_l, **_drawStyles_s} + # Need a list ordered with long names first: + drawStyleKeys = [*_drawStyles_l, *_drawStyles_s] + + # Referenced here to maintain API. These are defined in + # MarkerStyle + markers = MarkerStyle.markers + filled_markers = MarkerStyle.filled_markers + fillStyles = MarkerStyle.fillstyles + + zorder = 2 + + _subslice_optim_min_size = 1000 + + def __str__(self): + if self._label != "": + return f"Line2D({self._label})" + elif self._x is None: + return "Line2D()" + elif len(self._x) > 3: + return "Line2D(({:g},{:g}),({:g},{:g}),...,({:g},{:g}))".format( + self._x[0], self._y[0], + self._x[1], self._y[1], + self._x[-1], self._y[-1]) + else: + return "Line2D(%s)" % ",".join( + map("({:g},{:g})".format, self._x, self._y)) + + def __init__(self, xdata, ydata, *, + linewidth=None, # all Nones default to rc + linestyle=None, + color=None, + gapcolor=None, + marker=None, + markersize=None, + markeredgewidth=None, + markeredgecolor=None, + markerfacecolor=None, + markerfacecoloralt='none', + fillstyle=None, + antialiased=None, + dash_capstyle=None, + solid_capstyle=None, + dash_joinstyle=None, + solid_joinstyle=None, + pickradius=5, + drawstyle=None, + markevery=None, + **kwargs + ): + """ + Create a `.Line2D` instance with *x* and *y* data in sequences of + *xdata*, *ydata*. + + Additional keyword arguments are `.Line2D` properties: + + %(Line2D:kwdoc)s + + See :meth:`set_linestyle` for a description of the line styles, + :meth:`set_marker` for a description of the markers, and + :meth:`set_drawstyle` for a description of the draw styles. + + """ + super().__init__() + + # Convert sequences to NumPy arrays. + if not np.iterable(xdata): + raise RuntimeError('xdata must be a sequence') + if not np.iterable(ydata): + raise RuntimeError('ydata must be a sequence') + + if linewidth is None: + linewidth = mpl.rcParams['lines.linewidth'] + + if linestyle is None: + linestyle = mpl.rcParams['lines.linestyle'] + if marker is None: + marker = mpl.rcParams['lines.marker'] + if color is None: + color = mpl.rcParams['lines.color'] + + if markersize is None: + markersize = mpl.rcParams['lines.markersize'] + if antialiased is None: + antialiased = mpl.rcParams['lines.antialiased'] + if dash_capstyle is None: + dash_capstyle = mpl.rcParams['lines.dash_capstyle'] + if dash_joinstyle is None: + dash_joinstyle = mpl.rcParams['lines.dash_joinstyle'] + if solid_capstyle is None: + solid_capstyle = mpl.rcParams['lines.solid_capstyle'] + if solid_joinstyle is None: + solid_joinstyle = mpl.rcParams['lines.solid_joinstyle'] + + if drawstyle is None: + drawstyle = 'default' + + self._dashcapstyle = None + self._dashjoinstyle = None + self._solidjoinstyle = None + self._solidcapstyle = None + self.set_dash_capstyle(dash_capstyle) + self.set_dash_joinstyle(dash_joinstyle) + self.set_solid_capstyle(solid_capstyle) + self.set_solid_joinstyle(solid_joinstyle) + + self._linestyles = None + self._drawstyle = None + self._linewidth = linewidth + self._unscaled_dash_pattern = (0, None) # offset, dash + self._dash_pattern = (0, None) # offset, dash (scaled by linewidth) + + self.set_linewidth(linewidth) + self.set_linestyle(linestyle) + self.set_drawstyle(drawstyle) + + self._color = None + self.set_color(color) + if marker is None: + marker = 'none' # Default. + if not isinstance(marker, MarkerStyle): + self._marker = MarkerStyle(marker, fillstyle) + else: + self._marker = marker + + self._gapcolor = None + self.set_gapcolor(gapcolor) + + self._markevery = None + self._markersize = None + self._antialiased = None + + self.set_markevery(markevery) + self.set_antialiased(antialiased) + self.set_markersize(markersize) + + self._markeredgecolor = None + self._markeredgewidth = None + self._markerfacecolor = None + self._markerfacecoloralt = None + + self.set_markerfacecolor(markerfacecolor) # Normalizes None to rc. + self.set_markerfacecoloralt(markerfacecoloralt) + self.set_markeredgecolor(markeredgecolor) # Normalizes None to rc. + self.set_markeredgewidth(markeredgewidth) + + # update kwargs before updating data to give the caller a + # chance to init axes (and hence unit support) + self._internal_update(kwargs) + self.pickradius = pickradius + self.ind_offset = 0 + if (isinstance(self._picker, Number) and + not isinstance(self._picker, bool)): + self._pickradius = self._picker + + self._xorig = np.asarray([]) + self._yorig = np.asarray([]) + self._invalidx = True + self._invalidy = True + self._x = None + self._y = None + self._xy = None + self._path = None + self._transformed_path = None + self._subslice = False + self._x_filled = None # used in subslicing; only x is needed + + self.set_data(xdata, ydata) + + def contains(self, mouseevent): + """ + Test whether *mouseevent* occurred on the line. + + An event is deemed to have occurred "on" the line if it is less + than ``self.pickradius`` (default: 5 points) away from it. Use + `~.Line2D.get_pickradius` or `~.Line2D.set_pickradius` to get or set + the pick radius. + + Parameters + ---------- + mouseevent : `~matplotlib.backend_bases.MouseEvent` + + Returns + ------- + contains : bool + Whether any values are within the radius. + details : dict + A dictionary ``{'ind': pointlist}``, where *pointlist* is a + list of points of the line that are within the pickradius around + the event position. + + TODO: sort returned indices by distance + """ + if self._different_canvas(mouseevent): + return False, {} + + # Make sure we have data to plot + if self._invalidy or self._invalidx: + self.recache() + if len(self._xy) == 0: + return False, {} + + # Convert points to pixels + transformed_path = self._get_transformed_path() + path, affine = transformed_path.get_transformed_path_and_affine() + path = affine.transform_path(path) + xy = path.vertices + xt = xy[:, 0] + yt = xy[:, 1] + + # Convert pick radius from points to pixels + fig = self.get_figure(root=True) + if fig is None: + _log.warning('no figure set when check if mouse is on line') + pixels = self._pickradius + else: + pixels = fig.dpi / 72. * self._pickradius + + # The math involved in checking for containment (here and inside of + # segment_hits) assumes that it is OK to overflow, so temporarily set + # the error flags accordingly. + with np.errstate(all='ignore'): + # Check for collision + if self._linestyle in ['None', None]: + # If no line, return the nearby point(s) + ind, = np.nonzero( + (xt - mouseevent.x) ** 2 + (yt - mouseevent.y) ** 2 + <= pixels ** 2) + else: + # If line, return the nearby segment(s) + ind = segment_hits(mouseevent.x, mouseevent.y, xt, yt, pixels) + if self._drawstyle.startswith("steps"): + ind //= 2 + + ind += self.ind_offset + + # Return the point(s) within radius + return len(ind) > 0, dict(ind=ind) + + def get_pickradius(self): + """ + Return the pick radius used for containment tests. + + See `.contains` for more details. + """ + return self._pickradius + + def set_pickradius(self, pickradius): + """ + Set the pick radius used for containment tests. + + See `.contains` for more details. + + Parameters + ---------- + pickradius : float + Pick radius, in points. + """ + if not isinstance(pickradius, Real) or pickradius < 0: + raise ValueError("pick radius should be a distance") + self._pickradius = pickradius + + pickradius = property(get_pickradius, set_pickradius) + + def get_fillstyle(self): + """ + Return the marker fill style. + + See also `~.Line2D.set_fillstyle`. + """ + return self._marker.get_fillstyle() + + def set_fillstyle(self, fs): + """ + Set the marker fill style. + + Parameters + ---------- + fs : {'full', 'left', 'right', 'bottom', 'top', 'none'} + Possible values: + + - 'full': Fill the whole marker with the *markerfacecolor*. + - 'left', 'right', 'bottom', 'top': Fill the marker half at + the given side with the *markerfacecolor*. The other + half of the marker is filled with *markerfacecoloralt*. + - 'none': No filling. + + For examples see :ref:`marker_fill_styles`. + """ + self.set_marker(MarkerStyle(self._marker.get_marker(), fs)) + self.stale = True + + def set_markevery(self, every): + """ + Set the markevery property to subsample the plot when using markers. + + e.g., if ``every=5``, every 5-th marker will be plotted. + + Parameters + ---------- + every : None or int or (int, int) or slice or list[int] or float or \ +(float, float) or list[bool] + Which markers to plot. + + - ``every=None``: every point will be plotted. + - ``every=N``: every N-th marker will be plotted starting with + marker 0. + - ``every=(start, N)``: every N-th marker, starting at index + *start*, will be plotted. + - ``every=slice(start, end, N)``: every N-th marker, starting at + index *start*, up to but not including index *end*, will be + plotted. + - ``every=[i, j, m, ...]``: only markers at the given indices + will be plotted. + - ``every=[True, False, True, ...]``: only positions that are True + will be plotted. The list must have the same length as the data + points. + - ``every=0.1``, (i.e. a float): markers will be spaced at + approximately equal visual distances along the line; the distance + along the line between markers is determined by multiplying the + display-coordinate distance of the Axes bounding-box diagonal + by the value of *every*. + - ``every=(0.5, 0.1)`` (i.e. a length-2 tuple of float): similar + to ``every=0.1`` but the first marker will be offset along the + line by 0.5 multiplied by the + display-coordinate-diagonal-distance along the line. + + For examples see + :doc:`/gallery/lines_bars_and_markers/markevery_demo`. + + Notes + ----- + Setting *markevery* will still only draw markers at actual data points. + While the float argument form aims for uniform visual spacing, it has + to coerce from the ideal spacing to the nearest available data point. + Depending on the number and distribution of data points, the result + may still not look evenly spaced. + + When using a start offset to specify the first marker, the offset will + be from the first data point which may be different from the first + the visible data point if the plot is zoomed in. + + If zooming in on a plot when using float arguments then the actual + data points that have markers will change because the distance between + markers is always determined from the display-coordinates + axes-bounding-box-diagonal regardless of the actual axes data limits. + + """ + self._markevery = every + self.stale = True + + def get_markevery(self): + """ + Return the markevery setting for marker subsampling. + + See also `~.Line2D.set_markevery`. + """ + return self._markevery + + def set_picker(self, p): + """ + Set the event picker details for the line. + + Parameters + ---------- + p : float or callable[[Artist, Event], tuple[bool, dict]] + If a float, it is used as the pick radius in points. + """ + if not callable(p): + self.set_pickradius(p) + self._picker = p + + def get_bbox(self): + """Get the bounding box of this line.""" + bbox = Bbox([[0, 0], [0, 0]]) + bbox.update_from_data_xy(self.get_xydata()) + return bbox + + def get_window_extent(self, renderer=None): + bbox = Bbox([[0, 0], [0, 0]]) + trans_data_to_xy = self.get_transform().transform + bbox.update_from_data_xy(trans_data_to_xy(self.get_xydata()), + ignore=True) + # correct for marker size, if any + if self._marker: + ms = (self._markersize / 72.0 * self.get_figure(root=True).dpi) * 0.5 + bbox = bbox.padded(ms) + return bbox + + def set_data(self, *args): + """ + Set the x and y data. + + Parameters + ---------- + *args : (2, N) array or two 1D arrays + + See Also + -------- + set_xdata + set_ydata + """ + if len(args) == 1: + (x, y), = args + else: + x, y = args + + self.set_xdata(x) + self.set_ydata(y) + + def recache_always(self): + self.recache(always=True) + + def recache(self, always=False): + if always or self._invalidx: + xconv = self.convert_xunits(self._xorig) + x = _to_unmasked_float_array(xconv).ravel() + else: + x = self._x + if always or self._invalidy: + yconv = self.convert_yunits(self._yorig) + y = _to_unmasked_float_array(yconv).ravel() + else: + y = self._y + + self._xy = np.column_stack(np.broadcast_arrays(x, y)).astype(float) + self._x, self._y = self._xy.T # views + + self._subslice = False + if (self.axes + and len(x) > self._subslice_optim_min_size + and _path.is_sorted_and_has_non_nan(x) + and self.axes.name == 'rectilinear' + and self.axes.get_xscale() == 'linear' + and self._markevery is None + and self.get_clip_on() + and self.get_transform() == self.axes.transData): + self._subslice = True + nanmask = np.isnan(x) + if nanmask.any(): + self._x_filled = self._x.copy() + indices = np.arange(len(x)) + self._x_filled[nanmask] = np.interp( + indices[nanmask], indices[~nanmask], self._x[~nanmask]) + else: + self._x_filled = self._x + + if self._path is not None: + interpolation_steps = self._path._interpolation_steps + else: + interpolation_steps = 1 + xy = STEP_LOOKUP_MAP[self._drawstyle](*self._xy.T) + self._path = Path(np.asarray(xy).T, + _interpolation_steps=interpolation_steps) + self._transformed_path = None + self._invalidx = False + self._invalidy = False + + def _transform_path(self, subslice=None): + """ + Put a TransformedPath instance at self._transformed_path; + all invalidation of the transform is then handled by the + TransformedPath instance. + """ + # Masked arrays are now handled by the Path class itself + if subslice is not None: + xy = STEP_LOOKUP_MAP[self._drawstyle](*self._xy[subslice, :].T) + _path = Path(np.asarray(xy).T, + _interpolation_steps=self._path._interpolation_steps) + else: + _path = self._path + self._transformed_path = TransformedPath(_path, self.get_transform()) + + def _get_transformed_path(self): + """Return this line's `~matplotlib.transforms.TransformedPath`.""" + if self._transformed_path is None: + self._transform_path() + return self._transformed_path + + def set_transform(self, t): + # docstring inherited + self._invalidx = True + self._invalidy = True + super().set_transform(t) + + @allow_rasterization + def draw(self, renderer): + # docstring inherited + + if not self.get_visible(): + return + + if self._invalidy or self._invalidx: + self.recache() + self.ind_offset = 0 # Needed for contains() method. + if self._subslice and self.axes: + x0, x1 = self.axes.get_xbound() + i0 = self._x_filled.searchsorted(x0, 'left') + i1 = self._x_filled.searchsorted(x1, 'right') + subslice = slice(max(i0 - 1, 0), i1 + 1) + self.ind_offset = subslice.start + self._transform_path(subslice) + else: + subslice = None + + if self.get_path_effects(): + from matplotlib.patheffects import PathEffectRenderer + renderer = PathEffectRenderer(self.get_path_effects(), renderer) + + renderer.open_group('line2d', self.get_gid()) + if self._lineStyles[self._linestyle] != '_draw_nothing': + tpath, affine = (self._get_transformed_path() + .get_transformed_path_and_affine()) + if len(tpath.vertices): + gc = renderer.new_gc() + self._set_gc_clip(gc) + gc.set_url(self.get_url()) + + gc.set_antialiased(self._antialiased) + gc.set_linewidth(self._linewidth) + + if self.is_dashed(): + cap = self._dashcapstyle + join = self._dashjoinstyle + else: + cap = self._solidcapstyle + join = self._solidjoinstyle + gc.set_joinstyle(join) + gc.set_capstyle(cap) + gc.set_snap(self.get_snap()) + if self.get_sketch_params() is not None: + gc.set_sketch_params(*self.get_sketch_params()) + + # We first draw a path within the gaps if needed. + if self.is_dashed() and self._gapcolor is not None: + lc_rgba = mcolors.to_rgba(self._gapcolor, self._alpha) + gc.set_foreground(lc_rgba, isRGBA=True) + + offset_gaps, gaps = _get_inverse_dash_pattern( + *self._dash_pattern) + + gc.set_dashes(offset_gaps, gaps) + renderer.draw_path(gc, tpath, affine.frozen()) + + lc_rgba = mcolors.to_rgba(self._color, self._alpha) + gc.set_foreground(lc_rgba, isRGBA=True) + + gc.set_dashes(*self._dash_pattern) + renderer.draw_path(gc, tpath, affine.frozen()) + gc.restore() + + if self._marker and self._markersize > 0: + gc = renderer.new_gc() + self._set_gc_clip(gc) + gc.set_url(self.get_url()) + gc.set_linewidth(self._markeredgewidth) + gc.set_antialiased(self._antialiased) + + ec_rgba = mcolors.to_rgba( + self.get_markeredgecolor(), self._alpha) + fc_rgba = mcolors.to_rgba( + self._get_markerfacecolor(), self._alpha) + fcalt_rgba = mcolors.to_rgba( + self._get_markerfacecolor(alt=True), self._alpha) + # If the edgecolor is "auto", it is set according to the *line* + # color but inherits the alpha value of the *face* color, if any. + if (cbook._str_equal(self._markeredgecolor, "auto") + and not cbook._str_lower_equal( + self.get_markerfacecolor(), "none")): + ec_rgba = ec_rgba[:3] + (fc_rgba[3],) + gc.set_foreground(ec_rgba, isRGBA=True) + if self.get_sketch_params() is not None: + scale, length, randomness = self.get_sketch_params() + gc.set_sketch_params(scale/2, length/2, 2*randomness) + + marker = self._marker + + # Markers *must* be drawn ignoring the drawstyle (but don't pay the + # recaching if drawstyle is already "default"). + if self.get_drawstyle() != "default": + with cbook._setattr_cm( + self, _drawstyle="default", _transformed_path=None): + self.recache() + self._transform_path(subslice) + tpath, affine = (self._get_transformed_path() + .get_transformed_points_and_affine()) + else: + tpath, affine = (self._get_transformed_path() + .get_transformed_points_and_affine()) + + if len(tpath.vertices): + # subsample the markers if markevery is not None + markevery = self.get_markevery() + if markevery is not None: + subsampled = _mark_every_path( + markevery, tpath, affine, self.axes) + else: + subsampled = tpath + + snap = marker.get_snap_threshold() + if isinstance(snap, Real): + snap = renderer.points_to_pixels(self._markersize) >= snap + gc.set_snap(snap) + gc.set_joinstyle(marker.get_joinstyle()) + gc.set_capstyle(marker.get_capstyle()) + marker_path = marker.get_path() + marker_trans = marker.get_transform() + w = renderer.points_to_pixels(self._markersize) + + if cbook._str_equal(marker.get_marker(), ","): + gc.set_linewidth(0) + else: + # Don't scale for pixels, and don't stroke them + marker_trans = marker_trans.scale(w) + renderer.draw_markers(gc, marker_path, marker_trans, + subsampled, affine.frozen(), + fc_rgba) + + alt_marker_path = marker.get_alt_path() + if alt_marker_path: + alt_marker_trans = marker.get_alt_transform() + alt_marker_trans = alt_marker_trans.scale(w) + renderer.draw_markers( + gc, alt_marker_path, alt_marker_trans, subsampled, + affine.frozen(), fcalt_rgba) + + gc.restore() + + renderer.close_group('line2d') + self.stale = False + + def get_antialiased(self): + """Return whether antialiased rendering is used.""" + return self._antialiased + + def get_color(self): + """ + Return the line color. + + See also `~.Line2D.set_color`. + """ + return self._color + + def get_drawstyle(self): + """ + Return the drawstyle. + + See also `~.Line2D.set_drawstyle`. + """ + return self._drawstyle + + def get_gapcolor(self): + """ + Return the line gapcolor. + + See also `~.Line2D.set_gapcolor`. + """ + return self._gapcolor + + def get_linestyle(self): + """ + Return the linestyle. + + See also `~.Line2D.set_linestyle`. + """ + return self._linestyle + + def get_linewidth(self): + """ + Return the linewidth in points. + + See also `~.Line2D.set_linewidth`. + """ + return self._linewidth + + def get_marker(self): + """ + Return the line marker. + + See also `~.Line2D.set_marker`. + """ + return self._marker.get_marker() + + def get_markeredgecolor(self): + """ + Return the marker edge color. + + See also `~.Line2D.set_markeredgecolor`. + """ + mec = self._markeredgecolor + if cbook._str_equal(mec, 'auto'): + if mpl.rcParams['_internal.classic_mode']: + if self._marker.get_marker() in ('.', ','): + return self._color + if (self._marker.is_filled() + and self._marker.get_fillstyle() != 'none'): + return 'k' # Bad hard-wired default... + return self._color + else: + return mec + + def get_markeredgewidth(self): + """ + Return the marker edge width in points. + + See also `~.Line2D.set_markeredgewidth`. + """ + return self._markeredgewidth + + def _get_markerfacecolor(self, alt=False): + if self._marker.get_fillstyle() == 'none': + return 'none' + fc = self._markerfacecoloralt if alt else self._markerfacecolor + if cbook._str_lower_equal(fc, 'auto'): + return self._color + else: + return fc + + def get_markerfacecolor(self): + """ + Return the marker face color. + + See also `~.Line2D.set_markerfacecolor`. + """ + return self._get_markerfacecolor(alt=False) + + def get_markerfacecoloralt(self): + """ + Return the alternate marker face color. + + See also `~.Line2D.set_markerfacecoloralt`. + """ + return self._get_markerfacecolor(alt=True) + + def get_markersize(self): + """ + Return the marker size in points. + + See also `~.Line2D.set_markersize`. + """ + return self._markersize + + def get_data(self, orig=True): + """ + Return the line data as an ``(xdata, ydata)`` pair. + + If *orig* is *True*, return the original data. + """ + return self.get_xdata(orig=orig), self.get_ydata(orig=orig) + + def get_xdata(self, orig=True): + """ + Return the xdata. + + If *orig* is *True*, return the original data, else the + processed data. + """ + if orig: + return self._xorig + if self._invalidx: + self.recache() + return self._x + + def get_ydata(self, orig=True): + """ + Return the ydata. + + If *orig* is *True*, return the original data, else the + processed data. + """ + if orig: + return self._yorig + if self._invalidy: + self.recache() + return self._y + + def get_path(self): + """Return the `~matplotlib.path.Path` associated with this line.""" + if self._invalidy or self._invalidx: + self.recache() + return self._path + + def get_xydata(self): + """Return the *xy* data as a (N, 2) array.""" + if self._invalidy or self._invalidx: + self.recache() + return self._xy + + def set_antialiased(self, b): + """ + Set whether to use antialiased rendering. + + Parameters + ---------- + b : bool + """ + if self._antialiased != b: + self.stale = True + self._antialiased = b + + def set_color(self, color): + """ + Set the color of the line. + + Parameters + ---------- + color : :mpltype:`color` + """ + mcolors._check_color_like(color=color) + self._color = color + self.stale = True + + def set_drawstyle(self, drawstyle): + """ + Set the drawstyle of the plot. + + The drawstyle determines how the points are connected. + + Parameters + ---------- + drawstyle : {'default', 'steps', 'steps-pre', 'steps-mid', \ +'steps-post'}, default: 'default' + For 'default', the points are connected with straight lines. + + The steps variants connect the points with step-like lines, + i.e. horizontal lines with vertical steps. They differ in the + location of the step: + + - 'steps-pre': The step is at the beginning of the line segment, + i.e. the line will be at the y-value of point to the right. + - 'steps-mid': The step is halfway between the points. + - 'steps-post: The step is at the end of the line segment, + i.e. the line will be at the y-value of the point to the left. + - 'steps' is equal to 'steps-pre' and is maintained for + backward-compatibility. + + For examples see :doc:`/gallery/lines_bars_and_markers/step_demo`. + """ + if drawstyle is None: + drawstyle = 'default' + _api.check_in_list(self.drawStyles, drawstyle=drawstyle) + if self._drawstyle != drawstyle: + self.stale = True + # invalidate to trigger a recache of the path + self._invalidx = True + self._drawstyle = drawstyle + + def set_gapcolor(self, gapcolor): + """ + Set a color to fill the gaps in the dashed line style. + + .. note:: + + Striped lines are created by drawing two interleaved dashed lines. + There can be overlaps between those two, which may result in + artifacts when using transparency. + + This functionality is experimental and may change. + + Parameters + ---------- + gapcolor : :mpltype:`color` or None + The color with which to fill the gaps. If None, the gaps are + unfilled. + """ + if gapcolor is not None: + mcolors._check_color_like(color=gapcolor) + self._gapcolor = gapcolor + self.stale = True + + def set_linewidth(self, w): + """ + Set the line width in points. + + Parameters + ---------- + w : float + Line width, in points. + """ + w = float(w) + if self._linewidth != w: + self.stale = True + self._linewidth = w + self._dash_pattern = _scale_dashes(*self._unscaled_dash_pattern, w) + + def set_linestyle(self, ls): + """ + Set the linestyle of the line. + + Parameters + ---------- + ls : {'-', '--', '-.', ':', '', (offset, on-off-seq), ...} + Possible values: + + - A string: + + ========================================== ================= + linestyle description + ========================================== ================= + ``'-'`` or ``'solid'`` solid line + ``'--'`` or ``'dashed'`` dashed line + ``'-.'`` or ``'dashdot'`` dash-dotted line + ``':'`` or ``'dotted'`` dotted line + ``'none'``, ``'None'``, ``' '``, or ``''`` draw nothing + ========================================== ================= + + - Alternatively a dash tuple of the following form can be + provided:: + + (offset, onoffseq) + + where ``onoffseq`` is an even length tuple of on and off ink + in points. See also :meth:`set_dashes`. + + For examples see :doc:`/gallery/lines_bars_and_markers/linestyles`. + """ + if isinstance(ls, str): + if ls in [' ', '', 'none']: + ls = 'None' + _api.check_in_list([*self._lineStyles, *ls_mapper_r], ls=ls) + if ls not in self._lineStyles: + ls = ls_mapper_r[ls] + self._linestyle = ls + else: + self._linestyle = '--' + self._unscaled_dash_pattern = _get_dash_pattern(ls) + self._dash_pattern = _scale_dashes( + *self._unscaled_dash_pattern, self._linewidth) + self.stale = True + + @_docstring.interpd + def set_marker(self, marker): + """ + Set the line marker. + + Parameters + ---------- + marker : marker style string, `~.path.Path` or `~.markers.MarkerStyle` + See `~matplotlib.markers` for full description of possible + arguments. + """ + self._marker = MarkerStyle(marker, self._marker.get_fillstyle()) + self.stale = True + + def _set_markercolor(self, name, has_rcdefault, val): + if val is None: + val = mpl.rcParams[f"lines.{name}"] if has_rcdefault else "auto" + attr = f"_{name}" + current = getattr(self, attr) + if current is None: + self.stale = True + else: + neq = current != val + # Much faster than `np.any(current != val)` if no arrays are used. + if neq.any() if isinstance(neq, np.ndarray) else neq: + self.stale = True + setattr(self, attr, val) + + def set_markeredgecolor(self, ec): + """ + Set the marker edge color. + + Parameters + ---------- + ec : :mpltype:`color` + """ + self._set_markercolor("markeredgecolor", True, ec) + + def set_markerfacecolor(self, fc): + """ + Set the marker face color. + + Parameters + ---------- + fc : :mpltype:`color` + """ + self._set_markercolor("markerfacecolor", True, fc) + + def set_markerfacecoloralt(self, fc): + """ + Set the alternate marker face color. + + Parameters + ---------- + fc : :mpltype:`color` + """ + self._set_markercolor("markerfacecoloralt", False, fc) + + def set_markeredgewidth(self, ew): + """ + Set the marker edge width in points. + + Parameters + ---------- + ew : float + Marker edge width, in points. + """ + if ew is None: + ew = mpl.rcParams['lines.markeredgewidth'] + if self._markeredgewidth != ew: + self.stale = True + self._markeredgewidth = ew + + def set_markersize(self, sz): + """ + Set the marker size in points. + + Parameters + ---------- + sz : float + Marker size, in points. + """ + sz = float(sz) + if self._markersize != sz: + self.stale = True + self._markersize = sz + + def set_xdata(self, x): + """ + Set the data array for x. + + Parameters + ---------- + x : 1D array + + See Also + -------- + set_data + set_ydata + """ + if not np.iterable(x): + raise RuntimeError('x must be a sequence') + self._xorig = copy.copy(x) + self._invalidx = True + self.stale = True + + def set_ydata(self, y): + """ + Set the data array for y. + + Parameters + ---------- + y : 1D array + + See Also + -------- + set_data + set_xdata + """ + if not np.iterable(y): + raise RuntimeError('y must be a sequence') + self._yorig = copy.copy(y) + self._invalidy = True + self.stale = True + + def set_dashes(self, seq): + """ + Set the dash sequence. + + The dash sequence is a sequence of floats of even length describing + the length of dashes and spaces in points. + + For example, (5, 2, 1, 2) describes a sequence of 5 point and 1 point + dashes separated by 2 point spaces. + + See also `~.Line2D.set_gapcolor`, which allows those spaces to be + filled with a color. + + Parameters + ---------- + seq : sequence of floats (on/off ink in points) or (None, None) + If *seq* is empty or ``(None, None)``, the linestyle will be set + to solid. + """ + if seq == (None, None) or len(seq) == 0: + self.set_linestyle('-') + else: + self.set_linestyle((0, seq)) + + def update_from(self, other): + """Copy properties from *other* to self.""" + super().update_from(other) + self._linestyle = other._linestyle + self._linewidth = other._linewidth + self._color = other._color + self._gapcolor = other._gapcolor + self._markersize = other._markersize + self._markerfacecolor = other._markerfacecolor + self._markerfacecoloralt = other._markerfacecoloralt + self._markeredgecolor = other._markeredgecolor + self._markeredgewidth = other._markeredgewidth + self._unscaled_dash_pattern = other._unscaled_dash_pattern + self._dash_pattern = other._dash_pattern + self._dashcapstyle = other._dashcapstyle + self._dashjoinstyle = other._dashjoinstyle + self._solidcapstyle = other._solidcapstyle + self._solidjoinstyle = other._solidjoinstyle + + self._linestyle = other._linestyle + self._marker = MarkerStyle(marker=other._marker) + self._drawstyle = other._drawstyle + + @_docstring.interpd + def set_dash_joinstyle(self, s): + """ + How to join segments of the line if it `~Line2D.is_dashed`. + + The default joinstyle is :rc:`lines.dash_joinstyle`. + + Parameters + ---------- + s : `.JoinStyle` or %(JoinStyle)s + """ + js = JoinStyle(s) + if self._dashjoinstyle != js: + self.stale = True + self._dashjoinstyle = js + + @_docstring.interpd + def set_solid_joinstyle(self, s): + """ + How to join segments if the line is solid (not `~Line2D.is_dashed`). + + The default joinstyle is :rc:`lines.solid_joinstyle`. + + Parameters + ---------- + s : `.JoinStyle` or %(JoinStyle)s + """ + js = JoinStyle(s) + if self._solidjoinstyle != js: + self.stale = True + self._solidjoinstyle = js + + def get_dash_joinstyle(self): + """ + Return the `.JoinStyle` for dashed lines. + + See also `~.Line2D.set_dash_joinstyle`. + """ + return self._dashjoinstyle.name + + def get_solid_joinstyle(self): + """ + Return the `.JoinStyle` for solid lines. + + See also `~.Line2D.set_solid_joinstyle`. + """ + return self._solidjoinstyle.name + + @_docstring.interpd + def set_dash_capstyle(self, s): + """ + How to draw the end caps if the line is `~Line2D.is_dashed`. + + The default capstyle is :rc:`lines.dash_capstyle`. + + Parameters + ---------- + s : `.CapStyle` or %(CapStyle)s + """ + cs = CapStyle(s) + if self._dashcapstyle != cs: + self.stale = True + self._dashcapstyle = cs + + @_docstring.interpd + def set_solid_capstyle(self, s): + """ + How to draw the end caps if the line is solid (not `~Line2D.is_dashed`) + + The default capstyle is :rc:`lines.solid_capstyle`. + + Parameters + ---------- + s : `.CapStyle` or %(CapStyle)s + """ + cs = CapStyle(s) + if self._solidcapstyle != cs: + self.stale = True + self._solidcapstyle = cs + + def get_dash_capstyle(self): + """ + Return the `.CapStyle` for dashed lines. + + See also `~.Line2D.set_dash_capstyle`. + """ + return self._dashcapstyle.name + + def get_solid_capstyle(self): + """ + Return the `.CapStyle` for solid lines. + + See also `~.Line2D.set_solid_capstyle`. + """ + return self._solidcapstyle.name + + def is_dashed(self): + """ + Return whether line has a dashed linestyle. + + A custom linestyle is assumed to be dashed, we do not inspect the + ``onoffseq`` directly. + + See also `~.Line2D.set_linestyle`. + """ + return self._linestyle in ('--', '-.', ':') + + +class AxLine(Line2D): + """ + A helper class that implements `~.Axes.axline`, by recomputing the artist + transform at draw time. + """ + + def __init__(self, xy1, xy2, slope, **kwargs): + """ + Parameters + ---------- + xy1 : (float, float) + The first set of (x, y) coordinates for the line to pass through. + xy2 : (float, float) or None + The second set of (x, y) coordinates for the line to pass through. + Both *xy2* and *slope* must be passed, but one of them must be None. + slope : float or None + The slope of the line. Both *xy2* and *slope* must be passed, but one of + them must be None. + """ + super().__init__([0, 1], [0, 1], **kwargs) + + if (xy2 is None and slope is None or + xy2 is not None and slope is not None): + raise TypeError( + "Exactly one of 'xy2' and 'slope' must be given") + + self._slope = slope + self._xy1 = xy1 + self._xy2 = xy2 + + def get_transform(self): + ax = self.axes + points_transform = self._transform - ax.transData + ax.transScale + + if self._xy2 is not None: + # two points were given + (x1, y1), (x2, y2) = \ + points_transform.transform([self._xy1, self._xy2]) + dx = x2 - x1 + dy = y2 - y1 + if dx == 0: + if dy == 0: + raise ValueError( + f"Cannot draw a line through two identical points " + f"(x={(x1, x2)}, y={(y1, y2)})") + slope = np.inf + else: + slope = dy / dx + else: + # one point and a slope were given + x1, y1 = points_transform.transform(self._xy1) + slope = self._slope + (vxlo, vylo), (vxhi, vyhi) = ax.transScale.transform(ax.viewLim) + # General case: find intersections with view limits in either + # direction, and draw between the middle two points. + if slope == 0: + start = vxlo, y1 + stop = vxhi, y1 + elif np.isinf(slope): + start = x1, vylo + stop = x1, vyhi + else: + _, start, stop, _ = sorted([ + (vxlo, y1 + (vxlo - x1) * slope), + (vxhi, y1 + (vxhi - x1) * slope), + (x1 + (vylo - y1) / slope, vylo), + (x1 + (vyhi - y1) / slope, vyhi), + ]) + return (BboxTransformTo(Bbox([start, stop])) + + ax.transLimits + ax.transAxes) + + def draw(self, renderer): + self._transformed_path = None # Force regen. + super().draw(renderer) + + def get_xy1(self): + """Return the *xy1* value of the line.""" + return self._xy1 + + def get_xy2(self): + """Return the *xy2* value of the line.""" + return self._xy2 + + def get_slope(self): + """Return the *slope* value of the line.""" + return self._slope + + def set_xy1(self, *args, **kwargs): + """ + Set the *xy1* value of the line. + + Parameters + ---------- + xy1 : tuple[float, float] + Points for the line to pass through. + """ + params = _api.select_matching_signature([ + lambda self, x, y: locals(), lambda self, xy1: locals(), + ], self, *args, **kwargs) + if "x" in params: + _api.warn_deprecated("3.10", message=( + "Passing x and y separately to AxLine.set_xy1 is deprecated since " + "%(since)s; pass them as a single tuple instead.")) + xy1 = params["x"], params["y"] + else: + xy1 = params["xy1"] + self._xy1 = xy1 + + def set_xy2(self, *args, **kwargs): + """ + Set the *xy2* value of the line. + + .. note:: + + You can only set *xy2* if the line was created using the *xy2* + parameter. If the line was created using *slope*, please use + `~.AxLine.set_slope`. + + Parameters + ---------- + xy2 : tuple[float, float] + Points for the line to pass through. + """ + if self._slope is None: + params = _api.select_matching_signature([ + lambda self, x, y: locals(), lambda self, xy2: locals(), + ], self, *args, **kwargs) + if "x" in params: + _api.warn_deprecated("3.10", message=( + "Passing x and y separately to AxLine.set_xy2 is deprecated since " + "%(since)s; pass them as a single tuple instead.")) + xy2 = params["x"], params["y"] + else: + xy2 = params["xy2"] + self._xy2 = xy2 + else: + raise ValueError("Cannot set an 'xy2' value while 'slope' is set;" + " they differ but their functionalities overlap") + + def set_slope(self, slope): + """ + Set the *slope* value of the line. + + .. note:: + + You can only set *slope* if the line was created using the *slope* + parameter. If the line was created using *xy2*, please use + `~.AxLine.set_xy2`. + + Parameters + ---------- + slope : float + The slope of the line. + """ + if self._xy2 is None: + self._slope = slope + else: + raise ValueError("Cannot set a 'slope' value while 'xy2' is set;" + " they differ but their functionalities overlap") + + +class VertexSelector: + """ + Manage the callbacks to maintain a list of selected vertices for `.Line2D`. + Derived classes should override the `process_selected` method to do + something with the picks. + + Here is an example which highlights the selected verts with red circles:: + + import numpy as np + import matplotlib.pyplot as plt + import matplotlib.lines as lines + + class HighlightSelected(lines.VertexSelector): + def __init__(self, line, fmt='ro', **kwargs): + super().__init__(line) + self.markers, = self.axes.plot([], [], fmt, **kwargs) + + def process_selected(self, ind, xs, ys): + self.markers.set_data(xs, ys) + self.canvas.draw() + + fig, ax = plt.subplots() + x, y = np.random.rand(2, 30) + line, = ax.plot(x, y, 'bs-', picker=5) + + selector = HighlightSelected(line) + plt.show() + """ + + def __init__(self, line): + """ + Parameters + ---------- + line : `~matplotlib.lines.Line2D` + The line must already have been added to an `~.axes.Axes` and must + have its picker property set. + """ + if line.axes is None: + raise RuntimeError('You must first add the line to the Axes') + if line.get_picker() is None: + raise RuntimeError('You must first set the picker property ' + 'of the line') + self.axes = line.axes + self.line = line + self.cid = self.canvas.callbacks._connect_picklable( + 'pick_event', self.onpick) + self.ind = set() + + canvas = property(lambda self: self.axes.get_figure(root=True).canvas) + + def process_selected(self, ind, xs, ys): + """ + Default "do nothing" implementation of the `process_selected` method. + + Parameters + ---------- + ind : list of int + The indices of the selected vertices. + xs, ys : array-like + The coordinates of the selected vertices. + """ + pass + + def onpick(self, event): + """When the line is picked, update the set of selected indices.""" + if event.artist is not self.line: + return + self.ind ^= set(event.ind) + ind = sorted(self.ind) + xdata, ydata = self.line.get_data() + self.process_selected(ind, xdata[ind], ydata[ind]) + + +lineStyles = Line2D._lineStyles +lineMarkers = MarkerStyle.markers +drawStyles = Line2D.drawStyles +fillStyles = MarkerStyle.fillstyles diff --git a/infer_4_30_0/lib/python3.10/site-packages/matplotlib/markers.py b/infer_4_30_0/lib/python3.10/site-packages/matplotlib/markers.py new file mode 100644 index 0000000000000000000000000000000000000000..fa5e66e73ade4926c518905c0575e6bf99dfcb24 --- /dev/null +++ b/infer_4_30_0/lib/python3.10/site-packages/matplotlib/markers.py @@ -0,0 +1,908 @@ +r""" +Functions to handle markers; used by the marker functionality of +`~matplotlib.axes.Axes.plot`, `~matplotlib.axes.Axes.scatter`, and +`~matplotlib.axes.Axes.errorbar`. + +All possible markers are defined here: + +============================== ====== ========================================= +marker symbol description +============================== ====== ========================================= +``"."`` |m00| point +``","`` |m01| pixel +``"o"`` |m02| circle +``"v"`` |m03| triangle_down +``"^"`` |m04| triangle_up +``"<"`` |m05| triangle_left +``">"`` |m06| triangle_right +``"1"`` |m07| tri_down +``"2"`` |m08| tri_up +``"3"`` |m09| tri_left +``"4"`` |m10| tri_right +``"8"`` |m11| octagon +``"s"`` |m12| square +``"p"`` |m13| pentagon +``"P"`` |m23| plus (filled) +``"*"`` |m14| star +``"h"`` |m15| hexagon1 +``"H"`` |m16| hexagon2 +``"+"`` |m17| plus +``"x"`` |m18| x +``"X"`` |m24| x (filled) +``"D"`` |m19| diamond +``"d"`` |m20| thin_diamond +``"|"`` |m21| vline +``"_"`` |m22| hline +``0`` (``TICKLEFT``) |m25| tickleft +``1`` (``TICKRIGHT``) |m26| tickright +``2`` (``TICKUP``) |m27| tickup +``3`` (``TICKDOWN``) |m28| tickdown +``4`` (``CARETLEFT``) |m29| caretleft +``5`` (``CARETRIGHT``) |m30| caretright +``6`` (``CARETUP``) |m31| caretup +``7`` (``CARETDOWN``) |m32| caretdown +``8`` (``CARETLEFTBASE``) |m33| caretleft (centered at base) +``9`` (``CARETRIGHTBASE``) |m34| caretright (centered at base) +``10`` (``CARETUPBASE``) |m35| caretup (centered at base) +``11`` (``CARETDOWNBASE``) |m36| caretdown (centered at base) +``"none"`` or ``"None"`` nothing +``" "`` or ``""`` nothing +``"$...$"`` |m37| Render the string using mathtext. + E.g ``"$f$"`` for marker showing the + letter ``f``. +``verts`` A list of (x, y) pairs used for Path + vertices. The center of the marker is + located at (0, 0) and the size is + normalized, such that the created path + is encapsulated inside the unit cell. +``path`` A `~matplotlib.path.Path` instance. +``(numsides, 0, angle)`` A regular polygon with ``numsides`` + sides, rotated by ``angle``. +``(numsides, 1, angle)`` A star-like symbol with ``numsides`` + sides, rotated by ``angle``. +``(numsides, 2, angle)`` An asterisk with ``numsides`` sides, + rotated by ``angle``. +============================== ====== ========================================= + +Note that special symbols can be defined via the +:ref:`STIX math font `, +e.g. ``"$\u266B$"``. For an overview over the STIX font symbols refer to the +`STIX font table `_. +Also see the :doc:`/gallery/text_labels_and_annotations/stix_fonts_demo`. + +Integer numbers from ``0`` to ``11`` create lines and triangles. Those are +equally accessible via capitalized variables, like ``CARETDOWNBASE``. +Hence the following are equivalent:: + + plt.plot([1, 2, 3], marker=11) + plt.plot([1, 2, 3], marker=matplotlib.markers.CARETDOWNBASE) + +Markers join and cap styles can be customized by creating a new instance of +MarkerStyle. +A MarkerStyle can also have a custom `~matplotlib.transforms.Transform` +allowing it to be arbitrarily rotated or offset. + +Examples showing the use of markers: + +* :doc:`/gallery/lines_bars_and_markers/marker_reference` +* :doc:`/gallery/lines_bars_and_markers/scatter_star_poly` +* :doc:`/gallery/lines_bars_and_markers/multivariate_marker_plot` + +.. |m00| image:: /_static/markers/m00.png +.. |m01| image:: /_static/markers/m01.png +.. |m02| image:: /_static/markers/m02.png +.. |m03| image:: /_static/markers/m03.png +.. |m04| image:: /_static/markers/m04.png +.. |m05| image:: /_static/markers/m05.png +.. |m06| image:: /_static/markers/m06.png +.. |m07| image:: /_static/markers/m07.png +.. |m08| image:: /_static/markers/m08.png +.. |m09| image:: /_static/markers/m09.png +.. |m10| image:: /_static/markers/m10.png +.. |m11| image:: /_static/markers/m11.png +.. |m12| image:: /_static/markers/m12.png +.. |m13| image:: /_static/markers/m13.png +.. |m14| image:: /_static/markers/m14.png +.. |m15| image:: /_static/markers/m15.png +.. |m16| image:: /_static/markers/m16.png +.. |m17| image:: /_static/markers/m17.png +.. |m18| image:: /_static/markers/m18.png +.. |m19| image:: /_static/markers/m19.png +.. |m20| image:: /_static/markers/m20.png +.. |m21| image:: /_static/markers/m21.png +.. |m22| image:: /_static/markers/m22.png +.. |m23| image:: /_static/markers/m23.png +.. |m24| image:: /_static/markers/m24.png +.. |m25| image:: /_static/markers/m25.png +.. |m26| image:: /_static/markers/m26.png +.. |m27| image:: /_static/markers/m27.png +.. |m28| image:: /_static/markers/m28.png +.. |m29| image:: /_static/markers/m29.png +.. |m30| image:: /_static/markers/m30.png +.. |m31| image:: /_static/markers/m31.png +.. |m32| image:: /_static/markers/m32.png +.. |m33| image:: /_static/markers/m33.png +.. |m34| image:: /_static/markers/m34.png +.. |m35| image:: /_static/markers/m35.png +.. |m36| image:: /_static/markers/m36.png +.. |m37| image:: /_static/markers/m37.png +""" +import copy + +from collections.abc import Sized + +import numpy as np + +import matplotlib as mpl +from . import _api, cbook +from .path import Path +from .transforms import IdentityTransform, Affine2D +from ._enums import JoinStyle, CapStyle + +# special-purpose marker identifiers: +(TICKLEFT, TICKRIGHT, TICKUP, TICKDOWN, + CARETLEFT, CARETRIGHT, CARETUP, CARETDOWN, + CARETLEFTBASE, CARETRIGHTBASE, CARETUPBASE, CARETDOWNBASE) = range(12) + +_empty_path = Path(np.empty((0, 2))) + + +class MarkerStyle: + """ + A class representing marker types. + + Instances are immutable. If you need to change anything, create a new + instance. + + Attributes + ---------- + markers : dict + All known markers. + filled_markers : tuple + All known filled markers. This is a subset of *markers*. + fillstyles : tuple + The supported fillstyles. + """ + + markers = { + '.': 'point', + ',': 'pixel', + 'o': 'circle', + 'v': 'triangle_down', + '^': 'triangle_up', + '<': 'triangle_left', + '>': 'triangle_right', + '1': 'tri_down', + '2': 'tri_up', + '3': 'tri_left', + '4': 'tri_right', + '8': 'octagon', + 's': 'square', + 'p': 'pentagon', + '*': 'star', + 'h': 'hexagon1', + 'H': 'hexagon2', + '+': 'plus', + 'x': 'x', + 'D': 'diamond', + 'd': 'thin_diamond', + '|': 'vline', + '_': 'hline', + 'P': 'plus_filled', + 'X': 'x_filled', + TICKLEFT: 'tickleft', + TICKRIGHT: 'tickright', + TICKUP: 'tickup', + TICKDOWN: 'tickdown', + CARETLEFT: 'caretleft', + CARETRIGHT: 'caretright', + CARETUP: 'caretup', + CARETDOWN: 'caretdown', + CARETLEFTBASE: 'caretleftbase', + CARETRIGHTBASE: 'caretrightbase', + CARETUPBASE: 'caretupbase', + CARETDOWNBASE: 'caretdownbase', + "None": 'nothing', + "none": 'nothing', + ' ': 'nothing', + '': 'nothing' + } + + # Just used for informational purposes. is_filled() + # is calculated in the _set_* functions. + filled_markers = ( + '.', 'o', 'v', '^', '<', '>', '8', 's', 'p', '*', 'h', 'H', 'D', 'd', + 'P', 'X') + + fillstyles = ('full', 'left', 'right', 'bottom', 'top', 'none') + _half_fillstyles = ('left', 'right', 'bottom', 'top') + + def __init__(self, marker, + fillstyle=None, transform=None, capstyle=None, joinstyle=None): + """ + Parameters + ---------- + marker : str, array-like, Path, MarkerStyle + - Another instance of `MarkerStyle` copies the details of that *marker*. + - For other possible marker values, see the module docstring + `matplotlib.markers`. + + fillstyle : str, default: :rc:`markers.fillstyle` + One of 'full', 'left', 'right', 'bottom', 'top', 'none'. + + transform : `~matplotlib.transforms.Transform`, optional + Transform that will be combined with the native transform of the + marker. + + capstyle : `.CapStyle` or %(CapStyle)s, optional + Cap style that will override the default cap style of the marker. + + joinstyle : `.JoinStyle` or %(JoinStyle)s, optional + Join style that will override the default join style of the marker. + """ + self._marker_function = None + self._user_transform = transform + self._user_capstyle = CapStyle(capstyle) if capstyle is not None else None + self._user_joinstyle = JoinStyle(joinstyle) if joinstyle is not None else None + self._set_fillstyle(fillstyle) + self._set_marker(marker) + + def _recache(self): + if self._marker_function is None: + return + self._path = _empty_path + self._transform = IdentityTransform() + self._alt_path = None + self._alt_transform = None + self._snap_threshold = None + self._joinstyle = JoinStyle.round + self._capstyle = self._user_capstyle or CapStyle.butt + # Initial guess: Assume the marker is filled unless the fillstyle is + # set to 'none'. The marker function will override this for unfilled + # markers. + self._filled = self._fillstyle != 'none' + self._marker_function() + + def __bool__(self): + return bool(len(self._path.vertices)) + + def is_filled(self): + return self._filled + + def get_fillstyle(self): + return self._fillstyle + + def _set_fillstyle(self, fillstyle): + """ + Set the fillstyle. + + Parameters + ---------- + fillstyle : {'full', 'left', 'right', 'bottom', 'top', 'none'} + The part of the marker surface that is colored with + markerfacecolor. + """ + if fillstyle is None: + fillstyle = mpl.rcParams['markers.fillstyle'] + _api.check_in_list(self.fillstyles, fillstyle=fillstyle) + self._fillstyle = fillstyle + + def get_joinstyle(self): + return self._joinstyle.name + + def get_capstyle(self): + return self._capstyle.name + + def get_marker(self): + return self._marker + + def _set_marker(self, marker): + """ + Set the marker. + + Parameters + ---------- + marker : str, array-like, Path, MarkerStyle + - Another instance of `MarkerStyle` copies the details of that *marker*. + - For other possible marker values see the module docstring + `matplotlib.markers`. + """ + if isinstance(marker, str) and cbook.is_math_text(marker): + self._marker_function = self._set_mathtext_path + elif isinstance(marker, (int, str)) and marker in self.markers: + self._marker_function = getattr(self, '_set_' + self.markers[marker]) + elif (isinstance(marker, np.ndarray) and marker.ndim == 2 and + marker.shape[1] == 2): + self._marker_function = self._set_vertices + elif isinstance(marker, Path): + self._marker_function = self._set_path_marker + elif (isinstance(marker, Sized) and len(marker) in (2, 3) and + marker[1] in (0, 1, 2)): + self._marker_function = self._set_tuple_marker + elif isinstance(marker, MarkerStyle): + self.__dict__ = copy.deepcopy(marker.__dict__) + else: + try: + Path(marker) + self._marker_function = self._set_vertices + except ValueError as err: + raise ValueError( + f'Unrecognized marker style {marker!r}') from err + + if not isinstance(marker, MarkerStyle): + self._marker = marker + self._recache() + + def get_path(self): + """ + Return a `.Path` for the primary part of the marker. + + For unfilled markers this is the whole marker, for filled markers, + this is the area to be drawn with *markerfacecolor*. + """ + return self._path + + def get_transform(self): + """ + Return the transform to be applied to the `.Path` from + `MarkerStyle.get_path()`. + """ + if self._user_transform is None: + return self._transform.frozen() + else: + return (self._transform + self._user_transform).frozen() + + def get_alt_path(self): + """ + Return a `.Path` for the alternate part of the marker. + + For unfilled markers, this is *None*; for filled markers, this is the + area to be drawn with *markerfacecoloralt*. + """ + return self._alt_path + + def get_alt_transform(self): + """ + Return the transform to be applied to the `.Path` from + `MarkerStyle.get_alt_path()`. + """ + if self._user_transform is None: + return self._alt_transform.frozen() + else: + return (self._alt_transform + self._user_transform).frozen() + + def get_snap_threshold(self): + return self._snap_threshold + + def get_user_transform(self): + """Return user supplied part of marker transform.""" + if self._user_transform is not None: + return self._user_transform.frozen() + + def transformed(self, transform): + """ + Return a new version of this marker with the transform applied. + + Parameters + ---------- + transform : `~matplotlib.transforms.Affine2D` + Transform will be combined with current user supplied transform. + """ + new_marker = MarkerStyle(self) + if new_marker._user_transform is not None: + new_marker._user_transform += transform + else: + new_marker._user_transform = transform + return new_marker + + def rotated(self, *, deg=None, rad=None): + """ + Return a new version of this marker rotated by specified angle. + + Parameters + ---------- + deg : float, optional + Rotation angle in degrees. + + rad : float, optional + Rotation angle in radians. + + .. note:: You must specify exactly one of deg or rad. + """ + if deg is None and rad is None: + raise ValueError('One of deg or rad is required') + if deg is not None and rad is not None: + raise ValueError('Only one of deg and rad can be supplied') + new_marker = MarkerStyle(self) + if new_marker._user_transform is None: + new_marker._user_transform = Affine2D() + + if deg is not None: + new_marker._user_transform.rotate_deg(deg) + if rad is not None: + new_marker._user_transform.rotate(rad) + + return new_marker + + def scaled(self, sx, sy=None): + """ + Return new marker scaled by specified scale factors. + + If *sy* is not given, the same scale is applied in both the *x*- and + *y*-directions. + + Parameters + ---------- + sx : float + *X*-direction scaling factor. + sy : float, optional + *Y*-direction scaling factor. + """ + if sy is None: + sy = sx + + new_marker = MarkerStyle(self) + _transform = new_marker._user_transform or Affine2D() + new_marker._user_transform = _transform.scale(sx, sy) + return new_marker + + def _set_nothing(self): + self._filled = False + + def _set_custom_marker(self, path): + rescale = np.max(np.abs(path.vertices)) # max of x's and y's. + self._transform = Affine2D().scale(0.5 / rescale) + self._path = path + + def _set_path_marker(self): + self._set_custom_marker(self._marker) + + def _set_vertices(self): + self._set_custom_marker(Path(self._marker)) + + def _set_tuple_marker(self): + marker = self._marker + if len(marker) == 2: + numsides, rotation = marker[0], 0.0 + elif len(marker) == 3: + numsides, rotation = marker[0], marker[2] + symstyle = marker[1] + if symstyle == 0: + self._path = Path.unit_regular_polygon(numsides) + self._joinstyle = self._user_joinstyle or JoinStyle.miter + elif symstyle == 1: + self._path = Path.unit_regular_star(numsides) + self._joinstyle = self._user_joinstyle or JoinStyle.bevel + elif symstyle == 2: + self._path = Path.unit_regular_asterisk(numsides) + self._filled = False + self._joinstyle = self._user_joinstyle or JoinStyle.bevel + else: + raise ValueError(f"Unexpected tuple marker: {marker}") + self._transform = Affine2D().scale(0.5).rotate_deg(rotation) + + def _set_mathtext_path(self): + """ + Draw mathtext markers '$...$' using `.TextPath` object. + + Submitted by tcb + """ + from matplotlib.text import TextPath + + # again, the properties could be initialised just once outside + # this function + text = TextPath(xy=(0, 0), s=self.get_marker(), + usetex=mpl.rcParams['text.usetex']) + if len(text.vertices) == 0: + return + + bbox = text.get_extents() + max_dim = max(bbox.width, bbox.height) + self._transform = ( + Affine2D() + .translate(-bbox.xmin + 0.5 * -bbox.width, -bbox.ymin + 0.5 * -bbox.height) + .scale(1.0 / max_dim)) + self._path = text + self._snap = False + + def _half_fill(self): + return self.get_fillstyle() in self._half_fillstyles + + def _set_circle(self, size=1.0): + self._transform = Affine2D().scale(0.5 * size) + self._snap_threshold = np.inf + if not self._half_fill(): + self._path = Path.unit_circle() + else: + self._path = self._alt_path = Path.unit_circle_righthalf() + fs = self.get_fillstyle() + self._transform.rotate_deg( + {'right': 0, 'top': 90, 'left': 180, 'bottom': 270}[fs]) + self._alt_transform = self._transform.frozen().rotate_deg(180.) + + def _set_point(self): + self._set_circle(size=0.5) + + def _set_pixel(self): + self._path = Path.unit_rectangle() + # Ideally, you'd want -0.5, -0.5 here, but then the snapping + # algorithm in the Agg backend will round this to a 2x2 + # rectangle from (-1, -1) to (1, 1). By offsetting it + # slightly, we can force it to be (0, 0) to (1, 1), which both + # makes it only be a single pixel and places it correctly + # aligned to 1-width stroking (i.e. the ticks). This hack is + # the best of a number of bad alternatives, mainly because the + # backends are not aware of what marker is actually being used + # beyond just its path data. + self._transform = Affine2D().translate(-0.49999, -0.49999) + self._snap_threshold = None + + _triangle_path = Path._create_closed([[0, 1], [-1, -1], [1, -1]]) + # Going down halfway looks to small. Golden ratio is too far. + _triangle_path_u = Path._create_closed([[0, 1], [-3/5, -1/5], [3/5, -1/5]]) + _triangle_path_d = Path._create_closed( + [[-3/5, -1/5], [3/5, -1/5], [1, -1], [-1, -1]]) + _triangle_path_l = Path._create_closed([[0, 1], [0, -1], [-1, -1]]) + _triangle_path_r = Path._create_closed([[0, 1], [0, -1], [1, -1]]) + + def _set_triangle(self, rot, skip): + self._transform = Affine2D().scale(0.5).rotate_deg(rot) + self._snap_threshold = 5.0 + + if not self._half_fill(): + self._path = self._triangle_path + else: + mpaths = [self._triangle_path_u, + self._triangle_path_l, + self._triangle_path_d, + self._triangle_path_r] + + fs = self.get_fillstyle() + if fs == 'top': + self._path = mpaths[(0 + skip) % 4] + self._alt_path = mpaths[(2 + skip) % 4] + elif fs == 'bottom': + self._path = mpaths[(2 + skip) % 4] + self._alt_path = mpaths[(0 + skip) % 4] + elif fs == 'left': + self._path = mpaths[(1 + skip) % 4] + self._alt_path = mpaths[(3 + skip) % 4] + else: + self._path = mpaths[(3 + skip) % 4] + self._alt_path = mpaths[(1 + skip) % 4] + + self._alt_transform = self._transform + + self._joinstyle = self._user_joinstyle or JoinStyle.miter + + def _set_triangle_up(self): + return self._set_triangle(0.0, 0) + + def _set_triangle_down(self): + return self._set_triangle(180.0, 2) + + def _set_triangle_left(self): + return self._set_triangle(90.0, 3) + + def _set_triangle_right(self): + return self._set_triangle(270.0, 1) + + def _set_square(self): + self._transform = Affine2D().translate(-0.5, -0.5) + self._snap_threshold = 2.0 + if not self._half_fill(): + self._path = Path.unit_rectangle() + else: + # Build a bottom filled square out of two rectangles, one filled. + self._path = Path([[0.0, 0.0], [1.0, 0.0], [1.0, 0.5], + [0.0, 0.5], [0.0, 0.0]]) + self._alt_path = Path([[0.0, 0.5], [1.0, 0.5], [1.0, 1.0], + [0.0, 1.0], [0.0, 0.5]]) + fs = self.get_fillstyle() + rotate = {'bottom': 0, 'right': 90, 'top': 180, 'left': 270}[fs] + self._transform.rotate_deg(rotate) + self._alt_transform = self._transform + + self._joinstyle = self._user_joinstyle or JoinStyle.miter + + def _set_diamond(self): + self._transform = Affine2D().translate(-0.5, -0.5).rotate_deg(45) + self._snap_threshold = 5.0 + if not self._half_fill(): + self._path = Path.unit_rectangle() + else: + self._path = Path([[0, 0], [1, 0], [1, 1], [0, 0]]) + self._alt_path = Path([[0, 0], [0, 1], [1, 1], [0, 0]]) + fs = self.get_fillstyle() + rotate = {'right': 0, 'top': 90, 'left': 180, 'bottom': 270}[fs] + self._transform.rotate_deg(rotate) + self._alt_transform = self._transform + self._joinstyle = self._user_joinstyle or JoinStyle.miter + + def _set_thin_diamond(self): + self._set_diamond() + self._transform.scale(0.6, 1.0) + + def _set_pentagon(self): + self._transform = Affine2D().scale(0.5) + self._snap_threshold = 5.0 + + polypath = Path.unit_regular_polygon(5) + + if not self._half_fill(): + self._path = polypath + else: + verts = polypath.vertices + y = (1 + np.sqrt(5)) / 4. + top = Path(verts[[0, 1, 4, 0]]) + bottom = Path(verts[[1, 2, 3, 4, 1]]) + left = Path([verts[0], verts[1], verts[2], [0, -y], verts[0]]) + right = Path([verts[0], verts[4], verts[3], [0, -y], verts[0]]) + self._path, self._alt_path = { + 'top': (top, bottom), 'bottom': (bottom, top), + 'left': (left, right), 'right': (right, left), + }[self.get_fillstyle()] + self._alt_transform = self._transform + + self._joinstyle = self._user_joinstyle or JoinStyle.miter + + def _set_star(self): + self._transform = Affine2D().scale(0.5) + self._snap_threshold = 5.0 + + polypath = Path.unit_regular_star(5, innerCircle=0.381966) + + if not self._half_fill(): + self._path = polypath + else: + verts = polypath.vertices + top = Path(np.concatenate([verts[0:4], verts[7:10], verts[0:1]])) + bottom = Path(np.concatenate([verts[3:8], verts[3:4]])) + left = Path(np.concatenate([verts[0:6], verts[0:1]])) + right = Path(np.concatenate([verts[0:1], verts[5:10], verts[0:1]])) + self._path, self._alt_path = { + 'top': (top, bottom), 'bottom': (bottom, top), + 'left': (left, right), 'right': (right, left), + }[self.get_fillstyle()] + self._alt_transform = self._transform + + self._joinstyle = self._user_joinstyle or JoinStyle.bevel + + def _set_hexagon1(self): + self._transform = Affine2D().scale(0.5) + self._snap_threshold = None + + polypath = Path.unit_regular_polygon(6) + + if not self._half_fill(): + self._path = polypath + else: + verts = polypath.vertices + # not drawing inside lines + x = np.abs(np.cos(5 * np.pi / 6.)) + top = Path(np.concatenate([[(-x, 0)], verts[[1, 0, 5]], [(x, 0)]])) + bottom = Path(np.concatenate([[(-x, 0)], verts[2:5], [(x, 0)]])) + left = Path(verts[0:4]) + right = Path(verts[[0, 5, 4, 3]]) + self._path, self._alt_path = { + 'top': (top, bottom), 'bottom': (bottom, top), + 'left': (left, right), 'right': (right, left), + }[self.get_fillstyle()] + self._alt_transform = self._transform + + self._joinstyle = self._user_joinstyle or JoinStyle.miter + + def _set_hexagon2(self): + self._transform = Affine2D().scale(0.5).rotate_deg(30) + self._snap_threshold = None + + polypath = Path.unit_regular_polygon(6) + + if not self._half_fill(): + self._path = polypath + else: + verts = polypath.vertices + # not drawing inside lines + x, y = np.sqrt(3) / 4, 3 / 4. + top = Path(verts[[1, 0, 5, 4, 1]]) + bottom = Path(verts[1:5]) + left = Path(np.concatenate([ + [(x, y)], verts[:3], [(-x, -y), (x, y)]])) + right = Path(np.concatenate([ + [(x, y)], verts[5:2:-1], [(-x, -y)]])) + self._path, self._alt_path = { + 'top': (top, bottom), 'bottom': (bottom, top), + 'left': (left, right), 'right': (right, left), + }[self.get_fillstyle()] + self._alt_transform = self._transform + + self._joinstyle = self._user_joinstyle or JoinStyle.miter + + def _set_octagon(self): + self._transform = Affine2D().scale(0.5) + self._snap_threshold = 5.0 + + polypath = Path.unit_regular_polygon(8) + + if not self._half_fill(): + self._transform.rotate_deg(22.5) + self._path = polypath + else: + x = np.sqrt(2.) / 4. + self._path = self._alt_path = Path( + [[0, -1], [0, 1], [-x, 1], [-1, x], + [-1, -x], [-x, -1], [0, -1]]) + fs = self.get_fillstyle() + self._transform.rotate_deg( + {'left': 0, 'bottom': 90, 'right': 180, 'top': 270}[fs]) + self._alt_transform = self._transform.frozen().rotate_deg(180.0) + + self._joinstyle = self._user_joinstyle or JoinStyle.miter + + _line_marker_path = Path([[0.0, -1.0], [0.0, 1.0]]) + + def _set_vline(self): + self._transform = Affine2D().scale(0.5) + self._snap_threshold = 1.0 + self._filled = False + self._path = self._line_marker_path + + def _set_hline(self): + self._set_vline() + self._transform = self._transform.rotate_deg(90) + + _tickhoriz_path = Path([[0.0, 0.0], [1.0, 0.0]]) + + def _set_tickleft(self): + self._transform = Affine2D().scale(-1.0, 1.0) + self._snap_threshold = 1.0 + self._filled = False + self._path = self._tickhoriz_path + + def _set_tickright(self): + self._transform = Affine2D().scale(1.0, 1.0) + self._snap_threshold = 1.0 + self._filled = False + self._path = self._tickhoriz_path + + _tickvert_path = Path([[-0.0, 0.0], [-0.0, 1.0]]) + + def _set_tickup(self): + self._transform = Affine2D().scale(1.0, 1.0) + self._snap_threshold = 1.0 + self._filled = False + self._path = self._tickvert_path + + def _set_tickdown(self): + self._transform = Affine2D().scale(1.0, -1.0) + self._snap_threshold = 1.0 + self._filled = False + self._path = self._tickvert_path + + _tri_path = Path([[0.0, 0.0], [0.0, -1.0], + [0.0, 0.0], [0.8, 0.5], + [0.0, 0.0], [-0.8, 0.5]], + [Path.MOVETO, Path.LINETO, + Path.MOVETO, Path.LINETO, + Path.MOVETO, Path.LINETO]) + + def _set_tri_down(self): + self._transform = Affine2D().scale(0.5) + self._snap_threshold = 5.0 + self._filled = False + self._path = self._tri_path + + def _set_tri_up(self): + self._set_tri_down() + self._transform = self._transform.rotate_deg(180) + + def _set_tri_left(self): + self._set_tri_down() + self._transform = self._transform.rotate_deg(270) + + def _set_tri_right(self): + self._set_tri_down() + self._transform = self._transform.rotate_deg(90) + + _caret_path = Path([[-1.0, 1.5], [0.0, 0.0], [1.0, 1.5]]) + + def _set_caretdown(self): + self._transform = Affine2D().scale(0.5) + self._snap_threshold = 3.0 + self._filled = False + self._path = self._caret_path + self._joinstyle = self._user_joinstyle or JoinStyle.miter + + def _set_caretup(self): + self._set_caretdown() + self._transform = self._transform.rotate_deg(180) + + def _set_caretleft(self): + self._set_caretdown() + self._transform = self._transform.rotate_deg(270) + + def _set_caretright(self): + self._set_caretdown() + self._transform = self._transform.rotate_deg(90) + + _caret_path_base = Path([[-1.0, 0.0], [0.0, -1.5], [1.0, 0]]) + + def _set_caretdownbase(self): + self._set_caretdown() + self._path = self._caret_path_base + + def _set_caretupbase(self): + self._set_caretdownbase() + self._transform = self._transform.rotate_deg(180) + + def _set_caretleftbase(self): + self._set_caretdownbase() + self._transform = self._transform.rotate_deg(270) + + def _set_caretrightbase(self): + self._set_caretdownbase() + self._transform = self._transform.rotate_deg(90) + + _plus_path = Path([[-1.0, 0.0], [1.0, 0.0], + [0.0, -1.0], [0.0, 1.0]], + [Path.MOVETO, Path.LINETO, + Path.MOVETO, Path.LINETO]) + + def _set_plus(self): + self._transform = Affine2D().scale(0.5) + self._snap_threshold = 1.0 + self._filled = False + self._path = self._plus_path + + _x_path = Path([[-1.0, -1.0], [1.0, 1.0], + [-1.0, 1.0], [1.0, -1.0]], + [Path.MOVETO, Path.LINETO, + Path.MOVETO, Path.LINETO]) + + def _set_x(self): + self._transform = Affine2D().scale(0.5) + self._snap_threshold = 3.0 + self._filled = False + self._path = self._x_path + + _plus_filled_path = Path._create_closed(np.array([ + (-1, -3), (+1, -3), (+1, -1), (+3, -1), (+3, +1), (+1, +1), + (+1, +3), (-1, +3), (-1, +1), (-3, +1), (-3, -1), (-1, -1)]) / 6) + _plus_filled_path_t = Path._create_closed(np.array([ + (+3, 0), (+3, +1), (+1, +1), (+1, +3), + (-1, +3), (-1, +1), (-3, +1), (-3, 0)]) / 6) + + def _set_plus_filled(self): + self._transform = Affine2D() + self._snap_threshold = 5.0 + self._joinstyle = self._user_joinstyle or JoinStyle.miter + if not self._half_fill(): + self._path = self._plus_filled_path + else: + # Rotate top half path to support all partitions + self._path = self._alt_path = self._plus_filled_path_t + fs = self.get_fillstyle() + self._transform.rotate_deg( + {'top': 0, 'left': 90, 'bottom': 180, 'right': 270}[fs]) + self._alt_transform = self._transform.frozen().rotate_deg(180) + + _x_filled_path = Path._create_closed(np.array([ + (-1, -2), (0, -1), (+1, -2), (+2, -1), (+1, 0), (+2, +1), + (+1, +2), (0, +1), (-1, +2), (-2, +1), (-1, 0), (-2, -1)]) / 4) + _x_filled_path_t = Path._create_closed(np.array([ + (+1, 0), (+2, +1), (+1, +2), (0, +1), + (-1, +2), (-2, +1), (-1, 0)]) / 4) + + def _set_x_filled(self): + self._transform = Affine2D() + self._snap_threshold = 5.0 + self._joinstyle = self._user_joinstyle or JoinStyle.miter + if not self._half_fill(): + self._path = self._x_filled_path + else: + # Rotate top half path to support all partitions + self._path = self._alt_path = self._x_filled_path_t + fs = self.get_fillstyle() + self._transform.rotate_deg( + {'top': 0, 'left': 90, 'bottom': 180, 'right': 270}[fs]) + self._alt_transform = self._transform.frozen().rotate_deg(180) diff --git a/infer_4_30_0/lib/python3.10/site-packages/matplotlib/markers.pyi b/infer_4_30_0/lib/python3.10/site-packages/matplotlib/markers.pyi new file mode 100644 index 0000000000000000000000000000000000000000..bd2f7dbcaf0ce4a774d743551ce8b3d5e5e1621c --- /dev/null +++ b/infer_4_30_0/lib/python3.10/site-packages/matplotlib/markers.pyi @@ -0,0 +1,51 @@ +from typing import Literal + +from .path import Path +from .transforms import Affine2D, Transform + +from numpy.typing import ArrayLike +from .typing import CapStyleType, FillStyleType, JoinStyleType + +TICKLEFT: int +TICKRIGHT: int +TICKUP: int +TICKDOWN: int +CARETLEFT: int +CARETRIGHT: int +CARETUP: int +CARETDOWN: int +CARETLEFTBASE: int +CARETRIGHTBASE: int +CARETUPBASE: int +CARETDOWNBASE: int + +class MarkerStyle: + markers: dict[str | int, str] + filled_markers: tuple[str, ...] + fillstyles: tuple[FillStyleType, ...] + + def __init__( + self, + marker: str | ArrayLike | Path | MarkerStyle, + fillstyle: FillStyleType | None = ..., + transform: Transform | None = ..., + capstyle: CapStyleType | None = ..., + joinstyle: JoinStyleType | None = ..., + ) -> None: ... + def __bool__(self) -> bool: ... + def is_filled(self) -> bool: ... + def get_fillstyle(self) -> FillStyleType: ... + def get_joinstyle(self) -> Literal["miter", "round", "bevel"]: ... + def get_capstyle(self) -> Literal["butt", "projecting", "round"]: ... + def get_marker(self) -> str | ArrayLike | Path | None: ... + def get_path(self) -> Path: ... + def get_transform(self) -> Transform: ... + def get_alt_path(self) -> Path | None: ... + def get_alt_transform(self) -> Transform: ... + def get_snap_threshold(self) -> float | None: ... + def get_user_transform(self) -> Transform | None: ... + def transformed(self, transform: Affine2D) -> MarkerStyle: ... + def rotated( + self, *, deg: float | None = ..., rad: float | None = ... + ) -> MarkerStyle: ... + def scaled(self, sx: float, sy: float | None = ...) -> MarkerStyle: ... diff --git a/infer_4_30_0/lib/python3.10/site-packages/matplotlib/mathtext.py b/infer_4_30_0/lib/python3.10/site-packages/matplotlib/mathtext.py new file mode 100644 index 0000000000000000000000000000000000000000..a88c35c15676b027c773eead1e9d0a8b13270768 --- /dev/null +++ b/infer_4_30_0/lib/python3.10/site-packages/matplotlib/mathtext.py @@ -0,0 +1,140 @@ +r""" +A module for parsing a subset of the TeX math syntax and rendering it to a +Matplotlib backend. + +For a tutorial of its usage, see :ref:`mathtext`. This +document is primarily concerned with implementation details. + +The module uses pyparsing_ to parse the TeX expression. + +.. _pyparsing: https://pypi.org/project/pyparsing/ + +The Bakoma distribution of the TeX Computer Modern fonts, and STIX +fonts are supported. There is experimental support for using +arbitrary fonts, but results may vary without proper tweaking and +metrics for those fonts. +""" + +import functools +import logging + +import matplotlib as mpl +from matplotlib import _api, _mathtext +from matplotlib.ft2font import LoadFlags +from matplotlib.font_manager import FontProperties +from ._mathtext import ( # noqa: F401, reexported API + RasterParse, VectorParse, get_unicode_index) + +_log = logging.getLogger(__name__) + + +get_unicode_index.__module__ = __name__ + +############################################################################## +# MAIN + + +class MathTextParser: + _parser = None + _font_type_mapping = { + 'cm': _mathtext.BakomaFonts, + 'dejavuserif': _mathtext.DejaVuSerifFonts, + 'dejavusans': _mathtext.DejaVuSansFonts, + 'stix': _mathtext.StixFonts, + 'stixsans': _mathtext.StixSansFonts, + 'custom': _mathtext.UnicodeFonts, + } + + def __init__(self, output): + """ + Create a MathTextParser for the given backend *output*. + + Parameters + ---------- + output : {"path", "agg"} + Whether to return a `VectorParse` ("path") or a + `RasterParse` ("agg", or its synonym "macosx"). + """ + self._output_type = _api.check_getitem( + {"path": "vector", "agg": "raster", "macosx": "raster"}, + output=output.lower()) + + def parse(self, s, dpi=72, prop=None, *, antialiased=None): + """ + Parse the given math expression *s* at the given *dpi*. If *prop* is + provided, it is a `.FontProperties` object specifying the "default" + font to use in the math expression, used for all non-math text. + + The results are cached, so multiple calls to `parse` + with the same expression should be fast. + + Depending on the *output* type, this returns either a `VectorParse` or + a `RasterParse`. + """ + # lru_cache can't decorate parse() directly because prop is + # mutable, so we key the cache using an internal copy (see + # Text._get_text_metrics_with_cache for a similar case); likewise, + # we need to check the mutable state of the text.antialiased and + # text.hinting rcParams. + prop = prop.copy() if prop is not None else None + antialiased = mpl._val_or_rc(antialiased, 'text.antialiased') + from matplotlib.backends import backend_agg + load_glyph_flags = { + "vector": LoadFlags.NO_HINTING, + "raster": backend_agg.get_hinting_flag(), + }[self._output_type] + return self._parse_cached(s, dpi, prop, antialiased, load_glyph_flags) + + @functools.lru_cache(50) + def _parse_cached(self, s, dpi, prop, antialiased, load_glyph_flags): + if prop is None: + prop = FontProperties() + fontset_class = _api.check_getitem( + self._font_type_mapping, fontset=prop.get_math_fontfamily()) + fontset = fontset_class(prop, load_glyph_flags) + fontsize = prop.get_size_in_points() + + if self._parser is None: # Cache the parser globally. + self.__class__._parser = _mathtext.Parser() + + box = self._parser.parse(s, fontset, fontsize, dpi) + output = _mathtext.ship(box) + if self._output_type == "vector": + return output.to_vector() + elif self._output_type == "raster": + return output.to_raster(antialiased=antialiased) + + +def math_to_image(s, filename_or_obj, prop=None, dpi=None, format=None, + *, color=None): + """ + Given a math expression, renders it in a closely-clipped bounding + box to an image file. + + Parameters + ---------- + s : str + A math expression. The math portion must be enclosed in dollar signs. + filename_or_obj : str or path-like or file-like + Where to write the image data. + prop : `.FontProperties`, optional + The size and style of the text. + dpi : float, optional + The output dpi. If not set, the dpi is determined as for + `.Figure.savefig`. + format : str, optional + The output format, e.g., 'svg', 'pdf', 'ps' or 'png'. If not set, the + format is determined as for `.Figure.savefig`. + color : str, optional + Foreground color, defaults to :rc:`text.color`. + """ + from matplotlib import figure + + parser = MathTextParser('path') + width, height, depth, _, _ = parser.parse(s, dpi=72, prop=prop) + + fig = figure.Figure(figsize=(width / 72.0, height / 72.0)) + fig.text(0, depth/height, s, fontproperties=prop, color=color) + fig.savefig(filename_or_obj, dpi=dpi, format=format) + + return depth diff --git a/infer_4_30_0/lib/python3.10/site-packages/matplotlib/mathtext.pyi b/infer_4_30_0/lib/python3.10/site-packages/matplotlib/mathtext.pyi new file mode 100644 index 0000000000000000000000000000000000000000..607501a275c67941e2a67883dc9c99a887ac0581 --- /dev/null +++ b/infer_4_30_0/lib/python3.10/site-packages/matplotlib/mathtext.pyi @@ -0,0 +1,33 @@ +import os +from typing import Generic, IO, Literal, TypeVar, overload + +from matplotlib.font_manager import FontProperties +from matplotlib.typing import ColorType + +# Re-exported API from _mathtext. +from ._mathtext import ( + RasterParse as RasterParse, + VectorParse as VectorParse, + get_unicode_index as get_unicode_index, +) + +_ParseType = TypeVar("_ParseType", RasterParse, VectorParse) + +class MathTextParser(Generic[_ParseType]): + @overload + def __init__(self: MathTextParser[VectorParse], output: Literal["path"]) -> None: ... + @overload + def __init__(self: MathTextParser[RasterParse], output: Literal["agg", "raster", "macosx"]) -> None: ... + def parse( + self, s: str, dpi: float = ..., prop: FontProperties | None = ..., *, antialiased: bool | None = ... + ) -> _ParseType: ... + +def math_to_image( + s: str, + filename_or_obj: str | os.PathLike | IO, + prop: FontProperties | None = ..., + dpi: float | None = ..., + format: str | None = ..., + *, + color: ColorType | None = ... +) -> float: ... diff --git a/infer_4_30_0/lib/python3.10/site-packages/matplotlib/offsetbox.py b/infer_4_30_0/lib/python3.10/site-packages/matplotlib/offsetbox.py new file mode 100644 index 0000000000000000000000000000000000000000..8dd5f4ec23c15e96ede7362c312e369daef14144 --- /dev/null +++ b/infer_4_30_0/lib/python3.10/site-packages/matplotlib/offsetbox.py @@ -0,0 +1,1607 @@ +r""" +Container classes for `.Artist`\s. + +`OffsetBox` + The base of all container artists defined in this module. + +`AnchoredOffsetbox`, `AnchoredText` + Anchor and align an arbitrary `.Artist` or a text relative to the parent + axes or a specific anchor point. + +`DrawingArea` + A container with fixed width and height. Children have a fixed position + inside the container and may be clipped. + +`HPacker`, `VPacker` + Containers for layouting their children vertically or horizontally. + +`PaddedBox` + A container to add a padding around an `.Artist`. + +`TextArea` + Contains a single `.Text` instance. +""" + +import functools + +import numpy as np + +import matplotlib as mpl +from matplotlib import _api, _docstring +import matplotlib.artist as martist +import matplotlib.path as mpath +import matplotlib.text as mtext +import matplotlib.transforms as mtransforms +from matplotlib.font_manager import FontProperties +from matplotlib.image import BboxImage +from matplotlib.patches import ( + FancyBboxPatch, FancyArrowPatch, bbox_artist as mbbox_artist) +from matplotlib.transforms import Bbox, BboxBase, TransformedBbox + + +DEBUG = False + + +def _compat_get_offset(meth): + """ + Decorator for the get_offset method of OffsetBox and subclasses, that + allows supporting both the new signature (self, bbox, renderer) and the old + signature (self, width, height, xdescent, ydescent, renderer). + """ + sigs = [lambda self, width, height, xdescent, ydescent, renderer: locals(), + lambda self, bbox, renderer: locals()] + + @functools.wraps(meth) + def get_offset(self, *args, **kwargs): + params = _api.select_matching_signature(sigs, self, *args, **kwargs) + bbox = (params["bbox"] if "bbox" in params else + Bbox.from_bounds(-params["xdescent"], -params["ydescent"], + params["width"], params["height"])) + return meth(params["self"], bbox, params["renderer"]) + return get_offset + + +# for debugging use +def _bbox_artist(*args, **kwargs): + if DEBUG: + mbbox_artist(*args, **kwargs) + + +def _get_packed_offsets(widths, total, sep, mode="fixed"): + r""" + Pack boxes specified by their *widths*. + + For simplicity of the description, the terminology used here assumes a + horizontal layout, but the function works equally for a vertical layout. + + There are three packing *mode*\s: + + - 'fixed': The elements are packed tight to the left with a spacing of + *sep* in between. If *total* is *None* the returned total will be the + right edge of the last box. A non-*None* total will be passed unchecked + to the output. In particular this means that right edge of the last + box may be further to the right than the returned total. + + - 'expand': Distribute the boxes with equal spacing so that the left edge + of the first box is at 0, and the right edge of the last box is at + *total*. The parameter *sep* is ignored in this mode. A total of *None* + is accepted and considered equal to 1. The total is returned unchanged + (except for the conversion *None* to 1). If the total is smaller than + the sum of the widths, the laid out boxes will overlap. + + - 'equal': If *total* is given, the total space is divided in N equal + ranges and each box is left-aligned within its subspace. + Otherwise (*total* is *None*), *sep* must be provided and each box is + left-aligned in its subspace of width ``(max(widths) + sep)``. The + total width is then calculated to be ``N * (max(widths) + sep)``. + + Parameters + ---------- + widths : list of float + Widths of boxes to be packed. + total : float or None + Intended total length. *None* if not used. + sep : float or None + Spacing between boxes. + mode : {'fixed', 'expand', 'equal'} + The packing mode. + + Returns + ------- + total : float + The total width needed to accommodate the laid out boxes. + offsets : array of float + The left offsets of the boxes. + """ + _api.check_in_list(["fixed", "expand", "equal"], mode=mode) + + if mode == "fixed": + offsets_ = np.cumsum([0] + [w + sep for w in widths]) + offsets = offsets_[:-1] + if total is None: + total = offsets_[-1] - sep + return total, offsets + + elif mode == "expand": + # This is a bit of a hack to avoid a TypeError when *total* + # is None and used in conjugation with tight layout. + if total is None: + total = 1 + if len(widths) > 1: + sep = (total - sum(widths)) / (len(widths) - 1) + else: + sep = 0 + offsets_ = np.cumsum([0] + [w + sep for w in widths]) + offsets = offsets_[:-1] + return total, offsets + + elif mode == "equal": + maxh = max(widths) + if total is None: + if sep is None: + raise ValueError("total and sep cannot both be None when " + "using layout mode 'equal'") + total = (maxh + sep) * len(widths) + else: + sep = total / len(widths) - maxh + offsets = (maxh + sep) * np.arange(len(widths)) + return total, offsets + + +def _get_aligned_offsets(yspans, height, align="baseline"): + """ + Align boxes each specified by their ``(y0, y1)`` spans. + + For simplicity of the description, the terminology used here assumes a + horizontal layout (i.e., vertical alignment), but the function works + equally for a vertical layout. + + Parameters + ---------- + yspans + List of (y0, y1) spans of boxes to be aligned. + height : float or None + Intended total height. If None, the maximum of the heights + (``y1 - y0``) in *yspans* is used. + align : {'baseline', 'left', 'top', 'right', 'bottom', 'center'} + The alignment anchor of the boxes. + + Returns + ------- + (y0, y1) + y range spanned by the packing. If a *height* was originally passed + in, then for all alignments other than "baseline", a span of ``(0, + height)`` is used without checking that it is actually large enough). + descent + The descent of the packing. + offsets + The bottom offsets of the boxes. + """ + + _api.check_in_list( + ["baseline", "left", "top", "right", "bottom", "center"], align=align) + if height is None: + height = max(y1 - y0 for y0, y1 in yspans) + + if align == "baseline": + yspan = (min(y0 for y0, y1 in yspans), max(y1 for y0, y1 in yspans)) + offsets = [0] * len(yspans) + elif align in ["left", "bottom"]: + yspan = (0, height) + offsets = [-y0 for y0, y1 in yspans] + elif align in ["right", "top"]: + yspan = (0, height) + offsets = [height - y1 for y0, y1 in yspans] + elif align == "center": + yspan = (0, height) + offsets = [(height - (y1 - y0)) * .5 - y0 for y0, y1 in yspans] + + return yspan, offsets + + +class OffsetBox(martist.Artist): + """ + The OffsetBox is a simple container artist. + + The child artists are meant to be drawn at a relative position to its + parent. + + Being an artist itself, all parameters are passed on to `.Artist`. + """ + def __init__(self, *args, **kwargs): + super().__init__(*args) + self._internal_update(kwargs) + # Clipping has not been implemented in the OffsetBox family, so + # disable the clip flag for consistency. It can always be turned back + # on to zero effect. + self.set_clip_on(False) + self._children = [] + self._offset = (0, 0) + + def set_figure(self, fig): + """ + Set the `.Figure` for the `.OffsetBox` and all its children. + + Parameters + ---------- + fig : `~matplotlib.figure.Figure` + """ + super().set_figure(fig) + for c in self.get_children(): + c.set_figure(fig) + + @martist.Artist.axes.setter + def axes(self, ax): + # TODO deal with this better + martist.Artist.axes.fset(self, ax) + for c in self.get_children(): + if c is not None: + c.axes = ax + + def contains(self, mouseevent): + """ + Delegate the mouse event contains-check to the children. + + As a container, the `.OffsetBox` does not respond itself to + mouseevents. + + Parameters + ---------- + mouseevent : `~matplotlib.backend_bases.MouseEvent` + + Returns + ------- + contains : bool + Whether any values are within the radius. + details : dict + An artist-specific dictionary of details of the event context, + such as which points are contained in the pick radius. See the + individual Artist subclasses for details. + + See Also + -------- + .Artist.contains + """ + if self._different_canvas(mouseevent): + return False, {} + for c in self.get_children(): + a, b = c.contains(mouseevent) + if a: + return a, b + return False, {} + + def set_offset(self, xy): + """ + Set the offset. + + Parameters + ---------- + xy : (float, float) or callable + The (x, y) coordinates of the offset in display units. These can + either be given explicitly as a tuple (x, y), or by providing a + function that converts the extent into the offset. This function + must have the signature:: + + def offset(width, height, xdescent, ydescent, renderer) \ +-> (float, float) + """ + self._offset = xy + self.stale = True + + @_compat_get_offset + def get_offset(self, bbox, renderer): + """ + Return the offset as a tuple (x, y). + + The extent parameters have to be provided to handle the case where the + offset is dynamically determined by a callable (see + `~.OffsetBox.set_offset`). + + Parameters + ---------- + bbox : `.Bbox` + renderer : `.RendererBase` subclass + """ + return ( + self._offset(bbox.width, bbox.height, -bbox.x0, -bbox.y0, renderer) + if callable(self._offset) + else self._offset) + + def set_width(self, width): + """ + Set the width of the box. + + Parameters + ---------- + width : float + """ + self.width = width + self.stale = True + + def set_height(self, height): + """ + Set the height of the box. + + Parameters + ---------- + height : float + """ + self.height = height + self.stale = True + + def get_visible_children(self): + r"""Return a list of the visible child `.Artist`\s.""" + return [c for c in self._children if c.get_visible()] + + def get_children(self): + r"""Return a list of the child `.Artist`\s.""" + return self._children + + def _get_bbox_and_child_offsets(self, renderer): + """ + Return the bbox of the offsetbox and the child offsets. + + The bbox should satisfy ``x0 <= x1 and y0 <= y1``. + + Parameters + ---------- + renderer : `.RendererBase` subclass + + Returns + ------- + bbox + list of (xoffset, yoffset) pairs + """ + raise NotImplementedError( + "get_bbox_and_offsets must be overridden in derived classes") + + def get_bbox(self, renderer): + """Return the bbox of the offsetbox, ignoring parent offsets.""" + bbox, offsets = self._get_bbox_and_child_offsets(renderer) + return bbox + + def get_window_extent(self, renderer=None): + # docstring inherited + if renderer is None: + renderer = self.get_figure(root=True)._get_renderer() + bbox = self.get_bbox(renderer) + try: # Some subclasses redefine get_offset to take no args. + px, py = self.get_offset(bbox, renderer) + except TypeError: + px, py = self.get_offset() + return bbox.translated(px, py) + + def draw(self, renderer): + """ + Update the location of children if necessary and draw them + to the given *renderer*. + """ + bbox, offsets = self._get_bbox_and_child_offsets(renderer) + px, py = self.get_offset(bbox, renderer) + for c, (ox, oy) in zip(self.get_visible_children(), offsets): + c.set_offset((px + ox, py + oy)) + c.draw(renderer) + _bbox_artist(self, renderer, fill=False, props=dict(pad=0.)) + self.stale = False + + +class PackerBase(OffsetBox): + def __init__(self, pad=0., sep=0., width=None, height=None, + align="baseline", mode="fixed", children=None): + """ + Parameters + ---------- + pad : float, default: 0.0 + The boundary padding in points. + + sep : float, default: 0.0 + The spacing between items in points. + + width, height : float, optional + Width and height of the container box in pixels, calculated if + *None*. + + align : {'top', 'bottom', 'left', 'right', 'center', 'baseline'}, \ +default: 'baseline' + Alignment of boxes. + + mode : {'fixed', 'expand', 'equal'}, default: 'fixed' + The packing mode. + + - 'fixed' packs the given `.Artist`\\s tight with *sep* spacing. + - 'expand' uses the maximal available space to distribute the + artists with equal spacing in between. + - 'equal': Each artist an equal fraction of the available space + and is left-aligned (or top-aligned) therein. + + children : list of `.Artist` + The artists to pack. + + Notes + ----- + *pad* and *sep* are in points and will be scaled with the renderer + dpi, while *width* and *height* are in pixels. + """ + super().__init__() + self.height = height + self.width = width + self.sep = sep + self.pad = pad + self.mode = mode + self.align = align + self._children = children + + +class VPacker(PackerBase): + """ + VPacker packs its children vertically, automatically adjusting their + relative positions at draw time. + + .. code-block:: none + + +---------+ + | Child 1 | + | Child 2 | + | Child 3 | + +---------+ + """ + + def _get_bbox_and_child_offsets(self, renderer): + # docstring inherited + dpicor = renderer.points_to_pixels(1.) + pad = self.pad * dpicor + sep = self.sep * dpicor + + if self.width is not None: + for c in self.get_visible_children(): + if isinstance(c, PackerBase) and c.mode == "expand": + c.set_width(self.width) + + bboxes = [c.get_bbox(renderer) for c in self.get_visible_children()] + (x0, x1), xoffsets = _get_aligned_offsets( + [bbox.intervalx for bbox in bboxes], self.width, self.align) + height, yoffsets = _get_packed_offsets( + [bbox.height for bbox in bboxes], self.height, sep, self.mode) + + yoffsets = height - (yoffsets + [bbox.y1 for bbox in bboxes]) + ydescent = yoffsets[0] + yoffsets = yoffsets - ydescent + + return ( + Bbox.from_bounds(x0, -ydescent, x1 - x0, height).padded(pad), + [*zip(xoffsets, yoffsets)]) + + +class HPacker(PackerBase): + """ + HPacker packs its children horizontally, automatically adjusting their + relative positions at draw time. + + .. code-block:: none + + +-------------------------------+ + | Child 1 Child 2 Child 3 | + +-------------------------------+ + """ + + def _get_bbox_and_child_offsets(self, renderer): + # docstring inherited + dpicor = renderer.points_to_pixels(1.) + pad = self.pad * dpicor + sep = self.sep * dpicor + + bboxes = [c.get_bbox(renderer) for c in self.get_visible_children()] + if not bboxes: + return Bbox.from_bounds(0, 0, 0, 0).padded(pad), [] + + (y0, y1), yoffsets = _get_aligned_offsets( + [bbox.intervaly for bbox in bboxes], self.height, self.align) + width, xoffsets = _get_packed_offsets( + [bbox.width for bbox in bboxes], self.width, sep, self.mode) + + x0 = bboxes[0].x0 + xoffsets -= ([bbox.x0 for bbox in bboxes] - x0) + + return (Bbox.from_bounds(x0, y0, width, y1 - y0).padded(pad), + [*zip(xoffsets, yoffsets)]) + + +class PaddedBox(OffsetBox): + """ + A container to add a padding around an `.Artist`. + + The `.PaddedBox` contains a `.FancyBboxPatch` that is used to visualize + it when rendering. + + .. code-block:: none + + +----------------------------+ + | | + | | + | | + | <--pad--> Artist | + | ^ | + | pad | + | v | + +----------------------------+ + + Attributes + ---------- + pad : float + The padding in points. + patch : `.FancyBboxPatch` + When *draw_frame* is True, this `.FancyBboxPatch` is made visible and + creates a border around the box. + """ + + def __init__(self, child, pad=0., *, draw_frame=False, patch_attrs=None): + """ + Parameters + ---------- + child : `~matplotlib.artist.Artist` + The contained `.Artist`. + pad : float, default: 0.0 + The padding in points. This will be scaled with the renderer dpi. + In contrast, *width* and *height* are in *pixels* and thus not + scaled. + draw_frame : bool + Whether to draw the contained `.FancyBboxPatch`. + patch_attrs : dict or None + Additional parameters passed to the contained `.FancyBboxPatch`. + """ + super().__init__() + self.pad = pad + self._children = [child] + self.patch = FancyBboxPatch( + xy=(0.0, 0.0), width=1., height=1., + facecolor='w', edgecolor='k', + mutation_scale=1, # self.prop.get_size_in_points(), + snap=True, + visible=draw_frame, + boxstyle="square,pad=0", + ) + if patch_attrs is not None: + self.patch.update(patch_attrs) + + def _get_bbox_and_child_offsets(self, renderer): + # docstring inherited. + pad = self.pad * renderer.points_to_pixels(1.) + return (self._children[0].get_bbox(renderer).padded(pad), [(0, 0)]) + + def draw(self, renderer): + # docstring inherited + bbox, offsets = self._get_bbox_and_child_offsets(renderer) + px, py = self.get_offset(bbox, renderer) + for c, (ox, oy) in zip(self.get_visible_children(), offsets): + c.set_offset((px + ox, py + oy)) + + self.draw_frame(renderer) + + for c in self.get_visible_children(): + c.draw(renderer) + + self.stale = False + + def update_frame(self, bbox, fontsize=None): + self.patch.set_bounds(bbox.bounds) + if fontsize: + self.patch.set_mutation_scale(fontsize) + self.stale = True + + def draw_frame(self, renderer): + # update the location and size of the legend + self.update_frame(self.get_window_extent(renderer)) + self.patch.draw(renderer) + + +class DrawingArea(OffsetBox): + """ + The DrawingArea can contain any Artist as a child. The DrawingArea + has a fixed width and height. The position of children relative to + the parent is fixed. The children can be clipped at the + boundaries of the parent. + """ + + def __init__(self, width, height, xdescent=0., ydescent=0., clip=False): + """ + Parameters + ---------- + width, height : float + Width and height of the container box. + xdescent, ydescent : float + Descent of the box in x- and y-direction. + clip : bool + Whether to clip the children to the box. + """ + super().__init__() + self.width = width + self.height = height + self.xdescent = xdescent + self.ydescent = ydescent + self._clip_children = clip + self.offset_transform = mtransforms.Affine2D() + self.dpi_transform = mtransforms.Affine2D() + + @property + def clip_children(self): + """ + If the children of this DrawingArea should be clipped + by DrawingArea bounding box. + """ + return self._clip_children + + @clip_children.setter + def clip_children(self, val): + self._clip_children = bool(val) + self.stale = True + + def get_transform(self): + """ + Return the `~matplotlib.transforms.Transform` applied to the children. + """ + return self.dpi_transform + self.offset_transform + + def set_transform(self, t): + """ + set_transform is ignored. + """ + + def set_offset(self, xy): + """ + Set the offset of the container. + + Parameters + ---------- + xy : (float, float) + The (x, y) coordinates of the offset in display units. + """ + self._offset = xy + self.offset_transform.clear() + self.offset_transform.translate(xy[0], xy[1]) + self.stale = True + + def get_offset(self): + """Return offset of the container.""" + return self._offset + + def get_bbox(self, renderer): + # docstring inherited + dpi_cor = renderer.points_to_pixels(1.) + return Bbox.from_bounds( + -self.xdescent * dpi_cor, -self.ydescent * dpi_cor, + self.width * dpi_cor, self.height * dpi_cor) + + def add_artist(self, a): + """Add an `.Artist` to the container box.""" + self._children.append(a) + if not a.is_transform_set(): + a.set_transform(self.get_transform()) + if self.axes is not None: + a.axes = self.axes + fig = self.get_figure(root=False) + if fig is not None: + a.set_figure(fig) + + def draw(self, renderer): + # docstring inherited + + dpi_cor = renderer.points_to_pixels(1.) + self.dpi_transform.clear() + self.dpi_transform.scale(dpi_cor) + + # At this point the DrawingArea has a transform + # to the display space so the path created is + # good for clipping children + tpath = mtransforms.TransformedPath( + mpath.Path([[0, 0], [0, self.height], + [self.width, self.height], + [self.width, 0]]), + self.get_transform()) + for c in self._children: + if self._clip_children and not (c.clipbox or c._clippath): + c.set_clip_path(tpath) + c.draw(renderer) + + _bbox_artist(self, renderer, fill=False, props=dict(pad=0.)) + self.stale = False + + +class TextArea(OffsetBox): + """ + The TextArea is a container artist for a single Text instance. + + The text is placed at (0, 0) with baseline+left alignment, by default. The + width and height of the TextArea instance is the width and height of its + child text. + """ + + def __init__(self, s, + *, + textprops=None, + multilinebaseline=False, + ): + """ + Parameters + ---------- + s : str + The text to be displayed. + textprops : dict, default: {} + Dictionary of keyword parameters to be passed to the `.Text` + instance in the TextArea. + multilinebaseline : bool, default: False + Whether the baseline for multiline text is adjusted so that it + is (approximately) center-aligned with single-line text. + """ + if textprops is None: + textprops = {} + self._text = mtext.Text(0, 0, s, **textprops) + super().__init__() + self._children = [self._text] + self.offset_transform = mtransforms.Affine2D() + self._baseline_transform = mtransforms.Affine2D() + self._text.set_transform(self.offset_transform + + self._baseline_transform) + self._multilinebaseline = multilinebaseline + + def set_text(self, s): + """Set the text of this area as a string.""" + self._text.set_text(s) + self.stale = True + + def get_text(self): + """Return the string representation of this area's text.""" + return self._text.get_text() + + def set_multilinebaseline(self, t): + """ + Set multilinebaseline. + + If True, the baseline for multiline text is adjusted so that it is + (approximately) center-aligned with single-line text. This is used + e.g. by the legend implementation so that single-line labels are + baseline-aligned, but multiline labels are "center"-aligned with them. + """ + self._multilinebaseline = t + self.stale = True + + def get_multilinebaseline(self): + """ + Get multilinebaseline. + """ + return self._multilinebaseline + + def set_transform(self, t): + """ + set_transform is ignored. + """ + + def set_offset(self, xy): + """ + Set the offset of the container. + + Parameters + ---------- + xy : (float, float) + The (x, y) coordinates of the offset in display units. + """ + self._offset = xy + self.offset_transform.clear() + self.offset_transform.translate(xy[0], xy[1]) + self.stale = True + + def get_offset(self): + """Return offset of the container.""" + return self._offset + + def get_bbox(self, renderer): + _, h_, d_ = renderer.get_text_width_height_descent( + "lp", self._text._fontproperties, + ismath="TeX" if self._text.get_usetex() else False) + + bbox, info, yd = self._text._get_layout(renderer) + w, h = bbox.size + + self._baseline_transform.clear() + + if len(info) > 1 and self._multilinebaseline: + yd_new = 0.5 * h - 0.5 * (h_ - d_) + self._baseline_transform.translate(0, yd - yd_new) + yd = yd_new + else: # single line + h_d = max(h_ - d_, h - yd) + h = h_d + yd + + ha = self._text.get_horizontalalignment() + x0 = {"left": 0, "center": -w / 2, "right": -w}[ha] + + return Bbox.from_bounds(x0, -yd, w, h) + + def draw(self, renderer): + # docstring inherited + self._text.draw(renderer) + _bbox_artist(self, renderer, fill=False, props=dict(pad=0.)) + self.stale = False + + +class AuxTransformBox(OffsetBox): + """ + Offset Box with the aux_transform. Its children will be + transformed with the aux_transform first then will be + offsetted. The absolute coordinate of the aux_transform is meaning + as it will be automatically adjust so that the left-lower corner + of the bounding box of children will be set to (0, 0) before the + offset transform. + + It is similar to drawing area, except that the extent of the box + is not predetermined but calculated from the window extent of its + children. Furthermore, the extent of the children will be + calculated in the transformed coordinate. + """ + def __init__(self, aux_transform): + self.aux_transform = aux_transform + super().__init__() + self.offset_transform = mtransforms.Affine2D() + # ref_offset_transform makes offset_transform always relative to the + # lower-left corner of the bbox of its children. + self.ref_offset_transform = mtransforms.Affine2D() + + def add_artist(self, a): + """Add an `.Artist` to the container box.""" + self._children.append(a) + a.set_transform(self.get_transform()) + self.stale = True + + def get_transform(self): + """ + Return the :class:`~matplotlib.transforms.Transform` applied + to the children + """ + return (self.aux_transform + + self.ref_offset_transform + + self.offset_transform) + + def set_transform(self, t): + """ + set_transform is ignored. + """ + + def set_offset(self, xy): + """ + Set the offset of the container. + + Parameters + ---------- + xy : (float, float) + The (x, y) coordinates of the offset in display units. + """ + self._offset = xy + self.offset_transform.clear() + self.offset_transform.translate(xy[0], xy[1]) + self.stale = True + + def get_offset(self): + """Return offset of the container.""" + return self._offset + + def get_bbox(self, renderer): + # clear the offset transforms + _off = self.offset_transform.get_matrix() # to be restored later + self.ref_offset_transform.clear() + self.offset_transform.clear() + # calculate the extent + bboxes = [c.get_window_extent(renderer) for c in self._children] + ub = Bbox.union(bboxes) + # adjust ref_offset_transform + self.ref_offset_transform.translate(-ub.x0, -ub.y0) + # restore offset transform + self.offset_transform.set_matrix(_off) + return Bbox.from_bounds(0, 0, ub.width, ub.height) + + def draw(self, renderer): + # docstring inherited + for c in self._children: + c.draw(renderer) + _bbox_artist(self, renderer, fill=False, props=dict(pad=0.)) + self.stale = False + + +class AnchoredOffsetbox(OffsetBox): + """ + An offset box placed according to location *loc*. + + AnchoredOffsetbox has a single child. When multiple children are needed, + use an extra OffsetBox to enclose them. By default, the offset box is + anchored against its parent Axes. You may explicitly specify the + *bbox_to_anchor*. + """ + zorder = 5 # zorder of the legend + + # Location codes + codes = {'upper right': 1, + 'upper left': 2, + 'lower left': 3, + 'lower right': 4, + 'right': 5, + 'center left': 6, + 'center right': 7, + 'lower center': 8, + 'upper center': 9, + 'center': 10, + } + + def __init__(self, loc, *, + pad=0.4, borderpad=0.5, + child=None, prop=None, frameon=True, + bbox_to_anchor=None, + bbox_transform=None, + **kwargs): + """ + Parameters + ---------- + loc : str + The box location. Valid locations are + 'upper left', 'upper center', 'upper right', + 'center left', 'center', 'center right', + 'lower left', 'lower center', 'lower right'. + For backward compatibility, numeric values are accepted as well. + See the parameter *loc* of `.Legend` for details. + pad : float, default: 0.4 + Padding around the child as fraction of the fontsize. + borderpad : float, default: 0.5 + Padding between the offsetbox frame and the *bbox_to_anchor*. + child : `.OffsetBox` + The box that will be anchored. + prop : `.FontProperties` + This is only used as a reference for paddings. If not given, + :rc:`legend.fontsize` is used. + frameon : bool + Whether to draw a frame around the box. + bbox_to_anchor : `.BboxBase`, 2-tuple, or 4-tuple of floats + Box that is used to position the legend in conjunction with *loc*. + bbox_transform : None or :class:`matplotlib.transforms.Transform` + The transform for the bounding box (*bbox_to_anchor*). + **kwargs + All other parameters are passed on to `.OffsetBox`. + + Notes + ----- + See `.Legend` for a detailed description of the anchoring mechanism. + """ + super().__init__(**kwargs) + + self.set_bbox_to_anchor(bbox_to_anchor, bbox_transform) + self.set_child(child) + + if isinstance(loc, str): + loc = _api.check_getitem(self.codes, loc=loc) + + self.loc = loc + self.borderpad = borderpad + self.pad = pad + + if prop is None: + self.prop = FontProperties(size=mpl.rcParams["legend.fontsize"]) + else: + self.prop = FontProperties._from_any(prop) + if isinstance(prop, dict) and "size" not in prop: + self.prop.set_size(mpl.rcParams["legend.fontsize"]) + + self.patch = FancyBboxPatch( + xy=(0.0, 0.0), width=1., height=1., + facecolor='w', edgecolor='k', + mutation_scale=self.prop.get_size_in_points(), + snap=True, + visible=frameon, + boxstyle="square,pad=0", + ) + + def set_child(self, child): + """Set the child to be anchored.""" + self._child = child + if child is not None: + child.axes = self.axes + self.stale = True + + def get_child(self): + """Return the child.""" + return self._child + + def get_children(self): + """Return the list of children.""" + return [self._child] + + def get_bbox(self, renderer): + # docstring inherited + fontsize = renderer.points_to_pixels(self.prop.get_size_in_points()) + pad = self.pad * fontsize + return self.get_child().get_bbox(renderer).padded(pad) + + def get_bbox_to_anchor(self): + """Return the bbox that the box is anchored to.""" + if self._bbox_to_anchor is None: + return self.axes.bbox + else: + transform = self._bbox_to_anchor_transform + if transform is None: + return self._bbox_to_anchor + else: + return TransformedBbox(self._bbox_to_anchor, transform) + + def set_bbox_to_anchor(self, bbox, transform=None): + """ + Set the bbox that the box is anchored to. + + *bbox* can be a Bbox instance, a list of [left, bottom, width, + height], or a list of [left, bottom] where the width and + height will be assumed to be zero. The bbox will be + transformed to display coordinate by the given transform. + """ + if bbox is None or isinstance(bbox, BboxBase): + self._bbox_to_anchor = bbox + else: + try: + l = len(bbox) + except TypeError as err: + raise ValueError(f"Invalid bbox: {bbox}") from err + + if l == 2: + bbox = [bbox[0], bbox[1], 0, 0] + + self._bbox_to_anchor = Bbox.from_bounds(*bbox) + + self._bbox_to_anchor_transform = transform + self.stale = True + + @_compat_get_offset + def get_offset(self, bbox, renderer): + # docstring inherited + pad = (self.borderpad + * renderer.points_to_pixels(self.prop.get_size_in_points())) + bbox_to_anchor = self.get_bbox_to_anchor() + x0, y0 = _get_anchored_bbox( + self.loc, Bbox.from_bounds(0, 0, bbox.width, bbox.height), + bbox_to_anchor, pad) + return x0 - bbox.x0, y0 - bbox.y0 + + def update_frame(self, bbox, fontsize=None): + self.patch.set_bounds(bbox.bounds) + if fontsize: + self.patch.set_mutation_scale(fontsize) + + def draw(self, renderer): + # docstring inherited + if not self.get_visible(): + return + + # update the location and size of the legend + bbox = self.get_window_extent(renderer) + fontsize = renderer.points_to_pixels(self.prop.get_size_in_points()) + self.update_frame(bbox, fontsize) + self.patch.draw(renderer) + + px, py = self.get_offset(self.get_bbox(renderer), renderer) + self.get_child().set_offset((px, py)) + self.get_child().draw(renderer) + self.stale = False + + +def _get_anchored_bbox(loc, bbox, parentbbox, borderpad): + """ + Return the (x, y) position of the *bbox* anchored at the *parentbbox* with + the *loc* code with the *borderpad*. + """ + # This is only called internally and *loc* should already have been + # validated. If 0 (None), we just let ``bbox.anchored`` raise. + c = [None, "NE", "NW", "SW", "SE", "E", "W", "E", "S", "N", "C"][loc] + container = parentbbox.padded(-borderpad) + return bbox.anchored(c, container=container).p0 + + +class AnchoredText(AnchoredOffsetbox): + """ + AnchoredOffsetbox with Text. + """ + + def __init__(self, s, loc, *, pad=0.4, borderpad=0.5, prop=None, **kwargs): + """ + Parameters + ---------- + s : str + Text. + + loc : str + Location code. See `AnchoredOffsetbox`. + + pad : float, default: 0.4 + Padding around the text as fraction of the fontsize. + + borderpad : float, default: 0.5 + Spacing between the offsetbox frame and the *bbox_to_anchor*. + + prop : dict, optional + Dictionary of keyword parameters to be passed to the + `~matplotlib.text.Text` instance contained inside AnchoredText. + + **kwargs + All other parameters are passed to `AnchoredOffsetbox`. + """ + + if prop is None: + prop = {} + badkwargs = {'va', 'verticalalignment'} + if badkwargs & set(prop): + raise ValueError( + 'Mixing verticalalignment with AnchoredText is not supported.') + + self.txt = TextArea(s, textprops=prop) + fp = self.txt._text.get_fontproperties() + super().__init__( + loc, pad=pad, borderpad=borderpad, child=self.txt, prop=fp, + **kwargs) + + +class OffsetImage(OffsetBox): + + def __init__(self, arr, *, + zoom=1, + cmap=None, + norm=None, + interpolation=None, + origin=None, + filternorm=True, + filterrad=4.0, + resample=False, + dpi_cor=True, + **kwargs + ): + + super().__init__() + self._dpi_cor = dpi_cor + + self.image = BboxImage(bbox=self.get_window_extent, + cmap=cmap, + norm=norm, + interpolation=interpolation, + origin=origin, + filternorm=filternorm, + filterrad=filterrad, + resample=resample, + **kwargs + ) + + self._children = [self.image] + + self.set_zoom(zoom) + self.set_data(arr) + + def set_data(self, arr): + self._data = np.asarray(arr) + self.image.set_data(self._data) + self.stale = True + + def get_data(self): + return self._data + + def set_zoom(self, zoom): + self._zoom = zoom + self.stale = True + + def get_zoom(self): + return self._zoom + + def get_offset(self): + """Return offset of the container.""" + return self._offset + + def get_children(self): + return [self.image] + + def get_bbox(self, renderer): + dpi_cor = renderer.points_to_pixels(1.) if self._dpi_cor else 1. + zoom = self.get_zoom() + data = self.get_data() + ny, nx = data.shape[:2] + w, h = dpi_cor * nx * zoom, dpi_cor * ny * zoom + return Bbox.from_bounds(0, 0, w, h) + + def draw(self, renderer): + # docstring inherited + self.image.draw(renderer) + # bbox_artist(self, renderer, fill=False, props=dict(pad=0.)) + self.stale = False + + +class AnnotationBbox(martist.Artist, mtext._AnnotationBase): + """ + Container for an `OffsetBox` referring to a specific position *xy*. + + Optionally an arrow pointing from the offsetbox to *xy* can be drawn. + + This is like `.Annotation`, but with `OffsetBox` instead of `.Text`. + """ + + zorder = 3 + + def __str__(self): + return f"AnnotationBbox({self.xy[0]:g},{self.xy[1]:g})" + + @_docstring.interpd + def __init__(self, offsetbox, xy, xybox=None, xycoords='data', boxcoords=None, *, + frameon=True, pad=0.4, # FancyBboxPatch boxstyle. + annotation_clip=None, + box_alignment=(0.5, 0.5), + bboxprops=None, + arrowprops=None, + fontsize=None, + **kwargs): + """ + Parameters + ---------- + offsetbox : `OffsetBox` + + xy : (float, float) + The point *(x, y)* to annotate. The coordinate system is determined + by *xycoords*. + + xybox : (float, float), default: *xy* + The position *(x, y)* to place the text at. The coordinate system + is determined by *boxcoords*. + + xycoords : single or two-tuple of str or `.Artist` or `.Transform` or \ +callable, default: 'data' + The coordinate system that *xy* is given in. See the parameter + *xycoords* in `.Annotation` for a detailed description. + + boxcoords : single or two-tuple of str or `.Artist` or `.Transform` \ +or callable, default: value of *xycoords* + The coordinate system that *xybox* is given in. See the parameter + *textcoords* in `.Annotation` for a detailed description. + + frameon : bool, default: True + By default, the text is surrounded by a white `.FancyBboxPatch` + (accessible as the ``patch`` attribute of the `.AnnotationBbox`). + If *frameon* is set to False, this patch is made invisible. + + annotation_clip: bool or None, default: None + Whether to clip (i.e. not draw) the annotation when the annotation + point *xy* is outside the Axes area. + + - If *True*, the annotation will be clipped when *xy* is outside + the Axes. + - If *False*, the annotation will always be drawn. + - If *None*, the annotation will be clipped when *xy* is outside + the Axes and *xycoords* is 'data'. + + pad : float, default: 0.4 + Padding around the offsetbox. + + box_alignment : (float, float) + A tuple of two floats for a vertical and horizontal alignment of + the offset box w.r.t. the *boxcoords*. + The lower-left corner is (0, 0) and upper-right corner is (1, 1). + + bboxprops : dict, optional + A dictionary of properties to set for the annotation bounding box, + for example *boxstyle* and *alpha*. See `.FancyBboxPatch` for + details. + + arrowprops: dict, optional + Arrow properties, see `.Annotation` for description. + + fontsize: float or str, optional + Translated to points and passed as *mutation_scale* into + `.FancyBboxPatch` to scale attributes of the box style (e.g. pad + or rounding_size). The name is chosen in analogy to `.Text` where + *fontsize* defines the mutation scale as well. If not given, + :rc:`legend.fontsize` is used. See `.Text.set_fontsize` for valid + values. + + **kwargs + Other `AnnotationBbox` properties. See `.AnnotationBbox.set` for + a list. + """ + + martist.Artist.__init__(self) + mtext._AnnotationBase.__init__( + self, xy, xycoords=xycoords, annotation_clip=annotation_clip) + + self.offsetbox = offsetbox + self.arrowprops = arrowprops.copy() if arrowprops is not None else None + self.set_fontsize(fontsize) + self.xybox = xybox if xybox is not None else xy + self.boxcoords = boxcoords if boxcoords is not None else xycoords + self._box_alignment = box_alignment + + if arrowprops is not None: + self._arrow_relpos = self.arrowprops.pop("relpos", (0.5, 0.5)) + self.arrow_patch = FancyArrowPatch((0, 0), (1, 1), + **self.arrowprops) + else: + self._arrow_relpos = None + self.arrow_patch = None + + self.patch = FancyBboxPatch( # frame + xy=(0.0, 0.0), width=1., height=1., + facecolor='w', edgecolor='k', + mutation_scale=self.prop.get_size_in_points(), + snap=True, + visible=frameon, + ) + self.patch.set_boxstyle("square", pad=pad) + if bboxprops: + self.patch.set(**bboxprops) + + self._internal_update(kwargs) + + @property + def xyann(self): + return self.xybox + + @xyann.setter + def xyann(self, xyann): + self.xybox = xyann + self.stale = True + + @property + def anncoords(self): + return self.boxcoords + + @anncoords.setter + def anncoords(self, coords): + self.boxcoords = coords + self.stale = True + + def contains(self, mouseevent): + if self._different_canvas(mouseevent): + return False, {} + if not self._check_xy(None): + return False, {} + return self.offsetbox.contains(mouseevent) + # self.arrow_patch is currently not checked as this can be a line - JJ + + def get_children(self): + children = [self.offsetbox, self.patch] + if self.arrow_patch: + children.append(self.arrow_patch) + return children + + def set_figure(self, fig): + if self.arrow_patch is not None: + self.arrow_patch.set_figure(fig) + self.offsetbox.set_figure(fig) + martist.Artist.set_figure(self, fig) + + def set_fontsize(self, s=None): + """ + Set the fontsize in points. + + If *s* is not given, reset to :rc:`legend.fontsize`. + """ + if s is None: + s = mpl.rcParams["legend.fontsize"] + + self.prop = FontProperties(size=s) + self.stale = True + + def get_fontsize(self): + """Return the fontsize in points.""" + return self.prop.get_size_in_points() + + def get_window_extent(self, renderer=None): + # docstring inherited + if renderer is None: + renderer = self.get_figure(root=True)._get_renderer() + self.update_positions(renderer) + return Bbox.union([child.get_window_extent(renderer) + for child in self.get_children()]) + + def get_tightbbox(self, renderer=None): + # docstring inherited + if renderer is None: + renderer = self.get_figure(root=True)._get_renderer() + self.update_positions(renderer) + return Bbox.union([child.get_tightbbox(renderer) + for child in self.get_children()]) + + def update_positions(self, renderer): + """Update pixel positions for the annotated point, the text, and the arrow.""" + + ox0, oy0 = self._get_xy(renderer, self.xybox, self.boxcoords) + bbox = self.offsetbox.get_bbox(renderer) + fw, fh = self._box_alignment + self.offsetbox.set_offset( + (ox0 - fw*bbox.width - bbox.x0, oy0 - fh*bbox.height - bbox.y0)) + + bbox = self.offsetbox.get_window_extent(renderer) + self.patch.set_bounds(bbox.bounds) + + mutation_scale = renderer.points_to_pixels(self.get_fontsize()) + self.patch.set_mutation_scale(mutation_scale) + + if self.arrowprops: + # Use FancyArrowPatch if self.arrowprops has "arrowstyle" key. + + # Adjust the starting point of the arrow relative to the textbox. + # TODO: Rotation needs to be accounted. + arrow_begin = bbox.p0 + bbox.size * self._arrow_relpos + arrow_end = self._get_position_xy(renderer) + # The arrow (from arrow_begin to arrow_end) will be first clipped + # by patchA and patchB, then shrunk by shrinkA and shrinkB (in + # points). If patch A is not set, self.bbox_patch is used. + self.arrow_patch.set_positions(arrow_begin, arrow_end) + + if "mutation_scale" in self.arrowprops: + mutation_scale = renderer.points_to_pixels( + self.arrowprops["mutation_scale"]) + # Else, use fontsize-based mutation_scale defined above. + self.arrow_patch.set_mutation_scale(mutation_scale) + + patchA = self.arrowprops.get("patchA", self.patch) + self.arrow_patch.set_patchA(patchA) + + def draw(self, renderer): + # docstring inherited + if not self.get_visible() or not self._check_xy(renderer): + return + renderer.open_group(self.__class__.__name__, gid=self.get_gid()) + self.update_positions(renderer) + if self.arrow_patch is not None: + if (self.arrow_patch.get_figure(root=False) is None and + (fig := self.get_figure(root=False)) is not None): + self.arrow_patch.set_figure(fig) + self.arrow_patch.draw(renderer) + self.patch.draw(renderer) + self.offsetbox.draw(renderer) + renderer.close_group(self.__class__.__name__) + self.stale = False + + +class DraggableBase: + """ + Helper base class for a draggable artist (legend, offsetbox). + + Derived classes must override the following methods:: + + def save_offset(self): + ''' + Called when the object is picked for dragging; should save the + reference position of the artist. + ''' + + def update_offset(self, dx, dy): + ''' + Called during the dragging; (*dx*, *dy*) is the pixel offset from + the point where the mouse drag started. + ''' + + Optionally, you may override the following method:: + + def finalize_offset(self): + '''Called when the mouse is released.''' + + In the current implementation of `.DraggableLegend` and + `DraggableAnnotation`, `update_offset` places the artists in display + coordinates, and `finalize_offset` recalculates their position in axes + coordinate and set a relevant attribute. + """ + + def __init__(self, ref_artist, use_blit=False): + self.ref_artist = ref_artist + if not ref_artist.pickable(): + ref_artist.set_picker(True) + self.got_artist = False + self._use_blit = use_blit and self.canvas.supports_blit + callbacks = self.canvas.callbacks + self._disconnectors = [ + functools.partial( + callbacks.disconnect, callbacks._connect_picklable(name, func)) + for name, func in [ + ("pick_event", self.on_pick), + ("button_release_event", self.on_release), + ("motion_notify_event", self.on_motion), + ] + ] + + # A property, not an attribute, to maintain picklability. + canvas = property(lambda self: self.ref_artist.get_figure(root=True).canvas) + cids = property(lambda self: [ + disconnect.args[0] for disconnect in self._disconnectors[:2]]) + + def on_motion(self, evt): + if self._check_still_parented() and self.got_artist: + dx = evt.x - self.mouse_x + dy = evt.y - self.mouse_y + self.update_offset(dx, dy) + if self._use_blit: + self.canvas.restore_region(self.background) + self.ref_artist.draw( + self.ref_artist.get_figure(root=True)._get_renderer()) + self.canvas.blit() + else: + self.canvas.draw() + + def on_pick(self, evt): + if self._check_still_parented(): + if evt.artist == self.ref_artist: + self.mouse_x = evt.mouseevent.x + self.mouse_y = evt.mouseevent.y + self.save_offset() + self.got_artist = True + if self.got_artist and self._use_blit: + self.ref_artist.set_animated(True) + self.canvas.draw() + fig = self.ref_artist.get_figure(root=False) + self.background = self.canvas.copy_from_bbox(fig.bbox) + self.ref_artist.draw(fig._get_renderer()) + self.canvas.blit() + + def on_release(self, event): + if self._check_still_parented() and self.got_artist: + self.finalize_offset() + self.got_artist = False + if self._use_blit: + self.canvas.restore_region(self.background) + self.ref_artist.draw(self.ref_artist.figure._get_renderer()) + self.canvas.blit() + self.ref_artist.set_animated(False) + + def _check_still_parented(self): + if self.ref_artist.get_figure(root=False) is None: + self.disconnect() + return False + else: + return True + + def disconnect(self): + """Disconnect the callbacks.""" + for disconnector in self._disconnectors: + disconnector() + + def save_offset(self): + pass + + def update_offset(self, dx, dy): + pass + + def finalize_offset(self): + pass + + +class DraggableOffsetBox(DraggableBase): + def __init__(self, ref_artist, offsetbox, use_blit=False): + super().__init__(ref_artist, use_blit=use_blit) + self.offsetbox = offsetbox + + def save_offset(self): + offsetbox = self.offsetbox + renderer = offsetbox.get_figure(root=True)._get_renderer() + offset = offsetbox.get_offset(offsetbox.get_bbox(renderer), renderer) + self.offsetbox_x, self.offsetbox_y = offset + self.offsetbox.set_offset(offset) + + def update_offset(self, dx, dy): + loc_in_canvas = self.offsetbox_x + dx, self.offsetbox_y + dy + self.offsetbox.set_offset(loc_in_canvas) + + def get_loc_in_canvas(self): + offsetbox = self.offsetbox + renderer = offsetbox.get_figure(root=True)._get_renderer() + bbox = offsetbox.get_bbox(renderer) + ox, oy = offsetbox._offset + loc_in_canvas = (ox + bbox.x0, oy + bbox.y0) + return loc_in_canvas + + +class DraggableAnnotation(DraggableBase): + def __init__(self, annotation, use_blit=False): + super().__init__(annotation, use_blit=use_blit) + self.annotation = annotation + + def save_offset(self): + ann = self.annotation + self.ox, self.oy = ann.get_transform().transform(ann.xyann) + + def update_offset(self, dx, dy): + ann = self.annotation + ann.xyann = ann.get_transform().inverted().transform( + (self.ox + dx, self.oy + dy)) diff --git a/infer_4_30_0/lib/python3.10/site-packages/matplotlib/path.pyi b/infer_4_30_0/lib/python3.10/site-packages/matplotlib/path.pyi new file mode 100644 index 0000000000000000000000000000000000000000..464fc6d9a912e359d1deb0f3bb71a8ac349cfb6a --- /dev/null +++ b/infer_4_30_0/lib/python3.10/site-packages/matplotlib/path.pyi @@ -0,0 +1,140 @@ +from .bezier import BezierSegment +from .transforms import Affine2D, Transform, Bbox +from collections.abc import Generator, Iterable, Sequence + +import numpy as np +from numpy.typing import ArrayLike + +from typing import Any, overload + +class Path: + code_type: type[np.uint8] + STOP: np.uint8 + MOVETO: np.uint8 + LINETO: np.uint8 + CURVE3: np.uint8 + CURVE4: np.uint8 + CLOSEPOLY: np.uint8 + NUM_VERTICES_FOR_CODE: dict[np.uint8, int] + + def __init__( + self, + vertices: ArrayLike, + codes: ArrayLike | None = ..., + _interpolation_steps: int = ..., + closed: bool = ..., + readonly: bool = ..., + ) -> None: ... + @property + def vertices(self) -> ArrayLike: ... + @vertices.setter + def vertices(self, vertices: ArrayLike) -> None: ... + @property + def codes(self) -> ArrayLike | None: ... + @codes.setter + def codes(self, codes: ArrayLike) -> None: ... + @property + def simplify_threshold(self) -> float: ... + @simplify_threshold.setter + def simplify_threshold(self, threshold: float) -> None: ... + @property + def should_simplify(self) -> bool: ... + @should_simplify.setter + def should_simplify(self, should_simplify: bool) -> None: ... + @property + def readonly(self) -> bool: ... + def copy(self) -> Path: ... + def __deepcopy__(self, memo: dict[int, Any] | None = ...) -> Path: ... + deepcopy = __deepcopy__ + + @classmethod + def make_compound_path_from_polys(cls, XY: ArrayLike) -> Path: ... + @classmethod + def make_compound_path(cls, *args: Path) -> Path: ... + def __len__(self) -> int: ... + def iter_segments( + self, + transform: Transform | None = ..., + remove_nans: bool = ..., + clip: tuple[float, float, float, float] | None = ..., + snap: bool | None = ..., + stroke_width: float = ..., + simplify: bool | None = ..., + curves: bool = ..., + sketch: tuple[float, float, float] | None = ..., + ) -> Generator[tuple[np.ndarray, np.uint8], None, None]: ... + def iter_bezier(self, **kwargs) -> Generator[BezierSegment, None, None]: ... + def cleaned( + self, + transform: Transform | None = ..., + remove_nans: bool = ..., + clip: tuple[float, float, float, float] | None = ..., + *, + simplify: bool | None = ..., + curves: bool = ..., + stroke_width: float = ..., + snap: bool | None = ..., + sketch: tuple[float, float, float] | None = ... + ) -> Path: ... + def transformed(self, transform: Transform) -> Path: ... + def contains_point( + self, + point: tuple[float, float], + transform: Transform | None = ..., + radius: float = ..., + ) -> bool: ... + def contains_points( + self, points: ArrayLike, transform: Transform | None = ..., radius: float = ... + ) -> np.ndarray: ... + def contains_path(self, path: Path, transform: Transform | None = ...) -> bool: ... + def get_extents(self, transform: Transform | None = ..., **kwargs) -> Bbox: ... + def intersects_path(self, other: Path, filled: bool = ...) -> bool: ... + def intersects_bbox(self, bbox: Bbox, filled: bool = ...) -> bool: ... + def interpolated(self, steps: int) -> Path: ... + def to_polygons( + self, + transform: Transform | None = ..., + width: float = ..., + height: float = ..., + closed_only: bool = ..., + ) -> list[ArrayLike]: ... + @classmethod + def unit_rectangle(cls) -> Path: ... + @classmethod + def unit_regular_polygon(cls, numVertices: int) -> Path: ... + @classmethod + def unit_regular_star(cls, numVertices: int, innerCircle: float = ...) -> Path: ... + @classmethod + def unit_regular_asterisk(cls, numVertices: int) -> Path: ... + @classmethod + def unit_circle(cls) -> Path: ... + @classmethod + def circle( + cls, + center: tuple[float, float] = ..., + radius: float = ..., + readonly: bool = ..., + ) -> Path: ... + @classmethod + def unit_circle_righthalf(cls) -> Path: ... + @classmethod + def arc( + cls, theta1: float, theta2: float, n: int | None = ..., is_wedge: bool = ... + ) -> Path: ... + @classmethod + def wedge(cls, theta1: float, theta2: float, n: int | None = ...) -> Path: ... + @overload + @staticmethod + def hatch(hatchpattern: str, density: float = ...) -> Path: ... + @overload + @staticmethod + def hatch(hatchpattern: None, density: float = ...) -> None: ... + def clip_to_bbox(self, bbox: Bbox, inside: bool = ...) -> Path: ... + +def get_path_collection_extents( + master_transform: Transform, + paths: Sequence[Path], + transforms: Iterable[Affine2D], + offsets: ArrayLike, + offset_transform: Affine2D, +) -> Bbox: ... diff --git a/infer_4_30_0/lib/python3.10/site-packages/matplotlib/patheffects.py b/infer_4_30_0/lib/python3.10/site-packages/matplotlib/patheffects.py new file mode 100644 index 0000000000000000000000000000000000000000..e7a0138bd7507a18f96e445572c59fdd2cde0e7c --- /dev/null +++ b/infer_4_30_0/lib/python3.10/site-packages/matplotlib/patheffects.py @@ -0,0 +1,511 @@ +""" +Defines classes for path effects. The path effects are supported in `.Text`, +`.Line2D` and `.Patch`. + +.. seealso:: + :ref:`patheffects_guide` +""" + +from matplotlib.backend_bases import RendererBase +from matplotlib import colors as mcolors +from matplotlib import patches as mpatches +from matplotlib import transforms as mtransforms +from matplotlib.path import Path +import numpy as np + + +class AbstractPathEffect: + """ + A base class for path effects. + + Subclasses should override the ``draw_path`` method to add effect + functionality. + """ + + def __init__(self, offset=(0., 0.)): + """ + Parameters + ---------- + offset : (float, float), default: (0, 0) + The (x, y) offset to apply to the path, measured in points. + """ + self._offset = offset + + def _offset_transform(self, renderer): + """Apply the offset to the given transform.""" + return mtransforms.Affine2D().translate( + *map(renderer.points_to_pixels, self._offset)) + + def _update_gc(self, gc, new_gc_dict): + """ + Update the given GraphicsContext with the given dict of properties. + + The keys in the dictionary are used to identify the appropriate + ``set_`` method on the *gc*. + """ + new_gc_dict = new_gc_dict.copy() + + dashes = new_gc_dict.pop("dashes", None) + if dashes: + gc.set_dashes(**dashes) + + for k, v in new_gc_dict.items(): + set_method = getattr(gc, 'set_' + k, None) + if not callable(set_method): + raise AttributeError(f'Unknown property {k}') + set_method(v) + return gc + + def draw_path(self, renderer, gc, tpath, affine, rgbFace=None): + """ + Derived should override this method. The arguments are the same + as :meth:`matplotlib.backend_bases.RendererBase.draw_path` + except the first argument is a renderer. + """ + # Get the real renderer, not a PathEffectRenderer. + if isinstance(renderer, PathEffectRenderer): + renderer = renderer._renderer + return renderer.draw_path(gc, tpath, affine, rgbFace) + + +class PathEffectRenderer(RendererBase): + """ + Implements a Renderer which contains another renderer. + + This proxy then intercepts draw calls, calling the appropriate + :class:`AbstractPathEffect` draw method. + + .. note:: + Not all methods have been overridden on this RendererBase subclass. + It may be necessary to add further methods to extend the PathEffects + capabilities further. + """ + + def __init__(self, path_effects, renderer): + """ + Parameters + ---------- + path_effects : iterable of :class:`AbstractPathEffect` + The path effects which this renderer represents. + renderer : `~matplotlib.backend_bases.RendererBase` subclass + + """ + self._path_effects = path_effects + self._renderer = renderer + + def copy_with_path_effect(self, path_effects): + return self.__class__(path_effects, self._renderer) + + def __getattribute__(self, name): + if name in ['flipy', 'get_canvas_width_height', 'new_gc', + 'points_to_pixels', '_text2path', 'height', 'width']: + return getattr(self._renderer, name) + else: + return object.__getattribute__(self, name) + + def draw_path(self, gc, tpath, affine, rgbFace=None): + for path_effect in self._path_effects: + path_effect.draw_path(self._renderer, gc, tpath, affine, + rgbFace) + + def draw_markers( + self, gc, marker_path, marker_trans, path, *args, **kwargs): + # We do a little shimmy so that all markers are drawn for each path + # effect in turn. Essentially, we induce recursion (depth 1) which is + # terminated once we have just a single path effect to work with. + if len(self._path_effects) == 1: + # Call the base path effect function - this uses the unoptimised + # approach of calling "draw_path" multiple times. + return super().draw_markers(gc, marker_path, marker_trans, path, + *args, **kwargs) + + for path_effect in self._path_effects: + renderer = self.copy_with_path_effect([path_effect]) + # Recursively call this method, only next time we will only have + # one path effect. + renderer.draw_markers(gc, marker_path, marker_trans, path, + *args, **kwargs) + + def draw_path_collection(self, gc, master_transform, paths, *args, + **kwargs): + # We do a little shimmy so that all paths are drawn for each path + # effect in turn. Essentially, we induce recursion (depth 1) which is + # terminated once we have just a single path effect to work with. + if len(self._path_effects) == 1: + # Call the base path effect function - this uses the unoptimised + # approach of calling "draw_path" multiple times. + return super().draw_path_collection(gc, master_transform, paths, + *args, **kwargs) + + for path_effect in self._path_effects: + renderer = self.copy_with_path_effect([path_effect]) + # Recursively call this method, only next time we will only have + # one path effect. + renderer.draw_path_collection(gc, master_transform, paths, + *args, **kwargs) + + def open_group(self, s, gid=None): + return self._renderer.open_group(s, gid) + + def close_group(self, s): + return self._renderer.close_group(s) + + +class Normal(AbstractPathEffect): + """ + The "identity" PathEffect. + + The Normal PathEffect's sole purpose is to draw the original artist with + no special path effect. + """ + + +def _subclass_with_normal(effect_class): + """ + Create a PathEffect class combining *effect_class* and a normal draw. + """ + + class withEffect(effect_class): + def draw_path(self, renderer, gc, tpath, affine, rgbFace): + super().draw_path(renderer, gc, tpath, affine, rgbFace) + renderer.draw_path(gc, tpath, affine, rgbFace) + + withEffect.__name__ = f"with{effect_class.__name__}" + withEffect.__qualname__ = f"with{effect_class.__name__}" + withEffect.__doc__ = f""" + A shortcut PathEffect for applying `.{effect_class.__name__}` and then + drawing the original Artist. + + With this class you can use :: + + artist.set_path_effects([patheffects.with{effect_class.__name__}()]) + + as a shortcut for :: + + artist.set_path_effects([patheffects.{effect_class.__name__}(), + patheffects.Normal()]) + """ + # Docstring inheritance doesn't work for locally-defined subclasses. + withEffect.draw_path.__doc__ = effect_class.draw_path.__doc__ + return withEffect + + +class Stroke(AbstractPathEffect): + """A line based PathEffect which re-draws a stroke.""" + + def __init__(self, offset=(0, 0), **kwargs): + """ + The path will be stroked with its gc updated with the given + keyword arguments, i.e., the keyword arguments should be valid + gc parameter values. + """ + super().__init__(offset) + self._gc = kwargs + + def draw_path(self, renderer, gc, tpath, affine, rgbFace): + """Draw the path with updated gc.""" + gc0 = renderer.new_gc() # Don't modify gc, but a copy! + gc0.copy_properties(gc) + gc0 = self._update_gc(gc0, self._gc) + renderer.draw_path( + gc0, tpath, affine + self._offset_transform(renderer), rgbFace) + gc0.restore() + + +withStroke = _subclass_with_normal(effect_class=Stroke) + + +class SimplePatchShadow(AbstractPathEffect): + """A simple shadow via a filled patch.""" + + def __init__(self, offset=(2, -2), + shadow_rgbFace=None, alpha=None, + rho=0.3, **kwargs): + """ + Parameters + ---------- + offset : (float, float), default: (2, -2) + The (x, y) offset of the shadow in points. + shadow_rgbFace : :mpltype:`color` + The shadow color. + alpha : float, default: 0.3 + The alpha transparency of the created shadow patch. + rho : float, default: 0.3 + A scale factor to apply to the rgbFace color if *shadow_rgbFace* + is not specified. + **kwargs + Extra keywords are stored and passed through to + :meth:`AbstractPathEffect._update_gc`. + + """ + super().__init__(offset) + + if shadow_rgbFace is None: + self._shadow_rgbFace = shadow_rgbFace + else: + self._shadow_rgbFace = mcolors.to_rgba(shadow_rgbFace) + + if alpha is None: + alpha = 0.3 + + self._alpha = alpha + self._rho = rho + + #: The dictionary of keywords to update the graphics collection with. + self._gc = kwargs + + def draw_path(self, renderer, gc, tpath, affine, rgbFace): + """ + Overrides the standard draw_path to add the shadow offset and + necessary color changes for the shadow. + """ + gc0 = renderer.new_gc() # Don't modify gc, but a copy! + gc0.copy_properties(gc) + + if self._shadow_rgbFace is None: + r, g, b = (rgbFace or (1., 1., 1.))[:3] + # Scale the colors by a factor to improve the shadow effect. + shadow_rgbFace = (r * self._rho, g * self._rho, b * self._rho) + else: + shadow_rgbFace = self._shadow_rgbFace + + gc0.set_foreground("none") + gc0.set_alpha(self._alpha) + gc0.set_linewidth(0) + + gc0 = self._update_gc(gc0, self._gc) + renderer.draw_path( + gc0, tpath, affine + self._offset_transform(renderer), + shadow_rgbFace) + gc0.restore() + + +withSimplePatchShadow = _subclass_with_normal(effect_class=SimplePatchShadow) + + +class SimpleLineShadow(AbstractPathEffect): + """A simple shadow via a line.""" + + def __init__(self, offset=(2, -2), + shadow_color='k', alpha=0.3, rho=0.3, **kwargs): + """ + Parameters + ---------- + offset : (float, float), default: (2, -2) + The (x, y) offset to apply to the path, in points. + shadow_color : :mpltype:`color`, default: 'black' + The shadow color. + A value of ``None`` takes the original artist's color + with a scale factor of *rho*. + alpha : float, default: 0.3 + The alpha transparency of the created shadow patch. + rho : float, default: 0.3 + A scale factor to apply to the rgbFace color if *shadow_color* + is ``None``. + **kwargs + Extra keywords are stored and passed through to + :meth:`AbstractPathEffect._update_gc`. + """ + super().__init__(offset) + if shadow_color is None: + self._shadow_color = shadow_color + else: + self._shadow_color = mcolors.to_rgba(shadow_color) + self._alpha = alpha + self._rho = rho + #: The dictionary of keywords to update the graphics collection with. + self._gc = kwargs + + def draw_path(self, renderer, gc, tpath, affine, rgbFace): + """ + Overrides the standard draw_path to add the shadow offset and + necessary color changes for the shadow. + """ + gc0 = renderer.new_gc() # Don't modify gc, but a copy! + gc0.copy_properties(gc) + + if self._shadow_color is None: + r, g, b = (gc0.get_foreground() or (1., 1., 1.))[:3] + # Scale the colors by a factor to improve the shadow effect. + shadow_rgbFace = (r * self._rho, g * self._rho, b * self._rho) + else: + shadow_rgbFace = self._shadow_color + + gc0.set_foreground(shadow_rgbFace) + gc0.set_alpha(self._alpha) + + gc0 = self._update_gc(gc0, self._gc) + renderer.draw_path( + gc0, tpath, affine + self._offset_transform(renderer)) + gc0.restore() + + +class PathPatchEffect(AbstractPathEffect): + """ + Draws a `.PathPatch` instance whose Path comes from the original + PathEffect artist. + """ + + def __init__(self, offset=(0, 0), **kwargs): + """ + Parameters + ---------- + offset : (float, float), default: (0, 0) + The (x, y) offset to apply to the path, in points. + **kwargs + All keyword arguments are passed through to the + :class:`~matplotlib.patches.PathPatch` constructor. The + properties which cannot be overridden are "path", "clip_box" + "transform" and "clip_path". + """ + super().__init__(offset=offset) + self.patch = mpatches.PathPatch([], **kwargs) + + def draw_path(self, renderer, gc, tpath, affine, rgbFace): + self.patch._path = tpath + self.patch.set_transform(affine + self._offset_transform(renderer)) + self.patch.set_clip_box(gc.get_clip_rectangle()) + clip_path = gc.get_clip_path() + if clip_path and self.patch.get_clip_path() is None: + self.patch.set_clip_path(*clip_path) + self.patch.draw(renderer) + + +class TickedStroke(AbstractPathEffect): + """ + A line-based PathEffect which draws a path with a ticked style. + + This line style is frequently used to represent constraints in + optimization. The ticks may be used to indicate that one side + of the line is invalid or to represent a closed boundary of a + domain (i.e. a wall or the edge of a pipe). + + The spacing, length, and angle of ticks can be controlled. + + This line style is sometimes referred to as a hatched line. + + See also the :doc:`/gallery/misc/tickedstroke_demo` example. + """ + + def __init__(self, offset=(0, 0), + spacing=10.0, angle=45.0, length=np.sqrt(2), + **kwargs): + """ + Parameters + ---------- + offset : (float, float), default: (0, 0) + The (x, y) offset to apply to the path, in points. + spacing : float, default: 10.0 + The spacing between ticks in points. + angle : float, default: 45.0 + The angle between the path and the tick in degrees. The angle + is measured as if you were an ant walking along the curve, with + zero degrees pointing directly ahead, 90 to your left, -90 + to your right, and 180 behind you. To change side of the ticks, + change sign of the angle. + length : float, default: 1.414 + The length of the tick relative to spacing. + Recommended length = 1.414 (sqrt(2)) when angle=45, length=1.0 + when angle=90 and length=2.0 when angle=60. + **kwargs + Extra keywords are stored and passed through to + :meth:`AbstractPathEffect._update_gc`. + + Examples + -------- + See :doc:`/gallery/misc/tickedstroke_demo`. + """ + super().__init__(offset) + + self._spacing = spacing + self._angle = angle + self._length = length + self._gc = kwargs + + def draw_path(self, renderer, gc, tpath, affine, rgbFace): + """Draw the path with updated gc.""" + # Do not modify the input! Use copy instead. + gc0 = renderer.new_gc() + gc0.copy_properties(gc) + + gc0 = self._update_gc(gc0, self._gc) + trans = affine + self._offset_transform(renderer) + + theta = -np.radians(self._angle) + trans_matrix = np.array([[np.cos(theta), -np.sin(theta)], + [np.sin(theta), np.cos(theta)]]) + + # Convert spacing parameter to pixels. + spacing_px = renderer.points_to_pixels(self._spacing) + + # Transform before evaluation because to_polygons works at resolution + # of one -- assuming it is working in pixel space. + transpath = affine.transform_path(tpath) + + # Evaluate path to straight line segments that can be used to + # construct line ticks. + polys = transpath.to_polygons(closed_only=False) + + for p in polys: + x = p[:, 0] + y = p[:, 1] + + # Can not interpolate points or draw line if only one point in + # polyline. + if x.size < 2: + continue + + # Find distance between points on the line + ds = np.hypot(x[1:] - x[:-1], y[1:] - y[:-1]) + + # Build parametric coordinate along curve + s = np.concatenate(([0.0], np.cumsum(ds))) + s_total = s[-1] + + num = int(np.ceil(s_total / spacing_px)) - 1 + # Pick parameter values for ticks. + s_tick = np.linspace(spacing_px/2, s_total - spacing_px/2, num) + + # Find points along the parameterized curve + x_tick = np.interp(s_tick, s, x) + y_tick = np.interp(s_tick, s, y) + + # Find unit vectors in local direction of curve + delta_s = self._spacing * .001 + u = (np.interp(s_tick + delta_s, s, x) - x_tick) / delta_s + v = (np.interp(s_tick + delta_s, s, y) - y_tick) / delta_s + + # Normalize slope into unit slope vector. + n = np.hypot(u, v) + mask = n == 0 + n[mask] = 1.0 + + uv = np.array([u / n, v / n]).T + uv[mask] = np.array([0, 0]).T + + # Rotate and scale unit vector into tick vector + dxy = np.dot(uv, trans_matrix) * self._length * spacing_px + + # Build tick endpoints + x_end = x_tick + dxy[:, 0] + y_end = y_tick + dxy[:, 1] + + # Interleave ticks to form Path vertices + xyt = np.empty((2 * num, 2), dtype=x_tick.dtype) + xyt[0::2, 0] = x_tick + xyt[1::2, 0] = x_end + xyt[0::2, 1] = y_tick + xyt[1::2, 1] = y_end + + # Build up vector of Path codes + codes = np.tile([Path.MOVETO, Path.LINETO], num) + + # Construct and draw resulting path + h = Path(xyt, codes) + # Transform back to data space during render + renderer.draw_path(gc0, h, affine.inverted() + trans, rgbFace) + + gc0.restore() + + +withTickedStroke = _subclass_with_normal(effect_class=TickedStroke) diff --git a/infer_4_30_0/lib/python3.10/site-packages/matplotlib/py.typed b/infer_4_30_0/lib/python3.10/site-packages/matplotlib/py.typed new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/infer_4_30_0/lib/python3.10/site-packages/matplotlib/quiver.pyi b/infer_4_30_0/lib/python3.10/site-packages/matplotlib/quiver.pyi new file mode 100644 index 0000000000000000000000000000000000000000..8a14083c434863d229b4b14287df06c8c85b102d --- /dev/null +++ b/infer_4_30_0/lib/python3.10/site-packages/matplotlib/quiver.pyi @@ -0,0 +1,184 @@ +import matplotlib.artist as martist +import matplotlib.collections as mcollections +from matplotlib.axes import Axes +from matplotlib.figure import Figure, SubFigure +from matplotlib.text import Text +from matplotlib.transforms import Transform, Bbox + + +import numpy as np +from numpy.typing import ArrayLike +from collections.abc import Sequence +from typing import Any, Literal, overload +from matplotlib.typing import ColorType + +class QuiverKey(martist.Artist): + halign: dict[Literal["N", "S", "E", "W"], Literal["left", "center", "right"]] + valign: dict[Literal["N", "S", "E", "W"], Literal["top", "center", "bottom"]] + pivot: dict[Literal["N", "S", "E", "W"], Literal["middle", "tip", "tail"]] + Q: Quiver + X: float + Y: float + U: float + angle: float + coord: Literal["axes", "figure", "data", "inches"] + color: ColorType | None + label: str + labelpos: Literal["N", "S", "E", "W"] + labelcolor: ColorType | None + fontproperties: dict[str, Any] + kw: dict[str, Any] + text: Text + zorder: float + def __init__( + self, + Q: Quiver, + X: float, + Y: float, + U: float, + label: str, + *, + angle: float = ..., + coordinates: Literal["axes", "figure", "data", "inches"] = ..., + color: ColorType | None = ..., + labelsep: float = ..., + labelpos: Literal["N", "S", "E", "W"] = ..., + labelcolor: ColorType | None = ..., + fontproperties: dict[str, Any] | None = ..., + zorder: float | None = ..., + **kwargs + ) -> None: ... + @property + def labelsep(self) -> float: ... + def set_figure(self, fig: Figure | SubFigure) -> None: ... + +class Quiver(mcollections.PolyCollection): + X: ArrayLike + Y: ArrayLike + XY: ArrayLike + U: ArrayLike + V: ArrayLike + Umask: ArrayLike + N: int + scale: float | None + headwidth: float + headlength: float + headaxislength: float + minshaft: float + minlength: float + units: Literal["width", "height", "dots", "inches", "x", "y", "xy"] + scale_units: Literal["width", "height", "dots", "inches", "x", "y", "xy"] | None + angles: Literal["uv", "xy"] | ArrayLike + width: float | None + pivot: Literal["tail", "middle", "tip"] + transform: Transform + polykw: dict[str, Any] + + @overload + def __init__( + self, + ax: Axes, + U: ArrayLike, + V: ArrayLike, + C: ArrayLike = ..., + *, + scale: float | None = ..., + headwidth: float = ..., + headlength: float = ..., + headaxislength: float = ..., + minshaft: float = ..., + minlength: float = ..., + units: Literal["width", "height", "dots", "inches", "x", "y", "xy"] = ..., + scale_units: Literal["width", "height", "dots", "inches", "x", "y", "xy"] + | None = ..., + angles: Literal["uv", "xy"] | ArrayLike = ..., + width: float | None = ..., + color: ColorType | Sequence[ColorType] = ..., + pivot: Literal["tail", "mid", "middle", "tip"] = ..., + **kwargs + ) -> None: ... + @overload + def __init__( + self, + ax: Axes, + X: ArrayLike, + Y: ArrayLike, + U: ArrayLike, + V: ArrayLike, + C: ArrayLike = ..., + *, + scale: float | None = ..., + headwidth: float = ..., + headlength: float = ..., + headaxislength: float = ..., + minshaft: float = ..., + minlength: float = ..., + units: Literal["width", "height", "dots", "inches", "x", "y", "xy"] = ..., + scale_units: Literal["width", "height", "dots", "inches", "x", "y", "xy"] + | None = ..., + angles: Literal["uv", "xy"] | ArrayLike = ..., + width: float | None = ..., + color: ColorType | Sequence[ColorType] = ..., + pivot: Literal["tail", "mid", "middle", "tip"] = ..., + **kwargs + ) -> None: ... + def get_datalim(self, transData: Transform) -> Bbox: ... + def set_UVC( + self, U: ArrayLike, V: ArrayLike, C: ArrayLike | None = ... + ) -> None: ... + +class Barbs(mcollections.PolyCollection): + sizes: dict[str, float] + fill_empty: bool + barb_increments: dict[str, float] + rounding: bool + flip: np.ndarray + x: ArrayLike + y: ArrayLike + u: ArrayLike + v: ArrayLike + + @overload + def __init__( + self, + ax: Axes, + U: ArrayLike, + V: ArrayLike, + C: ArrayLike = ..., + *, + pivot: str = ..., + length: int = ..., + barbcolor: ColorType | Sequence[ColorType] | None = ..., + flagcolor: ColorType | Sequence[ColorType] | None = ..., + sizes: dict[str, float] | None = ..., + fill_empty: bool = ..., + barb_increments: dict[str, float] | None = ..., + rounding: bool = ..., + flip_barb: bool | ArrayLike = ..., + **kwargs + ) -> None: ... + @overload + def __init__( + self, + ax: Axes, + X: ArrayLike, + Y: ArrayLike, + U: ArrayLike, + V: ArrayLike, + C: ArrayLike = ..., + *, + pivot: str = ..., + length: int = ..., + barbcolor: ColorType | Sequence[ColorType] | None = ..., + flagcolor: ColorType | Sequence[ColorType] | None = ..., + sizes: dict[str, float] | None = ..., + fill_empty: bool = ..., + barb_increments: dict[str, float] | None = ..., + rounding: bool = ..., + flip_barb: bool | ArrayLike = ..., + **kwargs + ) -> None: ... + def set_UVC( + self, U: ArrayLike, V: ArrayLike, C: ArrayLike | None = ... + ) -> None: ... + def set_offsets(self, xy: ArrayLike) -> None: ... diff --git a/infer_4_30_0/lib/python3.10/site-packages/matplotlib/rcsetup.py b/infer_4_30_0/lib/python3.10/site-packages/matplotlib/rcsetup.py new file mode 100644 index 0000000000000000000000000000000000000000..c23d9f818454cda653ed6e2b08f6bb0e1045cbf4 --- /dev/null +++ b/infer_4_30_0/lib/python3.10/site-packages/matplotlib/rcsetup.py @@ -0,0 +1,1371 @@ +""" +The rcsetup module contains the validation code for customization using +Matplotlib's rc settings. + +Each rc setting is assigned a function used to validate any attempted changes +to that setting. The validation functions are defined in the rcsetup module, +and are used to construct the rcParams global object which stores the settings +and is referenced throughout Matplotlib. + +The default values of the rc settings are set in the default matplotlibrc file. +Any additions or deletions to the parameter set listed here should also be +propagated to the :file:`lib/matplotlib/mpl-data/matplotlibrc` in Matplotlib's +root source directory. +""" + +import ast +from functools import lru_cache, reduce +from numbers import Real +import operator +import os +import re + +import numpy as np + +from matplotlib import _api, cbook +from matplotlib.backends import BackendFilter, backend_registry +from matplotlib.cbook import ls_mapper +from matplotlib.colors import Colormap, is_color_like +from matplotlib._fontconfig_pattern import parse_fontconfig_pattern +from matplotlib._enums import JoinStyle, CapStyle + +# Don't let the original cycler collide with our validating cycler +from cycler import Cycler, cycler as ccycler + + +@_api.caching_module_getattr +class __getattr__: + @_api.deprecated( + "3.9", + alternative="``matplotlib.backends.backend_registry.list_builtin" + "(matplotlib.backends.BackendFilter.INTERACTIVE)``") + @property + def interactive_bk(self): + return backend_registry.list_builtin(BackendFilter.INTERACTIVE) + + @_api.deprecated( + "3.9", + alternative="``matplotlib.backends.backend_registry.list_builtin" + "(matplotlib.backends.BackendFilter.NON_INTERACTIVE)``") + @property + def non_interactive_bk(self): + return backend_registry.list_builtin(BackendFilter.NON_INTERACTIVE) + + @_api.deprecated( + "3.9", + alternative="``matplotlib.backends.backend_registry.list_builtin()``") + @property + def all_backends(self): + return backend_registry.list_builtin() + + +class ValidateInStrings: + def __init__(self, key, valid, ignorecase=False, *, + _deprecated_since=None): + """*valid* is a list of legal strings.""" + self.key = key + self.ignorecase = ignorecase + self._deprecated_since = _deprecated_since + + def func(s): + if ignorecase: + return s.lower() + else: + return s + self.valid = {func(k): k for k in valid} + + def __call__(self, s): + if self._deprecated_since: + name, = (k for k, v in globals().items() if v is self) + _api.warn_deprecated( + self._deprecated_since, name=name, obj_type="function") + if self.ignorecase and isinstance(s, str): + s = s.lower() + if s in self.valid: + return self.valid[s] + msg = (f"{s!r} is not a valid value for {self.key}; supported values " + f"are {[*self.valid.values()]}") + if (isinstance(s, str) + and (s.startswith('"') and s.endswith('"') + or s.startswith("'") and s.endswith("'")) + and s[1:-1] in self.valid): + msg += "; remove quotes surrounding your string" + raise ValueError(msg) + + +@lru_cache +def _listify_validator(scalar_validator, allow_stringlist=False, *, + n=None, doc=None): + def f(s): + if isinstance(s, str): + try: + val = [scalar_validator(v.strip()) for v in s.split(',') + if v.strip()] + except Exception: + if allow_stringlist: + # Sometimes, a list of colors might be a single string + # of single-letter colornames. So give that a shot. + val = [scalar_validator(v.strip()) for v in s if v.strip()] + else: + raise + # Allow any ordered sequence type -- generators, np.ndarray, pd.Series + # -- but not sets, whose iteration order is non-deterministic. + elif np.iterable(s) and not isinstance(s, (set, frozenset)): + # The condition on this list comprehension will preserve the + # behavior of filtering out any empty strings (behavior was + # from the original validate_stringlist()), while allowing + # any non-string/text scalar values such as numbers and arrays. + val = [scalar_validator(v) for v in s + if not isinstance(v, str) or v] + else: + raise ValueError( + f"Expected str or other non-set iterable, but got {s}") + if n is not None and len(val) != n: + raise ValueError( + f"Expected {n} values, but there are {len(val)} values in {s}") + return val + + try: + f.__name__ = f"{scalar_validator.__name__}list" + except AttributeError: # class instance. + f.__name__ = f"{type(scalar_validator).__name__}List" + f.__qualname__ = f.__qualname__.rsplit(".", 1)[0] + "." + f.__name__ + f.__doc__ = doc if doc is not None else scalar_validator.__doc__ + return f + + +def validate_any(s): + return s +validate_anylist = _listify_validator(validate_any) + + +def _validate_date(s): + try: + np.datetime64(s) + return s + except ValueError: + raise ValueError( + f'{s!r} should be a string that can be parsed by numpy.datetime64') + + +def validate_bool(b): + """Convert b to ``bool`` or raise.""" + if isinstance(b, str): + b = b.lower() + if b in ('t', 'y', 'yes', 'on', 'true', '1', 1, True): + return True + elif b in ('f', 'n', 'no', 'off', 'false', '0', 0, False): + return False + else: + raise ValueError(f'Cannot convert {b!r} to bool') + + +def validate_axisbelow(s): + try: + return validate_bool(s) + except ValueError: + if isinstance(s, str): + if s == 'line': + return 'line' + raise ValueError(f'{s!r} cannot be interpreted as' + ' True, False, or "line"') + + +def validate_dpi(s): + """Confirm s is string 'figure' or convert s to float or raise.""" + if s == 'figure': + return s + try: + return float(s) + except ValueError as e: + raise ValueError(f'{s!r} is not string "figure" and ' + f'could not convert {s!r} to float') from e + + +def _make_type_validator(cls, *, allow_none=False): + """ + Return a validator that converts inputs to *cls* or raises (and possibly + allows ``None`` as well). + """ + + def validator(s): + if (allow_none and + (s is None or cbook._str_lower_equal(s, "none"))): + return None + if cls is str and not isinstance(s, str): + raise ValueError(f'Could not convert {s!r} to str') + try: + return cls(s) + except (TypeError, ValueError) as e: + raise ValueError( + f'Could not convert {s!r} to {cls.__name__}') from e + + validator.__name__ = f"validate_{cls.__name__}" + if allow_none: + validator.__name__ += "_or_None" + validator.__qualname__ = ( + validator.__qualname__.rsplit(".", 1)[0] + "." + validator.__name__) + return validator + + +validate_string = _make_type_validator(str) +validate_string_or_None = _make_type_validator(str, allow_none=True) +validate_stringlist = _listify_validator( + validate_string, doc='return a list of strings') +validate_int = _make_type_validator(int) +validate_int_or_None = _make_type_validator(int, allow_none=True) +validate_float = _make_type_validator(float) +validate_float_or_None = _make_type_validator(float, allow_none=True) +validate_floatlist = _listify_validator( + validate_float, doc='return a list of floats') + + +def _validate_marker(s): + try: + return validate_int(s) + except ValueError as e: + try: + return validate_string(s) + except ValueError as e: + raise ValueError('Supported markers are [string, int]') from e + + +_validate_markerlist = _listify_validator( + _validate_marker, doc='return a list of markers') + + +def _validate_pathlike(s): + if isinstance(s, (str, os.PathLike)): + # Store value as str because savefig.directory needs to distinguish + # between "" (cwd) and "." (cwd, but gets updated by user selections). + return os.fsdecode(s) + else: + return validate_string(s) + + +def validate_fonttype(s): + """ + Confirm that this is a Postscript or PDF font type that we know how to + convert to. + """ + fonttypes = {'type3': 3, + 'truetype': 42} + try: + fonttype = validate_int(s) + except ValueError: + try: + return fonttypes[s.lower()] + except KeyError as e: + raise ValueError('Supported Postscript/PDF font types are %s' + % list(fonttypes)) from e + else: + if fonttype not in fonttypes.values(): + raise ValueError( + 'Supported Postscript/PDF font types are %s' % + list(fonttypes.values())) + return fonttype + + +_auto_backend_sentinel = object() + + +def validate_backend(s): + if s is _auto_backend_sentinel or backend_registry.is_valid_backend(s): + return s + else: + msg = (f"'{s}' is not a valid value for backend; supported values are " + f"{backend_registry.list_all()}") + raise ValueError(msg) + + +def _validate_toolbar(s): + s = ValidateInStrings( + 'toolbar', ['None', 'toolbar2', 'toolmanager'], ignorecase=True)(s) + if s == 'toolmanager': + _api.warn_external( + "Treat the new Tool classes introduced in v1.5 as experimental " + "for now; the API and rcParam may change in future versions.") + return s + + +def validate_color_or_inherit(s): + """Return a valid color arg.""" + if cbook._str_equal(s, 'inherit'): + return s + return validate_color(s) + + +def validate_color_or_auto(s): + if cbook._str_equal(s, 'auto'): + return s + return validate_color(s) + + +def validate_color_for_prop_cycle(s): + # N-th color cycle syntax can't go into the color cycle. + if isinstance(s, str) and re.match("^C[0-9]$", s): + raise ValueError(f"Cannot put cycle reference ({s!r}) in prop_cycler") + return validate_color(s) + + +def _validate_color_or_linecolor(s): + if cbook._str_equal(s, 'linecolor'): + return s + elif cbook._str_equal(s, 'mfc') or cbook._str_equal(s, 'markerfacecolor'): + return 'markerfacecolor' + elif cbook._str_equal(s, 'mec') or cbook._str_equal(s, 'markeredgecolor'): + return 'markeredgecolor' + elif s is None: + return None + elif isinstance(s, str) and len(s) == 6 or len(s) == 8: + stmp = '#' + s + if is_color_like(stmp): + return stmp + if s.lower() == 'none': + return None + elif is_color_like(s): + return s + + raise ValueError(f'{s!r} does not look like a color arg') + + +def validate_color(s): + """Return a valid color arg.""" + if isinstance(s, str): + if s.lower() == 'none': + return 'none' + if len(s) == 6 or len(s) == 8: + stmp = '#' + s + if is_color_like(stmp): + return stmp + + if is_color_like(s): + return s + + # If it is still valid, it must be a tuple (as a string from matplotlibrc). + try: + color = ast.literal_eval(s) + except (SyntaxError, ValueError): + pass + else: + if is_color_like(color): + return color + + raise ValueError(f'{s!r} does not look like a color arg') + + +validate_colorlist = _listify_validator( + validate_color, allow_stringlist=True, doc='return a list of colorspecs') + + +def _validate_cmap(s): + _api.check_isinstance((str, Colormap), cmap=s) + return s + + +def validate_aspect(s): + if s in ('auto', 'equal'): + return s + try: + return float(s) + except ValueError as e: + raise ValueError('not a valid aspect specification') from e + + +def validate_fontsize_None(s): + if s is None or s == 'None': + return None + else: + return validate_fontsize(s) + + +def validate_fontsize(s): + fontsizes = ['xx-small', 'x-small', 'small', 'medium', 'large', + 'x-large', 'xx-large', 'smaller', 'larger'] + if isinstance(s, str): + s = s.lower() + if s in fontsizes: + return s + try: + return float(s) + except ValueError as e: + raise ValueError("%s is not a valid font size. Valid font sizes " + "are %s." % (s, ", ".join(fontsizes))) from e + + +validate_fontsizelist = _listify_validator(validate_fontsize) + + +def validate_fontweight(s): + weights = [ + 'ultralight', 'light', 'normal', 'regular', 'book', 'medium', 'roman', + 'semibold', 'demibold', 'demi', 'bold', 'heavy', 'extra bold', 'black'] + # Note: Historically, weights have been case-sensitive in Matplotlib + if s in weights: + return s + try: + return int(s) + except (ValueError, TypeError) as e: + raise ValueError(f'{s} is not a valid font weight.') from e + + +def validate_fontstretch(s): + stretchvalues = [ + 'ultra-condensed', 'extra-condensed', 'condensed', 'semi-condensed', + 'normal', 'semi-expanded', 'expanded', 'extra-expanded', + 'ultra-expanded'] + # Note: Historically, stretchvalues have been case-sensitive in Matplotlib + if s in stretchvalues: + return s + try: + return int(s) + except (ValueError, TypeError) as e: + raise ValueError(f'{s} is not a valid font stretch.') from e + + +def validate_font_properties(s): + parse_fontconfig_pattern(s) + return s + + +def _validate_mathtext_fallback(s): + _fallback_fonts = ['cm', 'stix', 'stixsans'] + if isinstance(s, str): + s = s.lower() + if s is None or s == 'none': + return None + elif s.lower() in _fallback_fonts: + return s + else: + raise ValueError( + f"{s} is not a valid fallback font name. Valid fallback font " + f"names are {','.join(_fallback_fonts)}. Passing 'None' will turn " + "fallback off.") + + +def validate_whiskers(s): + try: + return _listify_validator(validate_float, n=2)(s) + except (TypeError, ValueError): + try: + return float(s) + except ValueError as e: + raise ValueError("Not a valid whisker value [float, " + "(float, float)]") from e + + +def validate_ps_distiller(s): + if isinstance(s, str): + s = s.lower() + if s in ('none', None, 'false', False): + return None + else: + return ValidateInStrings('ps.usedistiller', ['ghostscript', 'xpdf'])(s) + + +# A validator dedicated to the named line styles, based on the items in +# ls_mapper, and a list of possible strings read from Line2D.set_linestyle +_validate_named_linestyle = ValidateInStrings( + 'linestyle', + [*ls_mapper.keys(), *ls_mapper.values(), 'None', 'none', ' ', ''], + ignorecase=True) + + +def _validate_linestyle(ls): + """ + A validator for all possible line styles, the named ones *and* + the on-off ink sequences. + """ + if isinstance(ls, str): + try: # Look first for a valid named line style, like '--' or 'solid'. + return _validate_named_linestyle(ls) + except ValueError: + pass + try: + ls = ast.literal_eval(ls) # Parsing matplotlibrc. + except (SyntaxError, ValueError): + pass # Will error with the ValueError at the end. + + def _is_iterable_not_string_like(x): + # Explicitly exclude bytes/bytearrays so that they are not + # nonsensically interpreted as sequences of numbers (codepoints). + return np.iterable(x) and not isinstance(x, (str, bytes, bytearray)) + + if _is_iterable_not_string_like(ls): + if len(ls) == 2 and _is_iterable_not_string_like(ls[1]): + # (offset, (on, off, on, off, ...)) + offset, onoff = ls + else: + # For backcompat: (on, off, on, off, ...); the offset is implicit. + offset = 0 + onoff = ls + + if (isinstance(offset, Real) + and len(onoff) % 2 == 0 + and all(isinstance(elem, Real) for elem in onoff)): + return (offset, onoff) + + raise ValueError(f"linestyle {ls!r} is not a valid on-off ink sequence.") + + +validate_fillstyle = ValidateInStrings( + 'markers.fillstyle', ['full', 'left', 'right', 'bottom', 'top', 'none']) + + +validate_fillstylelist = _listify_validator(validate_fillstyle) + + +def validate_markevery(s): + """ + Validate the markevery property of a Line2D object. + + Parameters + ---------- + s : None, int, (int, int), slice, float, (float, float), or list[int] + + Returns + ------- + None, int, (int, int), slice, float, (float, float), or list[int] + """ + # Validate s against type slice float int and None + if isinstance(s, (slice, float, int, type(None))): + return s + # Validate s against type tuple + if isinstance(s, tuple): + if (len(s) == 2 + and (all(isinstance(e, int) for e in s) + or all(isinstance(e, float) for e in s))): + return s + else: + raise TypeError( + "'markevery' tuple must be pair of ints or of floats") + # Validate s against type list + if isinstance(s, list): + if all(isinstance(e, int) for e in s): + return s + else: + raise TypeError( + "'markevery' list must have all elements of type int") + raise TypeError("'markevery' is of an invalid type") + + +validate_markeverylist = _listify_validator(validate_markevery) + + +def validate_bbox(s): + if isinstance(s, str): + s = s.lower() + if s == 'tight': + return s + if s == 'standard': + return None + raise ValueError("bbox should be 'tight' or 'standard'") + elif s is not None: + # Backwards compatibility. None is equivalent to 'standard'. + raise ValueError("bbox should be 'tight' or 'standard'") + return s + + +def validate_sketch(s): + + if isinstance(s, str): + s = s.lower().strip() + if s.startswith("(") and s.endswith(")"): + s = s[1:-1] + if s == 'none' or s is None: + return None + try: + return tuple(_listify_validator(validate_float, n=3)(s)) + except ValueError as exc: + raise ValueError("Expected a (scale, length, randomness) tuple") from exc + + +def _validate_greaterthan_minushalf(s): + s = validate_float(s) + if s > -0.5: + return s + else: + raise RuntimeError(f'Value must be >-0.5; got {s}') + + +def _validate_greaterequal0_lessequal1(s): + s = validate_float(s) + if 0 <= s <= 1: + return s + else: + raise RuntimeError(f'Value must be >=0 and <=1; got {s}') + + +def _validate_int_greaterequal0(s): + s = validate_int(s) + if s >= 0: + return s + else: + raise RuntimeError(f'Value must be >=0; got {s}') + + +def validate_hatch(s): + r""" + Validate a hatch pattern. + A hatch pattern string can have any sequence of the following + characters: ``\ / | - + * . x o O``. + """ + if not isinstance(s, str): + raise ValueError("Hatch pattern must be a string") + _api.check_isinstance(str, hatch_pattern=s) + unknown = set(s) - {'\\', '/', '|', '-', '+', '*', '.', 'x', 'o', 'O'} + if unknown: + raise ValueError("Unknown hatch symbol(s): %s" % list(unknown)) + return s + + +validate_hatchlist = _listify_validator(validate_hatch) +validate_dashlist = _listify_validator(validate_floatlist) + + +def _validate_minor_tick_ndivs(n): + """ + Validate ndiv parameter related to the minor ticks. + It controls the number of minor ticks to be placed between + two major ticks. + """ + + if cbook._str_lower_equal(n, 'auto'): + return n + try: + n = _validate_int_greaterequal0(n) + return n + except (RuntimeError, ValueError): + pass + + raise ValueError("'tick.minor.ndivs' must be 'auto' or non-negative int") + + +_prop_validators = { + 'color': _listify_validator(validate_color_for_prop_cycle, + allow_stringlist=True), + 'linewidth': validate_floatlist, + 'linestyle': _listify_validator(_validate_linestyle), + 'facecolor': validate_colorlist, + 'edgecolor': validate_colorlist, + 'joinstyle': _listify_validator(JoinStyle), + 'capstyle': _listify_validator(CapStyle), + 'fillstyle': validate_fillstylelist, + 'markerfacecolor': validate_colorlist, + 'markersize': validate_floatlist, + 'markeredgewidth': validate_floatlist, + 'markeredgecolor': validate_colorlist, + 'markevery': validate_markeverylist, + 'alpha': validate_floatlist, + 'marker': _validate_markerlist, + 'hatch': validate_hatchlist, + 'dashes': validate_dashlist, + } +_prop_aliases = { + 'c': 'color', + 'lw': 'linewidth', + 'ls': 'linestyle', + 'fc': 'facecolor', + 'ec': 'edgecolor', + 'mfc': 'markerfacecolor', + 'mec': 'markeredgecolor', + 'mew': 'markeredgewidth', + 'ms': 'markersize', + } + + +def cycler(*args, **kwargs): + """ + Create a `~cycler.Cycler` object much like :func:`cycler.cycler`, + but includes input validation. + + Call signatures:: + + cycler(cycler) + cycler(label=values, label2=values2, ...) + cycler(label, values) + + Form 1 copies a given `~cycler.Cycler` object. + + Form 2 creates a `~cycler.Cycler` which cycles over one or more + properties simultaneously. If multiple properties are given, their + value lists must have the same length. + + Form 3 creates a `~cycler.Cycler` for a single property. This form + exists for compatibility with the original cycler. Its use is + discouraged in favor of the kwarg form, i.e. ``cycler(label=values)``. + + Parameters + ---------- + cycler : Cycler + Copy constructor for Cycler. + + label : str + The property key. Must be a valid `.Artist` property. + For example, 'color' or 'linestyle'. Aliases are allowed, + such as 'c' for 'color' and 'lw' for 'linewidth'. + + values : iterable + Finite-length iterable of the property values. These values + are validated and will raise a ValueError if invalid. + + Returns + ------- + Cycler + A new :class:`~cycler.Cycler` for the given properties. + + Examples + -------- + Creating a cycler for a single property: + + >>> c = cycler(color=['red', 'green', 'blue']) + + Creating a cycler for simultaneously cycling over multiple properties + (e.g. red circle, green plus, blue cross): + + >>> c = cycler(color=['red', 'green', 'blue'], + ... marker=['o', '+', 'x']) + + """ + if args and kwargs: + raise TypeError("cycler() can only accept positional OR keyword " + "arguments -- not both.") + elif not args and not kwargs: + raise TypeError("cycler() must have positional OR keyword arguments") + + if len(args) == 1: + if not isinstance(args[0], Cycler): + raise TypeError("If only one positional argument given, it must " + "be a Cycler instance.") + return validate_cycler(args[0]) + elif len(args) == 2: + pairs = [(args[0], args[1])] + elif len(args) > 2: + raise _api.nargs_error('cycler', '0-2', len(args)) + else: + pairs = kwargs.items() + + validated = [] + for prop, vals in pairs: + norm_prop = _prop_aliases.get(prop, prop) + validator = _prop_validators.get(norm_prop, None) + if validator is None: + raise TypeError("Unknown artist property: %s" % prop) + vals = validator(vals) + # We will normalize the property names as well to reduce + # the amount of alias handling code elsewhere. + validated.append((norm_prop, vals)) + + return reduce(operator.add, (ccycler(k, v) for k, v in validated)) + + +class _DunderChecker(ast.NodeVisitor): + def visit_Attribute(self, node): + if node.attr.startswith("__") and node.attr.endswith("__"): + raise ValueError("cycler strings with dunders are forbidden") + self.generic_visit(node) + + +# A validator dedicated to the named legend loc +_validate_named_legend_loc = ValidateInStrings( + 'legend.loc', + [ + "best", + "upper right", "upper left", "lower left", "lower right", "right", + "center left", "center right", "lower center", "upper center", + "center"], + ignorecase=True) + + +def _validate_legend_loc(loc): + """ + Confirm that loc is a type which rc.Params["legend.loc"] supports. + + .. versionadded:: 3.8 + + Parameters + ---------- + loc : str | int | (float, float) | str((float, float)) + The location of the legend. + + Returns + ------- + loc : str | int | (float, float) or raise ValueError exception + The location of the legend. + """ + if isinstance(loc, str): + try: + return _validate_named_legend_loc(loc) + except ValueError: + pass + try: + loc = ast.literal_eval(loc) + except (SyntaxError, ValueError): + pass + if isinstance(loc, int): + if 0 <= loc <= 10: + return loc + if isinstance(loc, tuple): + if len(loc) == 2 and all(isinstance(e, Real) for e in loc): + return loc + raise ValueError(f"{loc} is not a valid legend location.") + + +def validate_cycler(s): + """Return a Cycler object from a string repr or the object itself.""" + if isinstance(s, str): + # TODO: We might want to rethink this... + # While I think I have it quite locked down, it is execution of + # arbitrary code without sanitation. + # Combine this with the possibility that rcparams might come from the + # internet (future plans), this could be downright dangerous. + # I locked it down by only having the 'cycler()' function available. + # UPDATE: Partly plugging a security hole. + # I really should have read this: + # https://nedbatchelder.com/blog/201206/eval_really_is_dangerous.html + # We should replace this eval with a combo of PyParsing and + # ast.literal_eval() + try: + _DunderChecker().visit(ast.parse(s)) + s = eval(s, {'cycler': cycler, '__builtins__': {}}) + except BaseException as e: + raise ValueError(f"{s!r} is not a valid cycler construction: {e}" + ) from e + # Should make sure what comes from the above eval() + # is a Cycler object. + if isinstance(s, Cycler): + cycler_inst = s + else: + raise ValueError(f"Object is not a string or Cycler instance: {s!r}") + + unknowns = cycler_inst.keys - (set(_prop_validators) | set(_prop_aliases)) + if unknowns: + raise ValueError("Unknown artist properties: %s" % unknowns) + + # Not a full validation, but it'll at least normalize property names + # A fuller validation would require v0.10 of cycler. + checker = set() + for prop in cycler_inst.keys: + norm_prop = _prop_aliases.get(prop, prop) + if norm_prop != prop and norm_prop in cycler_inst.keys: + raise ValueError(f"Cannot specify both {norm_prop!r} and alias " + f"{prop!r} in the same prop_cycle") + if norm_prop in checker: + raise ValueError(f"Another property was already aliased to " + f"{norm_prop!r}. Collision normalizing {prop!r}.") + checker.update([norm_prop]) + + # This is just an extra-careful check, just in case there is some + # edge-case I haven't thought of. + assert len(checker) == len(cycler_inst.keys) + + # Now, it should be safe to mutate this cycler + for prop in cycler_inst.keys: + norm_prop = _prop_aliases.get(prop, prop) + cycler_inst.change_key(prop, norm_prop) + + for key, vals in cycler_inst.by_key().items(): + _prop_validators[key](vals) + + return cycler_inst + + +def validate_hist_bins(s): + valid_strs = ["auto", "sturges", "fd", "doane", "scott", "rice", "sqrt"] + if isinstance(s, str) and s in valid_strs: + return s + try: + return int(s) + except (TypeError, ValueError): + pass + try: + return validate_floatlist(s) + except ValueError: + pass + raise ValueError(f"'hist.bins' must be one of {valid_strs}, an int or" + " a sequence of floats") + + +class _ignorecase(list): + """A marker class indicating that a list-of-str is case-insensitive.""" + + +def _convert_validator_spec(key, conv): + if isinstance(conv, list): + ignorecase = isinstance(conv, _ignorecase) + return ValidateInStrings(key, conv, ignorecase=ignorecase) + else: + return conv + + +# Mapping of rcParams to validators. +# Converters given as lists or _ignorecase are converted to ValidateInStrings +# immediately below. +# The rcParams defaults are defined in lib/matplotlib/mpl-data/matplotlibrc, which +# gets copied to matplotlib/mpl-data/matplotlibrc by the setup script. +_validators = { + "backend": validate_backend, + "backend_fallback": validate_bool, + "figure.hooks": validate_stringlist, + "toolbar": _validate_toolbar, + "interactive": validate_bool, + "timezone": validate_string, + + "webagg.port": validate_int, + "webagg.address": validate_string, + "webagg.open_in_browser": validate_bool, + "webagg.port_retries": validate_int, + + # line props + "lines.linewidth": validate_float, # line width in points + "lines.linestyle": _validate_linestyle, # solid line + "lines.color": validate_color, # first color in color cycle + "lines.marker": _validate_marker, # marker name + "lines.markerfacecolor": validate_color_or_auto, # default color + "lines.markeredgecolor": validate_color_or_auto, # default color + "lines.markeredgewidth": validate_float, + "lines.markersize": validate_float, # markersize, in points + "lines.antialiased": validate_bool, # antialiased (no jaggies) + "lines.dash_joinstyle": JoinStyle, + "lines.solid_joinstyle": JoinStyle, + "lines.dash_capstyle": CapStyle, + "lines.solid_capstyle": CapStyle, + "lines.dashed_pattern": validate_floatlist, + "lines.dashdot_pattern": validate_floatlist, + "lines.dotted_pattern": validate_floatlist, + "lines.scale_dashes": validate_bool, + + # marker props + "markers.fillstyle": validate_fillstyle, + + ## pcolor(mesh) props: + "pcolor.shading": ["auto", "flat", "nearest", "gouraud"], + "pcolormesh.snap": validate_bool, + + ## patch props + "patch.linewidth": validate_float, # line width in points + "patch.edgecolor": validate_color, + "patch.force_edgecolor": validate_bool, + "patch.facecolor": validate_color, # first color in cycle + "patch.antialiased": validate_bool, # antialiased (no jaggies) + + ## hatch props + "hatch.color": validate_color, + "hatch.linewidth": validate_float, + + ## Histogram properties + "hist.bins": validate_hist_bins, + + ## Boxplot properties + "boxplot.notch": validate_bool, + "boxplot.vertical": validate_bool, + "boxplot.whiskers": validate_whiskers, + "boxplot.bootstrap": validate_int_or_None, + "boxplot.patchartist": validate_bool, + "boxplot.showmeans": validate_bool, + "boxplot.showcaps": validate_bool, + "boxplot.showbox": validate_bool, + "boxplot.showfliers": validate_bool, + "boxplot.meanline": validate_bool, + + "boxplot.flierprops.color": validate_color, + "boxplot.flierprops.marker": _validate_marker, + "boxplot.flierprops.markerfacecolor": validate_color_or_auto, + "boxplot.flierprops.markeredgecolor": validate_color, + "boxplot.flierprops.markeredgewidth": validate_float, + "boxplot.flierprops.markersize": validate_float, + "boxplot.flierprops.linestyle": _validate_linestyle, + "boxplot.flierprops.linewidth": validate_float, + + "boxplot.boxprops.color": validate_color, + "boxplot.boxprops.linewidth": validate_float, + "boxplot.boxprops.linestyle": _validate_linestyle, + + "boxplot.whiskerprops.color": validate_color, + "boxplot.whiskerprops.linewidth": validate_float, + "boxplot.whiskerprops.linestyle": _validate_linestyle, + + "boxplot.capprops.color": validate_color, + "boxplot.capprops.linewidth": validate_float, + "boxplot.capprops.linestyle": _validate_linestyle, + + "boxplot.medianprops.color": validate_color, + "boxplot.medianprops.linewidth": validate_float, + "boxplot.medianprops.linestyle": _validate_linestyle, + + "boxplot.meanprops.color": validate_color, + "boxplot.meanprops.marker": _validate_marker, + "boxplot.meanprops.markerfacecolor": validate_color, + "boxplot.meanprops.markeredgecolor": validate_color, + "boxplot.meanprops.markersize": validate_float, + "boxplot.meanprops.linestyle": _validate_linestyle, + "boxplot.meanprops.linewidth": validate_float, + + ## font props + "font.family": validate_stringlist, # used by text object + "font.style": validate_string, + "font.variant": validate_string, + "font.stretch": validate_fontstretch, + "font.weight": validate_fontweight, + "font.size": validate_float, # Base font size in points + "font.serif": validate_stringlist, + "font.sans-serif": validate_stringlist, + "font.cursive": validate_stringlist, + "font.fantasy": validate_stringlist, + "font.monospace": validate_stringlist, + + # text props + "text.color": validate_color, + "text.usetex": validate_bool, + "text.latex.preamble": validate_string, + "text.hinting": ["default", "no_autohint", "force_autohint", + "no_hinting", "auto", "native", "either", "none"], + "text.hinting_factor": validate_int, + "text.kerning_factor": validate_int, + "text.antialiased": validate_bool, + "text.parse_math": validate_bool, + + "mathtext.cal": validate_font_properties, + "mathtext.rm": validate_font_properties, + "mathtext.tt": validate_font_properties, + "mathtext.it": validate_font_properties, + "mathtext.bf": validate_font_properties, + "mathtext.bfit": validate_font_properties, + "mathtext.sf": validate_font_properties, + "mathtext.fontset": ["dejavusans", "dejavuserif", "cm", "stix", + "stixsans", "custom"], + "mathtext.default": ["rm", "cal", "bfit", "it", "tt", "sf", "bf", "default", + "bb", "frak", "scr", "regular"], + "mathtext.fallback": _validate_mathtext_fallback, + + "image.aspect": validate_aspect, # equal, auto, a number + "image.interpolation": validate_string, + "image.interpolation_stage": ["auto", "data", "rgba"], + "image.cmap": _validate_cmap, # gray, jet, etc. + "image.lut": validate_int, # lookup table + "image.origin": ["upper", "lower"], + "image.resample": validate_bool, + # Specify whether vector graphics backends will combine all images on a + # set of Axes into a single composite image + "image.composite_image": validate_bool, + + # contour props + "contour.negative_linestyle": _validate_linestyle, + "contour.corner_mask": validate_bool, + "contour.linewidth": validate_float_or_None, + "contour.algorithm": ["mpl2005", "mpl2014", "serial", "threaded"], + + # errorbar props + "errorbar.capsize": validate_float, + + # axis props + # alignment of x/y axis title + "xaxis.labellocation": ["left", "center", "right"], + "yaxis.labellocation": ["bottom", "center", "top"], + + # Axes props + "axes.axisbelow": validate_axisbelow, + "axes.facecolor": validate_color, # background color + "axes.edgecolor": validate_color, # edge color + "axes.linewidth": validate_float, # edge linewidth + + "axes.spines.left": validate_bool, # Set visibility of axes spines, + "axes.spines.right": validate_bool, # i.e., the lines around the chart + "axes.spines.bottom": validate_bool, # denoting data boundary. + "axes.spines.top": validate_bool, + + "axes.titlesize": validate_fontsize, # Axes title fontsize + "axes.titlelocation": ["left", "center", "right"], # Axes title alignment + "axes.titleweight": validate_fontweight, # Axes title font weight + "axes.titlecolor": validate_color_or_auto, # Axes title font color + # title location, axes units, None means auto + "axes.titley": validate_float_or_None, + # pad from Axes top decoration to title in points + "axes.titlepad": validate_float, + "axes.grid": validate_bool, # display grid or not + "axes.grid.which": ["minor", "both", "major"], # which grids are drawn + "axes.grid.axis": ["x", "y", "both"], # grid type + "axes.labelsize": validate_fontsize, # fontsize of x & y labels + "axes.labelpad": validate_float, # space between label and axis + "axes.labelweight": validate_fontweight, # fontsize of x & y labels + "axes.labelcolor": validate_color, # color of axis label + # use scientific notation if log10 of the axis range is smaller than the + # first or larger than the second + "axes.formatter.limits": _listify_validator(validate_int, n=2), + # use current locale to format ticks + "axes.formatter.use_locale": validate_bool, + "axes.formatter.use_mathtext": validate_bool, + # minimum exponent to format in scientific notation + "axes.formatter.min_exponent": validate_int, + "axes.formatter.useoffset": validate_bool, + "axes.formatter.offset_threshold": validate_int, + "axes.unicode_minus": validate_bool, + # This entry can be either a cycler object or a string repr of a + # cycler-object, which gets eval()'ed to create the object. + "axes.prop_cycle": validate_cycler, + # If "data", axes limits are set close to the data. + # If "round_numbers" axes limits are set to the nearest round numbers. + "axes.autolimit_mode": ["data", "round_numbers"], + "axes.xmargin": _validate_greaterthan_minushalf, # margin added to xaxis + "axes.ymargin": _validate_greaterthan_minushalf, # margin added to yaxis + "axes.zmargin": _validate_greaterthan_minushalf, # margin added to zaxis + + "polaraxes.grid": validate_bool, # display polar grid or not + "axes3d.grid": validate_bool, # display 3d grid + "axes3d.automargin": validate_bool, # automatically add margin when + # manually setting 3D axis limits + + "axes3d.xaxis.panecolor": validate_color, # 3d background pane + "axes3d.yaxis.panecolor": validate_color, # 3d background pane + "axes3d.zaxis.panecolor": validate_color, # 3d background pane + + "axes3d.mouserotationstyle": ["azel", "trackball", "sphere", "arcball"], + "axes3d.trackballsize": validate_float, + "axes3d.trackballborder": validate_float, + + # scatter props + "scatter.marker": _validate_marker, + "scatter.edgecolors": validate_string, + + "date.epoch": _validate_date, + "date.autoformatter.year": validate_string, + "date.autoformatter.month": validate_string, + "date.autoformatter.day": validate_string, + "date.autoformatter.hour": validate_string, + "date.autoformatter.minute": validate_string, + "date.autoformatter.second": validate_string, + "date.autoformatter.microsecond": validate_string, + + 'date.converter': ['auto', 'concise'], + # for auto date locator, choose interval_multiples + 'date.interval_multiples': validate_bool, + + # legend properties + "legend.fancybox": validate_bool, + "legend.loc": _validate_legend_loc, + + # the number of points in the legend line + "legend.numpoints": validate_int, + # the number of points in the legend line for scatter + "legend.scatterpoints": validate_int, + "legend.fontsize": validate_fontsize, + "legend.title_fontsize": validate_fontsize_None, + # color of the legend + "legend.labelcolor": _validate_color_or_linecolor, + # the relative size of legend markers vs. original + "legend.markerscale": validate_float, + # using dict in rcParams not yet supported, so make sure it is bool + "legend.shadow": validate_bool, + # whether or not to draw a frame around legend + "legend.frameon": validate_bool, + # alpha value of the legend frame + "legend.framealpha": validate_float_or_None, + + ## the following dimensions are in fraction of the font size + "legend.borderpad": validate_float, # units are fontsize + # the vertical space between the legend entries + "legend.labelspacing": validate_float, + # the length of the legend lines + "legend.handlelength": validate_float, + # the length of the legend lines + "legend.handleheight": validate_float, + # the space between the legend line and legend text + "legend.handletextpad": validate_float, + # the border between the Axes and legend edge + "legend.borderaxespad": validate_float, + # the border between the Axes and legend edge + "legend.columnspacing": validate_float, + "legend.facecolor": validate_color_or_inherit, + "legend.edgecolor": validate_color_or_inherit, + + # tick properties + "xtick.top": validate_bool, # draw ticks on top side + "xtick.bottom": validate_bool, # draw ticks on bottom side + "xtick.labeltop": validate_bool, # draw label on top + "xtick.labelbottom": validate_bool, # draw label on bottom + "xtick.major.size": validate_float, # major xtick size in points + "xtick.minor.size": validate_float, # minor xtick size in points + "xtick.major.width": validate_float, # major xtick width in points + "xtick.minor.width": validate_float, # minor xtick width in points + "xtick.major.pad": validate_float, # distance to label in points + "xtick.minor.pad": validate_float, # distance to label in points + "xtick.color": validate_color, # color of xticks + "xtick.labelcolor": validate_color_or_inherit, # color of xtick labels + "xtick.minor.visible": validate_bool, # visibility of minor xticks + "xtick.minor.top": validate_bool, # draw top minor xticks + "xtick.minor.bottom": validate_bool, # draw bottom minor xticks + "xtick.major.top": validate_bool, # draw top major xticks + "xtick.major.bottom": validate_bool, # draw bottom major xticks + # number of minor xticks + "xtick.minor.ndivs": _validate_minor_tick_ndivs, + "xtick.labelsize": validate_fontsize, # fontsize of xtick labels + "xtick.direction": ["out", "in", "inout"], # direction of xticks + "xtick.alignment": ["center", "right", "left"], + + "ytick.left": validate_bool, # draw ticks on left side + "ytick.right": validate_bool, # draw ticks on right side + "ytick.labelleft": validate_bool, # draw tick labels on left side + "ytick.labelright": validate_bool, # draw tick labels on right side + "ytick.major.size": validate_float, # major ytick size in points + "ytick.minor.size": validate_float, # minor ytick size in points + "ytick.major.width": validate_float, # major ytick width in points + "ytick.minor.width": validate_float, # minor ytick width in points + "ytick.major.pad": validate_float, # distance to label in points + "ytick.minor.pad": validate_float, # distance to label in points + "ytick.color": validate_color, # color of yticks + "ytick.labelcolor": validate_color_or_inherit, # color of ytick labels + "ytick.minor.visible": validate_bool, # visibility of minor yticks + "ytick.minor.left": validate_bool, # draw left minor yticks + "ytick.minor.right": validate_bool, # draw right minor yticks + "ytick.major.left": validate_bool, # draw left major yticks + "ytick.major.right": validate_bool, # draw right major yticks + # number of minor yticks + "ytick.minor.ndivs": _validate_minor_tick_ndivs, + "ytick.labelsize": validate_fontsize, # fontsize of ytick labels + "ytick.direction": ["out", "in", "inout"], # direction of yticks + "ytick.alignment": [ + "center", "top", "bottom", "baseline", "center_baseline"], + + "grid.color": validate_color, # grid color + "grid.linestyle": _validate_linestyle, # solid + "grid.linewidth": validate_float, # in points + "grid.alpha": validate_float, + + ## figure props + # figure title + "figure.titlesize": validate_fontsize, + "figure.titleweight": validate_fontweight, + + # figure labels + "figure.labelsize": validate_fontsize, + "figure.labelweight": validate_fontweight, + + # figure size in inches: width by height + "figure.figsize": _listify_validator(validate_float, n=2), + "figure.dpi": validate_float, + "figure.facecolor": validate_color, + "figure.edgecolor": validate_color, + "figure.frameon": validate_bool, + "figure.autolayout": validate_bool, + "figure.max_open_warning": validate_int, + "figure.raise_window": validate_bool, + "macosx.window_mode": ["system", "tab", "window"], + + "figure.subplot.left": validate_float, + "figure.subplot.right": validate_float, + "figure.subplot.bottom": validate_float, + "figure.subplot.top": validate_float, + "figure.subplot.wspace": validate_float, + "figure.subplot.hspace": validate_float, + + "figure.constrained_layout.use": validate_bool, # run constrained_layout? + # wspace and hspace are fraction of adjacent subplots to use for space. + # Much smaller than above because we don't need room for the text. + "figure.constrained_layout.hspace": validate_float, + "figure.constrained_layout.wspace": validate_float, + # buffer around the Axes, in inches. + "figure.constrained_layout.h_pad": validate_float, + "figure.constrained_layout.w_pad": validate_float, + + ## Saving figure's properties + 'savefig.dpi': validate_dpi, + 'savefig.facecolor': validate_color_or_auto, + 'savefig.edgecolor': validate_color_or_auto, + 'savefig.orientation': ['landscape', 'portrait'], + "savefig.format": validate_string, + "savefig.bbox": validate_bbox, # "tight", or "standard" (= None) + "savefig.pad_inches": validate_float, + # default directory in savefig dialog box + "savefig.directory": _validate_pathlike, + "savefig.transparent": validate_bool, + + "tk.window_focus": validate_bool, # Maintain shell focus for TkAgg + + # Set the papersize/type + "ps.papersize": _ignorecase( + ["figure", "letter", "legal", "ledger", + *[f"{ab}{i}" for ab in "ab" for i in range(11)]]), + "ps.useafm": validate_bool, + # use ghostscript or xpdf to distill ps output + "ps.usedistiller": validate_ps_distiller, + "ps.distiller.res": validate_int, # dpi + "ps.fonttype": validate_fonttype, # 3 (Type3) or 42 (Truetype) + "pdf.compression": validate_int, # 0-9 compression level; 0 to disable + "pdf.inheritcolor": validate_bool, # skip color setting commands + # use only the 14 PDF core fonts embedded in every PDF viewing application + "pdf.use14corefonts": validate_bool, + "pdf.fonttype": validate_fonttype, # 3 (Type3) or 42 (Truetype) + + "pgf.texsystem": ["xelatex", "lualatex", "pdflatex"], # latex variant used + "pgf.rcfonts": validate_bool, # use mpl's rc settings for font config + "pgf.preamble": validate_string, # custom LaTeX preamble + + # write raster image data into the svg file + "svg.image_inline": validate_bool, + "svg.fonttype": ["none", "path"], # save text as text ("none") or "paths" + "svg.hashsalt": validate_string_or_None, + "svg.id": validate_string_or_None, + + # set this when you want to generate hardcopy docstring + "docstring.hardcopy": validate_bool, + + "path.simplify": validate_bool, + "path.simplify_threshold": _validate_greaterequal0_lessequal1, + "path.snap": validate_bool, + "path.sketch": validate_sketch, + "path.effects": validate_anylist, + "agg.path.chunksize": validate_int, # 0 to disable chunking + + # key-mappings (multi-character mappings should be a list/tuple) + "keymap.fullscreen": validate_stringlist, + "keymap.home": validate_stringlist, + "keymap.back": validate_stringlist, + "keymap.forward": validate_stringlist, + "keymap.pan": validate_stringlist, + "keymap.zoom": validate_stringlist, + "keymap.save": validate_stringlist, + "keymap.quit": validate_stringlist, + "keymap.quit_all": validate_stringlist, # e.g.: "W", "cmd+W", "Q" + "keymap.grid": validate_stringlist, + "keymap.grid_minor": validate_stringlist, + "keymap.yscale": validate_stringlist, + "keymap.xscale": validate_stringlist, + "keymap.help": validate_stringlist, + "keymap.copy": validate_stringlist, + + # Animation settings + "animation.html": ["html5", "jshtml", "none"], + # Limit, in MB, of size of base64 encoded animation in HTML + # (i.e. IPython notebook) + "animation.embed_limit": validate_float, + "animation.writer": validate_string, + "animation.codec": validate_string, + "animation.bitrate": validate_int, + # Controls image format when frames are written to disk + "animation.frame_format": ["png", "jpeg", "tiff", "raw", "rgba", "ppm", + "sgi", "bmp", "pbm", "svg"], + # Path to ffmpeg binary. If just binary name, subprocess uses $PATH. + "animation.ffmpeg_path": _validate_pathlike, + # Additional arguments for ffmpeg movie writer (using pipes) + "animation.ffmpeg_args": validate_stringlist, + # Path to convert binary. If just binary name, subprocess uses $PATH. + "animation.convert_path": _validate_pathlike, + # Additional arguments for convert movie writer (using pipes) + "animation.convert_args": validate_stringlist, + + # Classic (pre 2.0) compatibility mode + # This is used for things that are hard to make backward compatible + # with a sane rcParam alone. This does *not* turn on classic mode + # altogether. For that use `matplotlib.style.use("classic")`. + "_internal.classic_mode": validate_bool +} +_hardcoded_defaults = { # Defaults not inferred from + # lib/matplotlib/mpl-data/matplotlibrc... + # ... because they are private: + "_internal.classic_mode": False, + # ... because they are deprecated: + # No current deprecations. + # backend is handled separately when constructing rcParamsDefault. +} +_validators = {k: _convert_validator_spec(k, conv) + for k, conv in _validators.items()} diff --git a/infer_4_30_0/lib/python3.10/site-packages/matplotlib/sankey.py b/infer_4_30_0/lib/python3.10/site-packages/matplotlib/sankey.py new file mode 100644 index 0000000000000000000000000000000000000000..637cfc849f9dc8ef3916883d5870bcbdde67e632 --- /dev/null +++ b/infer_4_30_0/lib/python3.10/site-packages/matplotlib/sankey.py @@ -0,0 +1,814 @@ +""" +Module for creating Sankey diagrams using Matplotlib. +""" + +import logging +from types import SimpleNamespace + +import numpy as np + +import matplotlib as mpl +from matplotlib.path import Path +from matplotlib.patches import PathPatch +from matplotlib.transforms import Affine2D +from matplotlib import _docstring + +_log = logging.getLogger(__name__) + +__author__ = "Kevin L. Davies" +__credits__ = ["Yannick Copin"] +__license__ = "BSD" +__version__ = "2011/09/16" + +# Angles [deg/90] +RIGHT = 0 +UP = 1 +# LEFT = 2 +DOWN = 3 + + +class Sankey: + """ + Sankey diagram. + + Sankey diagrams are a specific type of flow diagram, in which + the width of the arrows is shown proportionally to the flow + quantity. They are typically used to visualize energy or + material or cost transfers between processes. + `Wikipedia (6/1/2011) `_ + + """ + + def __init__(self, ax=None, scale=1.0, unit='', format='%G', gap=0.25, + radius=0.1, shoulder=0.03, offset=0.15, head_angle=100, + margin=0.4, tolerance=1e-6, **kwargs): + """ + Create a new Sankey instance. + + The optional arguments listed below are applied to all subdiagrams so + that there is consistent alignment and formatting. + + In order to draw a complex Sankey diagram, create an instance of + `Sankey` by calling it without any kwargs:: + + sankey = Sankey() + + Then add simple Sankey sub-diagrams:: + + sankey.add() # 1 + sankey.add() # 2 + #... + sankey.add() # n + + Finally, create the full diagram:: + + sankey.finish() + + Or, instead, simply daisy-chain those calls:: + + Sankey().add().add... .add().finish() + + Other Parameters + ---------------- + ax : `~matplotlib.axes.Axes` + Axes onto which the data should be plotted. If *ax* isn't + provided, new Axes will be created. + scale : float + Scaling factor for the flows. *scale* sizes the width of the paths + in order to maintain proper layout. The same scale is applied to + all subdiagrams. The value should be chosen such that the product + of the scale and the sum of the inputs is approximately 1.0 (and + the product of the scale and the sum of the outputs is + approximately -1.0). + unit : str + The physical unit associated with the flow quantities. If *unit* + is None, then none of the quantities are labeled. + format : str or callable + A Python number formatting string or callable used to label the + flows with their quantities (i.e., a number times a unit, where the + unit is given). If a format string is given, the label will be + ``format % quantity``. If a callable is given, it will be called + with ``quantity`` as an argument. + gap : float + Space between paths that break in/break away to/from the top or + bottom. + radius : float + Inner radius of the vertical paths. + shoulder : float + Size of the shoulders of output arrows. + offset : float + Text offset (from the dip or tip of the arrow). + head_angle : float + Angle, in degrees, of the arrow heads (and negative of the angle of + the tails). + margin : float + Minimum space between Sankey outlines and the edge of the plot + area. + tolerance : float + Acceptable maximum of the magnitude of the sum of flows. The + magnitude of the sum of connected flows cannot be greater than + *tolerance*. + **kwargs + Any additional keyword arguments will be passed to `add`, which + will create the first subdiagram. + + See Also + -------- + Sankey.add + Sankey.finish + + Examples + -------- + .. plot:: gallery/specialty_plots/sankey_basics.py + """ + # Check the arguments. + if gap < 0: + raise ValueError( + "'gap' is negative, which is not allowed because it would " + "cause the paths to overlap") + if radius > gap: + raise ValueError( + "'radius' is greater than 'gap', which is not allowed because " + "it would cause the paths to overlap") + if head_angle < 0: + raise ValueError( + "'head_angle' is negative, which is not allowed because it " + "would cause inputs to look like outputs and vice versa") + if tolerance < 0: + raise ValueError( + "'tolerance' is negative, but it must be a magnitude") + + # Create Axes if necessary. + if ax is None: + import matplotlib.pyplot as plt + fig = plt.figure() + ax = fig.add_subplot(1, 1, 1, xticks=[], yticks=[]) + + self.diagrams = [] + + # Store the inputs. + self.ax = ax + self.unit = unit + self.format = format + self.scale = scale + self.gap = gap + self.radius = radius + self.shoulder = shoulder + self.offset = offset + self.margin = margin + self.pitch = np.tan(np.pi * (1 - head_angle / 180.0) / 2.0) + self.tolerance = tolerance + + # Initialize the vertices of tight box around the diagram(s). + self.extent = np.array((np.inf, -np.inf, np.inf, -np.inf)) + + # If there are any kwargs, create the first subdiagram. + if len(kwargs): + self.add(**kwargs) + + def _arc(self, quadrant=0, cw=True, radius=1, center=(0, 0)): + """ + Return the codes and vertices for a rotated, scaled, and translated + 90 degree arc. + + Other Parameters + ---------------- + quadrant : {0, 1, 2, 3}, default: 0 + Uses 0-based indexing (0, 1, 2, or 3). + cw : bool, default: True + If True, the arc vertices are produced clockwise; counter-clockwise + otherwise. + radius : float, default: 1 + The radius of the arc. + center : (float, float), default: (0, 0) + (x, y) tuple of the arc's center. + """ + # Note: It would be possible to use matplotlib's transforms to rotate, + # scale, and translate the arc, but since the angles are discrete, + # it's just as easy and maybe more efficient to do it here. + ARC_CODES = [Path.LINETO, + Path.CURVE4, + Path.CURVE4, + Path.CURVE4, + Path.CURVE4, + Path.CURVE4, + Path.CURVE4] + # Vertices of a cubic Bezier curve approximating a 90 deg arc + # These can be determined by Path.arc(0, 90). + ARC_VERTICES = np.array([[1.00000000e+00, 0.00000000e+00], + [1.00000000e+00, 2.65114773e-01], + [8.94571235e-01, 5.19642327e-01], + [7.07106781e-01, 7.07106781e-01], + [5.19642327e-01, 8.94571235e-01], + [2.65114773e-01, 1.00000000e+00], + # Insignificant + # [6.12303177e-17, 1.00000000e+00]]) + [0.00000000e+00, 1.00000000e+00]]) + if quadrant in (0, 2): + if cw: + vertices = ARC_VERTICES + else: + vertices = ARC_VERTICES[:, ::-1] # Swap x and y. + else: # 1, 3 + # Negate x. + if cw: + # Swap x and y. + vertices = np.column_stack((-ARC_VERTICES[:, 1], + ARC_VERTICES[:, 0])) + else: + vertices = np.column_stack((-ARC_VERTICES[:, 0], + ARC_VERTICES[:, 1])) + if quadrant > 1: + radius = -radius # Rotate 180 deg. + return list(zip(ARC_CODES, radius * vertices + + np.tile(center, (ARC_VERTICES.shape[0], 1)))) + + def _add_input(self, path, angle, flow, length): + """ + Add an input to a path and return its tip and label locations. + """ + if angle is None: + return [0, 0], [0, 0] + else: + x, y = path[-1][1] # Use the last point as a reference. + dipdepth = (flow / 2) * self.pitch + if angle == RIGHT: + x -= length + dip = [x + dipdepth, y + flow / 2.0] + path.extend([(Path.LINETO, [x, y]), + (Path.LINETO, dip), + (Path.LINETO, [x, y + flow]), + (Path.LINETO, [x + self.gap, y + flow])]) + label_location = [dip[0] - self.offset, dip[1]] + else: # Vertical + x -= self.gap + if angle == UP: + sign = 1 + else: + sign = -1 + + dip = [x - flow / 2, y - sign * (length - dipdepth)] + if angle == DOWN: + quadrant = 2 + else: + quadrant = 1 + + # Inner arc isn't needed if inner radius is zero + if self.radius: + path.extend(self._arc(quadrant=quadrant, + cw=angle == UP, + radius=self.radius, + center=(x + self.radius, + y - sign * self.radius))) + else: + path.append((Path.LINETO, [x, y])) + path.extend([(Path.LINETO, [x, y - sign * length]), + (Path.LINETO, dip), + (Path.LINETO, [x - flow, y - sign * length])]) + path.extend(self._arc(quadrant=quadrant, + cw=angle == DOWN, + radius=flow + self.radius, + center=(x + self.radius, + y - sign * self.radius))) + path.append((Path.LINETO, [x - flow, y + sign * flow])) + label_location = [dip[0], dip[1] - sign * self.offset] + + return dip, label_location + + def _add_output(self, path, angle, flow, length): + """ + Append an output to a path and return its tip and label locations. + + .. note:: *flow* is negative for an output. + """ + if angle is None: + return [0, 0], [0, 0] + else: + x, y = path[-1][1] # Use the last point as a reference. + tipheight = (self.shoulder - flow / 2) * self.pitch + if angle == RIGHT: + x += length + tip = [x + tipheight, y + flow / 2.0] + path.extend([(Path.LINETO, [x, y]), + (Path.LINETO, [x, y + self.shoulder]), + (Path.LINETO, tip), + (Path.LINETO, [x, y - self.shoulder + flow]), + (Path.LINETO, [x, y + flow]), + (Path.LINETO, [x - self.gap, y + flow])]) + label_location = [tip[0] + self.offset, tip[1]] + else: # Vertical + x += self.gap + if angle == UP: + sign, quadrant = 1, 3 + else: + sign, quadrant = -1, 0 + + tip = [x - flow / 2.0, y + sign * (length + tipheight)] + # Inner arc isn't needed if inner radius is zero + if self.radius: + path.extend(self._arc(quadrant=quadrant, + cw=angle == UP, + radius=self.radius, + center=(x - self.radius, + y + sign * self.radius))) + else: + path.append((Path.LINETO, [x, y])) + path.extend([(Path.LINETO, [x, y + sign * length]), + (Path.LINETO, [x - self.shoulder, + y + sign * length]), + (Path.LINETO, tip), + (Path.LINETO, [x + self.shoulder - flow, + y + sign * length]), + (Path.LINETO, [x - flow, y + sign * length])]) + path.extend(self._arc(quadrant=quadrant, + cw=angle == DOWN, + radius=self.radius - flow, + center=(x - self.radius, + y + sign * self.radius))) + path.append((Path.LINETO, [x - flow, y + sign * flow])) + label_location = [tip[0], tip[1] + sign * self.offset] + return tip, label_location + + def _revert(self, path, first_action=Path.LINETO): + """ + A path is not simply reversible by path[::-1] since the code + specifies an action to take from the **previous** point. + """ + reverse_path = [] + next_code = first_action + for code, position in path[::-1]: + reverse_path.append((next_code, position)) + next_code = code + return reverse_path + # This might be more efficient, but it fails because 'tuple' object + # doesn't support item assignment: + # path[1] = path[1][-1:0:-1] + # path[1][0] = first_action + # path[2] = path[2][::-1] + # return path + + @_docstring.interpd + def add(self, patchlabel='', flows=None, orientations=None, labels='', + trunklength=1.0, pathlengths=0.25, prior=None, connect=(0, 0), + rotation=0, **kwargs): + """ + Add a simple Sankey diagram with flows at the same hierarchical level. + + Parameters + ---------- + patchlabel : str + Label to be placed at the center of the diagram. + Note that *label* (not *patchlabel*) can be passed as keyword + argument to create an entry in the legend. + + flows : list of float + Array of flow values. By convention, inputs are positive and + outputs are negative. + + Flows are placed along the top of the diagram from the inside out + in order of their index within *flows*. They are placed along the + sides of the diagram from the top down and along the bottom from + the outside in. + + If the sum of the inputs and outputs is + nonzero, the discrepancy will appear as a cubic Bézier curve along + the top and bottom edges of the trunk. + + orientations : list of {-1, 0, 1} + List of orientations of the flows (or a single orientation to be + used for all flows). Valid values are 0 (inputs from + the left, outputs to the right), 1 (from and to the top) or -1 + (from and to the bottom). + + labels : list of (str or None) + List of labels for the flows (or a single label to be used for all + flows). Each label may be *None* (no label), or a labeling string. + If an entry is a (possibly empty) string, then the quantity for the + corresponding flow will be shown below the string. However, if + the *unit* of the main diagram is None, then quantities are never + shown, regardless of the value of this argument. + + trunklength : float + Length between the bases of the input and output groups (in + data-space units). + + pathlengths : list of float + List of lengths of the vertical arrows before break-in or after + break-away. If a single value is given, then it will be applied to + the first (inside) paths on the top and bottom, and the length of + all other arrows will be justified accordingly. The *pathlengths* + are not applied to the horizontal inputs and outputs. + + prior : int + Index of the prior diagram to which this diagram should be + connected. + + connect : (int, int) + A (prior, this) tuple indexing the flow of the prior diagram and + the flow of this diagram which should be connected. If this is the + first diagram or *prior* is *None*, *connect* will be ignored. + + rotation : float + Angle of rotation of the diagram in degrees. The interpretation of + the *orientations* argument will be rotated accordingly (e.g., if + *rotation* == 90, an *orientations* entry of 1 means to/from the + left). *rotation* is ignored if this diagram is connected to an + existing one (using *prior* and *connect*). + + Returns + ------- + Sankey + The current `.Sankey` instance. + + Other Parameters + ---------------- + **kwargs + Additional keyword arguments set `matplotlib.patches.PathPatch` + properties, listed below. For example, one may want to use + ``fill=False`` or ``label="A legend entry"``. + + %(Patch:kwdoc)s + + See Also + -------- + Sankey.finish + """ + # Check and preprocess the arguments. + flows = np.array([1.0, -1.0]) if flows is None else np.array(flows) + n = flows.shape[0] # Number of flows + if rotation is None: + rotation = 0 + else: + # In the code below, angles are expressed in deg/90. + rotation /= 90.0 + if orientations is None: + orientations = 0 + try: + orientations = np.broadcast_to(orientations, n) + except ValueError: + raise ValueError( + f"The shapes of 'flows' {np.shape(flows)} and 'orientations' " + f"{np.shape(orientations)} are incompatible" + ) from None + try: + labels = np.broadcast_to(labels, n) + except ValueError: + raise ValueError( + f"The shapes of 'flows' {np.shape(flows)} and 'labels' " + f"{np.shape(labels)} are incompatible" + ) from None + if trunklength < 0: + raise ValueError( + "'trunklength' is negative, which is not allowed because it " + "would cause poor layout") + if abs(np.sum(flows)) > self.tolerance: + _log.info("The sum of the flows is nonzero (%f; patchlabel=%r); " + "is the system not at steady state?", + np.sum(flows), patchlabel) + scaled_flows = self.scale * flows + gain = sum(max(flow, 0) for flow in scaled_flows) + loss = sum(min(flow, 0) for flow in scaled_flows) + if prior is not None: + if prior < 0: + raise ValueError("The index of the prior diagram is negative") + if min(connect) < 0: + raise ValueError( + "At least one of the connection indices is negative") + if prior >= len(self.diagrams): + raise ValueError( + f"The index of the prior diagram is {prior}, but there " + f"are only {len(self.diagrams)} other diagrams") + if connect[0] >= len(self.diagrams[prior].flows): + raise ValueError( + "The connection index to the source diagram is {}, but " + "that diagram has only {} flows".format( + connect[0], len(self.diagrams[prior].flows))) + if connect[1] >= n: + raise ValueError( + f"The connection index to this diagram is {connect[1]}, " + f"but this diagram has only {n} flows") + if self.diagrams[prior].angles[connect[0]] is None: + raise ValueError( + f"The connection cannot be made, which may occur if the " + f"magnitude of flow {connect[0]} of diagram {prior} is " + f"less than the specified tolerance") + flow_error = (self.diagrams[prior].flows[connect[0]] + + flows[connect[1]]) + if abs(flow_error) >= self.tolerance: + raise ValueError( + f"The scaled sum of the connected flows is {flow_error}, " + f"which is not within the tolerance ({self.tolerance})") + + # Determine if the flows are inputs. + are_inputs = [None] * n + for i, flow in enumerate(flows): + if flow >= self.tolerance: + are_inputs[i] = True + elif flow <= -self.tolerance: + are_inputs[i] = False + else: + _log.info( + "The magnitude of flow %d (%f) is below the tolerance " + "(%f).\nIt will not be shown, and it cannot be used in a " + "connection.", i, flow, self.tolerance) + + # Determine the angles of the arrows (before rotation). + angles = [None] * n + for i, (orient, is_input) in enumerate(zip(orientations, are_inputs)): + if orient == 1: + if is_input: + angles[i] = DOWN + elif is_input is False: + # Be specific since is_input can be None. + angles[i] = UP + elif orient == 0: + if is_input is not None: + angles[i] = RIGHT + else: + if orient != -1: + raise ValueError( + f"The value of orientations[{i}] is {orient}, " + f"but it must be -1, 0, or 1") + if is_input: + angles[i] = UP + elif is_input is False: + angles[i] = DOWN + + # Justify the lengths of the paths. + if np.iterable(pathlengths): + if len(pathlengths) != n: + raise ValueError( + f"The lengths of 'flows' ({n}) and 'pathlengths' " + f"({len(pathlengths)}) are incompatible") + else: # Make pathlengths into a list. + urlength = pathlengths + ullength = pathlengths + lrlength = pathlengths + lllength = pathlengths + d = dict(RIGHT=pathlengths) + pathlengths = [d.get(angle, 0) for angle in angles] + # Determine the lengths of the top-side arrows + # from the middle outwards. + for i, (angle, is_input, flow) in enumerate(zip(angles, are_inputs, + scaled_flows)): + if angle == DOWN and is_input: + pathlengths[i] = ullength + ullength += flow + elif angle == UP and is_input is False: + pathlengths[i] = urlength + urlength -= flow # Flow is negative for outputs. + # Determine the lengths of the bottom-side arrows + # from the middle outwards. + for i, (angle, is_input, flow) in enumerate(reversed(list(zip( + angles, are_inputs, scaled_flows)))): + if angle == UP and is_input: + pathlengths[n - i - 1] = lllength + lllength += flow + elif angle == DOWN and is_input is False: + pathlengths[n - i - 1] = lrlength + lrlength -= flow + # Determine the lengths of the left-side arrows + # from the bottom upwards. + has_left_input = False + for i, (angle, is_input, spec) in enumerate(reversed(list(zip( + angles, are_inputs, zip(scaled_flows, pathlengths))))): + if angle == RIGHT: + if is_input: + if has_left_input: + pathlengths[n - i - 1] = 0 + else: + has_left_input = True + # Determine the lengths of the right-side arrows + # from the top downwards. + has_right_output = False + for i, (angle, is_input, spec) in enumerate(zip( + angles, are_inputs, list(zip(scaled_flows, pathlengths)))): + if angle == RIGHT: + if is_input is False: + if has_right_output: + pathlengths[i] = 0 + else: + has_right_output = True + + # Begin the subpaths, and smooth the transition if the sum of the flows + # is nonzero. + urpath = [(Path.MOVETO, [(self.gap - trunklength / 2.0), # Upper right + gain / 2.0]), + (Path.LINETO, [(self.gap - trunklength / 2.0) / 2.0, + gain / 2.0]), + (Path.CURVE4, [(self.gap - trunklength / 2.0) / 8.0, + gain / 2.0]), + (Path.CURVE4, [(trunklength / 2.0 - self.gap) / 8.0, + -loss / 2.0]), + (Path.LINETO, [(trunklength / 2.0 - self.gap) / 2.0, + -loss / 2.0]), + (Path.LINETO, [(trunklength / 2.0 - self.gap), + -loss / 2.0])] + llpath = [(Path.LINETO, [(trunklength / 2.0 - self.gap), # Lower left + loss / 2.0]), + (Path.LINETO, [(trunklength / 2.0 - self.gap) / 2.0, + loss / 2.0]), + (Path.CURVE4, [(trunklength / 2.0 - self.gap) / 8.0, + loss / 2.0]), + (Path.CURVE4, [(self.gap - trunklength / 2.0) / 8.0, + -gain / 2.0]), + (Path.LINETO, [(self.gap - trunklength / 2.0) / 2.0, + -gain / 2.0]), + (Path.LINETO, [(self.gap - trunklength / 2.0), + -gain / 2.0])] + lrpath = [(Path.LINETO, [(trunklength / 2.0 - self.gap), # Lower right + loss / 2.0])] + ulpath = [(Path.LINETO, [self.gap - trunklength / 2.0, # Upper left + gain / 2.0])] + + # Add the subpaths and assign the locations of the tips and labels. + tips = np.zeros((n, 2)) + label_locations = np.zeros((n, 2)) + # Add the top-side inputs and outputs from the middle outwards. + for i, (angle, is_input, spec) in enumerate(zip( + angles, are_inputs, list(zip(scaled_flows, pathlengths)))): + if angle == DOWN and is_input: + tips[i, :], label_locations[i, :] = self._add_input( + ulpath, angle, *spec) + elif angle == UP and is_input is False: + tips[i, :], label_locations[i, :] = self._add_output( + urpath, angle, *spec) + # Add the bottom-side inputs and outputs from the middle outwards. + for i, (angle, is_input, spec) in enumerate(reversed(list(zip( + angles, are_inputs, list(zip(scaled_flows, pathlengths)))))): + if angle == UP and is_input: + tip, label_location = self._add_input(llpath, angle, *spec) + tips[n - i - 1, :] = tip + label_locations[n - i - 1, :] = label_location + elif angle == DOWN and is_input is False: + tip, label_location = self._add_output(lrpath, angle, *spec) + tips[n - i - 1, :] = tip + label_locations[n - i - 1, :] = label_location + # Add the left-side inputs from the bottom upwards. + has_left_input = False + for i, (angle, is_input, spec) in enumerate(reversed(list(zip( + angles, are_inputs, list(zip(scaled_flows, pathlengths)))))): + if angle == RIGHT and is_input: + if not has_left_input: + # Make sure the lower path extends + # at least as far as the upper one. + if llpath[-1][1][0] > ulpath[-1][1][0]: + llpath.append((Path.LINETO, [ulpath[-1][1][0], + llpath[-1][1][1]])) + has_left_input = True + tip, label_location = self._add_input(llpath, angle, *spec) + tips[n - i - 1, :] = tip + label_locations[n - i - 1, :] = label_location + # Add the right-side outputs from the top downwards. + has_right_output = False + for i, (angle, is_input, spec) in enumerate(zip( + angles, are_inputs, list(zip(scaled_flows, pathlengths)))): + if angle == RIGHT and is_input is False: + if not has_right_output: + # Make sure the upper path extends + # at least as far as the lower one. + if urpath[-1][1][0] < lrpath[-1][1][0]: + urpath.append((Path.LINETO, [lrpath[-1][1][0], + urpath[-1][1][1]])) + has_right_output = True + tips[i, :], label_locations[i, :] = self._add_output( + urpath, angle, *spec) + # Trim any hanging vertices. + if not has_left_input: + ulpath.pop() + llpath.pop() + if not has_right_output: + lrpath.pop() + urpath.pop() + + # Concatenate the subpaths in the correct order (clockwise from top). + path = (urpath + self._revert(lrpath) + llpath + self._revert(ulpath) + + [(Path.CLOSEPOLY, urpath[0][1])]) + + # Create a patch with the Sankey outline. + codes, vertices = zip(*path) + vertices = np.array(vertices) + + def _get_angle(a, r): + if a is None: + return None + else: + return a + r + + if prior is None: + if rotation != 0: # By default, none of this is needed. + angles = [_get_angle(angle, rotation) for angle in angles] + rotate = Affine2D().rotate_deg(rotation * 90).transform_affine + tips = rotate(tips) + label_locations = rotate(label_locations) + vertices = rotate(vertices) + text = self.ax.text(0, 0, s=patchlabel, ha='center', va='center') + else: + rotation = (self.diagrams[prior].angles[connect[0]] - + angles[connect[1]]) + angles = [_get_angle(angle, rotation) for angle in angles] + rotate = Affine2D().rotate_deg(rotation * 90).transform_affine + tips = rotate(tips) + offset = self.diagrams[prior].tips[connect[0]] - tips[connect[1]] + translate = Affine2D().translate(*offset).transform_affine + tips = translate(tips) + label_locations = translate(rotate(label_locations)) + vertices = translate(rotate(vertices)) + kwds = dict(s=patchlabel, ha='center', va='center') + text = self.ax.text(*offset, **kwds) + if mpl.rcParams['_internal.classic_mode']: + fc = kwargs.pop('fc', kwargs.pop('facecolor', '#bfd1d4')) + lw = kwargs.pop('lw', kwargs.pop('linewidth', 0.5)) + else: + fc = kwargs.pop('fc', kwargs.pop('facecolor', None)) + lw = kwargs.pop('lw', kwargs.pop('linewidth', None)) + if fc is None: + fc = self.ax._get_patches_for_fill.get_next_color() + patch = PathPatch(Path(vertices, codes), fc=fc, lw=lw, **kwargs) + self.ax.add_patch(patch) + + # Add the path labels. + texts = [] + for number, angle, label, location in zip(flows, angles, labels, + label_locations): + if label is None or angle is None: + label = '' + elif self.unit is not None: + if isinstance(self.format, str): + quantity = self.format % abs(number) + self.unit + elif callable(self.format): + quantity = self.format(number) + else: + raise TypeError( + 'format must be callable or a format string') + if label != '': + label += "\n" + label += quantity + texts.append(self.ax.text(x=location[0], y=location[1], + s=label, + ha='center', va='center')) + # Text objects are placed even they are empty (as long as the magnitude + # of the corresponding flow is larger than the tolerance) in case the + # user wants to provide labels later. + + # Expand the size of the diagram if necessary. + self.extent = (min(np.min(vertices[:, 0]), + np.min(label_locations[:, 0]), + self.extent[0]), + max(np.max(vertices[:, 0]), + np.max(label_locations[:, 0]), + self.extent[1]), + min(np.min(vertices[:, 1]), + np.min(label_locations[:, 1]), + self.extent[2]), + max(np.max(vertices[:, 1]), + np.max(label_locations[:, 1]), + self.extent[3])) + # Include both vertices _and_ label locations in the extents; there are + # where either could determine the margins (e.g., arrow shoulders). + + # Add this diagram as a subdiagram. + self.diagrams.append( + SimpleNamespace(patch=patch, flows=flows, angles=angles, tips=tips, + text=text, texts=texts)) + + # Allow a daisy-chained call structure (see docstring for the class). + return self + + def finish(self): + """ + Adjust the Axes and return a list of information about the Sankey + subdiagram(s). + + Returns a list of subdiagrams with the following fields: + + ======== ============================================================= + Field Description + ======== ============================================================= + *patch* Sankey outline (a `~matplotlib.patches.PathPatch`). + *flows* Flow values (positive for input, negative for output). + *angles* List of angles of the arrows [deg/90]. + For example, if the diagram has not been rotated, + an input to the top side has an angle of 3 (DOWN), + and an output from the top side has an angle of 1 (UP). + If a flow has been skipped (because its magnitude is less + than *tolerance*), then its angle will be *None*. + *tips* (N, 2)-array of the (x, y) positions of the tips (or "dips") + of the flow paths. + If the magnitude of a flow is less the *tolerance* of this + `Sankey` instance, the flow is skipped and its tip will be at + the center of the diagram. + *text* `.Text` instance for the diagram label. + *texts* List of `.Text` instances for the flow labels. + ======== ============================================================= + + See Also + -------- + Sankey.add + """ + self.ax.axis([self.extent[0] - self.margin, + self.extent[1] + self.margin, + self.extent[2] - self.margin, + self.extent[3] + self.margin]) + self.ax.set_aspect('equal', adjustable='datalim') + return self.diagrams diff --git a/infer_4_30_0/lib/python3.10/site-packages/matplotlib/sankey.pyi b/infer_4_30_0/lib/python3.10/site-packages/matplotlib/sankey.pyi new file mode 100644 index 0000000000000000000000000000000000000000..33565b998a9caf00ead62bdfa0adb50e272dd6ac --- /dev/null +++ b/infer_4_30_0/lib/python3.10/site-packages/matplotlib/sankey.pyi @@ -0,0 +1,61 @@ +from matplotlib.axes import Axes + +from collections.abc import Callable, Iterable +from typing import Any +from typing_extensions import Self # < Py 3.11 + +import numpy as np + +__license__: str +__credits__: list[str] +__author__: str +__version__: str + +RIGHT: int +UP: int +DOWN: int + +# TODO typing units +class Sankey: + diagrams: list[Any] + ax: Axes + unit: Any + format: str | Callable[[float], str] + scale: float + gap: float + radius: float + shoulder: float + offset: float + margin: float + pitch: float + tolerance: float + extent: np.ndarray + def __init__( + self, + ax: Axes | None = ..., + scale: float = ..., + unit: Any = ..., + format: str | Callable[[float], str] = ..., + gap: float = ..., + radius: float = ..., + shoulder: float = ..., + offset: float = ..., + head_angle: float = ..., + margin: float = ..., + tolerance: float = ..., + **kwargs + ) -> None: ... + def add( + self, + patchlabel: str = ..., + flows: Iterable[float] | None = ..., + orientations: Iterable[int] | None = ..., + labels: str | Iterable[str | None] = ..., + trunklength: float = ..., + pathlengths: float | Iterable[float] = ..., + prior: int | None = ..., + connect: tuple[int, int] = ..., + rotation: float = ..., + **kwargs + ) -> Self: ... + def finish(self) -> list[Any]: ... diff --git a/infer_4_30_0/lib/python3.10/site-packages/matplotlib/spines.pyi b/infer_4_30_0/lib/python3.10/site-packages/matplotlib/spines.pyi new file mode 100644 index 0000000000000000000000000000000000000000..ff2a1a40bf947005692ccaf2b95977e57a1747b6 --- /dev/null +++ b/infer_4_30_0/lib/python3.10/site-packages/matplotlib/spines.pyi @@ -0,0 +1,83 @@ +from collections.abc import Callable, Iterator, MutableMapping +from typing import Literal, TypeVar, overload + +import matplotlib.patches as mpatches +from matplotlib.axes import Axes +from matplotlib.axis import Axis +from matplotlib.path import Path +from matplotlib.transforms import Transform +from matplotlib.typing import ColorType + +class Spine(mpatches.Patch): + axes: Axes + spine_type: str + axis: Axis | None + def __init__(self, axes: Axes, spine_type: str, path: Path, **kwargs) -> None: ... + def set_patch_arc( + self, center: tuple[float, float], radius: float, theta1: float, theta2: float + ) -> None: ... + def set_patch_circle(self, center: tuple[float, float], radius: float) -> None: ... + def set_patch_line(self) -> None: ... + def get_patch_transform(self) -> Transform: ... + def get_path(self) -> Path: ... + def register_axis(self, axis: Axis) -> None: ... + def clear(self) -> None: ... + def set_position( + self, + position: Literal["center", "zero"] + | tuple[Literal["outward", "axes", "data"], float], + ) -> None: ... + def get_position( + self, + ) -> Literal["center", "zero"] | tuple[ + Literal["outward", "axes", "data"], float + ]: ... + def get_spine_transform(self) -> Transform: ... + def set_bounds(self, low: float | None = ..., high: float | None = ...) -> None: ... + def get_bounds(self) -> tuple[float, float]: ... + + _T = TypeVar("_T", bound=Spine) + @classmethod + def linear_spine( + cls: type[_T], + axes: Axes, + spine_type: Literal["left", "right", "bottom", "top"], + **kwargs + ) -> _T: ... + @classmethod + def arc_spine( + cls: type[_T], + axes: Axes, + spine_type: Literal["left", "right", "bottom", "top"], + center: tuple[float, float], + radius: float, + theta1: float, + theta2: float, + **kwargs + ) -> _T: ... + @classmethod + def circular_spine( + cls: type[_T], axes: Axes, center: tuple[float, float], radius: float, **kwargs + ) -> _T: ... + def set_color(self, c: ColorType | None) -> None: ... + +class SpinesProxy: + def __init__(self, spine_dict: dict[str, Spine]) -> None: ... + def __getattr__(self, name: str) -> Callable[..., None]: ... + def __dir__(self) -> list[str]: ... + +class Spines(MutableMapping[str, Spine]): + def __init__(self, **kwargs: Spine) -> None: ... + @classmethod + def from_dict(cls, d: dict[str, Spine]) -> Spines: ... + def __getattr__(self, name: str) -> Spine: ... + @overload + def __getitem__(self, key: str) -> Spine: ... + @overload + def __getitem__(self, key: list[str]) -> SpinesProxy: ... + @overload + def __getitem__(self, key: slice) -> SpinesProxy: ... + def __setitem__(self, key: str, value: Spine) -> None: ... + def __delitem__(self, key: str) -> None: ... + def __iter__(self) -> Iterator[str]: ... + def __len__(self) -> int: ... diff --git a/infer_4_30_0/lib/python3.10/site-packages/matplotlib/stackplot.pyi b/infer_4_30_0/lib/python3.10/site-packages/matplotlib/stackplot.pyi new file mode 100644 index 0000000000000000000000000000000000000000..9509f858a4bfbf6fd54fa1111077341b31ec03b2 --- /dev/null +++ b/infer_4_30_0/lib/python3.10/site-packages/matplotlib/stackplot.pyi @@ -0,0 +1,20 @@ +from matplotlib.axes import Axes +from matplotlib.collections import PolyCollection + +from collections.abc import Iterable +from typing import Literal +from numpy.typing import ArrayLike +from matplotlib.typing import ColorType + +def stackplot( + axes: Axes, + x: ArrayLike, + *args: ArrayLike, + labels: Iterable[str] = ..., + colors: Iterable[ColorType] | None = ..., + hatch: Iterable[str] | str | None = ..., + baseline: Literal["zero", "sym", "wiggle", "weighted_wiggle"] = ..., + **kwargs +) -> list[PolyCollection]: ... + +__all__ = ['stackplot'] diff --git a/infer_4_30_0/lib/python3.10/site-packages/matplotlib/streamplot.py b/infer_4_30_0/lib/python3.10/site-packages/matplotlib/streamplot.py new file mode 100644 index 0000000000000000000000000000000000000000..84f99732c709d25a0efb2518156ef213f3ee6a4d --- /dev/null +++ b/infer_4_30_0/lib/python3.10/site-packages/matplotlib/streamplot.py @@ -0,0 +1,712 @@ +""" +Streamline plotting for 2D vector fields. + +""" + +import numpy as np + +import matplotlib as mpl +from matplotlib import _api, cm, patches +import matplotlib.colors as mcolors +import matplotlib.collections as mcollections +import matplotlib.lines as mlines + + +__all__ = ['streamplot'] + + +def streamplot(axes, x, y, u, v, density=1, linewidth=None, color=None, + cmap=None, norm=None, arrowsize=1, arrowstyle='-|>', + minlength=0.1, transform=None, zorder=None, start_points=None, + maxlength=4.0, integration_direction='both', + broken_streamlines=True): + """ + Draw streamlines of a vector flow. + + Parameters + ---------- + x, y : 1D/2D arrays + Evenly spaced strictly increasing arrays to make a grid. If 2D, all + rows of *x* must be equal and all columns of *y* must be equal; i.e., + they must be as if generated by ``np.meshgrid(x_1d, y_1d)``. + u, v : 2D arrays + *x* and *y*-velocities. The number of rows and columns must match + the length of *y* and *x*, respectively. + density : float or (float, float) + Controls the closeness of streamlines. When ``density = 1``, the domain + is divided into a 30x30 grid. *density* linearly scales this grid. + Each cell in the grid can have, at most, one traversing streamline. + For different densities in each direction, use a tuple + (density_x, density_y). + linewidth : float or 2D array + The width of the streamlines. With a 2D array the line width can be + varied across the grid. The array must have the same shape as *u* + and *v*. + color : :mpltype:`color` or 2D array + The streamline color. If given an array, its values are converted to + colors using *cmap* and *norm*. The array must have the same shape + as *u* and *v*. + cmap, norm + Data normalization and colormapping parameters for *color*; only used + if *color* is an array of floats. See `~.Axes.imshow` for a detailed + description. + arrowsize : float + Scaling factor for the arrow size. + arrowstyle : str + Arrow style specification. + See `~matplotlib.patches.FancyArrowPatch`. + minlength : float + Minimum length of streamline in axes coordinates. + start_points : (N, 2) array + Coordinates of starting points for the streamlines in data coordinates + (the same coordinates as the *x* and *y* arrays). + zorder : float + The zorder of the streamlines and arrows. + Artists with lower zorder values are drawn first. + maxlength : float + Maximum length of streamline in axes coordinates. + integration_direction : {'forward', 'backward', 'both'}, default: 'both' + Integrate the streamline in forward, backward or both directions. + data : indexable object, optional + DATA_PARAMETER_PLACEHOLDER + broken_streamlines : boolean, default: True + If False, forces streamlines to continue until they + leave the plot domain. If True, they may be terminated if they + come too close to another streamline. + + Returns + ------- + StreamplotSet + Container object with attributes + + - ``lines``: `.LineCollection` of streamlines + + - ``arrows``: `.PatchCollection` containing `.FancyArrowPatch` + objects representing the arrows half-way along streamlines. + + This container will probably change in the future to allow changes + to the colormap, alpha, etc. for both lines and arrows, but these + changes should be backward compatible. + """ + grid = Grid(x, y) + mask = StreamMask(density) + dmap = DomainMap(grid, mask) + + if zorder is None: + zorder = mlines.Line2D.zorder + + # default to data coordinates + if transform is None: + transform = axes.transData + + if color is None: + color = axes._get_lines.get_next_color() + + if linewidth is None: + linewidth = mpl.rcParams['lines.linewidth'] + + line_kw = {} + arrow_kw = dict(arrowstyle=arrowstyle, mutation_scale=10 * arrowsize) + + _api.check_in_list(['both', 'forward', 'backward'], + integration_direction=integration_direction) + + if integration_direction == 'both': + maxlength /= 2. + + use_multicolor_lines = isinstance(color, np.ndarray) + if use_multicolor_lines: + if color.shape != grid.shape: + raise ValueError("If 'color' is given, it must match the shape of " + "the (x, y) grid") + line_colors = [[]] # Empty entry allows concatenation of zero arrays. + color = np.ma.masked_invalid(color) + else: + line_kw['color'] = color + arrow_kw['color'] = color + + if isinstance(linewidth, np.ndarray): + if linewidth.shape != grid.shape: + raise ValueError("If 'linewidth' is given, it must match the " + "shape of the (x, y) grid") + line_kw['linewidth'] = [] + else: + line_kw['linewidth'] = linewidth + arrow_kw['linewidth'] = linewidth + + line_kw['zorder'] = zorder + arrow_kw['zorder'] = zorder + + # Sanity checks. + if u.shape != grid.shape or v.shape != grid.shape: + raise ValueError("'u' and 'v' must match the shape of the (x, y) grid") + + u = np.ma.masked_invalid(u) + v = np.ma.masked_invalid(v) + + integrate = _get_integrator(u, v, dmap, minlength, maxlength, + integration_direction) + + trajectories = [] + if start_points is None: + for xm, ym in _gen_starting_points(mask.shape): + if mask[ym, xm] == 0: + xg, yg = dmap.mask2grid(xm, ym) + t = integrate(xg, yg, broken_streamlines) + if t is not None: + trajectories.append(t) + else: + sp2 = np.asanyarray(start_points, dtype=float).copy() + + # Check if start_points are outside the data boundaries + for xs, ys in sp2: + if not (grid.x_origin <= xs <= grid.x_origin + grid.width and + grid.y_origin <= ys <= grid.y_origin + grid.height): + raise ValueError(f"Starting point ({xs}, {ys}) outside of " + "data boundaries") + + # Convert start_points from data to array coords + # Shift the seed points from the bottom left of the data so that + # data2grid works properly. + sp2[:, 0] -= grid.x_origin + sp2[:, 1] -= grid.y_origin + + for xs, ys in sp2: + xg, yg = dmap.data2grid(xs, ys) + # Floating point issues can cause xg, yg to be slightly out of + # bounds for xs, ys on the upper boundaries. Because we have + # already checked that the starting points are within the original + # grid, clip the xg, yg to the grid to work around this issue + xg = np.clip(xg, 0, grid.nx - 1) + yg = np.clip(yg, 0, grid.ny - 1) + + t = integrate(xg, yg, broken_streamlines) + if t is not None: + trajectories.append(t) + + if use_multicolor_lines: + if norm is None: + norm = mcolors.Normalize(color.min(), color.max()) + cmap = cm._ensure_cmap(cmap) + + streamlines = [] + arrows = [] + for t in trajectories: + tgx, tgy = t.T + # Rescale from grid-coordinates to data-coordinates. + tx, ty = dmap.grid2data(tgx, tgy) + tx += grid.x_origin + ty += grid.y_origin + + # Create multiple tiny segments if varying width or color is given + if isinstance(linewidth, np.ndarray) or use_multicolor_lines: + points = np.transpose([tx, ty]).reshape(-1, 1, 2) + streamlines.extend(np.hstack([points[:-1], points[1:]])) + else: + points = np.transpose([tx, ty]) + streamlines.append(points) + + # Add arrows halfway along each trajectory. + s = np.cumsum(np.hypot(np.diff(tx), np.diff(ty))) + n = np.searchsorted(s, s[-1] / 2.) + arrow_tail = (tx[n], ty[n]) + arrow_head = (np.mean(tx[n:n + 2]), np.mean(ty[n:n + 2])) + + if isinstance(linewidth, np.ndarray): + line_widths = interpgrid(linewidth, tgx, tgy)[:-1] + line_kw['linewidth'].extend(line_widths) + arrow_kw['linewidth'] = line_widths[n] + + if use_multicolor_lines: + color_values = interpgrid(color, tgx, tgy)[:-1] + line_colors.append(color_values) + arrow_kw['color'] = cmap(norm(color_values[n])) + + p = patches.FancyArrowPatch( + arrow_tail, arrow_head, transform=transform, **arrow_kw) + arrows.append(p) + + lc = mcollections.LineCollection( + streamlines, transform=transform, **line_kw) + lc.sticky_edges.x[:] = [grid.x_origin, grid.x_origin + grid.width] + lc.sticky_edges.y[:] = [grid.y_origin, grid.y_origin + grid.height] + if use_multicolor_lines: + lc.set_array(np.ma.hstack(line_colors)) + lc.set_cmap(cmap) + lc.set_norm(norm) + axes.add_collection(lc) + + ac = mcollections.PatchCollection(arrows) + # Adding the collection itself is broken; see #2341. + for p in arrows: + axes.add_patch(p) + + axes.autoscale_view() + stream_container = StreamplotSet(lc, ac) + return stream_container + + +class StreamplotSet: + + def __init__(self, lines, arrows): + self.lines = lines + self.arrows = arrows + + +# Coordinate definitions +# ======================== + +class DomainMap: + """ + Map representing different coordinate systems. + + Coordinate definitions: + + * axes-coordinates goes from 0 to 1 in the domain. + * data-coordinates are specified by the input x-y coordinates. + * grid-coordinates goes from 0 to N and 0 to M for an N x M grid, + where N and M match the shape of the input data. + * mask-coordinates goes from 0 to N and 0 to M for an N x M mask, + where N and M are user-specified to control the density of streamlines. + + This class also has methods for adding trajectories to the StreamMask. + Before adding a trajectory, run `start_trajectory` to keep track of regions + crossed by a given trajectory. Later, if you decide the trajectory is bad + (e.g., if the trajectory is very short) just call `undo_trajectory`. + """ + + def __init__(self, grid, mask): + self.grid = grid + self.mask = mask + # Constants for conversion between grid- and mask-coordinates + self.x_grid2mask = (mask.nx - 1) / (grid.nx - 1) + self.y_grid2mask = (mask.ny - 1) / (grid.ny - 1) + + self.x_mask2grid = 1. / self.x_grid2mask + self.y_mask2grid = 1. / self.y_grid2mask + + self.x_data2grid = 1. / grid.dx + self.y_data2grid = 1. / grid.dy + + def grid2mask(self, xi, yi): + """Return nearest space in mask-coords from given grid-coords.""" + return round(xi * self.x_grid2mask), round(yi * self.y_grid2mask) + + def mask2grid(self, xm, ym): + return xm * self.x_mask2grid, ym * self.y_mask2grid + + def data2grid(self, xd, yd): + return xd * self.x_data2grid, yd * self.y_data2grid + + def grid2data(self, xg, yg): + return xg / self.x_data2grid, yg / self.y_data2grid + + def start_trajectory(self, xg, yg, broken_streamlines=True): + xm, ym = self.grid2mask(xg, yg) + self.mask._start_trajectory(xm, ym, broken_streamlines) + + def reset_start_point(self, xg, yg): + xm, ym = self.grid2mask(xg, yg) + self.mask._current_xy = (xm, ym) + + def update_trajectory(self, xg, yg, broken_streamlines=True): + if not self.grid.within_grid(xg, yg): + raise InvalidIndexError + xm, ym = self.grid2mask(xg, yg) + self.mask._update_trajectory(xm, ym, broken_streamlines) + + def undo_trajectory(self): + self.mask._undo_trajectory() + + +class Grid: + """Grid of data.""" + def __init__(self, x, y): + + if np.ndim(x) == 1: + pass + elif np.ndim(x) == 2: + x_row = x[0] + if not np.allclose(x_row, x): + raise ValueError("The rows of 'x' must be equal") + x = x_row + else: + raise ValueError("'x' can have at maximum 2 dimensions") + + if np.ndim(y) == 1: + pass + elif np.ndim(y) == 2: + yt = np.transpose(y) # Also works for nested lists. + y_col = yt[0] + if not np.allclose(y_col, yt): + raise ValueError("The columns of 'y' must be equal") + y = y_col + else: + raise ValueError("'y' can have at maximum 2 dimensions") + + if not (np.diff(x) > 0).all(): + raise ValueError("'x' must be strictly increasing") + if not (np.diff(y) > 0).all(): + raise ValueError("'y' must be strictly increasing") + + self.nx = len(x) + self.ny = len(y) + + self.dx = x[1] - x[0] + self.dy = y[1] - y[0] + + self.x_origin = x[0] + self.y_origin = y[0] + + self.width = x[-1] - x[0] + self.height = y[-1] - y[0] + + if not np.allclose(np.diff(x), self.width / (self.nx - 1)): + raise ValueError("'x' values must be equally spaced") + if not np.allclose(np.diff(y), self.height / (self.ny - 1)): + raise ValueError("'y' values must be equally spaced") + + @property + def shape(self): + return self.ny, self.nx + + def within_grid(self, xi, yi): + """Return whether (*xi*, *yi*) is a valid index of the grid.""" + # Note that xi/yi can be floats; so, for example, we can't simply check + # `xi < self.nx` since *xi* can be `self.nx - 1 < xi < self.nx` + return 0 <= xi <= self.nx - 1 and 0 <= yi <= self.ny - 1 + + +class StreamMask: + """ + Mask to keep track of discrete regions crossed by streamlines. + + The resolution of this grid determines the approximate spacing between + trajectories. Streamlines are only allowed to pass through zeroed cells: + When a streamline enters a cell, that cell is set to 1, and no new + streamlines are allowed to enter. + """ + + def __init__(self, density): + try: + self.nx, self.ny = (30 * np.broadcast_to(density, 2)).astype(int) + except ValueError as err: + raise ValueError("'density' must be a scalar or be of length " + "2") from err + if self.nx < 0 or self.ny < 0: + raise ValueError("'density' must be positive") + self._mask = np.zeros((self.ny, self.nx)) + self.shape = self._mask.shape + + self._current_xy = None + + def __getitem__(self, args): + return self._mask[args] + + def _start_trajectory(self, xm, ym, broken_streamlines=True): + """Start recording streamline trajectory""" + self._traj = [] + self._update_trajectory(xm, ym, broken_streamlines) + + def _undo_trajectory(self): + """Remove current trajectory from mask""" + for t in self._traj: + self._mask[t] = 0 + + def _update_trajectory(self, xm, ym, broken_streamlines=True): + """ + Update current trajectory position in mask. + + If the new position has already been filled, raise `InvalidIndexError`. + """ + if self._current_xy != (xm, ym): + if self[ym, xm] == 0: + self._traj.append((ym, xm)) + self._mask[ym, xm] = 1 + self._current_xy = (xm, ym) + else: + if broken_streamlines: + raise InvalidIndexError + else: + pass + + +class InvalidIndexError(Exception): + pass + + +class TerminateTrajectory(Exception): + pass + + +# Integrator definitions +# ======================= + +def _get_integrator(u, v, dmap, minlength, maxlength, integration_direction): + + # rescale velocity onto grid-coordinates for integrations. + u, v = dmap.data2grid(u, v) + + # speed (path length) will be in axes-coordinates + u_ax = u / (dmap.grid.nx - 1) + v_ax = v / (dmap.grid.ny - 1) + speed = np.ma.sqrt(u_ax ** 2 + v_ax ** 2) + + def forward_time(xi, yi): + if not dmap.grid.within_grid(xi, yi): + raise OutOfBounds + ds_dt = interpgrid(speed, xi, yi) + if ds_dt == 0: + raise TerminateTrajectory() + dt_ds = 1. / ds_dt + ui = interpgrid(u, xi, yi) + vi = interpgrid(v, xi, yi) + return ui * dt_ds, vi * dt_ds + + def backward_time(xi, yi): + dxi, dyi = forward_time(xi, yi) + return -dxi, -dyi + + def integrate(x0, y0, broken_streamlines=True): + """ + Return x, y grid-coordinates of trajectory based on starting point. + + Integrate both forward and backward in time from starting point in + grid coordinates. + + Integration is terminated when a trajectory reaches a domain boundary + or when it crosses into an already occupied cell in the StreamMask. The + resulting trajectory is None if it is shorter than `minlength`. + """ + + stotal, xy_traj = 0., [] + + try: + dmap.start_trajectory(x0, y0, broken_streamlines) + except InvalidIndexError: + return None + if integration_direction in ['both', 'backward']: + s, xyt = _integrate_rk12(x0, y0, dmap, backward_time, maxlength, + broken_streamlines) + stotal += s + xy_traj += xyt[::-1] + + if integration_direction in ['both', 'forward']: + dmap.reset_start_point(x0, y0) + s, xyt = _integrate_rk12(x0, y0, dmap, forward_time, maxlength, + broken_streamlines) + stotal += s + xy_traj += xyt[1:] + + if stotal > minlength: + return np.broadcast_arrays(xy_traj, np.empty((1, 2)))[0] + else: # reject short trajectories + dmap.undo_trajectory() + return None + + return integrate + + +class OutOfBounds(IndexError): + pass + + +def _integrate_rk12(x0, y0, dmap, f, maxlength, broken_streamlines=True): + """ + 2nd-order Runge-Kutta algorithm with adaptive step size. + + This method is also referred to as the improved Euler's method, or Heun's + method. This method is favored over higher-order methods because: + + 1. To get decent looking trajectories and to sample every mask cell + on the trajectory we need a small timestep, so a lower order + solver doesn't hurt us unless the data is *very* high resolution. + In fact, for cases where the user inputs + data smaller or of similar grid size to the mask grid, the higher + order corrections are negligible because of the very fast linear + interpolation used in `interpgrid`. + + 2. For high resolution input data (i.e. beyond the mask + resolution), we must reduce the timestep. Therefore, an adaptive + timestep is more suited to the problem as this would be very hard + to judge automatically otherwise. + + This integrator is about 1.5 - 2x as fast as RK4 and RK45 solvers (using + similar Python implementations) in most setups. + """ + # This error is below that needed to match the RK4 integrator. It + # is set for visual reasons -- too low and corners start + # appearing ugly and jagged. Can be tuned. + maxerror = 0.003 + + # This limit is important (for all integrators) to avoid the + # trajectory skipping some mask cells. We could relax this + # condition if we use the code which is commented out below to + # increment the location gradually. However, due to the efficient + # nature of the interpolation, this doesn't boost speed by much + # for quite a bit of complexity. + maxds = min(1. / dmap.mask.nx, 1. / dmap.mask.ny, 0.1) + + ds = maxds + stotal = 0 + xi = x0 + yi = y0 + xyf_traj = [] + + while True: + try: + if dmap.grid.within_grid(xi, yi): + xyf_traj.append((xi, yi)) + else: + raise OutOfBounds + + # Compute the two intermediate gradients. + # f should raise OutOfBounds if the locations given are + # outside the grid. + k1x, k1y = f(xi, yi) + k2x, k2y = f(xi + ds * k1x, yi + ds * k1y) + + except OutOfBounds: + # Out of the domain during this step. + # Take an Euler step to the boundary to improve neatness + # unless the trajectory is currently empty. + if xyf_traj: + ds, xyf_traj = _euler_step(xyf_traj, dmap, f) + stotal += ds + break + except TerminateTrajectory: + break + + dx1 = ds * k1x + dy1 = ds * k1y + dx2 = ds * 0.5 * (k1x + k2x) + dy2 = ds * 0.5 * (k1y + k2y) + + ny, nx = dmap.grid.shape + # Error is normalized to the axes coordinates + error = np.hypot((dx2 - dx1) / (nx - 1), (dy2 - dy1) / (ny - 1)) + + # Only save step if within error tolerance + if error < maxerror: + xi += dx2 + yi += dy2 + try: + dmap.update_trajectory(xi, yi, broken_streamlines) + except InvalidIndexError: + break + if stotal + ds > maxlength: + break + stotal += ds + + # recalculate stepsize based on step error + if error == 0: + ds = maxds + else: + ds = min(maxds, 0.85 * ds * (maxerror / error) ** 0.5) + + return stotal, xyf_traj + + +def _euler_step(xyf_traj, dmap, f): + """Simple Euler integration step that extends streamline to boundary.""" + ny, nx = dmap.grid.shape + xi, yi = xyf_traj[-1] + cx, cy = f(xi, yi) + if cx == 0: + dsx = np.inf + elif cx < 0: + dsx = xi / -cx + else: + dsx = (nx - 1 - xi) / cx + if cy == 0: + dsy = np.inf + elif cy < 0: + dsy = yi / -cy + else: + dsy = (ny - 1 - yi) / cy + ds = min(dsx, dsy) + xyf_traj.append((xi + cx * ds, yi + cy * ds)) + return ds, xyf_traj + + +# Utility functions +# ======================== + +def interpgrid(a, xi, yi): + """Fast 2D, linear interpolation on an integer grid""" + + Ny, Nx = np.shape(a) + if isinstance(xi, np.ndarray): + x = xi.astype(int) + y = yi.astype(int) + # Check that xn, yn don't exceed max index + xn = np.clip(x + 1, 0, Nx - 1) + yn = np.clip(y + 1, 0, Ny - 1) + else: + x = int(xi) + y = int(yi) + # conditional is faster than clipping for integers + if x == (Nx - 1): + xn = x + else: + xn = x + 1 + if y == (Ny - 1): + yn = y + else: + yn = y + 1 + + a00 = a[y, x] + a01 = a[y, xn] + a10 = a[yn, x] + a11 = a[yn, xn] + xt = xi - x + yt = yi - y + a0 = a00 * (1 - xt) + a01 * xt + a1 = a10 * (1 - xt) + a11 * xt + ai = a0 * (1 - yt) + a1 * yt + + if not isinstance(xi, np.ndarray): + if np.ma.is_masked(ai): + raise TerminateTrajectory + + return ai + + +def _gen_starting_points(shape): + """ + Yield starting points for streamlines. + + Trying points on the boundary first gives higher quality streamlines. + This algorithm starts with a point on the mask corner and spirals inward. + This algorithm is inefficient, but fast compared to rest of streamplot. + """ + ny, nx = shape + xfirst = 0 + yfirst = 1 + xlast = nx - 1 + ylast = ny - 1 + x, y = 0, 0 + direction = 'right' + for i in range(nx * ny): + yield x, y + + if direction == 'right': + x += 1 + if x >= xlast: + xlast -= 1 + direction = 'up' + elif direction == 'up': + y += 1 + if y >= ylast: + ylast -= 1 + direction = 'left' + elif direction == 'left': + x -= 1 + if x <= xfirst: + xfirst += 1 + direction = 'down' + elif direction == 'down': + y -= 1 + if y <= yfirst: + yfirst += 1 + direction = 'right' diff --git a/infer_4_30_0/lib/python3.10/site-packages/matplotlib/streamplot.pyi b/infer_4_30_0/lib/python3.10/site-packages/matplotlib/streamplot.pyi new file mode 100644 index 0000000000000000000000000000000000000000..be745802044907a32084934576269eaf228e07e4 --- /dev/null +++ b/infer_4_30_0/lib/python3.10/site-packages/matplotlib/streamplot.pyi @@ -0,0 +1,84 @@ +from matplotlib.axes import Axes +from matplotlib.colors import Normalize, Colormap +from matplotlib.collections import LineCollection, PatchCollection +from matplotlib.patches import ArrowStyle +from matplotlib.transforms import Transform + +from typing import Literal +from numpy.typing import ArrayLike +from .typing import ColorType + +def streamplot( + axes: Axes, + x: ArrayLike, + y: ArrayLike, + u: ArrayLike, + v: ArrayLike, + density: float | tuple[float, float] = ..., + linewidth: float | ArrayLike | None = ..., + color: ColorType | ArrayLike | None = ..., + cmap: str | Colormap | None = ..., + norm: str | Normalize | None = ..., + arrowsize: float = ..., + arrowstyle: str | ArrowStyle = ..., + minlength: float = ..., + transform: Transform | None = ..., + zorder: float | None = ..., + start_points: ArrayLike | None = ..., + maxlength: float = ..., + integration_direction: Literal["forward", "backward", "both"] = ..., + broken_streamlines: bool = ..., +) -> StreamplotSet: ... + +class StreamplotSet: + lines: LineCollection + arrows: PatchCollection + def __init__(self, lines: LineCollection, arrows: PatchCollection) -> None: ... + +class DomainMap: + grid: Grid + mask: StreamMask + x_grid2mask: float + y_grid2mask: float + x_mask2grid: float + y_mask2grid: float + x_data2grid: float + y_data2grid: float + def __init__(self, grid: Grid, mask: StreamMask) -> None: ... + def grid2mask(self, xi: float, yi: float) -> tuple[int, int]: ... + def mask2grid(self, xm: float, ym: float) -> tuple[float, float]: ... + def data2grid(self, xd: float, yd: float) -> tuple[float, float]: ... + def grid2data(self, xg: float, yg: float) -> tuple[float, float]: ... + def start_trajectory( + self, xg: float, yg: float, broken_streamlines: bool = ... + ) -> None: ... + def reset_start_point(self, xg: float, yg: float) -> None: ... + def update_trajectory(self, xg, yg, broken_streamlines: bool = ...) -> None: ... + def undo_trajectory(self) -> None: ... + +class Grid: + nx: int + ny: int + dx: float + dy: float + x_origin: float + y_origin: float + width: float + height: float + def __init__(self, x: ArrayLike, y: ArrayLike) -> None: ... + @property + def shape(self) -> tuple[int, int]: ... + def within_grid(self, xi: float, yi: float) -> bool: ... + +class StreamMask: + nx: int + ny: int + shape: tuple[int, int] + def __init__(self, density: float | tuple[float, float]) -> None: ... + def __getitem__(self, args): ... + +class InvalidIndexError(Exception): ... +class TerminateTrajectory(Exception): ... +class OutOfBounds(IndexError): ... + +__all__ = ['streamplot'] diff --git a/infer_4_30_0/lib/python3.10/site-packages/matplotlib/table.py b/infer_4_30_0/lib/python3.10/site-packages/matplotlib/table.py new file mode 100644 index 0000000000000000000000000000000000000000..370ce9fe922fab333b8acc418e36d57a228d74e5 --- /dev/null +++ b/infer_4_30_0/lib/python3.10/site-packages/matplotlib/table.py @@ -0,0 +1,846 @@ +# Original code by: +# John Gill +# Copyright 2004 John Gill and John Hunter +# +# Subsequent changes: +# The Matplotlib development team +# Copyright The Matplotlib development team + +""" +Tables drawing. + +.. note:: + The table implementation in Matplotlib is lightly maintained. For a more + featureful table implementation, you may wish to try `blume + `_. + +Use the factory function `~matplotlib.table.table` to create a ready-made +table from texts. If you need more control, use the `.Table` class and its +methods. + +The table consists of a grid of cells, which are indexed by (row, column). +The cell (0, 0) is positioned at the top left. + +Thanks to John Gill for providing the class and table. +""" + +import numpy as np + +from . import _api, _docstring +from .artist import Artist, allow_rasterization +from .patches import Rectangle +from .text import Text +from .transforms import Bbox +from .path import Path + +from .cbook import _is_pandas_dataframe + + +class Cell(Rectangle): + """ + A cell is a `.Rectangle` with some associated `.Text`. + + As a user, you'll most likely not creates cells yourself. Instead, you + should use either the `~matplotlib.table.table` factory function or + `.Table.add_cell`. + """ + + PAD = 0.1 + """Padding between text and rectangle.""" + + _edges = 'BRTL' + _edge_aliases = {'open': '', + 'closed': _edges, # default + 'horizontal': 'BT', + 'vertical': 'RL' + } + + def __init__(self, xy, width, height, *, + edgecolor='k', facecolor='w', + fill=True, + text='', + loc='right', + fontproperties=None, + visible_edges='closed', + ): + """ + Parameters + ---------- + xy : 2-tuple + The position of the bottom left corner of the cell. + width : float + The cell width. + height : float + The cell height. + edgecolor : :mpltype:`color`, default: 'k' + The color of the cell border. + facecolor : :mpltype:`color`, default: 'w' + The cell facecolor. + fill : bool, default: True + Whether the cell background is filled. + text : str, optional + The cell text. + loc : {'right', 'center', 'left'} + The alignment of the text within the cell. + fontproperties : dict, optional + A dict defining the font properties of the text. Supported keys and + values are the keyword arguments accepted by `.FontProperties`. + visible_edges : {'closed', 'open', 'horizontal', 'vertical'} or \ +substring of 'BRTL' + The cell edges to be drawn with a line: a substring of 'BRTL' + (bottom, right, top, left), or one of 'open' (no edges drawn), + 'closed' (all edges drawn), 'horizontal' (bottom and top), + 'vertical' (right and left). + """ + + # Call base + super().__init__(xy, width=width, height=height, fill=fill, + edgecolor=edgecolor, facecolor=facecolor) + self.set_clip_on(False) + self.visible_edges = visible_edges + + # Create text object + self._loc = loc + self._text = Text(x=xy[0], y=xy[1], clip_on=False, + text=text, fontproperties=fontproperties, + horizontalalignment=loc, verticalalignment='center') + + def set_transform(self, t): + super().set_transform(t) + # the text does not get the transform! + self.stale = True + + def set_figure(self, fig): + super().set_figure(fig) + self._text.set_figure(fig) + + def get_text(self): + """Return the cell `.Text` instance.""" + return self._text + + def set_fontsize(self, size): + """Set the text fontsize.""" + self._text.set_fontsize(size) + self.stale = True + + def get_fontsize(self): + """Return the cell fontsize.""" + return self._text.get_fontsize() + + def auto_set_font_size(self, renderer): + """Shrink font size until the text fits into the cell width.""" + fontsize = self.get_fontsize() + required = self.get_required_width(renderer) + while fontsize > 1 and required > self.get_width(): + fontsize -= 1 + self.set_fontsize(fontsize) + required = self.get_required_width(renderer) + + return fontsize + + @allow_rasterization + def draw(self, renderer): + if not self.get_visible(): + return + # draw the rectangle + super().draw(renderer) + # position the text + self._set_text_position(renderer) + self._text.draw(renderer) + self.stale = False + + def _set_text_position(self, renderer): + """Set text up so it is drawn in the right place.""" + bbox = self.get_window_extent(renderer) + # center vertically + y = bbox.y0 + bbox.height / 2 + # position horizontally + loc = self._text.get_horizontalalignment() + if loc == 'center': + x = bbox.x0 + bbox.width / 2 + elif loc == 'left': + x = bbox.x0 + bbox.width * self.PAD + else: # right. + x = bbox.x0 + bbox.width * (1 - self.PAD) + self._text.set_position((x, y)) + + def get_text_bounds(self, renderer): + """ + Return the text bounds as *(x, y, width, height)* in table coordinates. + """ + return (self._text.get_window_extent(renderer) + .transformed(self.get_data_transform().inverted()) + .bounds) + + def get_required_width(self, renderer): + """Return the minimal required width for the cell.""" + l, b, w, h = self.get_text_bounds(renderer) + return w * (1.0 + (2.0 * self.PAD)) + + @_docstring.interpd + def set_text_props(self, **kwargs): + """ + Update the text properties. + + Valid keyword arguments are: + + %(Text:kwdoc)s + """ + self._text._internal_update(kwargs) + self.stale = True + + @property + def visible_edges(self): + """ + The cell edges to be drawn with a line. + + Reading this property returns a substring of 'BRTL' (bottom, right, + top, left'). + + When setting this property, you can use a substring of 'BRTL' or one + of {'open', 'closed', 'horizontal', 'vertical'}. + """ + return self._visible_edges + + @visible_edges.setter + def visible_edges(self, value): + if value is None: + self._visible_edges = self._edges + elif value in self._edge_aliases: + self._visible_edges = self._edge_aliases[value] + else: + if any(edge not in self._edges for edge in value): + raise ValueError('Invalid edge param {}, must only be one of ' + '{} or string of {}'.format( + value, + ", ".join(self._edge_aliases), + ", ".join(self._edges))) + self._visible_edges = value + self.stale = True + + def get_path(self): + """Return a `.Path` for the `.visible_edges`.""" + codes = [Path.MOVETO] + codes.extend( + Path.LINETO if edge in self._visible_edges else Path.MOVETO + for edge in self._edges) + if Path.MOVETO not in codes[1:]: # All sides are visible + codes[-1] = Path.CLOSEPOLY + return Path( + [[0.0, 0.0], [1.0, 0.0], [1.0, 1.0], [0.0, 1.0], [0.0, 0.0]], + codes, + readonly=True + ) + + +CustomCell = Cell # Backcompat. alias. + + +class Table(Artist): + """ + A table of cells. + + The table consists of a grid of cells, which are indexed by (row, column). + + For a simple table, you'll have a full grid of cells with indices from + (0, 0) to (num_rows-1, num_cols-1), in which the cell (0, 0) is positioned + at the top left. However, you can also add cells with negative indices. + You don't have to add a cell to every grid position, so you can create + tables that have holes. + + *Note*: You'll usually not create an empty table from scratch. Instead use + `~matplotlib.table.table` to create a table from data. + """ + codes = {'best': 0, + 'upper right': 1, # default + 'upper left': 2, + 'lower left': 3, + 'lower right': 4, + 'center left': 5, + 'center right': 6, + 'lower center': 7, + 'upper center': 8, + 'center': 9, + 'top right': 10, + 'top left': 11, + 'bottom left': 12, + 'bottom right': 13, + 'right': 14, + 'left': 15, + 'top': 16, + 'bottom': 17, + } + """Possible values where to place the table relative to the Axes.""" + + FONTSIZE = 10 + + AXESPAD = 0.02 + """The border between the Axes and the table edge in Axes units.""" + + def __init__(self, ax, loc=None, bbox=None, **kwargs): + """ + Parameters + ---------- + ax : `~matplotlib.axes.Axes` + The `~.axes.Axes` to plot the table into. + loc : str, optional + The position of the cell with respect to *ax*. This must be one of + the `~.Table.codes`. + bbox : `.Bbox` or [xmin, ymin, width, height], optional + A bounding box to draw the table into. If this is not *None*, this + overrides *loc*. + + Other Parameters + ---------------- + **kwargs + `.Artist` properties. + """ + + super().__init__() + + if isinstance(loc, str): + if loc not in self.codes: + raise ValueError( + "Unrecognized location {!r}. Valid locations are\n\t{}" + .format(loc, '\n\t'.join(self.codes))) + loc = self.codes[loc] + self.set_figure(ax.get_figure(root=False)) + self._axes = ax + self._loc = loc + self._bbox = bbox + + # use axes coords + ax._unstale_viewLim() + self.set_transform(ax.transAxes) + + self._cells = {} + self._edges = None + self._autoColumns = [] + self._autoFontsize = True + self._internal_update(kwargs) + + self.set_clip_on(False) + + def add_cell(self, row, col, *args, **kwargs): + """ + Create a cell and add it to the table. + + Parameters + ---------- + row : int + Row index. + col : int + Column index. + *args, **kwargs + All other parameters are passed on to `Cell`. + + Returns + ------- + `.Cell` + The created cell. + + """ + xy = (0, 0) + cell = Cell(xy, visible_edges=self.edges, *args, **kwargs) + self[row, col] = cell + return cell + + def __setitem__(self, position, cell): + """ + Set a custom cell in a given position. + """ + _api.check_isinstance(Cell, cell=cell) + try: + row, col = position[0], position[1] + except Exception as err: + raise KeyError('Only tuples length 2 are accepted as ' + 'coordinates') from err + cell.set_figure(self.get_figure(root=False)) + cell.set_transform(self.get_transform()) + cell.set_clip_on(False) + self._cells[row, col] = cell + self.stale = True + + def __getitem__(self, position): + """Retrieve a custom cell from a given position.""" + return self._cells[position] + + @property + def edges(self): + """ + The default value of `~.Cell.visible_edges` for newly added + cells using `.add_cell`. + + Notes + ----- + This setting does currently only affect newly created cells using + `.add_cell`. + + To change existing cells, you have to set their edges explicitly:: + + for c in tab.get_celld().values(): + c.visible_edges = 'horizontal' + + """ + return self._edges + + @edges.setter + def edges(self, value): + self._edges = value + self.stale = True + + def _approx_text_height(self): + return (self.FONTSIZE / 72.0 * self.get_figure(root=True).dpi / + self._axes.bbox.height * 1.2) + + @allow_rasterization + def draw(self, renderer): + # docstring inherited + + # Need a renderer to do hit tests on mouseevent; assume the last one + # will do + if renderer is None: + renderer = self.get_figure(root=True)._get_renderer() + if renderer is None: + raise RuntimeError('No renderer defined') + + if not self.get_visible(): + return + renderer.open_group('table', gid=self.get_gid()) + self._update_positions(renderer) + + for key in sorted(self._cells): + self._cells[key].draw(renderer) + + renderer.close_group('table') + self.stale = False + + def _get_grid_bbox(self, renderer): + """ + Get a bbox, in axes coordinates for the cells. + + Only include those in the range (0, 0) to (maxRow, maxCol). + """ + boxes = [cell.get_window_extent(renderer) + for (row, col), cell in self._cells.items() + if row >= 0 and col >= 0] + bbox = Bbox.union(boxes) + return bbox.transformed(self.get_transform().inverted()) + + def contains(self, mouseevent): + # docstring inherited + if self._different_canvas(mouseevent): + return False, {} + # TODO: Return index of the cell containing the cursor so that the user + # doesn't have to bind to each one individually. + renderer = self.get_figure(root=True)._get_renderer() + if renderer is not None: + boxes = [cell.get_window_extent(renderer) + for (row, col), cell in self._cells.items() + if row >= 0 and col >= 0] + bbox = Bbox.union(boxes) + return bbox.contains(mouseevent.x, mouseevent.y), {} + else: + return False, {} + + def get_children(self): + """Return the Artists contained by the table.""" + return list(self._cells.values()) + + def get_window_extent(self, renderer=None): + # docstring inherited + if renderer is None: + renderer = self.get_figure(root=True)._get_renderer() + self._update_positions(renderer) + boxes = [cell.get_window_extent(renderer) + for cell in self._cells.values()] + return Bbox.union(boxes) + + def _do_cell_alignment(self): + """ + Calculate row heights and column widths; position cells accordingly. + """ + # Calculate row/column widths + widths = {} + heights = {} + for (row, col), cell in self._cells.items(): + height = heights.setdefault(row, 0.0) + heights[row] = max(height, cell.get_height()) + width = widths.setdefault(col, 0.0) + widths[col] = max(width, cell.get_width()) + + # work out left position for each column + xpos = 0 + lefts = {} + for col in sorted(widths): + lefts[col] = xpos + xpos += widths[col] + + ypos = 0 + bottoms = {} + for row in sorted(heights, reverse=True): + bottoms[row] = ypos + ypos += heights[row] + + # set cell positions + for (row, col), cell in self._cells.items(): + cell.set_x(lefts[col]) + cell.set_y(bottoms[row]) + + def auto_set_column_width(self, col): + """ + Automatically set the widths of given columns to optimal sizes. + + Parameters + ---------- + col : int or sequence of ints + The indices of the columns to auto-scale. + """ + col1d = np.atleast_1d(col) + if not np.issubdtype(col1d.dtype, np.integer): + raise TypeError("col must be an int or sequence of ints.") + for cell in col1d: + self._autoColumns.append(cell) + + self.stale = True + + def _auto_set_column_width(self, col, renderer): + """Automatically set width for column.""" + cells = [cell for key, cell in self._cells.items() if key[1] == col] + max_width = max((cell.get_required_width(renderer) for cell in cells), + default=0) + for cell in cells: + cell.set_width(max_width) + + def auto_set_font_size(self, value=True): + """Automatically set font size.""" + self._autoFontsize = value + self.stale = True + + def _auto_set_font_size(self, renderer): + + if len(self._cells) == 0: + return + fontsize = next(iter(self._cells.values())).get_fontsize() + cells = [] + for key, cell in self._cells.items(): + # ignore auto-sized columns + if key[1] in self._autoColumns: + continue + size = cell.auto_set_font_size(renderer) + fontsize = min(fontsize, size) + cells.append(cell) + + # now set all fontsizes equal + for cell in self._cells.values(): + cell.set_fontsize(fontsize) + + def scale(self, xscale, yscale): + """Scale column widths by *xscale* and row heights by *yscale*.""" + for c in self._cells.values(): + c.set_width(c.get_width() * xscale) + c.set_height(c.get_height() * yscale) + + def set_fontsize(self, size): + """ + Set the font size, in points, of the cell text. + + Parameters + ---------- + size : float + + Notes + ----- + As long as auto font size has not been disabled, the value will be + clipped such that the text fits horizontally into the cell. + + You can disable this behavior using `.auto_set_font_size`. + + >>> the_table.auto_set_font_size(False) + >>> the_table.set_fontsize(20) + + However, there is no automatic scaling of the row height so that the + text may exceed the cell boundary. + """ + for cell in self._cells.values(): + cell.set_fontsize(size) + self.stale = True + + def _offset(self, ox, oy): + """Move all the artists by ox, oy (axes coords).""" + for c in self._cells.values(): + x, y = c.get_x(), c.get_y() + c.set_x(x + ox) + c.set_y(y + oy) + + def _update_positions(self, renderer): + # called from renderer to allow more precise estimates of + # widths and heights with get_window_extent + + # Do any auto width setting + for col in self._autoColumns: + self._auto_set_column_width(col, renderer) + + if self._autoFontsize: + self._auto_set_font_size(renderer) + + # Align all the cells + self._do_cell_alignment() + + bbox = self._get_grid_bbox(renderer) + l, b, w, h = bbox.bounds + + if self._bbox is not None: + # Position according to bbox + if isinstance(self._bbox, Bbox): + rl, rb, rw, rh = self._bbox.bounds + else: + rl, rb, rw, rh = self._bbox + self.scale(rw / w, rh / h) + ox = rl - l + oy = rb - b + self._do_cell_alignment() + else: + # Position using loc + (BEST, UR, UL, LL, LR, CL, CR, LC, UC, C, + TR, TL, BL, BR, R, L, T, B) = range(len(self.codes)) + # defaults for center + ox = (0.5 - w / 2) - l + oy = (0.5 - h / 2) - b + if self._loc in (UL, LL, CL): # left + ox = self.AXESPAD - l + if self._loc in (BEST, UR, LR, R, CR): # right + ox = 1 - (l + w + self.AXESPAD) + if self._loc in (BEST, UR, UL, UC): # upper + oy = 1 - (b + h + self.AXESPAD) + if self._loc in (LL, LR, LC): # lower + oy = self.AXESPAD - b + if self._loc in (LC, UC, C): # center x + ox = (0.5 - w / 2) - l + if self._loc in (CL, CR, C): # center y + oy = (0.5 - h / 2) - b + + if self._loc in (TL, BL, L): # out left + ox = - (l + w) + if self._loc in (TR, BR, R): # out right + ox = 1.0 - l + if self._loc in (TR, TL, T): # out top + oy = 1.0 - b + if self._loc in (BL, BR, B): # out bottom + oy = - (b + h) + + self._offset(ox, oy) + + def get_celld(self): + r""" + Return a dict of cells in the table mapping *(row, column)* to + `.Cell`\s. + + Notes + ----- + You can also directly index into the Table object to access individual + cells:: + + cell = table[row, col] + + """ + return self._cells + + +@_docstring.interpd +def table(ax, + cellText=None, cellColours=None, + cellLoc='right', colWidths=None, + rowLabels=None, rowColours=None, rowLoc='left', + colLabels=None, colColours=None, colLoc='center', + loc='bottom', bbox=None, edges='closed', + **kwargs): + """ + Add a table to an `~.axes.Axes`. + + At least one of *cellText* or *cellColours* must be specified. These + parameters must be 2D lists, in which the outer lists define the rows and + the inner list define the column values per row. Each row must have the + same number of elements. + + The table can optionally have row and column headers, which are configured + using *rowLabels*, *rowColours*, *rowLoc* and *colLabels*, *colColours*, + *colLoc* respectively. + + For finer grained control over tables, use the `.Table` class and add it to + the Axes with `.Axes.add_table`. + + Parameters + ---------- + cellText : 2D list of str or pandas.DataFrame, optional + The texts to place into the table cells. + + *Note*: Line breaks in the strings are currently not accounted for and + will result in the text exceeding the cell boundaries. + + cellColours : 2D list of :mpltype:`color`, optional + The background colors of the cells. + + cellLoc : {'right', 'center', 'left'} + The alignment of the text within the cells. + + colWidths : list of float, optional + The column widths in units of the axes. If not given, all columns will + have a width of *1 / ncols*. + + rowLabels : list of str, optional + The text of the row header cells. + + rowColours : list of :mpltype:`color`, optional + The colors of the row header cells. + + rowLoc : {'left', 'center', 'right'} + The text alignment of the row header cells. + + colLabels : list of str, optional + The text of the column header cells. + + colColours : list of :mpltype:`color`, optional + The colors of the column header cells. + + colLoc : {'center', 'left', 'right'} + The text alignment of the column header cells. + + loc : str, default: 'bottom' + The position of the cell with respect to *ax*. This must be one of + the `~.Table.codes`. + + bbox : `.Bbox` or [xmin, ymin, width, height], optional + A bounding box to draw the table into. If this is not *None*, this + overrides *loc*. + + edges : {'closed', 'open', 'horizontal', 'vertical'} or substring of 'BRTL' + The cell edges to be drawn with a line. See also + `~.Cell.visible_edges`. + + Returns + ------- + `~matplotlib.table.Table` + The created table. + + Other Parameters + ---------------- + **kwargs + `.Table` properties. + + %(Table:kwdoc)s + """ + + if cellColours is None and cellText is None: + raise ValueError('At least one argument from "cellColours" or ' + '"cellText" must be provided to create a table.') + + # Check we have some cellText + if cellText is None: + # assume just colours are needed + rows = len(cellColours) + cols = len(cellColours[0]) + cellText = [[''] * cols] * rows + + # Check if we have a Pandas DataFrame + if _is_pandas_dataframe(cellText): + # if rowLabels/colLabels are empty, use DataFrame entries. + # Otherwise, throw an error. + if rowLabels is None: + rowLabels = cellText.index + else: + raise ValueError("rowLabels cannot be used alongside Pandas DataFrame") + if colLabels is None: + colLabels = cellText.columns + else: + raise ValueError("colLabels cannot be used alongside Pandas DataFrame") + # Update cellText with only values + cellText = cellText.values + + rows = len(cellText) + cols = len(cellText[0]) + for row in cellText: + if len(row) != cols: + raise ValueError(f"Each row in 'cellText' must have {cols} " + "columns") + + if cellColours is not None: + if len(cellColours) != rows: + raise ValueError(f"'cellColours' must have {rows} rows") + for row in cellColours: + if len(row) != cols: + raise ValueError("Each row in 'cellColours' must have " + f"{cols} columns") + else: + cellColours = ['w' * cols] * rows + + # Set colwidths if not given + if colWidths is None: + colWidths = [1.0 / cols] * cols + + # Fill in missing information for column + # and row labels + rowLabelWidth = 0 + if rowLabels is None: + if rowColours is not None: + rowLabels = [''] * rows + rowLabelWidth = colWidths[0] + elif rowColours is None: + rowColours = 'w' * rows + + if rowLabels is not None: + if len(rowLabels) != rows: + raise ValueError(f"'rowLabels' must be of length {rows}") + + # If we have column labels, need to shift + # the text and colour arrays down 1 row + offset = 1 + if colLabels is None: + if colColours is not None: + colLabels = [''] * cols + else: + offset = 0 + elif colColours is None: + colColours = 'w' * cols + + # Set up cell colours if not given + if cellColours is None: + cellColours = ['w' * cols] * rows + + # Now create the table + table = Table(ax, loc, bbox, **kwargs) + table.edges = edges + height = table._approx_text_height() + + # Add the cells + for row in range(rows): + for col in range(cols): + table.add_cell(row + offset, col, + width=colWidths[col], height=height, + text=cellText[row][col], + facecolor=cellColours[row][col], + loc=cellLoc) + # Do column labels + if colLabels is not None: + for col in range(cols): + table.add_cell(0, col, + width=colWidths[col], height=height, + text=colLabels[col], facecolor=colColours[col], + loc=colLoc) + + # Do row labels + if rowLabels is not None: + for row in range(rows): + table.add_cell(row + offset, -1, + width=rowLabelWidth or 1e-15, height=height, + text=rowLabels[row], facecolor=rowColours[row], + loc=rowLoc) + if rowLabelWidth == 0: + table.auto_set_column_width(-1) + + # set_fontsize is only effective after cells are added + if "fontsize" in kwargs: + table.set_fontsize(kwargs["fontsize"]) + + ax.add_table(table) + return table diff --git a/infer_4_30_0/lib/python3.10/site-packages/matplotlib/texmanager.py b/infer_4_30_0/lib/python3.10/site-packages/matplotlib/texmanager.py new file mode 100644 index 0000000000000000000000000000000000000000..2083510396f1af8325dafd98396f62a68c142f7d --- /dev/null +++ b/infer_4_30_0/lib/python3.10/site-packages/matplotlib/texmanager.py @@ -0,0 +1,368 @@ +r""" +Support for embedded TeX expressions in Matplotlib. + +Requirements: + +* LaTeX. +* \*Agg backends: dvipng>=1.6. +* PS backend: PSfrag, dvips, and Ghostscript>=9.0. +* PDF and SVG backends: if LuaTeX is present, it will be used to speed up some + post-processing steps, but note that it is not used to parse the TeX string + itself (only LaTeX is supported). + +To enable TeX rendering of all text in your Matplotlib figure, set +:rc:`text.usetex` to True. + +TeX and dvipng/dvips processing results are cached +in ~/.matplotlib/tex.cache for reuse between sessions. + +`TexManager.get_rgba` can also be used to directly obtain raster output as RGBA +NumPy arrays. +""" + +import functools +import hashlib +import logging +import os +from pathlib import Path +import subprocess +from tempfile import TemporaryDirectory + +import numpy as np + +import matplotlib as mpl +from matplotlib import cbook, dviread + +_log = logging.getLogger(__name__) + + +def _usepackage_if_not_loaded(package, *, option=None): + """ + Output LaTeX code that loads a package (possibly with an option) if it + hasn't been loaded yet. + + LaTeX cannot load twice a package with different options, so this helper + can be used to protect against users loading arbitrary packages/options in + their custom preamble. + """ + option = f"[{option}]" if option is not None else "" + return ( + r"\makeatletter" + r"\@ifpackageloaded{%(package)s}{}{\usepackage%(option)s{%(package)s}}" + r"\makeatother" + ) % {"package": package, "option": option} + + +class TexManager: + """ + Convert strings to dvi files using TeX, caching the results to a directory. + + The cache directory is called ``tex.cache`` and is located in the directory + returned by `.get_cachedir`. + + Repeated calls to this constructor always return the same instance. + """ + + _texcache = os.path.join(mpl.get_cachedir(), 'tex.cache') + _grey_arrayd = {} + + _font_families = ('serif', 'sans-serif', 'cursive', 'monospace') + _font_preambles = { + 'new century schoolbook': r'\renewcommand{\rmdefault}{pnc}', + 'bookman': r'\renewcommand{\rmdefault}{pbk}', + 'times': r'\usepackage{mathptmx}', + 'palatino': r'\usepackage{mathpazo}', + 'zapf chancery': r'\usepackage{chancery}', + 'cursive': r'\usepackage{chancery}', + 'charter': r'\usepackage{charter}', + 'serif': '', + 'sans-serif': '', + 'helvetica': r'\usepackage{helvet}', + 'avant garde': r'\usepackage{avant}', + 'courier': r'\usepackage{courier}', + # Loading the type1ec package ensures that cm-super is installed, which + # is necessary for Unicode computer modern. (It also allows the use of + # computer modern at arbitrary sizes, but that's just a side effect.) + 'monospace': r'\usepackage{type1ec}', + 'computer modern roman': r'\usepackage{type1ec}', + 'computer modern sans serif': r'\usepackage{type1ec}', + 'computer modern typewriter': r'\usepackage{type1ec}', + } + _font_types = { + 'new century schoolbook': 'serif', + 'bookman': 'serif', + 'times': 'serif', + 'palatino': 'serif', + 'zapf chancery': 'cursive', + 'charter': 'serif', + 'helvetica': 'sans-serif', + 'avant garde': 'sans-serif', + 'courier': 'monospace', + 'computer modern roman': 'serif', + 'computer modern sans serif': 'sans-serif', + 'computer modern typewriter': 'monospace', + } + + @functools.lru_cache # Always return the same instance. + def __new__(cls): + Path(cls._texcache).mkdir(parents=True, exist_ok=True) + return object.__new__(cls) + + @classmethod + def _get_font_family_and_reduced(cls): + """Return the font family name and whether the font is reduced.""" + ff = mpl.rcParams['font.family'] + ff_val = ff[0].lower() if len(ff) == 1 else None + if len(ff) == 1 and ff_val in cls._font_families: + return ff_val, False + elif len(ff) == 1 and ff_val in cls._font_preambles: + return cls._font_types[ff_val], True + else: + _log.info('font.family must be one of (%s) when text.usetex is ' + 'True. serif will be used by default.', + ', '.join(cls._font_families)) + return 'serif', False + + @classmethod + def _get_font_preamble_and_command(cls): + requested_family, is_reduced_font = cls._get_font_family_and_reduced() + + preambles = {} + for font_family in cls._font_families: + if is_reduced_font and font_family == requested_family: + preambles[font_family] = cls._font_preambles[ + mpl.rcParams['font.family'][0].lower()] + else: + rcfonts = mpl.rcParams[f"font.{font_family}"] + for i, font in enumerate(map(str.lower, rcfonts)): + if font in cls._font_preambles: + preambles[font_family] = cls._font_preambles[font] + _log.debug( + 'family: %s, package: %s, font: %s, skipped: %s', + font_family, cls._font_preambles[font], rcfonts[i], + ', '.join(rcfonts[:i]), + ) + break + else: + _log.info('No LaTeX-compatible font found for the %s font' + 'family in rcParams. Using default.', + font_family) + preambles[font_family] = cls._font_preambles[font_family] + + # The following packages and commands need to be included in the latex + # file's preamble: + cmd = {preambles[family] + for family in ['serif', 'sans-serif', 'monospace']} + if requested_family == 'cursive': + cmd.add(preambles['cursive']) + cmd.add(r'\usepackage{type1cm}') + preamble = '\n'.join(sorted(cmd)) + fontcmd = (r'\sffamily' if requested_family == 'sans-serif' else + r'\ttfamily' if requested_family == 'monospace' else + r'\rmfamily') + return preamble, fontcmd + + @classmethod + def get_basefile(cls, tex, fontsize, dpi=None): + """ + Return a filename based on a hash of the string, fontsize, and dpi. + """ + src = cls._get_tex_source(tex, fontsize) + str(dpi) + filehash = hashlib.sha256( + src.encode('utf-8'), + usedforsecurity=False + ).hexdigest() + filepath = Path(cls._texcache) + + num_letters, num_levels = 2, 2 + for i in range(0, num_letters*num_levels, num_letters): + filepath = filepath / Path(filehash[i:i+2]) + + filepath.mkdir(parents=True, exist_ok=True) + return os.path.join(filepath, filehash) + + @classmethod + def get_font_preamble(cls): + """ + Return a string containing font configuration for the tex preamble. + """ + font_preamble, command = cls._get_font_preamble_and_command() + return font_preamble + + @classmethod + def get_custom_preamble(cls): + """Return a string containing user additions to the tex preamble.""" + return mpl.rcParams['text.latex.preamble'] + + @classmethod + def _get_tex_source(cls, tex, fontsize): + """Return the complete TeX source for processing a TeX string.""" + font_preamble, fontcmd = cls._get_font_preamble_and_command() + baselineskip = 1.25 * fontsize + return "\n".join([ + r"\documentclass{article}", + r"% Pass-through \mathdefault, which is used in non-usetex mode", + r"% to use the default text font but was historically suppressed", + r"% in usetex mode.", + r"\newcommand{\mathdefault}[1]{#1}", + font_preamble, + r"\usepackage[utf8]{inputenc}", + r"\DeclareUnicodeCharacter{2212}{\ensuremath{-}}", + r"% geometry is loaded before the custom preamble as ", + r"% convert_psfrags relies on a custom preamble to change the ", + r"% geometry.", + r"\usepackage[papersize=72in, margin=1in]{geometry}", + cls.get_custom_preamble(), + r"% Use `underscore` package to take care of underscores in text.", + r"% The [strings] option allows to use underscores in file names.", + _usepackage_if_not_loaded("underscore", option="strings"), + r"% Custom packages (e.g. newtxtext) may already have loaded ", + r"% textcomp with different options.", + _usepackage_if_not_loaded("textcomp"), + r"\pagestyle{empty}", + r"\begin{document}", + r"% The empty hbox ensures that a page is printed even for empty", + r"% inputs, except when using psfrag which gets confused by it.", + r"% matplotlibbaselinemarker is used by dviread to detect the", + r"% last line's baseline.", + rf"\fontsize{{{fontsize}}}{{{baselineskip}}}%", + r"\ifdefined\psfrag\else\hbox{}\fi%", + rf"{{{fontcmd} {tex}}}%", + r"\end{document}", + ]) + + @classmethod + def make_tex(cls, tex, fontsize): + """ + Generate a tex file to render the tex string at a specific font size. + + Return the file name. + """ + texfile = cls.get_basefile(tex, fontsize) + ".tex" + Path(texfile).write_text(cls._get_tex_source(tex, fontsize), + encoding='utf-8') + return texfile + + @classmethod + def _run_checked_subprocess(cls, command, tex, *, cwd=None): + _log.debug(cbook._pformat_subprocess(command)) + try: + report = subprocess.check_output( + command, cwd=cwd if cwd is not None else cls._texcache, + stderr=subprocess.STDOUT) + except FileNotFoundError as exc: + raise RuntimeError( + f'Failed to process string with tex because {command[0]} ' + 'could not be found') from exc + except subprocess.CalledProcessError as exc: + raise RuntimeError( + '{prog} was not able to process the following string:\n' + '{tex!r}\n\n' + 'Here is the full command invocation and its output:\n\n' + '{format_command}\n\n' + '{exc}\n\n'.format( + prog=command[0], + format_command=cbook._pformat_subprocess(command), + tex=tex.encode('unicode_escape'), + exc=exc.output.decode('utf-8', 'backslashreplace')) + ) from None + _log.debug(report) + return report + + @classmethod + def make_dvi(cls, tex, fontsize): + """ + Generate a dvi file containing latex's layout of tex string. + + Return the file name. + """ + basefile = cls.get_basefile(tex, fontsize) + dvifile = '%s.dvi' % basefile + if not os.path.exists(dvifile): + texfile = Path(cls.make_tex(tex, fontsize)) + # Generate the dvi in a temporary directory to avoid race + # conditions e.g. if multiple processes try to process the same tex + # string at the same time. Having tmpdir be a subdirectory of the + # final output dir ensures that they are on the same filesystem, + # and thus replace() works atomically. It also allows referring to + # the texfile with a relative path (for pathological MPLCONFIGDIRs, + # the absolute path may contain characters (e.g. ~) that TeX does + # not support; n.b. relative paths cannot traverse parents, or it + # will be blocked when `openin_any = p` in texmf.cnf). + cwd = Path(dvifile).parent + with TemporaryDirectory(dir=cwd) as tmpdir: + tmppath = Path(tmpdir) + cls._run_checked_subprocess( + ["latex", "-interaction=nonstopmode", "--halt-on-error", + f"--output-directory={tmppath.name}", + f"{texfile.name}"], tex, cwd=cwd) + (tmppath / Path(dvifile).name).replace(dvifile) + return dvifile + + @classmethod + def make_png(cls, tex, fontsize, dpi): + """ + Generate a png file containing latex's rendering of tex string. + + Return the file name. + """ + basefile = cls.get_basefile(tex, fontsize, dpi) + pngfile = '%s.png' % basefile + # see get_rgba for a discussion of the background + if not os.path.exists(pngfile): + dvifile = cls.make_dvi(tex, fontsize) + cmd = ["dvipng", "-bg", "Transparent", "-D", str(dpi), + "-T", "tight", "-o", pngfile, dvifile] + # When testing, disable FreeType rendering for reproducibility; but + # dvipng 1.16 has a bug (fixed in f3ff241) that breaks --freetype0 + # mode, so for it we keep FreeType enabled; the image will be + # slightly off. + if (getattr(mpl, "_called_from_pytest", False) and + mpl._get_executable_info("dvipng").raw_version != "1.16"): + cmd.insert(1, "--freetype0") + cls._run_checked_subprocess(cmd, tex) + return pngfile + + @classmethod + def get_grey(cls, tex, fontsize=None, dpi=None): + """Return the alpha channel.""" + if not fontsize: + fontsize = mpl.rcParams['font.size'] + if not dpi: + dpi = mpl.rcParams['savefig.dpi'] + key = cls._get_tex_source(tex, fontsize), dpi + alpha = cls._grey_arrayd.get(key) + if alpha is None: + pngfile = cls.make_png(tex, fontsize, dpi) + rgba = mpl.image.imread(os.path.join(cls._texcache, pngfile)) + cls._grey_arrayd[key] = alpha = rgba[:, :, -1] + return alpha + + @classmethod + def get_rgba(cls, tex, fontsize=None, dpi=None, rgb=(0, 0, 0)): + r""" + Return latex's rendering of the tex string as an RGBA array. + + Examples + -------- + >>> texmanager = TexManager() + >>> s = r"\TeX\ is $\displaystyle\sum_n\frac{-e^{i\pi}}{2^n}$!" + >>> Z = texmanager.get_rgba(s, fontsize=12, dpi=80, rgb=(1, 0, 0)) + """ + alpha = cls.get_grey(tex, fontsize, dpi) + rgba = np.empty((*alpha.shape, 4)) + rgba[..., :3] = mpl.colors.to_rgb(rgb) + rgba[..., -1] = alpha + return rgba + + @classmethod + def get_text_width_height_descent(cls, tex, fontsize, renderer=None): + """Return width, height and descent of the text.""" + if tex.strip() == '': + return 0, 0, 0 + dvifile = cls.make_dvi(tex, fontsize) + dpi_fraction = renderer.points_to_pixels(1.) if renderer else 1 + with dviread.Dvi(dvifile, 72 * dpi_fraction) as dvi: + page, = dvi + # A total height (including the descent) needs to be returned. + return page.width, page.height + page.descent, page.descent diff --git a/infer_4_30_0/lib/python3.10/site-packages/matplotlib/text.py b/infer_4_30_0/lib/python3.10/site-packages/matplotlib/text.py new file mode 100644 index 0000000000000000000000000000000000000000..0b65450f760b72209a577807d35dcb5490c0399e --- /dev/null +++ b/infer_4_30_0/lib/python3.10/site-packages/matplotlib/text.py @@ -0,0 +1,2035 @@ +""" +Classes for including text in a figure. +""" + +import functools +import logging +import math +from numbers import Real +import weakref + +import numpy as np + +import matplotlib as mpl +from . import _api, artist, cbook, _docstring +from .artist import Artist +from .font_manager import FontProperties +from .patches import FancyArrowPatch, FancyBboxPatch, Rectangle +from .textpath import TextPath, TextToPath # noqa # Logically located here +from .transforms import ( + Affine2D, Bbox, BboxBase, BboxTransformTo, IdentityTransform, Transform) + + +_log = logging.getLogger(__name__) + + +def _get_textbox(text, renderer): + """ + Calculate the bounding box of the text. + + The bbox position takes text rotation into account, but the width and + height are those of the unrotated box (unlike `.Text.get_window_extent`). + """ + # TODO : This function may move into the Text class as a method. As a + # matter of fact, the information from the _get_textbox function + # should be available during the Text._get_layout() call, which is + # called within the _get_textbox. So, it would better to move this + # function as a method with some refactoring of _get_layout method. + + projected_xs = [] + projected_ys = [] + + theta = np.deg2rad(text.get_rotation()) + tr = Affine2D().rotate(-theta) + + _, parts, d = text._get_layout(renderer) + + for t, wh, x, y in parts: + w, h = wh + + xt1, yt1 = tr.transform((x, y)) + yt1 -= d + xt2, yt2 = xt1 + w, yt1 + h + + projected_xs.extend([xt1, xt2]) + projected_ys.extend([yt1, yt2]) + + xt_box, yt_box = min(projected_xs), min(projected_ys) + w_box, h_box = max(projected_xs) - xt_box, max(projected_ys) - yt_box + + x_box, y_box = Affine2D().rotate(theta).transform((xt_box, yt_box)) + + return x_box, y_box, w_box, h_box + + +def _get_text_metrics_with_cache(renderer, text, fontprop, ismath, dpi): + """Call ``renderer.get_text_width_height_descent``, caching the results.""" + # Cached based on a copy of fontprop so that later in-place mutations of + # the passed-in argument do not mess up the cache. + return _get_text_metrics_with_cache_impl( + weakref.ref(renderer), text, fontprop.copy(), ismath, dpi) + + +@functools.lru_cache(4096) +def _get_text_metrics_with_cache_impl( + renderer_ref, text, fontprop, ismath, dpi): + # dpi is unused, but participates in cache invalidation (via the renderer). + return renderer_ref().get_text_width_height_descent(text, fontprop, ismath) + + +@_docstring.interpd +@_api.define_aliases({ + "color": ["c"], + "fontproperties": ["font", "font_properties"], + "fontfamily": ["family"], + "fontname": ["name"], + "fontsize": ["size"], + "fontstretch": ["stretch"], + "fontstyle": ["style"], + "fontvariant": ["variant"], + "fontweight": ["weight"], + "horizontalalignment": ["ha"], + "verticalalignment": ["va"], + "multialignment": ["ma"], +}) +class Text(Artist): + """Handle storing and drawing of text in window or data coordinates.""" + + zorder = 3 + _charsize_cache = dict() + + def __repr__(self): + return f"Text({self._x}, {self._y}, {self._text!r})" + + def __init__(self, + x=0, y=0, text='', *, + color=None, # defaults to rc params + verticalalignment='baseline', + horizontalalignment='left', + multialignment=None, + fontproperties=None, # defaults to FontProperties() + rotation=None, + linespacing=None, + rotation_mode=None, + usetex=None, # defaults to rcParams['text.usetex'] + wrap=False, + transform_rotates_text=False, + parse_math=None, # defaults to rcParams['text.parse_math'] + antialiased=None, # defaults to rcParams['text.antialiased'] + **kwargs + ): + """ + Create a `.Text` instance at *x*, *y* with string *text*. + + The text is aligned relative to the anchor point (*x*, *y*) according + to ``horizontalalignment`` (default: 'left') and ``verticalalignment`` + (default: 'baseline'). See also + :doc:`/gallery/text_labels_and_annotations/text_alignment`. + + While Text accepts the 'label' keyword argument, by default it is not + added to the handles of a legend. + + Valid keyword arguments are: + + %(Text:kwdoc)s + """ + super().__init__() + self._x, self._y = x, y + self._text = '' + self._reset_visual_defaults( + text=text, + color=color, + fontproperties=fontproperties, + usetex=usetex, + parse_math=parse_math, + wrap=wrap, + verticalalignment=verticalalignment, + horizontalalignment=horizontalalignment, + multialignment=multialignment, + rotation=rotation, + transform_rotates_text=transform_rotates_text, + linespacing=linespacing, + rotation_mode=rotation_mode, + antialiased=antialiased + ) + self.update(kwargs) + + def _reset_visual_defaults( + self, + text='', + color=None, + fontproperties=None, + usetex=None, + parse_math=None, + wrap=False, + verticalalignment='baseline', + horizontalalignment='left', + multialignment=None, + rotation=None, + transform_rotates_text=False, + linespacing=None, + rotation_mode=None, + antialiased=None + ): + self.set_text(text) + self.set_color(mpl._val_or_rc(color, "text.color")) + self.set_fontproperties(fontproperties) + self.set_usetex(usetex) + self.set_parse_math(mpl._val_or_rc(parse_math, 'text.parse_math')) + self.set_wrap(wrap) + self.set_verticalalignment(verticalalignment) + self.set_horizontalalignment(horizontalalignment) + self._multialignment = multialignment + self.set_rotation(rotation) + self._transform_rotates_text = transform_rotates_text + self._bbox_patch = None # a FancyBboxPatch instance + self._renderer = None + if linespacing is None: + linespacing = 1.2 # Maybe use rcParam later. + self.set_linespacing(linespacing) + self.set_rotation_mode(rotation_mode) + self.set_antialiased(antialiased if antialiased is not None else + mpl.rcParams['text.antialiased']) + + def update(self, kwargs): + # docstring inherited + ret = [] + kwargs = cbook.normalize_kwargs(kwargs, Text) + sentinel = object() # bbox can be None, so use another sentinel. + # Update fontproperties first, as it has lowest priority. + fontproperties = kwargs.pop("fontproperties", sentinel) + if fontproperties is not sentinel: + ret.append(self.set_fontproperties(fontproperties)) + # Update bbox last, as it depends on font properties. + bbox = kwargs.pop("bbox", sentinel) + ret.extend(super().update(kwargs)) + if bbox is not sentinel: + ret.append(self.set_bbox(bbox)) + return ret + + def __getstate__(self): + d = super().__getstate__() + # remove the cached _renderer (if it exists) + d['_renderer'] = None + return d + + def contains(self, mouseevent): + """ + Return whether the mouse event occurred inside the axis-aligned + bounding-box of the text. + """ + if (self._different_canvas(mouseevent) or not self.get_visible() + or self._renderer is None): + return False, {} + # Explicitly use Text.get_window_extent(self) and not + # self.get_window_extent() so that Annotation.contains does not + # accidentally cover the entire annotation bounding box. + bbox = Text.get_window_extent(self) + inside = (bbox.x0 <= mouseevent.x <= bbox.x1 + and bbox.y0 <= mouseevent.y <= bbox.y1) + cattr = {} + # if the text has a surrounding patch, also check containment for it, + # and merge the results with the results for the text. + if self._bbox_patch: + patch_inside, patch_cattr = self._bbox_patch.contains(mouseevent) + inside = inside or patch_inside + cattr["bbox_patch"] = patch_cattr + return inside, cattr + + def _get_xy_display(self): + """ + Get the (possibly unit converted) transformed x, y in display coords. + """ + x, y = self.get_unitless_position() + return self.get_transform().transform((x, y)) + + def _get_multialignment(self): + if self._multialignment is not None: + return self._multialignment + else: + return self._horizontalalignment + + def _char_index_at(self, x): + """ + Calculate the index closest to the coordinate x in display space. + + The position of text[index] is assumed to be the sum of the widths + of all preceding characters text[:index]. + + This works only on single line texts. + """ + if not self._text: + return 0 + + text = self._text + + fontproperties = str(self._fontproperties) + if fontproperties not in Text._charsize_cache: + Text._charsize_cache[fontproperties] = dict() + + charsize_cache = Text._charsize_cache[fontproperties] + for char in set(text): + if char not in charsize_cache: + self.set_text(char) + bb = self.get_window_extent() + charsize_cache[char] = bb.x1 - bb.x0 + + self.set_text(text) + bb = self.get_window_extent() + + size_accum = np.cumsum([0] + [charsize_cache[x] for x in text]) + std_x = x - bb.x0 + return (np.abs(size_accum - std_x)).argmin() + + def get_rotation(self): + """Return the text angle in degrees between 0 and 360.""" + if self.get_transform_rotates_text(): + return self.get_transform().transform_angles( + [self._rotation], [self.get_unitless_position()]).item(0) + else: + return self._rotation + + def get_transform_rotates_text(self): + """ + Return whether rotations of the transform affect the text direction. + """ + return self._transform_rotates_text + + def set_rotation_mode(self, m): + """ + Set text rotation mode. + + Parameters + ---------- + m : {None, 'default', 'anchor'} + If ``"default"``, the text will be first rotated, then aligned according + to their horizontal and vertical alignments. If ``"anchor"``, then + alignment occurs before rotation. Passing ``None`` will set the rotation + mode to ``"default"``. + """ + if m is None: + m = "default" + else: + _api.check_in_list(("anchor", "default"), rotation_mode=m) + self._rotation_mode = m + self.stale = True + + def get_rotation_mode(self): + """Return the text rotation mode.""" + return self._rotation_mode + + def set_antialiased(self, antialiased): + """ + Set whether to use antialiased rendering. + + Parameters + ---------- + antialiased : bool + + Notes + ----- + Antialiasing will be determined by :rc:`text.antialiased` + and the parameter *antialiased* will have no effect if the text contains + math expressions. + """ + self._antialiased = antialiased + self.stale = True + + def get_antialiased(self): + """Return whether antialiased rendering is used.""" + return self._antialiased + + def update_from(self, other): + # docstring inherited + super().update_from(other) + self._color = other._color + self._multialignment = other._multialignment + self._verticalalignment = other._verticalalignment + self._horizontalalignment = other._horizontalalignment + self._fontproperties = other._fontproperties.copy() + self._usetex = other._usetex + self._rotation = other._rotation + self._transform_rotates_text = other._transform_rotates_text + self._picker = other._picker + self._linespacing = other._linespacing + self._antialiased = other._antialiased + self.stale = True + + def _get_layout(self, renderer): + """ + Return the extent (bbox) of the text together with + multiple-alignment information. Note that it returns an extent + of a rotated text when necessary. + """ + thisx, thisy = 0.0, 0.0 + lines = self._get_wrapped_text().split("\n") # Ensures lines is not empty. + + ws = [] + hs = [] + xs = [] + ys = [] + + # Full vertical extent of font, including ascenders and descenders: + _, lp_h, lp_d = _get_text_metrics_with_cache( + renderer, "lp", self._fontproperties, + ismath="TeX" if self.get_usetex() else False, + dpi=self.get_figure(root=True).dpi) + min_dy = (lp_h - lp_d) * self._linespacing + + for i, line in enumerate(lines): + clean_line, ismath = self._preprocess_math(line) + if clean_line: + w, h, d = _get_text_metrics_with_cache( + renderer, clean_line, self._fontproperties, + ismath=ismath, dpi=self.get_figure(root=True).dpi) + else: + w = h = d = 0 + + # For multiline text, increase the line spacing when the text + # net-height (excluding baseline) is larger than that of a "l" + # (e.g., use of superscripts), which seems what TeX does. + h = max(h, lp_h) + d = max(d, lp_d) + + ws.append(w) + hs.append(h) + + # Metrics of the last line that are needed later: + baseline = (h - d) - thisy + + if i == 0: + # position at baseline + thisy = -(h - d) + else: + # put baseline a good distance from bottom of previous line + thisy -= max(min_dy, (h - d) * self._linespacing) + + xs.append(thisx) # == 0. + ys.append(thisy) + + thisy -= d + + # Metrics of the last line that are needed later: + descent = d + + # Bounding box definition: + width = max(ws) + xmin = 0 + xmax = width + ymax = 0 + ymin = ys[-1] - descent # baseline of last line minus its descent + + # get the rotation matrix + M = Affine2D().rotate_deg(self.get_rotation()) + + # now offset the individual text lines within the box + malign = self._get_multialignment() + if malign == 'left': + offset_layout = [(x, y) for x, y in zip(xs, ys)] + elif malign == 'center': + offset_layout = [(x + width / 2 - w / 2, y) + for x, y, w in zip(xs, ys, ws)] + elif malign == 'right': + offset_layout = [(x + width - w, y) + for x, y, w in zip(xs, ys, ws)] + + # the corners of the unrotated bounding box + corners_horiz = np.array( + [(xmin, ymin), (xmin, ymax), (xmax, ymax), (xmax, ymin)]) + + # now rotate the bbox + corners_rotated = M.transform(corners_horiz) + # compute the bounds of the rotated box + xmin = corners_rotated[:, 0].min() + xmax = corners_rotated[:, 0].max() + ymin = corners_rotated[:, 1].min() + ymax = corners_rotated[:, 1].max() + width = xmax - xmin + height = ymax - ymin + + # Now move the box to the target position offset the display + # bbox by alignment + halign = self._horizontalalignment + valign = self._verticalalignment + + rotation_mode = self.get_rotation_mode() + if rotation_mode != "anchor": + # compute the text location in display coords and the offsets + # necessary to align the bbox with that location + if halign == 'center': + offsetx = (xmin + xmax) / 2 + elif halign == 'right': + offsetx = xmax + else: + offsetx = xmin + + if valign == 'center': + offsety = (ymin + ymax) / 2 + elif valign == 'top': + offsety = ymax + elif valign == 'baseline': + offsety = ymin + descent + elif valign == 'center_baseline': + offsety = ymin + height - baseline / 2.0 + else: + offsety = ymin + else: + xmin1, ymin1 = corners_horiz[0] + xmax1, ymax1 = corners_horiz[2] + + if halign == 'center': + offsetx = (xmin1 + xmax1) / 2.0 + elif halign == 'right': + offsetx = xmax1 + else: + offsetx = xmin1 + + if valign == 'center': + offsety = (ymin1 + ymax1) / 2.0 + elif valign == 'top': + offsety = ymax1 + elif valign == 'baseline': + offsety = ymax1 - baseline + elif valign == 'center_baseline': + offsety = ymax1 - baseline / 2.0 + else: + offsety = ymin1 + + offsetx, offsety = M.transform((offsetx, offsety)) + + xmin -= offsetx + ymin -= offsety + + bbox = Bbox.from_bounds(xmin, ymin, width, height) + + # now rotate the positions around the first (x, y) position + xys = M.transform(offset_layout) - (offsetx, offsety) + + return bbox, list(zip(lines, zip(ws, hs), *xys.T)), descent + + def set_bbox(self, rectprops): + """ + Draw a bounding box around self. + + Parameters + ---------- + rectprops : dict with properties for `.patches.FancyBboxPatch` + The default boxstyle is 'square'. The mutation + scale of the `.patches.FancyBboxPatch` is set to the fontsize. + + Examples + -------- + :: + + t.set_bbox(dict(facecolor='red', alpha=0.5)) + """ + + if rectprops is not None: + props = rectprops.copy() + boxstyle = props.pop("boxstyle", None) + pad = props.pop("pad", None) + if boxstyle is None: + boxstyle = "square" + if pad is None: + pad = 4 # points + pad /= self.get_size() # to fraction of font size + else: + if pad is None: + pad = 0.3 + # boxstyle could be a callable or a string + if isinstance(boxstyle, str) and "pad" not in boxstyle: + boxstyle += ",pad=%0.2f" % pad + self._bbox_patch = FancyBboxPatch( + (0, 0), 1, 1, + boxstyle=boxstyle, transform=IdentityTransform(), **props) + else: + self._bbox_patch = None + + self._update_clip_properties() + + def get_bbox_patch(self): + """ + Return the bbox Patch, or None if the `.patches.FancyBboxPatch` + is not made. + """ + return self._bbox_patch + + def update_bbox_position_size(self, renderer): + """ + Update the location and the size of the bbox. + + This method should be used when the position and size of the bbox needs + to be updated before actually drawing the bbox. + """ + if self._bbox_patch: + # don't use self.get_unitless_position here, which refers to text + # position in Text: + posx = float(self.convert_xunits(self._x)) + posy = float(self.convert_yunits(self._y)) + posx, posy = self.get_transform().transform((posx, posy)) + + x_box, y_box, w_box, h_box = _get_textbox(self, renderer) + self._bbox_patch.set_bounds(0., 0., w_box, h_box) + self._bbox_patch.set_transform( + Affine2D() + .rotate_deg(self.get_rotation()) + .translate(posx + x_box, posy + y_box)) + fontsize_in_pixel = renderer.points_to_pixels(self.get_size()) + self._bbox_patch.set_mutation_scale(fontsize_in_pixel) + + def _update_clip_properties(self): + if self._bbox_patch: + clipprops = dict(clip_box=self.clipbox, + clip_path=self._clippath, + clip_on=self._clipon) + self._bbox_patch.update(clipprops) + + def set_clip_box(self, clipbox): + # docstring inherited. + super().set_clip_box(clipbox) + self._update_clip_properties() + + def set_clip_path(self, path, transform=None): + # docstring inherited. + super().set_clip_path(path, transform) + self._update_clip_properties() + + def set_clip_on(self, b): + # docstring inherited. + super().set_clip_on(b) + self._update_clip_properties() + + def get_wrap(self): + """Return whether the text can be wrapped.""" + return self._wrap + + def set_wrap(self, wrap): + """ + Set whether the text can be wrapped. + + Wrapping makes sure the text is confined to the (sub)figure box. It + does not take into account any other artists. + + Parameters + ---------- + wrap : bool + + Notes + ----- + Wrapping does not work together with + ``savefig(..., bbox_inches='tight')`` (which is also used internally + by ``%matplotlib inline`` in IPython/Jupyter). The 'tight' setting + rescales the canvas to accommodate all content and happens before + wrapping. + """ + self._wrap = wrap + + def _get_wrap_line_width(self): + """ + Return the maximum line width for wrapping text based on the current + orientation. + """ + x0, y0 = self.get_transform().transform(self.get_position()) + figure_box = self.get_figure().get_window_extent() + + # Calculate available width based on text alignment + alignment = self.get_horizontalalignment() + self.set_rotation_mode('anchor') + rotation = self.get_rotation() + + left = self._get_dist_to_box(rotation, x0, y0, figure_box) + right = self._get_dist_to_box( + (180 + rotation) % 360, x0, y0, figure_box) + + if alignment == 'left': + line_width = left + elif alignment == 'right': + line_width = right + else: + line_width = 2 * min(left, right) + + return line_width + + def _get_dist_to_box(self, rotation, x0, y0, figure_box): + """ + Return the distance from the given points to the boundaries of a + rotated box, in pixels. + """ + if rotation > 270: + quad = rotation - 270 + h1 = (y0 - figure_box.y0) / math.cos(math.radians(quad)) + h2 = (figure_box.x1 - x0) / math.cos(math.radians(90 - quad)) + elif rotation > 180: + quad = rotation - 180 + h1 = (x0 - figure_box.x0) / math.cos(math.radians(quad)) + h2 = (y0 - figure_box.y0) / math.cos(math.radians(90 - quad)) + elif rotation > 90: + quad = rotation - 90 + h1 = (figure_box.y1 - y0) / math.cos(math.radians(quad)) + h2 = (x0 - figure_box.x0) / math.cos(math.radians(90 - quad)) + else: + h1 = (figure_box.x1 - x0) / math.cos(math.radians(rotation)) + h2 = (figure_box.y1 - y0) / math.cos(math.radians(90 - rotation)) + + return min(h1, h2) + + def _get_rendered_text_width(self, text): + """ + Return the width of a given text string, in pixels. + """ + + w, h, d = self._renderer.get_text_width_height_descent( + text, + self.get_fontproperties(), + cbook.is_math_text(text)) + return math.ceil(w) + + def _get_wrapped_text(self): + """ + Return a copy of the text string with new lines added so that the text + is wrapped relative to the parent figure (if `get_wrap` is True). + """ + if not self.get_wrap(): + return self.get_text() + + # Not fit to handle breaking up latex syntax correctly, so + # ignore latex for now. + if self.get_usetex(): + return self.get_text() + + # Build the line incrementally, for a more accurate measure of length + line_width = self._get_wrap_line_width() + wrapped_lines = [] + + # New lines in the user's text force a split + unwrapped_lines = self.get_text().split('\n') + + # Now wrap each individual unwrapped line + for unwrapped_line in unwrapped_lines: + + sub_words = unwrapped_line.split(' ') + # Remove items from sub_words as we go, so stop when empty + while len(sub_words) > 0: + if len(sub_words) == 1: + # Only one word, so just add it to the end + wrapped_lines.append(sub_words.pop(0)) + continue + + for i in range(2, len(sub_words) + 1): + # Get width of all words up to and including here + line = ' '.join(sub_words[:i]) + current_width = self._get_rendered_text_width(line) + + # If all these words are too wide, append all not including + # last word + if current_width > line_width: + wrapped_lines.append(' '.join(sub_words[:i - 1])) + sub_words = sub_words[i - 1:] + break + + # Otherwise if all words fit in the width, append them all + elif i == len(sub_words): + wrapped_lines.append(' '.join(sub_words[:i])) + sub_words = [] + break + + return '\n'.join(wrapped_lines) + + @artist.allow_rasterization + def draw(self, renderer): + # docstring inherited + + if renderer is not None: + self._renderer = renderer + if not self.get_visible(): + return + if self.get_text() == '': + return + + renderer.open_group('text', self.get_gid()) + + with self._cm_set(text=self._get_wrapped_text()): + bbox, info, descent = self._get_layout(renderer) + trans = self.get_transform() + + # don't use self.get_position here, which refers to text + # position in Text: + x, y = self._x, self._y + if np.ma.is_masked(x): + x = np.nan + if np.ma.is_masked(y): + y = np.nan + posx = float(self.convert_xunits(x)) + posy = float(self.convert_yunits(y)) + posx, posy = trans.transform((posx, posy)) + if np.isnan(posx) or np.isnan(posy): + return # don't throw a warning here + if not np.isfinite(posx) or not np.isfinite(posy): + _log.warning("posx and posy should be finite values") + return + canvasw, canvash = renderer.get_canvas_width_height() + + # Update the location and size of the bbox + # (`.patches.FancyBboxPatch`), and draw it. + if self._bbox_patch: + self.update_bbox_position_size(renderer) + self._bbox_patch.draw(renderer) + + gc = renderer.new_gc() + gc.set_foreground(self.get_color()) + gc.set_alpha(self.get_alpha()) + gc.set_url(self._url) + gc.set_antialiased(self._antialiased) + self._set_gc_clip(gc) + + angle = self.get_rotation() + + for line, wh, x, y in info: + + mtext = self if len(info) == 1 else None + x = x + posx + y = y + posy + if renderer.flipy(): + y = canvash - y + clean_line, ismath = self._preprocess_math(line) + + if self.get_path_effects(): + from matplotlib.patheffects import PathEffectRenderer + textrenderer = PathEffectRenderer( + self.get_path_effects(), renderer) + else: + textrenderer = renderer + + if self.get_usetex(): + textrenderer.draw_tex(gc, x, y, clean_line, + self._fontproperties, angle, + mtext=mtext) + else: + textrenderer.draw_text(gc, x, y, clean_line, + self._fontproperties, angle, + ismath=ismath, mtext=mtext) + + gc.restore() + renderer.close_group('text') + self.stale = False + + def get_color(self): + """Return the color of the text.""" + return self._color + + def get_fontproperties(self): + """Return the `.font_manager.FontProperties`.""" + return self._fontproperties + + def get_fontfamily(self): + """ + Return the list of font families used for font lookup. + + See Also + -------- + .font_manager.FontProperties.get_family + """ + return self._fontproperties.get_family() + + def get_fontname(self): + """ + Return the font name as a string. + + See Also + -------- + .font_manager.FontProperties.get_name + """ + return self._fontproperties.get_name() + + def get_fontstyle(self): + """ + Return the font style as a string. + + See Also + -------- + .font_manager.FontProperties.get_style + """ + return self._fontproperties.get_style() + + def get_fontsize(self): + """ + Return the font size as an integer. + + See Also + -------- + .font_manager.FontProperties.get_size_in_points + """ + return self._fontproperties.get_size_in_points() + + def get_fontvariant(self): + """ + Return the font variant as a string. + + See Also + -------- + .font_manager.FontProperties.get_variant + """ + return self._fontproperties.get_variant() + + def get_fontweight(self): + """ + Return the font weight as a string or a number. + + See Also + -------- + .font_manager.FontProperties.get_weight + """ + return self._fontproperties.get_weight() + + def get_stretch(self): + """ + Return the font stretch as a string or a number. + + See Also + -------- + .font_manager.FontProperties.get_stretch + """ + return self._fontproperties.get_stretch() + + def get_horizontalalignment(self): + """ + Return the horizontal alignment as a string. Will be one of + 'left', 'center' or 'right'. + """ + return self._horizontalalignment + + def get_unitless_position(self): + """Return the (x, y) unitless position of the text.""" + # This will get the position with all unit information stripped away. + # This is here for convenience since it is done in several locations. + x = float(self.convert_xunits(self._x)) + y = float(self.convert_yunits(self._y)) + return x, y + + def get_position(self): + """Return the (x, y) position of the text.""" + # This should return the same data (possible unitized) as was + # specified with 'set_x' and 'set_y'. + return self._x, self._y + + def get_text(self): + """Return the text string.""" + return self._text + + def get_verticalalignment(self): + """ + Return the vertical alignment as a string. Will be one of + 'top', 'center', 'bottom', 'baseline' or 'center_baseline'. + """ + return self._verticalalignment + + def get_window_extent(self, renderer=None, dpi=None): + """ + Return the `.Bbox` bounding the text, in display units. + + In addition to being used internally, this is useful for specifying + clickable regions in a png file on a web page. + + Parameters + ---------- + renderer : Renderer, optional + A renderer is needed to compute the bounding box. If the artist + has already been drawn, the renderer is cached; thus, it is only + necessary to pass this argument when calling `get_window_extent` + before the first draw. In practice, it is usually easier to + trigger a draw first, e.g. by calling + `~.Figure.draw_without_rendering` or ``plt.show()``. + + dpi : float, optional + The dpi value for computing the bbox, defaults to + ``self.get_figure(root=True).dpi`` (*not* the renderer dpi); should be set + e.g. if to match regions with a figure saved with a custom dpi value. + """ + if not self.get_visible(): + return Bbox.unit() + + fig = self.get_figure(root=True) + if dpi is None: + dpi = fig.dpi + if self.get_text() == '': + with cbook._setattr_cm(fig, dpi=dpi): + tx, ty = self._get_xy_display() + return Bbox.from_bounds(tx, ty, 0, 0) + + if renderer is not None: + self._renderer = renderer + if self._renderer is None: + self._renderer = fig._get_renderer() + if self._renderer is None: + raise RuntimeError( + "Cannot get window extent of text w/o renderer. You likely " + "want to call 'figure.draw_without_rendering()' first.") + + with cbook._setattr_cm(fig, dpi=dpi): + bbox, info, descent = self._get_layout(self._renderer) + x, y = self.get_unitless_position() + x, y = self.get_transform().transform((x, y)) + bbox = bbox.translated(x, y) + return bbox + + def set_backgroundcolor(self, color): + """ + Set the background color of the text by updating the bbox. + + Parameters + ---------- + color : :mpltype:`color` + + See Also + -------- + .set_bbox : To change the position of the bounding box + """ + if self._bbox_patch is None: + self.set_bbox(dict(facecolor=color, edgecolor=color)) + else: + self._bbox_patch.update(dict(facecolor=color)) + + self._update_clip_properties() + self.stale = True + + def set_color(self, color): + """ + Set the foreground color of the text + + Parameters + ---------- + color : :mpltype:`color` + """ + # "auto" is only supported by axisartist, but we can just let it error + # out at draw time for simplicity. + if not cbook._str_equal(color, "auto"): + mpl.colors._check_color_like(color=color) + self._color = color + self.stale = True + + def set_horizontalalignment(self, align): + """ + Set the horizontal alignment relative to the anchor point. + + See also :doc:`/gallery/text_labels_and_annotations/text_alignment`. + + Parameters + ---------- + align : {'left', 'center', 'right'} + """ + _api.check_in_list(['center', 'right', 'left'], align=align) + self._horizontalalignment = align + self.stale = True + + def set_multialignment(self, align): + """ + Set the text alignment for multiline texts. + + The layout of the bounding box of all the lines is determined by the + horizontalalignment and verticalalignment properties. This property + controls the alignment of the text lines within that box. + + Parameters + ---------- + align : {'left', 'right', 'center'} + """ + _api.check_in_list(['center', 'right', 'left'], align=align) + self._multialignment = align + self.stale = True + + def set_linespacing(self, spacing): + """ + Set the line spacing as a multiple of the font size. + + The default line spacing is 1.2. + + Parameters + ---------- + spacing : float (multiple of font size) + """ + _api.check_isinstance(Real, spacing=spacing) + self._linespacing = spacing + self.stale = True + + def set_fontfamily(self, fontname): + """ + Set the font family. Can be either a single string, or a list of + strings in decreasing priority. Each string may be either a real font + name or a generic font class name. If the latter, the specific font + names will be looked up in the corresponding rcParams. + + If a `Text` instance is constructed with ``fontfamily=None``, then the + font is set to :rc:`font.family`, and the + same is done when `set_fontfamily()` is called on an existing + `Text` instance. + + Parameters + ---------- + fontname : {FONTNAME, 'serif', 'sans-serif', 'cursive', 'fantasy', \ +'monospace'} + + See Also + -------- + .font_manager.FontProperties.set_family + """ + self._fontproperties.set_family(fontname) + self.stale = True + + def set_fontvariant(self, variant): + """ + Set the font variant. + + Parameters + ---------- + variant : {'normal', 'small-caps'} + + See Also + -------- + .font_manager.FontProperties.set_variant + """ + self._fontproperties.set_variant(variant) + self.stale = True + + def set_fontstyle(self, fontstyle): + """ + Set the font style. + + Parameters + ---------- + fontstyle : {'normal', 'italic', 'oblique'} + + See Also + -------- + .font_manager.FontProperties.set_style + """ + self._fontproperties.set_style(fontstyle) + self.stale = True + + def set_fontsize(self, fontsize): + """ + Set the font size. + + Parameters + ---------- + fontsize : float or {'xx-small', 'x-small', 'small', 'medium', \ +'large', 'x-large', 'xx-large'} + If a float, the fontsize in points. The string values denote sizes + relative to the default font size. + + See Also + -------- + .font_manager.FontProperties.set_size + """ + self._fontproperties.set_size(fontsize) + self.stale = True + + def get_math_fontfamily(self): + """ + Return the font family name for math text rendered by Matplotlib. + + The default value is :rc:`mathtext.fontset`. + + See Also + -------- + set_math_fontfamily + """ + return self._fontproperties.get_math_fontfamily() + + def set_math_fontfamily(self, fontfamily): + """ + Set the font family for math text rendered by Matplotlib. + + This does only affect Matplotlib's own math renderer. It has no effect + when rendering with TeX (``usetex=True``). + + Parameters + ---------- + fontfamily : str + The name of the font family. + + Available font families are defined in the + :ref:`default matplotlibrc file + `. + + See Also + -------- + get_math_fontfamily + """ + self._fontproperties.set_math_fontfamily(fontfamily) + + def set_fontweight(self, weight): + """ + Set the font weight. + + Parameters + ---------- + weight : {a numeric value in range 0-1000, 'ultralight', 'light', \ +'normal', 'regular', 'book', 'medium', 'roman', 'semibold', 'demibold', \ +'demi', 'bold', 'heavy', 'extra bold', 'black'} + + See Also + -------- + .font_manager.FontProperties.set_weight + """ + self._fontproperties.set_weight(weight) + self.stale = True + + def set_fontstretch(self, stretch): + """ + Set the font stretch (horizontal condensation or expansion). + + Parameters + ---------- + stretch : {a numeric value in range 0-1000, 'ultra-condensed', \ +'extra-condensed', 'condensed', 'semi-condensed', 'normal', 'semi-expanded', \ +'expanded', 'extra-expanded', 'ultra-expanded'} + + See Also + -------- + .font_manager.FontProperties.set_stretch + """ + self._fontproperties.set_stretch(stretch) + self.stale = True + + def set_position(self, xy): + """ + Set the (*x*, *y*) position of the text. + + Parameters + ---------- + xy : (float, float) + """ + self.set_x(xy[0]) + self.set_y(xy[1]) + + def set_x(self, x): + """ + Set the *x* position of the text. + + Parameters + ---------- + x : float + """ + self._x = x + self.stale = True + + def set_y(self, y): + """ + Set the *y* position of the text. + + Parameters + ---------- + y : float + """ + self._y = y + self.stale = True + + def set_rotation(self, s): + """ + Set the rotation of the text. + + Parameters + ---------- + s : float or {'vertical', 'horizontal'} + The rotation angle in degrees in mathematically positive direction + (counterclockwise). 'horizontal' equals 0, 'vertical' equals 90. + """ + if isinstance(s, Real): + self._rotation = float(s) % 360 + elif cbook._str_equal(s, 'horizontal') or s is None: + self._rotation = 0. + elif cbook._str_equal(s, 'vertical'): + self._rotation = 90. + else: + raise ValueError("rotation must be 'vertical', 'horizontal' or " + f"a number, not {s}") + self.stale = True + + def set_transform_rotates_text(self, t): + """ + Whether rotations of the transform affect the text direction. + + Parameters + ---------- + t : bool + """ + self._transform_rotates_text = t + self.stale = True + + def set_verticalalignment(self, align): + """ + Set the vertical alignment relative to the anchor point. + + See also :doc:`/gallery/text_labels_and_annotations/text_alignment`. + + Parameters + ---------- + align : {'baseline', 'bottom', 'center', 'center_baseline', 'top'} + """ + _api.check_in_list( + ['top', 'bottom', 'center', 'baseline', 'center_baseline'], + align=align) + self._verticalalignment = align + self.stale = True + + def set_text(self, s): + r""" + Set the text string *s*. + + It may contain newlines (``\n``) or math in LaTeX syntax. + + Parameters + ---------- + s : object + Any object gets converted to its `str` representation, except for + ``None`` which is converted to an empty string. + """ + s = '' if s is None else str(s) + if s != self._text: + self._text = s + self.stale = True + + def _preprocess_math(self, s): + """ + Return the string *s* after mathtext preprocessing, and the kind of + mathtext support needed. + + - If *self* is configured to use TeX, return *s* unchanged except that + a single space gets escaped, and the flag "TeX". + - Otherwise, if *s* is mathtext (has an even number of unescaped dollar + signs) and ``parse_math`` is not set to False, return *s* and the + flag True. + - Otherwise, return *s* with dollar signs unescaped, and the flag + False. + """ + if self.get_usetex(): + if s == " ": + s = r"\ " + return s, "TeX" + elif not self.get_parse_math(): + return s, False + elif cbook.is_math_text(s): + return s, True + else: + return s.replace(r"\$", "$"), False + + def set_fontproperties(self, fp): + """ + Set the font properties that control the text. + + Parameters + ---------- + fp : `.font_manager.FontProperties` or `str` or `pathlib.Path` + If a `str`, it is interpreted as a fontconfig pattern parsed by + `.FontProperties`. If a `pathlib.Path`, it is interpreted as the + absolute path to a font file. + """ + self._fontproperties = FontProperties._from_any(fp).copy() + self.stale = True + + @_docstring.kwarg_doc("bool, default: :rc:`text.usetex`") + def set_usetex(self, usetex): + """ + Parameters + ---------- + usetex : bool or None + Whether to render using TeX, ``None`` means to use + :rc:`text.usetex`. + """ + if usetex is None: + self._usetex = mpl.rcParams['text.usetex'] + else: + self._usetex = bool(usetex) + self.stale = True + + def get_usetex(self): + """Return whether this `Text` object uses TeX for rendering.""" + return self._usetex + + def set_parse_math(self, parse_math): + """ + Override switch to disable any mathtext parsing for this `Text`. + + Parameters + ---------- + parse_math : bool + If False, this `Text` will never use mathtext. If True, mathtext + will be used if there is an even number of unescaped dollar signs. + """ + self._parse_math = bool(parse_math) + + def get_parse_math(self): + """Return whether mathtext parsing is considered for this `Text`.""" + return self._parse_math + + def set_fontname(self, fontname): + """ + Alias for `set_fontfamily`. + + One-way alias only: the getter differs. + + Parameters + ---------- + fontname : {FONTNAME, 'serif', 'sans-serif', 'cursive', 'fantasy', \ +'monospace'} + + See Also + -------- + .font_manager.FontProperties.set_family + + """ + self.set_fontfamily(fontname) + + +class OffsetFrom: + """Callable helper class for working with `Annotation`.""" + + def __init__(self, artist, ref_coord, unit="points"): + """ + Parameters + ---------- + artist : `~matplotlib.artist.Artist` or `.BboxBase` or `.Transform` + The object to compute the offset from. + + ref_coord : (float, float) + If *artist* is an `.Artist` or `.BboxBase`, this values is + the location to of the offset origin in fractions of the + *artist* bounding box. + + If *artist* is a transform, the offset origin is the + transform applied to this value. + + unit : {'points, 'pixels'}, default: 'points' + The screen units to use (pixels or points) for the offset input. + """ + self._artist = artist + x, y = ref_coord # Make copy when ref_coord is an array (and check the shape). + self._ref_coord = x, y + self.set_unit(unit) + + def set_unit(self, unit): + """ + Set the unit for input to the transform used by ``__call__``. + + Parameters + ---------- + unit : {'points', 'pixels'} + """ + _api.check_in_list(["points", "pixels"], unit=unit) + self._unit = unit + + def get_unit(self): + """Return the unit for input to the transform used by ``__call__``.""" + return self._unit + + def __call__(self, renderer): + """ + Return the offset transform. + + Parameters + ---------- + renderer : `RendererBase` + The renderer to use to compute the offset + + Returns + ------- + `Transform` + Maps (x, y) in pixel or point units to screen units + relative to the given artist. + """ + if isinstance(self._artist, Artist): + bbox = self._artist.get_window_extent(renderer) + xf, yf = self._ref_coord + x = bbox.x0 + bbox.width * xf + y = bbox.y0 + bbox.height * yf + elif isinstance(self._artist, BboxBase): + bbox = self._artist + xf, yf = self._ref_coord + x = bbox.x0 + bbox.width * xf + y = bbox.y0 + bbox.height * yf + elif isinstance(self._artist, Transform): + x, y = self._artist.transform(self._ref_coord) + else: + _api.check_isinstance((Artist, BboxBase, Transform), artist=self._artist) + scale = 1 if self._unit == "pixels" else renderer.points_to_pixels(1) + return Affine2D().scale(scale).translate(x, y) + + +class _AnnotationBase: + def __init__(self, + xy, + xycoords='data', + annotation_clip=None): + + x, y = xy # Make copy when xy is an array (and check the shape). + self.xy = x, y + self.xycoords = xycoords + self.set_annotation_clip(annotation_clip) + + self._draggable = None + + def _get_xy(self, renderer, xy, coords): + x, y = xy + xcoord, ycoord = coords if isinstance(coords, tuple) else (coords, coords) + if xcoord == 'data': + x = float(self.convert_xunits(x)) + if ycoord == 'data': + y = float(self.convert_yunits(y)) + return self._get_xy_transform(renderer, coords).transform((x, y)) + + def _get_xy_transform(self, renderer, coords): + + if isinstance(coords, tuple): + xcoord, ycoord = coords + from matplotlib.transforms import blended_transform_factory + tr1 = self._get_xy_transform(renderer, xcoord) + tr2 = self._get_xy_transform(renderer, ycoord) + return blended_transform_factory(tr1, tr2) + elif callable(coords): + tr = coords(renderer) + if isinstance(tr, BboxBase): + return BboxTransformTo(tr) + elif isinstance(tr, Transform): + return tr + else: + raise TypeError( + f"xycoords callable must return a BboxBase or Transform, not a " + f"{type(tr).__name__}") + elif isinstance(coords, Artist): + bbox = coords.get_window_extent(renderer) + return BboxTransformTo(bbox) + elif isinstance(coords, BboxBase): + return BboxTransformTo(coords) + elif isinstance(coords, Transform): + return coords + elif not isinstance(coords, str): + raise TypeError( + f"'xycoords' must be an instance of str, tuple[str, str], Artist, " + f"Transform, or Callable, not a {type(coords).__name__}") + + if coords == 'data': + return self.axes.transData + elif coords == 'polar': + from matplotlib.projections import PolarAxes + tr = PolarAxes.PolarTransform(apply_theta_transforms=False) + trans = tr + self.axes.transData + return trans + + try: + bbox_name, unit = coords.split() + except ValueError: # i.e. len(coords.split()) != 2. + raise ValueError(f"{coords!r} is not a valid coordinate") from None + + bbox0, xy0 = None, None + + # if unit is offset-like + if bbox_name == "figure": + bbox0 = self.get_figure(root=False).figbbox + elif bbox_name == "subfigure": + bbox0 = self.get_figure(root=False).bbox + elif bbox_name == "axes": + bbox0 = self.axes.bbox + + # reference x, y in display coordinate + if bbox0 is not None: + xy0 = bbox0.p0 + elif bbox_name == "offset": + xy0 = self._get_position_xy(renderer) + else: + raise ValueError(f"{coords!r} is not a valid coordinate") + + if unit == "points": + tr = Affine2D().scale( + self.get_figure(root=True).dpi / 72) # dpi/72 dots per point + elif unit == "pixels": + tr = Affine2D() + elif unit == "fontsize": + tr = Affine2D().scale( + self.get_size() * self.get_figure(root=True).dpi / 72) + elif unit == "fraction": + tr = Affine2D().scale(*bbox0.size) + else: + raise ValueError(f"{unit!r} is not a recognized unit") + + return tr.translate(*xy0) + + def set_annotation_clip(self, b): + """ + Set the annotation's clipping behavior. + + Parameters + ---------- + b : bool or None + - True: The annotation will be clipped when ``self.xy`` is + outside the Axes. + - False: The annotation will always be drawn. + - None: The annotation will be clipped when ``self.xy`` is + outside the Axes and ``self.xycoords == "data"``. + """ + self._annotation_clip = b + + def get_annotation_clip(self): + """ + Return the annotation's clipping behavior. + + See `set_annotation_clip` for the meaning of return values. + """ + return self._annotation_clip + + def _get_position_xy(self, renderer): + """Return the pixel position of the annotated point.""" + return self._get_xy(renderer, self.xy, self.xycoords) + + def _check_xy(self, renderer=None): + """Check whether the annotation at *xy_pixel* should be drawn.""" + if renderer is None: + renderer = self.get_figure(root=True)._get_renderer() + b = self.get_annotation_clip() + if b or (b is None and self.xycoords == "data"): + # check if self.xy is inside the Axes. + xy_pixel = self._get_position_xy(renderer) + return self.axes.contains_point(xy_pixel) + return True + + def draggable(self, state=None, use_blit=False): + """ + Set whether the annotation is draggable with the mouse. + + Parameters + ---------- + state : bool or None + - True or False: set the draggability. + - None: toggle the draggability. + use_blit : bool, default: False + Use blitting for faster image composition. For details see + :ref:`func-animation`. + + Returns + ------- + DraggableAnnotation or None + If the annotation is draggable, the corresponding + `.DraggableAnnotation` helper is returned. + """ + from matplotlib.offsetbox import DraggableAnnotation + is_draggable = self._draggable is not None + + # if state is None we'll toggle + if state is None: + state = not is_draggable + + if state: + if self._draggable is None: + self._draggable = DraggableAnnotation(self, use_blit) + else: + if self._draggable is not None: + self._draggable.disconnect() + self._draggable = None + + return self._draggable + + +class Annotation(Text, _AnnotationBase): + """ + An `.Annotation` is a `.Text` that can refer to a specific position *xy*. + Optionally an arrow pointing from the text to *xy* can be drawn. + + Attributes + ---------- + xy + The annotated position. + xycoords + The coordinate system for *xy*. + arrow_patch + A `.FancyArrowPatch` to point from *xytext* to *xy*. + """ + + def __str__(self): + return f"Annotation({self.xy[0]:g}, {self.xy[1]:g}, {self._text!r})" + + def __init__(self, text, xy, + xytext=None, + xycoords='data', + textcoords=None, + arrowprops=None, + annotation_clip=None, + **kwargs): + """ + Annotate the point *xy* with text *text*. + + In the simplest form, the text is placed at *xy*. + + Optionally, the text can be displayed in another position *xytext*. + An arrow pointing from the text to the annotated point *xy* can then + be added by defining *arrowprops*. + + Parameters + ---------- + text : str + The text of the annotation. + + xy : (float, float) + The point *(x, y)* to annotate. The coordinate system is determined + by *xycoords*. + + xytext : (float, float), default: *xy* + The position *(x, y)* to place the text at. The coordinate system + is determined by *textcoords*. + + xycoords : single or two-tuple of str or `.Artist` or `.Transform` or \ +callable, default: 'data' + + The coordinate system that *xy* is given in. The following types + of values are supported: + + - One of the following strings: + + ==================== ============================================ + Value Description + ==================== ============================================ + 'figure points' Points from the lower left of the figure + 'figure pixels' Pixels from the lower left of the figure + 'figure fraction' Fraction of figure from lower left + 'subfigure points' Points from the lower left of the subfigure + 'subfigure pixels' Pixels from the lower left of the subfigure + 'subfigure fraction' Fraction of subfigure from lower left + 'axes points' Points from lower left corner of the Axes + 'axes pixels' Pixels from lower left corner of the Axes + 'axes fraction' Fraction of Axes from lower left + 'data' Use the coordinate system of the object + being annotated (default) + 'polar' *(theta, r)* if not native 'data' + coordinates + ==================== ============================================ + + Note that 'subfigure pixels' and 'figure pixels' are the same + for the parent figure, so users who want code that is usable in + a subfigure can use 'subfigure pixels'. + + - An `.Artist`: *xy* is interpreted as a fraction of the artist's + `~matplotlib.transforms.Bbox`. E.g. *(0, 0)* would be the lower + left corner of the bounding box and *(0.5, 1)* would be the + center top of the bounding box. + + - A `.Transform` to transform *xy* to screen coordinates. + + - A function with one of the following signatures:: + + def transform(renderer) -> Bbox + def transform(renderer) -> Transform + + where *renderer* is a `.RendererBase` subclass. + + The result of the function is interpreted like the `.Artist` and + `.Transform` cases above. + + - A tuple *(xcoords, ycoords)* specifying separate coordinate + systems for *x* and *y*. *xcoords* and *ycoords* must each be + of one of the above described types. + + See :ref:`plotting-guide-annotation` for more details. + + textcoords : single or two-tuple of str or `.Artist` or `.Transform` \ +or callable, default: value of *xycoords* + The coordinate system that *xytext* is given in. + + All *xycoords* values are valid as well as the following strings: + + ================= ================================================= + Value Description + ================= ================================================= + 'offset points' Offset, in points, from the *xy* value + 'offset pixels' Offset, in pixels, from the *xy* value + 'offset fontsize' Offset, relative to fontsize, from the *xy* value + ================= ================================================= + + arrowprops : dict, optional + The properties used to draw a `.FancyArrowPatch` arrow between the + positions *xy* and *xytext*. Defaults to None, i.e. no arrow is + drawn. + + For historical reasons there are two different ways to specify + arrows, "simple" and "fancy": + + **Simple arrow:** + + If *arrowprops* does not contain the key 'arrowstyle' the + allowed keys are: + + ========== ================================================= + Key Description + ========== ================================================= + width The width of the arrow in points + headwidth The width of the base of the arrow head in points + headlength The length of the arrow head in points + shrink Fraction of total length to shrink from both ends + ? Any `.FancyArrowPatch` property + ========== ================================================= + + The arrow is attached to the edge of the text box, the exact + position (corners or centers) depending on where it's pointing to. + + **Fancy arrow:** + + This is used if 'arrowstyle' is provided in the *arrowprops*. + + Valid keys are the following `.FancyArrowPatch` parameters: + + =============== =================================== + Key Description + =============== =================================== + arrowstyle The arrow style + connectionstyle The connection style + relpos See below; default is (0.5, 0.5) + patchA Default is bounding box of the text + patchB Default is None + shrinkA In points. Default is 2 points + shrinkB In points. Default is 2 points + mutation_scale Default is text size (in points) + mutation_aspect Default is 1 + ? Any `.FancyArrowPatch` property + =============== =================================== + + The exact starting point position of the arrow is defined by + *relpos*. It's a tuple of relative coordinates of the text box, + where (0, 0) is the lower left corner and (1, 1) is the upper + right corner. Values <0 and >1 are supported and specify points + outside the text box. By default (0.5, 0.5), so the starting point + is centered in the text box. + + annotation_clip : bool or None, default: None + Whether to clip (i.e. not draw) the annotation when the annotation + point *xy* is outside the Axes area. + + - If *True*, the annotation will be clipped when *xy* is outside + the Axes. + - If *False*, the annotation will always be drawn. + - If *None*, the annotation will be clipped when *xy* is outside + the Axes and *xycoords* is 'data'. + + **kwargs + Additional kwargs are passed to `.Text`. + + Returns + ------- + `.Annotation` + + See Also + -------- + :ref:`annotations` + + """ + _AnnotationBase.__init__(self, + xy, + xycoords=xycoords, + annotation_clip=annotation_clip) + # warn about wonky input data + if (xytext is None and + textcoords is not None and + textcoords != xycoords): + _api.warn_external("You have used the `textcoords` kwarg, but " + "not the `xytext` kwarg. This can lead to " + "surprising results.") + + # clean up textcoords and assign default + if textcoords is None: + textcoords = self.xycoords + self._textcoords = textcoords + + # cleanup xytext defaults + if xytext is None: + xytext = self.xy + x, y = xytext + + self.arrowprops = arrowprops + if arrowprops is not None: + arrowprops = arrowprops.copy() + if "arrowstyle" in arrowprops: + self._arrow_relpos = arrowprops.pop("relpos", (0.5, 0.5)) + else: + # modified YAArrow API to be used with FancyArrowPatch + for key in ['width', 'headwidth', 'headlength', 'shrink']: + arrowprops.pop(key, None) + self.arrow_patch = FancyArrowPatch((0, 0), (1, 1), **arrowprops) + else: + self.arrow_patch = None + + # Must come last, as some kwargs may be propagated to arrow_patch. + Text.__init__(self, x, y, text, **kwargs) + + def contains(self, mouseevent): + if self._different_canvas(mouseevent): + return False, {} + contains, tinfo = Text.contains(self, mouseevent) + if self.arrow_patch is not None: + in_patch, _ = self.arrow_patch.contains(mouseevent) + contains = contains or in_patch + return contains, tinfo + + @property + def xycoords(self): + return self._xycoords + + @xycoords.setter + def xycoords(self, xycoords): + def is_offset(s): + return isinstance(s, str) and s.startswith("offset") + + if (isinstance(xycoords, tuple) and any(map(is_offset, xycoords)) + or is_offset(xycoords)): + raise ValueError("xycoords cannot be an offset coordinate") + self._xycoords = xycoords + + @property + def xyann(self): + """ + The text position. + + See also *xytext* in `.Annotation`. + """ + return self.get_position() + + @xyann.setter + def xyann(self, xytext): + self.set_position(xytext) + + def get_anncoords(self): + """ + Return the coordinate system to use for `.Annotation.xyann`. + + See also *xycoords* in `.Annotation`. + """ + return self._textcoords + + def set_anncoords(self, coords): + """ + Set the coordinate system to use for `.Annotation.xyann`. + + See also *xycoords* in `.Annotation`. + """ + self._textcoords = coords + + anncoords = property(get_anncoords, set_anncoords, doc=""" + The coordinate system to use for `.Annotation.xyann`.""") + + def set_figure(self, fig): + # docstring inherited + if self.arrow_patch is not None: + self.arrow_patch.set_figure(fig) + Artist.set_figure(self, fig) + + def update_positions(self, renderer): + """ + Update the pixel positions of the annotation text and the arrow patch. + """ + # generate transformation + self.set_transform(self._get_xy_transform(renderer, self.anncoords)) + + arrowprops = self.arrowprops + if arrowprops is None: + return + + bbox = Text.get_window_extent(self, renderer) + + arrow_end = x1, y1 = self._get_position_xy(renderer) # Annotated pos. + + ms = arrowprops.get("mutation_scale", self.get_size()) + self.arrow_patch.set_mutation_scale(ms) + + if "arrowstyle" not in arrowprops: + # Approximately simulate the YAArrow. + shrink = arrowprops.get('shrink', 0.0) + width = arrowprops.get('width', 4) + headwidth = arrowprops.get('headwidth', 12) + headlength = arrowprops.get('headlength', 12) + + # NB: ms is in pts + stylekw = dict(head_length=headlength / ms, + head_width=headwidth / ms, + tail_width=width / ms) + + self.arrow_patch.set_arrowstyle('simple', **stylekw) + + # using YAArrow style: + # pick the corner of the text bbox closest to annotated point. + xpos = [(bbox.x0, 0), ((bbox.x0 + bbox.x1) / 2, 0.5), (bbox.x1, 1)] + ypos = [(bbox.y0, 0), ((bbox.y0 + bbox.y1) / 2, 0.5), (bbox.y1, 1)] + x, relposx = min(xpos, key=lambda v: abs(v[0] - x1)) + y, relposy = min(ypos, key=lambda v: abs(v[0] - y1)) + self._arrow_relpos = (relposx, relposy) + r = np.hypot(y - y1, x - x1) + shrink_pts = shrink * r / renderer.points_to_pixels(1) + self.arrow_patch.shrinkA = self.arrow_patch.shrinkB = shrink_pts + + # adjust the starting point of the arrow relative to the textbox. + # TODO : Rotation needs to be accounted. + arrow_begin = bbox.p0 + bbox.size * self._arrow_relpos + # The arrow is drawn from arrow_begin to arrow_end. It will be first + # clipped by patchA and patchB. Then it will be shrunk by shrinkA and + # shrinkB (in points). If patchA is not set, self.bbox_patch is used. + self.arrow_patch.set_positions(arrow_begin, arrow_end) + + if "patchA" in arrowprops: + patchA = arrowprops["patchA"] + elif self._bbox_patch: + patchA = self._bbox_patch + elif self.get_text() == "": + patchA = None + else: + pad = renderer.points_to_pixels(4) + patchA = Rectangle( + xy=(bbox.x0 - pad / 2, bbox.y0 - pad / 2), + width=bbox.width + pad, height=bbox.height + pad, + transform=IdentityTransform(), clip_on=False) + self.arrow_patch.set_patchA(patchA) + + @artist.allow_rasterization + def draw(self, renderer): + # docstring inherited + if renderer is not None: + self._renderer = renderer + if not self.get_visible() or not self._check_xy(renderer): + return + # Update text positions before `Text.draw` would, so that the + # FancyArrowPatch is correctly positioned. + self.update_positions(renderer) + self.update_bbox_position_size(renderer) + if self.arrow_patch is not None: # FancyArrowPatch + if (self.arrow_patch.get_figure(root=False) is None and + (fig := self.get_figure(root=False)) is not None): + self.arrow_patch.set_figure(fig) + self.arrow_patch.draw(renderer) + # Draw text, including FancyBboxPatch, after FancyArrowPatch. + # Otherwise, a wedge arrowstyle can land partly on top of the Bbox. + Text.draw(self, renderer) + + def get_window_extent(self, renderer=None): + # docstring inherited + # This block is the same as in Text.get_window_extent, but we need to + # set the renderer before calling update_positions(). + if not self.get_visible() or not self._check_xy(renderer): + return Bbox.unit() + if renderer is not None: + self._renderer = renderer + if self._renderer is None: + self._renderer = self.get_figure(root=True)._get_renderer() + if self._renderer is None: + raise RuntimeError('Cannot get window extent without renderer') + + self.update_positions(self._renderer) + + text_bbox = Text.get_window_extent(self) + bboxes = [text_bbox] + + if self.arrow_patch is not None: + bboxes.append(self.arrow_patch.get_window_extent()) + + return Bbox.union(bboxes) + + def get_tightbbox(self, renderer=None): + # docstring inherited + if not self._check_xy(renderer): + return Bbox.null() + return super().get_tightbbox(renderer) + + +_docstring.interpd.register(Annotation=Annotation.__init__.__doc__) diff --git a/infer_4_30_0/lib/python3.10/site-packages/matplotlib/textpath.py b/infer_4_30_0/lib/python3.10/site-packages/matplotlib/textpath.py new file mode 100644 index 0000000000000000000000000000000000000000..83182e3f54002fbdef9c8fcae89f64ad0ff87d5f --- /dev/null +++ b/infer_4_30_0/lib/python3.10/site-packages/matplotlib/textpath.py @@ -0,0 +1,397 @@ +from collections import OrderedDict +import logging +import urllib.parse + +import numpy as np + +from matplotlib import _text_helpers, dviread +from matplotlib.font_manager import ( + FontProperties, get_font, fontManager as _fontManager +) +from matplotlib.ft2font import LoadFlags +from matplotlib.mathtext import MathTextParser +from matplotlib.path import Path +from matplotlib.texmanager import TexManager +from matplotlib.transforms import Affine2D + +_log = logging.getLogger(__name__) + + +class TextToPath: + """A class that converts strings to paths.""" + + FONT_SCALE = 100. + DPI = 72 + + def __init__(self): + self.mathtext_parser = MathTextParser('path') + self._texmanager = None + + def _get_font(self, prop): + """ + Find the `FT2Font` matching font properties *prop*, with its size set. + """ + filenames = _fontManager._find_fonts_by_props(prop) + font = get_font(filenames) + font.set_size(self.FONT_SCALE, self.DPI) + return font + + def _get_hinting_flag(self): + return LoadFlags.NO_HINTING + + def _get_char_id(self, font, ccode): + """ + Return a unique id for the given font and character-code set. + """ + return urllib.parse.quote(f"{font.postscript_name}-{ccode:x}") + + def get_text_width_height_descent(self, s, prop, ismath): + fontsize = prop.get_size_in_points() + + if ismath == "TeX": + return TexManager().get_text_width_height_descent(s, fontsize) + + scale = fontsize / self.FONT_SCALE + + if ismath: + prop = prop.copy() + prop.set_size(self.FONT_SCALE) + width, height, descent, *_ = \ + self.mathtext_parser.parse(s, 72, prop) + return width * scale, height * scale, descent * scale + + font = self._get_font(prop) + font.set_text(s, 0.0, flags=LoadFlags.NO_HINTING) + w, h = font.get_width_height() + w /= 64.0 # convert from subpixels + h /= 64.0 + d = font.get_descent() + d /= 64.0 + return w * scale, h * scale, d * scale + + def get_text_path(self, prop, s, ismath=False): + """ + Convert text *s* to path (a tuple of vertices and codes for + matplotlib.path.Path). + + Parameters + ---------- + prop : `~matplotlib.font_manager.FontProperties` + The font properties for the text. + s : str + The text to be converted. + ismath : {False, True, "TeX"} + If True, use mathtext parser. If "TeX", use tex for rendering. + + Returns + ------- + verts : list + A list of arrays containing the (x, y) coordinates of the vertices. + codes : list + A list of path codes. + + Examples + -------- + Create a list of vertices and codes from a text, and create a `.Path` + from those:: + + from matplotlib.path import Path + from matplotlib.text import TextToPath + from matplotlib.font_manager import FontProperties + + fp = FontProperties(family="Comic Neue", style="italic") + verts, codes = TextToPath().get_text_path(fp, "ABC") + path = Path(verts, codes, closed=False) + + Also see `TextPath` for a more direct way to create a path from a text. + """ + if ismath == "TeX": + glyph_info, glyph_map, rects = self.get_glyphs_tex(prop, s) + elif not ismath: + font = self._get_font(prop) + glyph_info, glyph_map, rects = self.get_glyphs_with_font(font, s) + else: + glyph_info, glyph_map, rects = self.get_glyphs_mathtext(prop, s) + + verts, codes = [], [] + for glyph_id, xposition, yposition, scale in glyph_info: + verts1, codes1 = glyph_map[glyph_id] + verts.extend(verts1 * scale + [xposition, yposition]) + codes.extend(codes1) + for verts1, codes1 in rects: + verts.extend(verts1) + codes.extend(codes1) + + # Make sure an empty string or one with nothing to print + # (e.g. only spaces & newlines) will be valid/empty path + if not verts: + verts = np.empty((0, 2)) + + return verts, codes + + def get_glyphs_with_font(self, font, s, glyph_map=None, + return_new_glyphs_only=False): + """ + Convert string *s* to vertices and codes using the provided ttf font. + """ + + if glyph_map is None: + glyph_map = OrderedDict() + + if return_new_glyphs_only: + glyph_map_new = OrderedDict() + else: + glyph_map_new = glyph_map + + xpositions = [] + glyph_ids = [] + for item in _text_helpers.layout(s, font): + char_id = self._get_char_id(item.ft_object, ord(item.char)) + glyph_ids.append(char_id) + xpositions.append(item.x) + if char_id not in glyph_map: + glyph_map_new[char_id] = item.ft_object.get_path() + + ypositions = [0] * len(xpositions) + sizes = [1.] * len(xpositions) + + rects = [] + + return (list(zip(glyph_ids, xpositions, ypositions, sizes)), + glyph_map_new, rects) + + def get_glyphs_mathtext(self, prop, s, glyph_map=None, + return_new_glyphs_only=False): + """ + Parse mathtext string *s* and convert it to a (vertices, codes) pair. + """ + + prop = prop.copy() + prop.set_size(self.FONT_SCALE) + + width, height, descent, glyphs, rects = self.mathtext_parser.parse( + s, self.DPI, prop) + + if not glyph_map: + glyph_map = OrderedDict() + + if return_new_glyphs_only: + glyph_map_new = OrderedDict() + else: + glyph_map_new = glyph_map + + xpositions = [] + ypositions = [] + glyph_ids = [] + sizes = [] + + for font, fontsize, ccode, ox, oy in glyphs: + char_id = self._get_char_id(font, ccode) + if char_id not in glyph_map: + font.clear() + font.set_size(self.FONT_SCALE, self.DPI) + font.load_char(ccode, flags=LoadFlags.NO_HINTING) + glyph_map_new[char_id] = font.get_path() + + xpositions.append(ox) + ypositions.append(oy) + glyph_ids.append(char_id) + size = fontsize / self.FONT_SCALE + sizes.append(size) + + myrects = [] + for ox, oy, w, h in rects: + vert1 = [(ox, oy), (ox, oy + h), (ox + w, oy + h), + (ox + w, oy), (ox, oy), (0, 0)] + code1 = [Path.MOVETO, + Path.LINETO, Path.LINETO, Path.LINETO, Path.LINETO, + Path.CLOSEPOLY] + myrects.append((vert1, code1)) + + return (list(zip(glyph_ids, xpositions, ypositions, sizes)), + glyph_map_new, myrects) + + def get_glyphs_tex(self, prop, s, glyph_map=None, + return_new_glyphs_only=False): + """Convert the string *s* to vertices and codes using usetex mode.""" + # Mostly borrowed from pdf backend. + + dvifile = TexManager().make_dvi(s, self.FONT_SCALE) + with dviread.Dvi(dvifile, self.DPI) as dvi: + page, = dvi + + if glyph_map is None: + glyph_map = OrderedDict() + + if return_new_glyphs_only: + glyph_map_new = OrderedDict() + else: + glyph_map_new = glyph_map + + glyph_ids, xpositions, ypositions, sizes = [], [], [], [] + + # Gather font information and do some setup for combining + # characters into strings. + for text in page.text: + font = get_font(text.font_path) + char_id = self._get_char_id(font, text.glyph) + if char_id not in glyph_map: + font.clear() + font.set_size(self.FONT_SCALE, self.DPI) + glyph_name_or_index = text.glyph_name_or_index + if isinstance(glyph_name_or_index, str): + index = font.get_name_index(glyph_name_or_index) + font.load_glyph(index, flags=LoadFlags.TARGET_LIGHT) + elif isinstance(glyph_name_or_index, int): + self._select_native_charmap(font) + font.load_char( + glyph_name_or_index, flags=LoadFlags.TARGET_LIGHT) + else: # Should not occur. + raise TypeError(f"Glyph spec of unexpected type: " + f"{glyph_name_or_index!r}") + glyph_map_new[char_id] = font.get_path() + + glyph_ids.append(char_id) + xpositions.append(text.x) + ypositions.append(text.y) + sizes.append(text.font_size / self.FONT_SCALE) + + myrects = [] + + for ox, oy, h, w in page.boxes: + vert1 = [(ox, oy), (ox + w, oy), (ox + w, oy + h), + (ox, oy + h), (ox, oy), (0, 0)] + code1 = [Path.MOVETO, + Path.LINETO, Path.LINETO, Path.LINETO, Path.LINETO, + Path.CLOSEPOLY] + myrects.append((vert1, code1)) + + return (list(zip(glyph_ids, xpositions, ypositions, sizes)), + glyph_map_new, myrects) + + @staticmethod + def _select_native_charmap(font): + # Select the native charmap. (we can't directly identify it but it's + # typically an Adobe charmap). + for charmap_code in [ + 1094992451, # ADOBE_CUSTOM. + 1094995778, # ADOBE_STANDARD. + ]: + try: + font.select_charmap(charmap_code) + except (ValueError, RuntimeError): + pass + else: + break + else: + _log.warning("No supported encoding in font (%s).", font.fname) + + +text_to_path = TextToPath() + + +class TextPath(Path): + """ + Create a path from the text. + """ + + def __init__(self, xy, s, size=None, prop=None, + _interpolation_steps=1, usetex=False): + r""" + Create a path from the text. Note that it simply is a path, + not an artist. You need to use the `.PathPatch` (or other artists) + to draw this path onto the canvas. + + Parameters + ---------- + xy : tuple or array of two float values + Position of the text. For no offset, use ``xy=(0, 0)``. + + s : str + The text to convert to a path. + + size : float, optional + Font size in points. Defaults to the size specified via the font + properties *prop*. + + prop : `~matplotlib.font_manager.FontProperties`, optional + Font property. If not provided, will use a default + `.FontProperties` with parameters from the + :ref:`rcParams`. + + _interpolation_steps : int, optional + (Currently ignored) + + usetex : bool, default: False + Whether to use tex rendering. + + Examples + -------- + The following creates a path from the string "ABC" with Helvetica + font face; and another path from the latex fraction 1/2:: + + from matplotlib.text import TextPath + from matplotlib.font_manager import FontProperties + + fp = FontProperties(family="Helvetica", style="italic") + path1 = TextPath((12, 12), "ABC", size=12, prop=fp) + path2 = TextPath((0, 0), r"$\frac{1}{2}$", size=12, usetex=True) + + Also see :doc:`/gallery/text_labels_and_annotations/demo_text_path`. + """ + # Circular import. + from matplotlib.text import Text + + prop = FontProperties._from_any(prop) + if size is None: + size = prop.get_size_in_points() + + self._xy = xy + self.set_size(size) + + self._cached_vertices = None + s, ismath = Text(usetex=usetex)._preprocess_math(s) + super().__init__( + *text_to_path.get_text_path(prop, s, ismath=ismath), + _interpolation_steps=_interpolation_steps, + readonly=True) + self._should_simplify = False + + def set_size(self, size): + """Set the text size.""" + self._size = size + self._invalid = True + + def get_size(self): + """Get the text size.""" + return self._size + + @property + def vertices(self): + """ + Return the cached path after updating it if necessary. + """ + self._revalidate_path() + return self._cached_vertices + + @property + def codes(self): + """ + Return the codes + """ + return self._codes + + def _revalidate_path(self): + """ + Update the path if necessary. + + The path for the text is initially create with the font size of + `.FONT_SCALE`, and this path is rescaled to other size when necessary. + """ + if self._invalid or self._cached_vertices is None: + tr = (Affine2D() + .scale(self._size / text_to_path.FONT_SCALE) + .translate(*self._xy)) + self._cached_vertices = tr.transform(self._vertices) + self._cached_vertices.flags.writeable = False + self._invalid = False diff --git a/infer_4_30_0/lib/python3.10/site-packages/matplotlib/ticker.py b/infer_4_30_0/lib/python3.10/site-packages/matplotlib/ticker.py new file mode 100644 index 0000000000000000000000000000000000000000..3d0059e5aca33923a167d8731de9285d5d24d833 --- /dev/null +++ b/infer_4_30_0/lib/python3.10/site-packages/matplotlib/ticker.py @@ -0,0 +1,2990 @@ +""" +Tick locating and formatting +============================ + +This module contains classes for configuring tick locating and formatting. +Generic tick locators and formatters are provided, as well as domain specific +custom ones. + +Although the locators know nothing about major or minor ticks, they are used +by the Axis class to support major and minor tick locating and formatting. + +.. _tick_locating: +.. _locators: + +Tick locating +------------- + +The Locator class is the base class for all tick locators. The locators +handle autoscaling of the view limits based on the data limits, and the +choosing of tick locations. A useful semi-automatic tick locator is +`MultipleLocator`. It is initialized with a base, e.g., 10, and it picks +axis limits and ticks that are multiples of that base. + +The Locator subclasses defined here are: + +======================= ======================================================= +`AutoLocator` `MaxNLocator` with simple defaults. This is the default + tick locator for most plotting. +`MaxNLocator` Finds up to a max number of intervals with ticks at + nice locations. +`LinearLocator` Space ticks evenly from min to max. +`LogLocator` Space ticks logarithmically from min to max. +`MultipleLocator` Ticks and range are a multiple of base; either integer + or float. +`FixedLocator` Tick locations are fixed. +`IndexLocator` Locator for index plots (e.g., where + ``x = range(len(y))``). +`NullLocator` No ticks. +`SymmetricalLogLocator` Locator for use with the symlog norm; works like + `LogLocator` for the part outside of the threshold and + adds 0 if inside the limits. +`AsinhLocator` Locator for use with the asinh norm, attempting to + space ticks approximately uniformly. +`LogitLocator` Locator for logit scaling. +`AutoMinorLocator` Locator for minor ticks when the axis is linear and the + major ticks are uniformly spaced. Subdivides the major + tick interval into a specified number of minor + intervals, defaulting to 4 or 5 depending on the major + interval. +======================= ======================================================= + +There are a number of locators specialized for date locations - see +the :mod:`.dates` module. + +You can define your own locator by deriving from Locator. You must +override the ``__call__`` method, which returns a sequence of locations, +and you will probably want to override the autoscale method to set the +view limits from the data limits. + +If you want to override the default locator, use one of the above or a custom +locator and pass it to the x- or y-axis instance. The relevant methods are:: + + ax.xaxis.set_major_locator(xmajor_locator) + ax.xaxis.set_minor_locator(xminor_locator) + ax.yaxis.set_major_locator(ymajor_locator) + ax.yaxis.set_minor_locator(yminor_locator) + +The default minor locator is `NullLocator`, i.e., no minor ticks on by default. + +.. note:: + `Locator` instances should not be used with more than one + `~matplotlib.axis.Axis` or `~matplotlib.axes.Axes`. So instead of:: + + locator = MultipleLocator(5) + ax.xaxis.set_major_locator(locator) + ax2.xaxis.set_major_locator(locator) + + do the following instead:: + + ax.xaxis.set_major_locator(MultipleLocator(5)) + ax2.xaxis.set_major_locator(MultipleLocator(5)) + +.. _formatters: + +Tick formatting +--------------- + +Tick formatting is controlled by classes derived from Formatter. The formatter +operates on a single tick value and returns a string to the axis. + +========================= ===================================================== +`NullFormatter` No labels on the ticks. +`FixedFormatter` Set the strings manually for the labels. +`FuncFormatter` User defined function sets the labels. +`StrMethodFormatter` Use string `format` method. +`FormatStrFormatter` Use an old-style sprintf format string. +`ScalarFormatter` Default formatter for scalars: autopick the format + string. +`LogFormatter` Formatter for log axes. +`LogFormatterExponent` Format values for log axis using + ``exponent = log_base(value)``. +`LogFormatterMathtext` Format values for log axis using + ``exponent = log_base(value)`` using Math text. +`LogFormatterSciNotation` Format values for log axis using scientific notation. +`LogitFormatter` Probability formatter. +`EngFormatter` Format labels in engineering notation. +`PercentFormatter` Format labels as a percentage. +========================= ===================================================== + +You can derive your own formatter from the Formatter base class by +simply overriding the ``__call__`` method. The formatter class has +access to the axis view and data limits. + +To control the major and minor tick label formats, use one of the +following methods:: + + ax.xaxis.set_major_formatter(xmajor_formatter) + ax.xaxis.set_minor_formatter(xminor_formatter) + ax.yaxis.set_major_formatter(ymajor_formatter) + ax.yaxis.set_minor_formatter(yminor_formatter) + +In addition to a `.Formatter` instance, `~.Axis.set_major_formatter` and +`~.Axis.set_minor_formatter` also accept a ``str`` or function. ``str`` input +will be internally replaced with an autogenerated `.StrMethodFormatter` with +the input ``str``. For function input, a `.FuncFormatter` with the input +function will be generated and used. + +See :doc:`/gallery/ticks/major_minor_demo` for an example of setting major +and minor ticks. See the :mod:`matplotlib.dates` module for more information +and examples of using date locators and formatters. +""" + +import itertools +import logging +import locale +import math +from numbers import Integral +import string + +import numpy as np + +import matplotlib as mpl +from matplotlib import _api, cbook +from matplotlib import transforms as mtransforms + +_log = logging.getLogger(__name__) + +__all__ = ('TickHelper', 'Formatter', 'FixedFormatter', + 'NullFormatter', 'FuncFormatter', 'FormatStrFormatter', + 'StrMethodFormatter', 'ScalarFormatter', 'LogFormatter', + 'LogFormatterExponent', 'LogFormatterMathtext', + 'LogFormatterSciNotation', + 'LogitFormatter', 'EngFormatter', 'PercentFormatter', + 'Locator', 'IndexLocator', 'FixedLocator', 'NullLocator', + 'LinearLocator', 'LogLocator', 'AutoLocator', + 'MultipleLocator', 'MaxNLocator', 'AutoMinorLocator', + 'SymmetricalLogLocator', 'AsinhLocator', 'LogitLocator') + + +class _DummyAxis: + __name__ = "dummy" + + def __init__(self, minpos=0): + self._data_interval = (0, 1) + self._view_interval = (0, 1) + self._minpos = minpos + + def get_view_interval(self): + return self._view_interval + + def set_view_interval(self, vmin, vmax): + self._view_interval = (vmin, vmax) + + def get_minpos(self): + return self._minpos + + def get_data_interval(self): + return self._data_interval + + def set_data_interval(self, vmin, vmax): + self._data_interval = (vmin, vmax) + + def get_tick_space(self): + # Just use the long-standing default of nbins==9 + return 9 + + +class TickHelper: + axis = None + + def set_axis(self, axis): + self.axis = axis + + def create_dummy_axis(self, **kwargs): + if self.axis is None: + self.axis = _DummyAxis(**kwargs) + + +class Formatter(TickHelper): + """ + Create a string based on a tick value and location. + """ + # some classes want to see all the locs to help format + # individual ones + locs = [] + + def __call__(self, x, pos=None): + """ + Return the format for tick value *x* at position pos. + ``pos=None`` indicates an unspecified location. + """ + raise NotImplementedError('Derived must override') + + def format_ticks(self, values): + """Return the tick labels for all the ticks at once.""" + self.set_locs(values) + return [self(value, i) for i, value in enumerate(values)] + + def format_data(self, value): + """ + Return the full string representation of the value with the + position unspecified. + """ + return self.__call__(value) + + def format_data_short(self, value): + """ + Return a short string version of the tick value. + + Defaults to the position-independent long value. + """ + return self.format_data(value) + + def get_offset(self): + return '' + + def set_locs(self, locs): + """ + Set the locations of the ticks. + + This method is called before computing the tick labels because some + formatters need to know all tick locations to do so. + """ + self.locs = locs + + @staticmethod + def fix_minus(s): + """ + Some classes may want to replace a hyphen for minus with the proper + Unicode symbol (U+2212) for typographical correctness. This is a + helper method to perform such a replacement when it is enabled via + :rc:`axes.unicode_minus`. + """ + return (s.replace('-', '\N{MINUS SIGN}') + if mpl.rcParams['axes.unicode_minus'] + else s) + + def _set_locator(self, locator): + """Subclasses may want to override this to set a locator.""" + pass + + +class NullFormatter(Formatter): + """Always return the empty string.""" + + def __call__(self, x, pos=None): + # docstring inherited + return '' + + +class FixedFormatter(Formatter): + """ + Return fixed strings for tick labels based only on position, not value. + + .. note:: + `.FixedFormatter` should only be used together with `.FixedLocator`. + Otherwise, the labels may end up in unexpected positions. + """ + + def __init__(self, seq): + """Set the sequence *seq* of strings that will be used for labels.""" + self.seq = seq + self.offset_string = '' + + def __call__(self, x, pos=None): + """ + Return the label that matches the position, regardless of the value. + + For positions ``pos < len(seq)``, return ``seq[i]`` regardless of + *x*. Otherwise return empty string. ``seq`` is the sequence of + strings that this object was initialized with. + """ + if pos is None or pos >= len(self.seq): + return '' + else: + return self.seq[pos] + + def get_offset(self): + return self.offset_string + + def set_offset_string(self, ofs): + self.offset_string = ofs + + +class FuncFormatter(Formatter): + """ + Use a user-defined function for formatting. + + The function should take in two inputs (a tick value ``x`` and a + position ``pos``), and return a string containing the corresponding + tick label. + """ + + def __init__(self, func): + self.func = func + self.offset_string = "" + + def __call__(self, x, pos=None): + """ + Return the value of the user defined function. + + *x* and *pos* are passed through as-is. + """ + return self.func(x, pos) + + def get_offset(self): + return self.offset_string + + def set_offset_string(self, ofs): + self.offset_string = ofs + + +class FormatStrFormatter(Formatter): + """ + Use an old-style ('%' operator) format string to format the tick. + + The format string should have a single variable format (%) in it. + It will be applied to the value (not the position) of the tick. + + Negative numeric values (e.g., -1) will use a dash, not a Unicode minus; + use mathtext to get a Unicode minus by wrapping the format specifier with $ + (e.g. "$%g$"). + """ + + def __init__(self, fmt): + self.fmt = fmt + + def __call__(self, x, pos=None): + """ + Return the formatted label string. + + Only the value *x* is formatted. The position is ignored. + """ + return self.fmt % x + + +class _UnicodeMinusFormat(string.Formatter): + """ + A specialized string formatter so that `.StrMethodFormatter` respects + :rc:`axes.unicode_minus`. This implementation relies on the fact that the + format string is only ever called with kwargs *x* and *pos*, so it blindly + replaces dashes by unicode minuses without further checking. + """ + + def format_field(self, value, format_spec): + return Formatter.fix_minus(super().format_field(value, format_spec)) + + +class StrMethodFormatter(Formatter): + """ + Use a new-style format string (as used by `str.format`) to format the tick. + + The field used for the tick value must be labeled *x* and the field used + for the tick position must be labeled *pos*. + + The formatter will respect :rc:`axes.unicode_minus` when formatting + negative numeric values. + + It is typically unnecessary to explicitly construct `.StrMethodFormatter` + objects, as `~.Axis.set_major_formatter` directly accepts the format string + itself. + """ + + def __init__(self, fmt): + self.fmt = fmt + + def __call__(self, x, pos=None): + """ + Return the formatted label string. + + *x* and *pos* are passed to `str.format` as keyword arguments + with those exact names. + """ + return _UnicodeMinusFormat().format(self.fmt, x=x, pos=pos) + + +class ScalarFormatter(Formatter): + """ + Format tick values as a number. + + Parameters + ---------- + useOffset : bool or float, default: :rc:`axes.formatter.useoffset` + Whether to use offset notation. See `.set_useOffset`. + useMathText : bool, default: :rc:`axes.formatter.use_mathtext` + Whether to use fancy math formatting. See `.set_useMathText`. + useLocale : bool, default: :rc:`axes.formatter.use_locale`. + Whether to use locale settings for decimal sign and positive sign. + See `.set_useLocale`. + usetex : bool, default: :rc:`text.usetex` + To enable/disable the use of TeX's math mode for rendering the + numbers in the formatter. + + .. versionadded:: 3.10 + + Notes + ----- + In addition to the parameters above, the formatting of scientific vs. + floating point representation can be configured via `.set_scientific` + and `.set_powerlimits`). + + **Offset notation and scientific notation** + + Offset notation and scientific notation look quite similar at first sight. + Both split some information from the formatted tick values and display it + at the end of the axis. + + - The scientific notation splits up the order of magnitude, i.e. a + multiplicative scaling factor, e.g. ``1e6``. + + - The offset notation separates an additive constant, e.g. ``+1e6``. The + offset notation label is always prefixed with a ``+`` or ``-`` sign + and is thus distinguishable from the order of magnitude label. + + The following plot with x limits ``1_000_000`` to ``1_000_010`` illustrates + the different formatting. Note the labels at the right edge of the x axis. + + .. plot:: + + lim = (1_000_000, 1_000_010) + + fig, (ax1, ax2, ax3) = plt.subplots(3, 1, gridspec_kw={'hspace': 2}) + ax1.set(title='offset notation', xlim=lim) + ax2.set(title='scientific notation', xlim=lim) + ax2.xaxis.get_major_formatter().set_useOffset(False) + ax3.set(title='floating-point notation', xlim=lim) + ax3.xaxis.get_major_formatter().set_useOffset(False) + ax3.xaxis.get_major_formatter().set_scientific(False) + + """ + + def __init__(self, useOffset=None, useMathText=None, useLocale=None, *, + usetex=None): + if useOffset is None: + useOffset = mpl.rcParams['axes.formatter.useoffset'] + self._offset_threshold = \ + mpl.rcParams['axes.formatter.offset_threshold'] + self.set_useOffset(useOffset) + self.set_usetex(usetex) + self.set_useMathText(useMathText) + self.orderOfMagnitude = 0 + self.format = '' + self._scientific = True + self._powerlimits = mpl.rcParams['axes.formatter.limits'] + self.set_useLocale(useLocale) + + def get_usetex(self): + """Return whether TeX's math mode is enabled for rendering.""" + return self._usetex + + def set_usetex(self, val): + """Set whether to use TeX's math mode for rendering numbers in the formatter.""" + self._usetex = mpl._val_or_rc(val, 'text.usetex') + + usetex = property(fget=get_usetex, fset=set_usetex) + + def get_useOffset(self): + """ + Return whether automatic mode for offset notation is active. + + This returns True if ``set_useOffset(True)``; it returns False if an + explicit offset was set, e.g. ``set_useOffset(1000)``. + + See Also + -------- + ScalarFormatter.set_useOffset + """ + return self._useOffset + + def set_useOffset(self, val): + """ + Set whether to use offset notation. + + When formatting a set numbers whose value is large compared to their + range, the formatter can separate an additive constant. This can + shorten the formatted numbers so that they are less likely to overlap + when drawn on an axis. + + Parameters + ---------- + val : bool or float + - If False, do not use offset notation. + - If True (=automatic mode), use offset notation if it can make + the residual numbers significantly shorter. The exact behavior + is controlled by :rc:`axes.formatter.offset_threshold`. + - If a number, force an offset of the given value. + + Examples + -------- + With active offset notation, the values + + ``100_000, 100_002, 100_004, 100_006, 100_008`` + + will be formatted as ``0, 2, 4, 6, 8`` plus an offset ``+1e5``, which + is written to the edge of the axis. + """ + if val in [True, False]: + self.offset = 0 + self._useOffset = val + else: + self._useOffset = False + self.offset = val + + useOffset = property(fget=get_useOffset, fset=set_useOffset) + + def get_useLocale(self): + """ + Return whether locale settings are used for formatting. + + See Also + -------- + ScalarFormatter.set_useLocale + """ + return self._useLocale + + def set_useLocale(self, val): + """ + Set whether to use locale settings for decimal sign and positive sign. + + Parameters + ---------- + val : bool or None + *None* resets to :rc:`axes.formatter.use_locale`. + """ + if val is None: + self._useLocale = mpl.rcParams['axes.formatter.use_locale'] + else: + self._useLocale = val + + useLocale = property(fget=get_useLocale, fset=set_useLocale) + + def _format_maybe_minus_and_locale(self, fmt, arg): + """ + Format *arg* with *fmt*, applying Unicode minus and locale if desired. + """ + return self.fix_minus( + # Escape commas introduced by locale.format_string if using math text, + # but not those present from the beginning in fmt. + (",".join(locale.format_string(part, (arg,), True).replace(",", "{,}") + for part in fmt.split(",")) if self._useMathText + else locale.format_string(fmt, (arg,), True)) + if self._useLocale + else fmt % arg) + + def get_useMathText(self): + """ + Return whether to use fancy math formatting. + + See Also + -------- + ScalarFormatter.set_useMathText + """ + return self._useMathText + + def set_useMathText(self, val): + r""" + Set whether to use fancy math formatting. + + If active, scientific notation is formatted as :math:`1.2 \times 10^3`. + + Parameters + ---------- + val : bool or None + *None* resets to :rc:`axes.formatter.use_mathtext`. + """ + if val is None: + self._useMathText = mpl.rcParams['axes.formatter.use_mathtext'] + if self._useMathText is False: + try: + from matplotlib import font_manager + ufont = font_manager.findfont( + font_manager.FontProperties( + family=mpl.rcParams["font.family"] + ), + fallback_to_default=False, + ) + except ValueError: + ufont = None + + if ufont == str(cbook._get_data_path("fonts/ttf/cmr10.ttf")): + _api.warn_external( + "cmr10 font should ideally be used with " + "mathtext, set axes.formatter.use_mathtext to True" + ) + else: + self._useMathText = val + + useMathText = property(fget=get_useMathText, fset=set_useMathText) + + def __call__(self, x, pos=None): + """ + Return the format for tick value *x* at position *pos*. + """ + if len(self.locs) == 0: + return '' + else: + xp = (x - self.offset) / (10. ** self.orderOfMagnitude) + if abs(xp) < 1e-8: + xp = 0 + return self._format_maybe_minus_and_locale(self.format, xp) + + def set_scientific(self, b): + """ + Turn scientific notation on or off. + + See Also + -------- + ScalarFormatter.set_powerlimits + """ + self._scientific = bool(b) + + def set_powerlimits(self, lims): + r""" + Set size thresholds for scientific notation. + + Parameters + ---------- + lims : (int, int) + A tuple *(min_exp, max_exp)* containing the powers of 10 that + determine the switchover threshold. For a number representable as + :math:`a \times 10^\mathrm{exp}` with :math:`1 <= |a| < 10`, + scientific notation will be used if ``exp <= min_exp`` or + ``exp >= max_exp``. + + The default limits are controlled by :rc:`axes.formatter.limits`. + + In particular numbers with *exp* equal to the thresholds are + written in scientific notation. + + Typically, *min_exp* will be negative and *max_exp* will be + positive. + + For example, ``formatter.set_powerlimits((-3, 4))`` will provide + the following formatting: + :math:`1 \times 10^{-3}, 9.9 \times 10^{-3}, 0.01,` + :math:`9999, 1 \times 10^4`. + + See Also + -------- + ScalarFormatter.set_scientific + """ + if len(lims) != 2: + raise ValueError("'lims' must be a sequence of length 2") + self._powerlimits = lims + + def format_data_short(self, value): + # docstring inherited + if value is np.ma.masked: + return "" + if isinstance(value, Integral): + fmt = "%d" + else: + if getattr(self.axis, "__name__", "") in ["xaxis", "yaxis"]: + if self.axis.__name__ == "xaxis": + axis_trf = self.axis.axes.get_xaxis_transform() + axis_inv_trf = axis_trf.inverted() + screen_xy = axis_trf.transform((value, 0)) + neighbor_values = axis_inv_trf.transform( + screen_xy + [[-1, 0], [+1, 0]])[:, 0] + else: # yaxis: + axis_trf = self.axis.axes.get_yaxis_transform() + axis_inv_trf = axis_trf.inverted() + screen_xy = axis_trf.transform((0, value)) + neighbor_values = axis_inv_trf.transform( + screen_xy + [[0, -1], [0, +1]])[:, 1] + delta = abs(neighbor_values - value).max() + else: + # Rough approximation: no more than 1e4 divisions. + a, b = self.axis.get_view_interval() + delta = (b - a) / 1e4 + fmt = f"%-#.{cbook._g_sig_digits(value, delta)}g" + return self._format_maybe_minus_and_locale(fmt, value) + + def format_data(self, value): + # docstring inherited + e = math.floor(math.log10(abs(value))) + s = round(value / 10**e, 10) + significand = self._format_maybe_minus_and_locale( + "%d" if s % 1 == 0 else "%1.10g", s) + if e == 0: + return significand + exponent = self._format_maybe_minus_and_locale("%d", e) + if self._useMathText or self._usetex: + exponent = "10^{%s}" % exponent + return (exponent if s == 1 # reformat 1x10^y as 10^y + else rf"{significand} \times {exponent}") + else: + return f"{significand}e{exponent}" + + def get_offset(self): + """ + Return scientific notation, plus offset. + """ + if len(self.locs) == 0: + return '' + if self.orderOfMagnitude or self.offset: + offsetStr = '' + sciNotStr = '' + if self.offset: + offsetStr = self.format_data(self.offset) + if self.offset > 0: + offsetStr = '+' + offsetStr + if self.orderOfMagnitude: + if self._usetex or self._useMathText: + sciNotStr = self.format_data(10 ** self.orderOfMagnitude) + else: + sciNotStr = '1e%d' % self.orderOfMagnitude + if self._useMathText or self._usetex: + if sciNotStr != '': + sciNotStr = r'\times\mathdefault{%s}' % sciNotStr + s = fr'${sciNotStr}\mathdefault{{{offsetStr}}}$' + else: + s = ''.join((sciNotStr, offsetStr)) + return self.fix_minus(s) + return '' + + def set_locs(self, locs): + # docstring inherited + self.locs = locs + if len(self.locs) > 0: + if self._useOffset: + self._compute_offset() + self._set_order_of_magnitude() + self._set_format() + + def _compute_offset(self): + locs = self.locs + # Restrict to visible ticks. + vmin, vmax = sorted(self.axis.get_view_interval()) + locs = np.asarray(locs) + locs = locs[(vmin <= locs) & (locs <= vmax)] + if not len(locs): + self.offset = 0 + return + lmin, lmax = locs.min(), locs.max() + # Only use offset if there are at least two ticks and every tick has + # the same sign. + if lmin == lmax or lmin <= 0 <= lmax: + self.offset = 0 + return + # min, max comparing absolute values (we want division to round towards + # zero so we work on absolute values). + abs_min, abs_max = sorted([abs(float(lmin)), abs(float(lmax))]) + sign = math.copysign(1, lmin) + # What is the smallest power of ten such that abs_min and abs_max are + # equal up to that precision? + # Note: Internally using oom instead of 10 ** oom avoids some numerical + # accuracy issues. + oom_max = np.ceil(math.log10(abs_max)) + oom = 1 + next(oom for oom in itertools.count(oom_max, -1) + if abs_min // 10 ** oom != abs_max // 10 ** oom) + if (abs_max - abs_min) / 10 ** oom <= 1e-2: + # Handle the case of straddling a multiple of a large power of ten + # (relative to the span). + # What is the smallest power of ten such that abs_min and abs_max + # are no more than 1 apart at that precision? + oom = 1 + next(oom for oom in itertools.count(oom_max, -1) + if abs_max // 10 ** oom - abs_min // 10 ** oom > 1) + # Only use offset if it saves at least _offset_threshold digits. + n = self._offset_threshold - 1 + self.offset = (sign * (abs_max // 10 ** oom) * 10 ** oom + if abs_max // 10 ** oom >= 10**n + else 0) + + def _set_order_of_magnitude(self): + # if scientific notation is to be used, find the appropriate exponent + # if using a numerical offset, find the exponent after applying the + # offset. When lower power limit = upper <> 0, use provided exponent. + if not self._scientific: + self.orderOfMagnitude = 0 + return + if self._powerlimits[0] == self._powerlimits[1] != 0: + # fixed scaling when lower power limit = upper <> 0. + self.orderOfMagnitude = self._powerlimits[0] + return + # restrict to visible ticks + vmin, vmax = sorted(self.axis.get_view_interval()) + locs = np.asarray(self.locs) + locs = locs[(vmin <= locs) & (locs <= vmax)] + locs = np.abs(locs) + if not len(locs): + self.orderOfMagnitude = 0 + return + if self.offset: + oom = math.floor(math.log10(vmax - vmin)) + else: + val = locs.max() + if val == 0: + oom = 0 + else: + oom = math.floor(math.log10(val)) + if oom <= self._powerlimits[0]: + self.orderOfMagnitude = oom + elif oom >= self._powerlimits[1]: + self.orderOfMagnitude = oom + else: + self.orderOfMagnitude = 0 + + def _set_format(self): + # set the format string to format all the ticklabels + if len(self.locs) < 2: + # Temporarily augment the locations with the axis end points. + _locs = [*self.locs, *self.axis.get_view_interval()] + else: + _locs = self.locs + locs = (np.asarray(_locs) - self.offset) / 10. ** self.orderOfMagnitude + loc_range = np.ptp(locs) + # Curvilinear coordinates can yield two identical points. + if loc_range == 0: + loc_range = np.max(np.abs(locs)) + # Both points might be zero. + if loc_range == 0: + loc_range = 1 + if len(self.locs) < 2: + # We needed the end points only for the loc_range calculation. + locs = locs[:-2] + loc_range_oom = int(math.floor(math.log10(loc_range))) + # first estimate: + sigfigs = max(0, 3 - loc_range_oom) + # refined estimate: + thresh = 1e-3 * 10 ** loc_range_oom + while sigfigs >= 0: + if np.abs(locs - np.round(locs, decimals=sigfigs)).max() < thresh: + sigfigs -= 1 + else: + break + sigfigs += 1 + self.format = f'%1.{sigfigs}f' + if self._usetex or self._useMathText: + self.format = r'$\mathdefault{%s}$' % self.format + + +class LogFormatter(Formatter): + """ + Base class for formatting ticks on a log or symlog scale. + + It may be instantiated directly, or subclassed. + + Parameters + ---------- + base : float, default: 10. + Base of the logarithm used in all calculations. + + labelOnlyBase : bool, default: False + If True, label ticks only at integer powers of base. + This is normally True for major ticks and False for + minor ticks. + + minor_thresholds : (subset, all), default: (1, 0.4) + If labelOnlyBase is False, these two numbers control + the labeling of ticks that are not at integer powers of + base; normally these are the minor ticks. The controlling + parameter is the log of the axis data range. In the typical + case where base is 10 it is the number of decades spanned + by the axis, so we can call it 'numdec'. If ``numdec <= all``, + all minor ticks will be labeled. If ``all < numdec <= subset``, + then only a subset of minor ticks will be labeled, so as to + avoid crowding. If ``numdec > subset`` then no minor ticks will + be labeled. + + linthresh : None or float, default: None + If a symmetric log scale is in use, its ``linthresh`` + parameter must be supplied here. + + Notes + ----- + The `set_locs` method must be called to enable the subsetting + logic controlled by the ``minor_thresholds`` parameter. + + In some cases such as the colorbar, there is no distinction between + major and minor ticks; the tick locations might be set manually, + or by a locator that puts ticks at integer powers of base and + at intermediate locations. For this situation, disable the + minor_thresholds logic by using ``minor_thresholds=(np.inf, np.inf)``, + so that all ticks will be labeled. + + To disable labeling of minor ticks when 'labelOnlyBase' is False, + use ``minor_thresholds=(0, 0)``. This is the default for the + "classic" style. + + Examples + -------- + To label a subset of minor ticks when the view limits span up + to 2 decades, and all of the ticks when zoomed in to 0.5 decades + or less, use ``minor_thresholds=(2, 0.5)``. + + To label all minor ticks when the view limits span up to 1.5 + decades, use ``minor_thresholds=(1.5, 1.5)``. + """ + + def __init__(self, base=10.0, labelOnlyBase=False, + minor_thresholds=None, + linthresh=None): + + self.set_base(base) + self.set_label_minor(labelOnlyBase) + if minor_thresholds is None: + if mpl.rcParams['_internal.classic_mode']: + minor_thresholds = (0, 0) + else: + minor_thresholds = (1, 0.4) + self.minor_thresholds = minor_thresholds + self._sublabels = None + self._linthresh = linthresh + + def set_base(self, base): + """ + Change the *base* for labeling. + + .. warning:: + Should always match the base used for :class:`LogLocator` + """ + self._base = float(base) + + def set_label_minor(self, labelOnlyBase): + """ + Switch minor tick labeling on or off. + + Parameters + ---------- + labelOnlyBase : bool + If True, label ticks only at integer powers of base. + """ + self.labelOnlyBase = labelOnlyBase + + def set_locs(self, locs=None): + """ + Use axis view limits to control which ticks are labeled. + + The *locs* parameter is ignored in the present algorithm. + """ + if np.isinf(self.minor_thresholds[0]): + self._sublabels = None + return + + # Handle symlog case: + linthresh = self._linthresh + if linthresh is None: + try: + linthresh = self.axis.get_transform().linthresh + except AttributeError: + pass + + vmin, vmax = self.axis.get_view_interval() + if vmin > vmax: + vmin, vmax = vmax, vmin + + if linthresh is None and vmin <= 0: + # It's probably a colorbar with + # a format kwarg setting a LogFormatter in the manner + # that worked with 1.5.x, but that doesn't work now. + self._sublabels = {1} # label powers of base + return + + b = self._base + if linthresh is not None: # symlog + # Only compute the number of decades in the logarithmic part of the + # axis + numdec = 0 + if vmin < -linthresh: + rhs = min(vmax, -linthresh) + numdec += math.log(vmin / rhs) / math.log(b) + if vmax > linthresh: + lhs = max(vmin, linthresh) + numdec += math.log(vmax / lhs) / math.log(b) + else: + vmin = math.log(vmin) / math.log(b) + vmax = math.log(vmax) / math.log(b) + numdec = abs(vmax - vmin) + + if numdec > self.minor_thresholds[0]: + # Label only bases + self._sublabels = {1} + elif numdec > self.minor_thresholds[1]: + # Add labels between bases at log-spaced coefficients; + # include base powers in case the locations include + # "major" and "minor" points, as in colorbar. + c = np.geomspace(1, b, int(b)//2 + 1) + self._sublabels = set(np.round(c)) + # For base 10, this yields (1, 2, 3, 4, 6, 10). + else: + # Label all integer multiples of base**n. + self._sublabels = set(np.arange(1, b + 1)) + + def _num_to_string(self, x, vmin, vmax): + return self._pprint_val(x, vmax - vmin) if 1 <= x <= 10000 else f"{x:1.0e}" + + def __call__(self, x, pos=None): + # docstring inherited + if x == 0.0: # Symlog + return '0' + + x = abs(x) + b = self._base + # only label the decades + fx = math.log(x) / math.log(b) + is_x_decade = _is_close_to_int(fx) + exponent = round(fx) if is_x_decade else np.floor(fx) + coeff = round(b ** (fx - exponent)) + + if self.labelOnlyBase and not is_x_decade: + return '' + if self._sublabels is not None and coeff not in self._sublabels: + return '' + + vmin, vmax = self.axis.get_view_interval() + vmin, vmax = mtransforms.nonsingular(vmin, vmax, expander=0.05) + s = self._num_to_string(x, vmin, vmax) + return self.fix_minus(s) + + def format_data(self, value): + with cbook._setattr_cm(self, labelOnlyBase=False): + return cbook.strip_math(self.__call__(value)) + + def format_data_short(self, value): + # docstring inherited + return ('%-12g' % value).rstrip() + + def _pprint_val(self, x, d): + # If the number is not too big and it's an int, format it as an int. + if abs(x) < 1e4 and x == int(x): + return '%d' % x + fmt = ('%1.3e' if d < 1e-2 else + '%1.3f' if d <= 1 else + '%1.2f' if d <= 10 else + '%1.1f' if d <= 1e5 else + '%1.1e') + s = fmt % x + tup = s.split('e') + if len(tup) == 2: + mantissa = tup[0].rstrip('0').rstrip('.') + exponent = int(tup[1]) + if exponent: + s = '%se%d' % (mantissa, exponent) + else: + s = mantissa + else: + s = s.rstrip('0').rstrip('.') + return s + + +class LogFormatterExponent(LogFormatter): + """ + Format values for log axis using ``exponent = log_base(value)``. + """ + + def _num_to_string(self, x, vmin, vmax): + fx = math.log(x) / math.log(self._base) + if 1 <= abs(fx) <= 10000: + fd = math.log(vmax - vmin) / math.log(self._base) + s = self._pprint_val(fx, fd) + else: + s = f"{fx:1.0g}" + return s + + +class LogFormatterMathtext(LogFormatter): + """ + Format values for log axis using ``exponent = log_base(value)``. + """ + + def _non_decade_format(self, sign_string, base, fx, usetex): + """Return string for non-decade locations.""" + return r'$\mathdefault{%s%s^{%.2f}}$' % (sign_string, base, fx) + + def __call__(self, x, pos=None): + # docstring inherited + if x == 0: # Symlog + return r'$\mathdefault{0}$' + + sign_string = '-' if x < 0 else '' + x = abs(x) + b = self._base + + # only label the decades + fx = math.log(x) / math.log(b) + is_x_decade = _is_close_to_int(fx) + exponent = round(fx) if is_x_decade else np.floor(fx) + coeff = round(b ** (fx - exponent)) + + if self.labelOnlyBase and not is_x_decade: + return '' + if self._sublabels is not None and coeff not in self._sublabels: + return '' + + if is_x_decade: + fx = round(fx) + + # use string formatting of the base if it is not an integer + if b % 1 == 0.0: + base = '%d' % b + else: + base = '%s' % b + + if abs(fx) < mpl.rcParams['axes.formatter.min_exponent']: + return r'$\mathdefault{%s%g}$' % (sign_string, x) + elif not is_x_decade: + usetex = mpl.rcParams['text.usetex'] + return self._non_decade_format(sign_string, base, fx, usetex) + else: + return r'$\mathdefault{%s%s^{%d}}$' % (sign_string, base, fx) + + +class LogFormatterSciNotation(LogFormatterMathtext): + """ + Format values following scientific notation in a logarithmic axis. + """ + + def _non_decade_format(self, sign_string, base, fx, usetex): + """Return string for non-decade locations.""" + b = float(base) + exponent = math.floor(fx) + coeff = b ** (fx - exponent) + if _is_close_to_int(coeff): + coeff = round(coeff) + return r'$\mathdefault{%s%g\times%s^{%d}}$' \ + % (sign_string, coeff, base, exponent) + + +class LogitFormatter(Formatter): + """ + Probability formatter (using Math text). + """ + + def __init__( + self, + *, + use_overline=False, + one_half=r"\frac{1}{2}", + minor=False, + minor_threshold=25, + minor_number=6, + ): + r""" + Parameters + ---------- + use_overline : bool, default: False + If x > 1/2, with x = 1 - v, indicate if x should be displayed as + $\overline{v}$. The default is to display $1 - v$. + + one_half : str, default: r"\\frac{1}{2}" + The string used to represent 1/2. + + minor : bool, default: False + Indicate if the formatter is formatting minor ticks or not. + Basically minor ticks are not labelled, except when only few ticks + are provided, ticks with most space with neighbor ticks are + labelled. See other parameters to change the default behavior. + + minor_threshold : int, default: 25 + Maximum number of locs for labelling some minor ticks. This + parameter have no effect if minor is False. + + minor_number : int, default: 6 + Number of ticks which are labelled when the number of ticks is + below the threshold. + """ + self._use_overline = use_overline + self._one_half = one_half + self._minor = minor + self._labelled = set() + self._minor_threshold = minor_threshold + self._minor_number = minor_number + + def use_overline(self, use_overline): + r""" + Switch display mode with overline for labelling p>1/2. + + Parameters + ---------- + use_overline : bool + If x > 1/2, with x = 1 - v, indicate if x should be displayed as + $\overline{v}$. The default is to display $1 - v$. + """ + self._use_overline = use_overline + + def set_one_half(self, one_half): + r""" + Set the way one half is displayed. + + one_half : str + The string used to represent 1/2. + """ + self._one_half = one_half + + def set_minor_threshold(self, minor_threshold): + """ + Set the threshold for labelling minors ticks. + + Parameters + ---------- + minor_threshold : int + Maximum number of locations for labelling some minor ticks. This + parameter have no effect if minor is False. + """ + self._minor_threshold = minor_threshold + + def set_minor_number(self, minor_number): + """ + Set the number of minor ticks to label when some minor ticks are + labelled. + + Parameters + ---------- + minor_number : int + Number of ticks which are labelled when the number of ticks is + below the threshold. + """ + self._minor_number = minor_number + + def set_locs(self, locs): + self.locs = np.array(locs) + self._labelled.clear() + + if not self._minor: + return None + if all( + _is_decade(x, rtol=1e-7) + or _is_decade(1 - x, rtol=1e-7) + or (_is_close_to_int(2 * x) and + int(np.round(2 * x)) == 1) + for x in locs + ): + # minor ticks are subsample from ideal, so no label + return None + if len(locs) < self._minor_threshold: + if len(locs) < self._minor_number: + self._labelled.update(locs) + else: + # we do not have a lot of minor ticks, so only few decades are + # displayed, then we choose some (spaced) minor ticks to label. + # Only minor ticks are known, we assume it is sufficient to + # choice which ticks are displayed. + # For each ticks we compute the distance between the ticks and + # the previous, and between the ticks and the next one. Ticks + # with smallest minimum are chosen. As tiebreak, the ticks + # with smallest sum is chosen. + diff = np.diff(-np.log(1 / self.locs - 1)) + space_pessimistic = np.minimum( + np.concatenate(((np.inf,), diff)), + np.concatenate((diff, (np.inf,))), + ) + space_sum = ( + np.concatenate(((0,), diff)) + + np.concatenate((diff, (0,))) + ) + good_minor = sorted( + range(len(self.locs)), + key=lambda i: (space_pessimistic[i], space_sum[i]), + )[-self._minor_number:] + self._labelled.update(locs[i] for i in good_minor) + + def _format_value(self, x, locs, sci_notation=True): + if sci_notation: + exponent = math.floor(np.log10(x)) + min_precision = 0 + else: + exponent = 0 + min_precision = 1 + value = x * 10 ** (-exponent) + if len(locs) < 2: + precision = min_precision + else: + diff = np.sort(np.abs(locs - x))[1] + precision = -np.log10(diff) + exponent + precision = ( + int(np.round(precision)) + if _is_close_to_int(precision) + else math.ceil(precision) + ) + if precision < min_precision: + precision = min_precision + mantissa = r"%.*f" % (precision, value) + if not sci_notation: + return mantissa + s = r"%s\cdot10^{%d}" % (mantissa, exponent) + return s + + def _one_minus(self, s): + if self._use_overline: + return r"\overline{%s}" % s + else: + return f"1-{s}" + + def __call__(self, x, pos=None): + if self._minor and x not in self._labelled: + return "" + if x <= 0 or x >= 1: + return "" + if _is_close_to_int(2 * x) and round(2 * x) == 1: + s = self._one_half + elif x < 0.5 and _is_decade(x, rtol=1e-7): + exponent = round(math.log10(x)) + s = "10^{%d}" % exponent + elif x > 0.5 and _is_decade(1 - x, rtol=1e-7): + exponent = round(math.log10(1 - x)) + s = self._one_minus("10^{%d}" % exponent) + elif x < 0.1: + s = self._format_value(x, self.locs) + elif x > 0.9: + s = self._one_minus(self._format_value(1-x, 1-self.locs)) + else: + s = self._format_value(x, self.locs, sci_notation=False) + return r"$\mathdefault{%s}$" % s + + def format_data_short(self, value): + # docstring inherited + # Thresholds chosen to use scientific notation iff exponent <= -2. + if value < 0.1: + return f"{value:e}" + if value < 0.9: + return f"{value:f}" + return f"1-{1 - value:e}" + + +class EngFormatter(ScalarFormatter): + """ + Format axis values using engineering prefixes to represent powers + of 1000, plus a specified unit, e.g., 10 MHz instead of 1e7. + """ + + # The SI engineering prefixes + ENG_PREFIXES = { + -30: "q", + -27: "r", + -24: "y", + -21: "z", + -18: "a", + -15: "f", + -12: "p", + -9: "n", + -6: "\N{MICRO SIGN}", + -3: "m", + 0: "", + 3: "k", + 6: "M", + 9: "G", + 12: "T", + 15: "P", + 18: "E", + 21: "Z", + 24: "Y", + 27: "R", + 30: "Q" + } + + def __init__(self, unit="", places=None, sep=" ", *, usetex=None, + useMathText=None, useOffset=False): + r""" + Parameters + ---------- + unit : str, default: "" + Unit symbol to use, suitable for use with single-letter + representations of powers of 1000. For example, 'Hz' or 'm'. + + places : int, default: None + Precision with which to display the number, specified in + digits after the decimal point (there will be between one + and three digits before the decimal point). If it is None, + the formatting falls back to the floating point format '%g', + which displays up to 6 *significant* digits, i.e. the equivalent + value for *places* varies between 0 and 5 (inclusive). + + sep : str, default: " " + Separator used between the value and the prefix/unit. For + example, one get '3.14 mV' if ``sep`` is " " (default) and + '3.14mV' if ``sep`` is "". Besides the default behavior, some + other useful options may be: + + * ``sep=""`` to append directly the prefix/unit to the value; + * ``sep="\N{THIN SPACE}"`` (``U+2009``); + * ``sep="\N{NARROW NO-BREAK SPACE}"`` (``U+202F``); + * ``sep="\N{NO-BREAK SPACE}"`` (``U+00A0``). + + usetex : bool, default: :rc:`text.usetex` + To enable/disable the use of TeX's math mode for rendering the + numbers in the formatter. + + useMathText : bool, default: :rc:`axes.formatter.use_mathtext` + To enable/disable the use mathtext for rendering the numbers in + the formatter. + useOffset : bool or float, default: False + Whether to use offset notation with :math:`10^{3*N}` based prefixes. + This features allows showing an offset with standard SI order of + magnitude prefix near the axis. Offset is computed similarly to + how `ScalarFormatter` computes it internally, but here you are + guaranteed to get an offset which will make the tick labels exceed + 3 digits. See also `.set_useOffset`. + + .. versionadded:: 3.10 + """ + self.unit = unit + self.places = places + self.sep = sep + super().__init__( + useOffset=useOffset, + useMathText=useMathText, + useLocale=False, + usetex=usetex, + ) + + def __call__(self, x, pos=None): + """ + Return the format for tick value *x* at position *pos*. + + If there is no currently offset in the data, it returns the best + engineering formatting that fits the given argument, independently. + """ + if len(self.locs) == 0 or self.offset == 0: + return self.fix_minus(self.format_data(x)) + else: + xp = (x - self.offset) / (10. ** self.orderOfMagnitude) + if abs(xp) < 1e-8: + xp = 0 + return self._format_maybe_minus_and_locale(self.format, xp) + + def set_locs(self, locs): + # docstring inherited + self.locs = locs + if len(self.locs) > 0: + vmin, vmax = sorted(self.axis.get_view_interval()) + if self._useOffset: + self._compute_offset() + if self.offset != 0: + # We don't want to use the offset computed by + # self._compute_offset because it rounds the offset unaware + # of our engineering prefixes preference, and this can + # cause ticks with 4+ digits to appear. These ticks are + # slightly less readable, so if offset is justified + # (decided by self._compute_offset) we set it to better + # value: + self.offset = round((vmin + vmax)/2, 3) + # Use log1000 to use engineers' oom standards + self.orderOfMagnitude = math.floor(math.log(vmax - vmin, 1000))*3 + self._set_format() + + # Simplify a bit ScalarFormatter.get_offset: We always want to use + # self.format_data. Also we want to return a non-empty string only if there + # is an offset, no matter what is self.orderOfMagnitude. If there _is_ an + # offset, self.orderOfMagnitude is consulted. This behavior is verified + # in `test_ticker.py`. + def get_offset(self): + # docstring inherited + if len(self.locs) == 0: + return '' + if self.offset: + offsetStr = '' + if self.offset: + offsetStr = self.format_data(self.offset) + if self.offset > 0: + offsetStr = '+' + offsetStr + sciNotStr = self.format_data(10 ** self.orderOfMagnitude) + if self._useMathText or self._usetex: + if sciNotStr != '': + sciNotStr = r'\times%s' % sciNotStr + s = f'${sciNotStr}{offsetStr}$' + else: + s = sciNotStr + offsetStr + return self.fix_minus(s) + return '' + + def format_eng(self, num): + """Alias to EngFormatter.format_data""" + return self.format_data(num) + + def format_data(self, value): + """ + Format a number in engineering notation, appending a letter + representing the power of 1000 of the original number. + Some examples: + + >>> format_data(0) # for self.places = 0 + '0' + + >>> format_data(1000000) # for self.places = 1 + '1.0 M' + + >>> format_data(-1e-6) # for self.places = 2 + '-1.00 \N{MICRO SIGN}' + """ + sign = 1 + fmt = "g" if self.places is None else f".{self.places:d}f" + + if value < 0: + sign = -1 + value = -value + + if value != 0: + pow10 = int(math.floor(math.log10(value) / 3) * 3) + else: + pow10 = 0 + # Force value to zero, to avoid inconsistencies like + # format_eng(-0) = "0" and format_eng(0.0) = "0" + # but format_eng(-0.0) = "-0.0" + value = 0.0 + + pow10 = np.clip(pow10, min(self.ENG_PREFIXES), max(self.ENG_PREFIXES)) + + mant = sign * value / (10.0 ** pow10) + # Taking care of the cases like 999.9..., which may be rounded to 1000 + # instead of 1 k. Beware of the corner case of values that are beyond + # the range of SI prefixes (i.e. > 'Y'). + if (abs(float(format(mant, fmt))) >= 1000 + and pow10 < max(self.ENG_PREFIXES)): + mant /= 1000 + pow10 += 3 + + unit_prefix = self.ENG_PREFIXES[int(pow10)] + if self.unit or unit_prefix: + suffix = f"{self.sep}{unit_prefix}{self.unit}" + else: + suffix = "" + if self._usetex or self._useMathText: + return f"${mant:{fmt}}${suffix}" + else: + return f"{mant:{fmt}}{suffix}" + + +class PercentFormatter(Formatter): + """ + Format numbers as a percentage. + + Parameters + ---------- + xmax : float + Determines how the number is converted into a percentage. + *xmax* is the data value that corresponds to 100%. + Percentages are computed as ``x / xmax * 100``. So if the data is + already scaled to be percentages, *xmax* will be 100. Another common + situation is where *xmax* is 1.0. + + decimals : None or int + The number of decimal places to place after the point. + If *None* (the default), the number will be computed automatically. + + symbol : str or None + A string that will be appended to the label. It may be + *None* or empty to indicate that no symbol should be used. LaTeX + special characters are escaped in *symbol* whenever latex mode is + enabled, unless *is_latex* is *True*. + + is_latex : bool + If *False*, reserved LaTeX characters in *symbol* will be escaped. + """ + def __init__(self, xmax=100, decimals=None, symbol='%', is_latex=False): + self.xmax = xmax + 0.0 + self.decimals = decimals + self._symbol = symbol + self._is_latex = is_latex + + def __call__(self, x, pos=None): + """Format the tick as a percentage with the appropriate scaling.""" + ax_min, ax_max = self.axis.get_view_interval() + display_range = abs(ax_max - ax_min) + return self.fix_minus(self.format_pct(x, display_range)) + + def format_pct(self, x, display_range): + """ + Format the number as a percentage number with the correct + number of decimals and adds the percent symbol, if any. + + If ``self.decimals`` is `None`, the number of digits after the + decimal point is set based on the *display_range* of the axis + as follows: + + ============= ======== ======================= + display_range decimals sample + ============= ======== ======================= + >50 0 ``x = 34.5`` => 35% + >5 1 ``x = 34.5`` => 34.5% + >0.5 2 ``x = 34.5`` => 34.50% + ... ... ... + ============= ======== ======================= + + This method will not be very good for tiny axis ranges or + extremely large ones. It assumes that the values on the chart + are percentages displayed on a reasonable scale. + """ + x = self.convert_to_pct(x) + if self.decimals is None: + # conversion works because display_range is a difference + scaled_range = self.convert_to_pct(display_range) + if scaled_range <= 0: + decimals = 0 + else: + # Luckily Python's built-in ceil rounds to +inf, not away from + # zero. This is very important since the equation for decimals + # starts out as `scaled_range > 0.5 * 10**(2 - decimals)` + # and ends up with `decimals > 2 - log10(2 * scaled_range)`. + decimals = math.ceil(2.0 - math.log10(2.0 * scaled_range)) + if decimals > 5: + decimals = 5 + elif decimals < 0: + decimals = 0 + else: + decimals = self.decimals + s = f'{x:0.{int(decimals)}f}' + + return s + self.symbol + + def convert_to_pct(self, x): + return 100.0 * (x / self.xmax) + + @property + def symbol(self): + r""" + The configured percent symbol as a string. + + If LaTeX is enabled via :rc:`text.usetex`, the special characters + ``{'#', '$', '%', '&', '~', '_', '^', '\', '{', '}'}`` are + automatically escaped in the string. + """ + symbol = self._symbol + if not symbol: + symbol = '' + elif not self._is_latex and mpl.rcParams['text.usetex']: + # Source: http://www.personal.ceu.hu/tex/specchar.htm + # Backslash must be first for this to work correctly since + # it keeps getting added in + for spec in r'\#$%&~_^{}': + symbol = symbol.replace(spec, '\\' + spec) + return symbol + + @symbol.setter + def symbol(self, symbol): + self._symbol = symbol + + +class Locator(TickHelper): + """ + Determine tick locations. + + Note that the same locator should not be used across multiple + `~matplotlib.axis.Axis` because the locator stores references to the Axis + data and view limits. + """ + + # Some automatic tick locators can generate so many ticks they + # kill the machine when you try and render them. + # This parameter is set to cause locators to raise an error if too + # many ticks are generated. + MAXTICKS = 1000 + + def tick_values(self, vmin, vmax): + """ + Return the values of the located ticks given **vmin** and **vmax**. + + .. note:: + To get tick locations with the vmin and vmax values defined + automatically for the associated ``axis`` simply call + the Locator instance:: + + >>> print(type(loc)) + + >>> print(loc()) + [1, 2, 3, 4] + + """ + raise NotImplementedError('Derived must override') + + def set_params(self, **kwargs): + """ + Do nothing, and raise a warning. Any locator class not supporting the + set_params() function will call this. + """ + _api.warn_external( + "'set_params()' not defined for locator of type " + + str(type(self))) + + def __call__(self): + """Return the locations of the ticks.""" + # note: some locators return data limits, other return view limits, + # hence there is no *one* interface to call self.tick_values. + raise NotImplementedError('Derived must override') + + def raise_if_exceeds(self, locs): + """ + Log at WARNING level if *locs* is longer than `Locator.MAXTICKS`. + + This is intended to be called immediately before returning *locs* from + ``__call__`` to inform users in case their Locator returns a huge + number of ticks, causing Matplotlib to run out of memory. + + The "strange" name of this method dates back to when it would raise an + exception instead of emitting a log. + """ + if len(locs) >= self.MAXTICKS: + _log.warning( + "Locator attempting to generate %s ticks ([%s, ..., %s]), " + "which exceeds Locator.MAXTICKS (%s).", + len(locs), locs[0], locs[-1], self.MAXTICKS) + return locs + + def nonsingular(self, v0, v1): + """ + Adjust a range as needed to avoid singularities. + + This method gets called during autoscaling, with ``(v0, v1)`` set to + the data limits on the Axes if the Axes contains any data, or + ``(-inf, +inf)`` if not. + + - If ``v0 == v1`` (possibly up to some floating point slop), this + method returns an expanded interval around this value. + - If ``(v0, v1) == (-inf, +inf)``, this method returns appropriate + default view limits. + - Otherwise, ``(v0, v1)`` is returned without modification. + """ + return mtransforms.nonsingular(v0, v1, expander=.05) + + def view_limits(self, vmin, vmax): + """ + Select a scale for the range from vmin to vmax. + + Subclasses should override this method to change locator behaviour. + """ + return mtransforms.nonsingular(vmin, vmax) + + +class IndexLocator(Locator): + """ + Place ticks at every nth point plotted. + + IndexLocator assumes index plotting; i.e., that the ticks are placed at integer + values in the range between 0 and len(data) inclusive. + """ + def __init__(self, base, offset): + """Place ticks every *base* data point, starting at *offset*.""" + self._base = base + self.offset = offset + + def set_params(self, base=None, offset=None): + """Set parameters within this locator""" + if base is not None: + self._base = base + if offset is not None: + self.offset = offset + + def __call__(self): + """Return the locations of the ticks""" + dmin, dmax = self.axis.get_data_interval() + return self.tick_values(dmin, dmax) + + def tick_values(self, vmin, vmax): + return self.raise_if_exceeds( + np.arange(vmin + self.offset, vmax + 1, self._base)) + + +class FixedLocator(Locator): + r""" + Place ticks at a set of fixed values. + + If *nbins* is None ticks are placed at all values. Otherwise, the *locs* array of + possible positions will be subsampled to keep the number of ticks + :math:`\leq nbins + 1`. The subsampling will be done to include the smallest + absolute value; for example, if zero is included in the array of possibilities, then + it will be included in the chosen ticks. + """ + + def __init__(self, locs, nbins=None): + self.locs = np.asarray(locs) + _api.check_shape((None,), locs=self.locs) + self.nbins = max(nbins, 2) if nbins is not None else None + + def set_params(self, nbins=None): + """Set parameters within this locator.""" + if nbins is not None: + self.nbins = nbins + + def __call__(self): + return self.tick_values(None, None) + + def tick_values(self, vmin, vmax): + """ + Return the locations of the ticks. + + .. note:: + + Because the values are fixed, vmin and vmax are not used in this + method. + + """ + if self.nbins is None: + return self.locs + step = max(int(np.ceil(len(self.locs) / self.nbins)), 1) + ticks = self.locs[::step] + for i in range(1, step): + ticks1 = self.locs[i::step] + if np.abs(ticks1).min() < np.abs(ticks).min(): + ticks = ticks1 + return self.raise_if_exceeds(ticks) + + +class NullLocator(Locator): + """ + No ticks + """ + + def __call__(self): + return self.tick_values(None, None) + + def tick_values(self, vmin, vmax): + """ + Return the locations of the ticks. + + .. note:: + + Because the values are Null, vmin and vmax are not used in this + method. + """ + return [] + + +class LinearLocator(Locator): + """ + Place ticks at evenly spaced values. + + The first time this function is called it will try to set the + number of ticks to make a nice tick partitioning. Thereafter, the + number of ticks will be fixed so that interactive navigation will + be nice + + """ + def __init__(self, numticks=None, presets=None): + """ + Parameters + ---------- + numticks : int or None, default None + Number of ticks. If None, *numticks* = 11. + presets : dict or None, default: None + Dictionary mapping ``(vmin, vmax)`` to an array of locations. + Overrides *numticks* if there is an entry for the current + ``(vmin, vmax)``. + """ + self.numticks = numticks + if presets is None: + self.presets = {} + else: + self.presets = presets + + @property + def numticks(self): + # Old hard-coded default. + return self._numticks if self._numticks is not None else 11 + + @numticks.setter + def numticks(self, numticks): + self._numticks = numticks + + def set_params(self, numticks=None, presets=None): + """Set parameters within this locator.""" + if presets is not None: + self.presets = presets + if numticks is not None: + self.numticks = numticks + + def __call__(self): + """Return the locations of the ticks.""" + vmin, vmax = self.axis.get_view_interval() + return self.tick_values(vmin, vmax) + + def tick_values(self, vmin, vmax): + vmin, vmax = mtransforms.nonsingular(vmin, vmax, expander=0.05) + + if (vmin, vmax) in self.presets: + return self.presets[(vmin, vmax)] + + if self.numticks == 0: + return [] + ticklocs = np.linspace(vmin, vmax, self.numticks) + + return self.raise_if_exceeds(ticklocs) + + def view_limits(self, vmin, vmax): + """Try to choose the view limits intelligently.""" + + if vmax < vmin: + vmin, vmax = vmax, vmin + + if vmin == vmax: + vmin -= 1 + vmax += 1 + + if mpl.rcParams['axes.autolimit_mode'] == 'round_numbers': + exponent, remainder = divmod( + math.log10(vmax - vmin), math.log10(max(self.numticks - 1, 1))) + exponent -= (remainder < .5) + scale = max(self.numticks - 1, 1) ** (-exponent) + vmin = math.floor(scale * vmin) / scale + vmax = math.ceil(scale * vmax) / scale + + return mtransforms.nonsingular(vmin, vmax) + + +class MultipleLocator(Locator): + """ + Place ticks at every integer multiple of a base plus an offset. + """ + + def __init__(self, base=1.0, offset=0.0): + """ + Parameters + ---------- + base : float > 0, default: 1.0 + Interval between ticks. + offset : float, default: 0.0 + Value added to each multiple of *base*. + + .. versionadded:: 3.8 + """ + self._edge = _Edge_integer(base, 0) + self._offset = offset + + def set_params(self, base=None, offset=None): + """ + Set parameters within this locator. + + Parameters + ---------- + base : float > 0, optional + Interval between ticks. + offset : float, optional + Value added to each multiple of *base*. + + .. versionadded:: 3.8 + """ + if base is not None: + self._edge = _Edge_integer(base, 0) + if offset is not None: + self._offset = offset + + def __call__(self): + """Return the locations of the ticks.""" + vmin, vmax = self.axis.get_view_interval() + return self.tick_values(vmin, vmax) + + def tick_values(self, vmin, vmax): + if vmax < vmin: + vmin, vmax = vmax, vmin + step = self._edge.step + vmin -= self._offset + vmax -= self._offset + vmin = self._edge.ge(vmin) * step + n = (vmax - vmin + 0.001 * step) // step + locs = vmin - step + np.arange(n + 3) * step + self._offset + return self.raise_if_exceeds(locs) + + def view_limits(self, dmin, dmax): + """ + Set the view limits to the nearest tick values that contain the data. + """ + if mpl.rcParams['axes.autolimit_mode'] == 'round_numbers': + vmin = self._edge.le(dmin - self._offset) * self._edge.step + self._offset + vmax = self._edge.ge(dmax - self._offset) * self._edge.step + self._offset + if vmin == vmax: + vmin -= 1 + vmax += 1 + else: + vmin = dmin + vmax = dmax + + return mtransforms.nonsingular(vmin, vmax) + + +def scale_range(vmin, vmax, n=1, threshold=100): + dv = abs(vmax - vmin) # > 0 as nonsingular is called before. + meanv = (vmax + vmin) / 2 + if abs(meanv) / dv < threshold: + offset = 0 + else: + offset = math.copysign(10 ** (math.log10(abs(meanv)) // 1), meanv) + scale = 10 ** (math.log10(dv / n) // 1) + return scale, offset + + +class _Edge_integer: + """ + Helper for `.MaxNLocator`, `.MultipleLocator`, etc. + + Take floating-point precision limitations into account when calculating + tick locations as integer multiples of a step. + """ + def __init__(self, step, offset): + """ + Parameters + ---------- + step : float > 0 + Interval between ticks. + offset : float + Offset subtracted from the data limits prior to calculating tick + locations. + """ + if step <= 0: + raise ValueError("'step' must be positive") + self.step = step + self._offset = abs(offset) + + def closeto(self, ms, edge): + # Allow more slop when the offset is large compared to the step. + if self._offset > 0: + digits = np.log10(self._offset / self.step) + tol = max(1e-10, 10 ** (digits - 12)) + tol = min(0.4999, tol) + else: + tol = 1e-10 + return abs(ms - edge) < tol + + def le(self, x): + """Return the largest n: n*step <= x.""" + d, m = divmod(x, self.step) + if self.closeto(m / self.step, 1): + return d + 1 + return d + + def ge(self, x): + """Return the smallest n: n*step >= x.""" + d, m = divmod(x, self.step) + if self.closeto(m / self.step, 0): + return d + return d + 1 + + +class MaxNLocator(Locator): + """ + Place evenly spaced ticks, with a cap on the total number of ticks. + + Finds nice tick locations with no more than :math:`nbins + 1` ticks being within the + view limits. Locations beyond the limits are added to support autoscaling. + """ + default_params = dict(nbins=10, + steps=None, + integer=False, + symmetric=False, + prune=None, + min_n_ticks=2) + + def __init__(self, nbins=None, **kwargs): + """ + Parameters + ---------- + nbins : int or 'auto', default: 10 + Maximum number of intervals; one less than max number of + ticks. If the string 'auto', the number of bins will be + automatically determined based on the length of the axis. + + steps : array-like, optional + Sequence of acceptable tick multiples, starting with 1 and + ending with 10. For example, if ``steps=[1, 2, 4, 5, 10]``, + ``20, 40, 60`` or ``0.4, 0.6, 0.8`` would be possible + sets of ticks because they are multiples of 2. + ``30, 60, 90`` would not be generated because 3 does not + appear in this example list of steps. + + integer : bool, default: False + If True, ticks will take only integer values, provided at least + *min_n_ticks* integers are found within the view limits. + + symmetric : bool, default: False + If True, autoscaling will result in a range symmetric about zero. + + prune : {'lower', 'upper', 'both', None}, default: None + Remove the 'lower' tick, the 'upper' tick, or ticks on 'both' sides + *if they fall exactly on an axis' edge* (this typically occurs when + :rc:`axes.autolimit_mode` is 'round_numbers'). Removing such ticks + is mostly useful for stacked or ganged plots, where the upper tick + of an Axes overlaps with the lower tick of the axes above it. + + min_n_ticks : int, default: 2 + Relax *nbins* and *integer* constraints if necessary to obtain + this minimum number of ticks. + """ + if nbins is not None: + kwargs['nbins'] = nbins + self.set_params(**{**self.default_params, **kwargs}) + + @staticmethod + def _validate_steps(steps): + if not np.iterable(steps): + raise ValueError('steps argument must be an increasing sequence ' + 'of numbers between 1 and 10 inclusive') + steps = np.asarray(steps) + if np.any(np.diff(steps) <= 0) or steps[-1] > 10 or steps[0] < 1: + raise ValueError('steps argument must be an increasing sequence ' + 'of numbers between 1 and 10 inclusive') + if steps[0] != 1: + steps = np.concatenate([[1], steps]) + if steps[-1] != 10: + steps = np.concatenate([steps, [10]]) + return steps + + @staticmethod + def _staircase(steps): + # Make an extended staircase within which the needed step will be + # found. This is probably much larger than necessary. + return np.concatenate([0.1 * steps[:-1], steps, [10 * steps[1]]]) + + def set_params(self, **kwargs): + """ + Set parameters for this locator. + + Parameters + ---------- + nbins : int or 'auto', optional + see `.MaxNLocator` + steps : array-like, optional + see `.MaxNLocator` + integer : bool, optional + see `.MaxNLocator` + symmetric : bool, optional + see `.MaxNLocator` + prune : {'lower', 'upper', 'both', None}, optional + see `.MaxNLocator` + min_n_ticks : int, optional + see `.MaxNLocator` + """ + if 'nbins' in kwargs: + self._nbins = kwargs.pop('nbins') + if self._nbins != 'auto': + self._nbins = int(self._nbins) + if 'symmetric' in kwargs: + self._symmetric = kwargs.pop('symmetric') + if 'prune' in kwargs: + prune = kwargs.pop('prune') + _api.check_in_list(['upper', 'lower', 'both', None], prune=prune) + self._prune = prune + if 'min_n_ticks' in kwargs: + self._min_n_ticks = max(1, kwargs.pop('min_n_ticks')) + if 'steps' in kwargs: + steps = kwargs.pop('steps') + if steps is None: + self._steps = np.array([1, 1.5, 2, 2.5, 3, 4, 5, 6, 8, 10]) + else: + self._steps = self._validate_steps(steps) + self._extended_steps = self._staircase(self._steps) + if 'integer' in kwargs: + self._integer = kwargs.pop('integer') + if kwargs: + raise _api.kwarg_error("set_params", kwargs) + + def _raw_ticks(self, vmin, vmax): + """ + Generate a list of tick locations including the range *vmin* to + *vmax*. In some applications, one or both of the end locations + will not be needed, in which case they are trimmed off + elsewhere. + """ + if self._nbins == 'auto': + if self.axis is not None: + nbins = np.clip(self.axis.get_tick_space(), + max(1, self._min_n_ticks - 1), 9) + else: + nbins = 9 + else: + nbins = self._nbins + + scale, offset = scale_range(vmin, vmax, nbins) + _vmin = vmin - offset + _vmax = vmax - offset + steps = self._extended_steps * scale + if self._integer: + # For steps > 1, keep only integer values. + igood = (steps < 1) | (np.abs(steps - np.round(steps)) < 0.001) + steps = steps[igood] + + raw_step = ((_vmax - _vmin) / nbins) + if hasattr(self.axis, "axes") and self.axis.axes.name == '3d': + # Due to the change in automargin behavior in mpl3.9, we need to + # adjust the raw step to match the mpl3.8 appearance. The zoom + # factor of 2/48, gives us the 23/24 modifier. + raw_step = raw_step * 23/24 + large_steps = steps >= raw_step + if mpl.rcParams['axes.autolimit_mode'] == 'round_numbers': + # Classic round_numbers mode may require a larger step. + # Get first multiple of steps that are <= _vmin + floored_vmins = (_vmin // steps) * steps + floored_vmaxs = floored_vmins + steps * nbins + large_steps = large_steps & (floored_vmaxs >= _vmax) + + # Find index of smallest large step + if any(large_steps): + istep = np.nonzero(large_steps)[0][0] + else: + istep = len(steps) - 1 + + # Start at smallest of the steps greater than the raw step, and check + # if it provides enough ticks. If not, work backwards through + # smaller steps until one is found that provides enough ticks. + for step in steps[:istep+1][::-1]: + + if (self._integer and + np.floor(_vmax) - np.ceil(_vmin) >= self._min_n_ticks - 1): + step = max(1, step) + best_vmin = (_vmin // step) * step + + # Find tick locations spanning the vmin-vmax range, taking into + # account degradation of precision when there is a large offset. + # The edge ticks beyond vmin and/or vmax are needed for the + # "round_numbers" autolimit mode. + edge = _Edge_integer(step, offset) + low = edge.le(_vmin - best_vmin) + high = edge.ge(_vmax - best_vmin) + ticks = np.arange(low, high + 1) * step + best_vmin + # Count only the ticks that will be displayed. + nticks = ((ticks <= _vmax) & (ticks >= _vmin)).sum() + if nticks >= self._min_n_ticks: + break + return ticks + offset + + def __call__(self): + vmin, vmax = self.axis.get_view_interval() + return self.tick_values(vmin, vmax) + + def tick_values(self, vmin, vmax): + if self._symmetric: + vmax = max(abs(vmin), abs(vmax)) + vmin = -vmax + vmin, vmax = mtransforms.nonsingular( + vmin, vmax, expander=1e-13, tiny=1e-14) + locs = self._raw_ticks(vmin, vmax) + + prune = self._prune + if prune == 'lower': + locs = locs[1:] + elif prune == 'upper': + locs = locs[:-1] + elif prune == 'both': + locs = locs[1:-1] + return self.raise_if_exceeds(locs) + + def view_limits(self, dmin, dmax): + if self._symmetric: + dmax = max(abs(dmin), abs(dmax)) + dmin = -dmax + + dmin, dmax = mtransforms.nonsingular( + dmin, dmax, expander=1e-12, tiny=1e-13) + + if mpl.rcParams['axes.autolimit_mode'] == 'round_numbers': + return self._raw_ticks(dmin, dmax)[[0, -1]] + else: + return dmin, dmax + + +def _is_decade(x, *, base=10, rtol=None): + """Return True if *x* is an integer power of *base*.""" + if not np.isfinite(x): + return False + if x == 0.0: + return True + lx = np.log(abs(x)) / np.log(base) + if rtol is None: + return np.isclose(lx, np.round(lx)) + else: + return np.isclose(lx, np.round(lx), rtol=rtol) + + +def _decade_less_equal(x, base): + """ + Return the largest integer power of *base* that's less or equal to *x*. + + If *x* is negative, the exponent will be *greater*. + """ + return (x if x == 0 else + -_decade_greater_equal(-x, base) if x < 0 else + base ** np.floor(np.log(x) / np.log(base))) + + +def _decade_greater_equal(x, base): + """ + Return the smallest integer power of *base* that's greater or equal to *x*. + + If *x* is negative, the exponent will be *smaller*. + """ + return (x if x == 0 else + -_decade_less_equal(-x, base) if x < 0 else + base ** np.ceil(np.log(x) / np.log(base))) + + +def _decade_less(x, base): + """ + Return the largest integer power of *base* that's less than *x*. + + If *x* is negative, the exponent will be *greater*. + """ + if x < 0: + return -_decade_greater(-x, base) + less = _decade_less_equal(x, base) + if less == x: + less /= base + return less + + +def _decade_greater(x, base): + """ + Return the smallest integer power of *base* that's greater than *x*. + + If *x* is negative, the exponent will be *smaller*. + """ + if x < 0: + return -_decade_less(-x, base) + greater = _decade_greater_equal(x, base) + if greater == x: + greater *= base + return greater + + +def _is_close_to_int(x): + return math.isclose(x, round(x)) + + +class LogLocator(Locator): + """ + Place logarithmically spaced ticks. + + Places ticks at the values ``subs[j] * base**i``. + """ + + def __init__(self, base=10.0, subs=(1.0,), *, numticks=None): + """ + Parameters + ---------- + base : float, default: 10.0 + The base of the log used, so major ticks are placed at ``base**n``, where + ``n`` is an integer. + subs : None or {'auto', 'all'} or sequence of float, default: (1.0,) + Gives the multiples of integer powers of the base at which to place ticks. + The default of ``(1.0, )`` places ticks only at integer powers of the base. + Permitted string values are ``'auto'`` and ``'all'``. Both of these use an + algorithm based on the axis view limits to determine whether and how to put + ticks between integer powers of the base: + - ``'auto'``: Ticks are placed only between integer powers. + - ``'all'``: Ticks are placed between *and* at integer powers. + - ``None``: Equivalent to ``'auto'``. + numticks : None or int, default: None + The maximum number of ticks to allow on a given axis. The default of + ``None`` will try to choose intelligently as long as this Locator has + already been assigned to an axis using `~.axis.Axis.get_tick_space`, but + otherwise falls back to 9. + """ + if numticks is None: + if mpl.rcParams['_internal.classic_mode']: + numticks = 15 + else: + numticks = 'auto' + self._base = float(base) + self._set_subs(subs) + self.numticks = numticks + + def set_params(self, base=None, subs=None, *, numticks=None): + """Set parameters within this locator.""" + if base is not None: + self._base = float(base) + if subs is not None: + self._set_subs(subs) + if numticks is not None: + self.numticks = numticks + + def _set_subs(self, subs): + """ + Set the minor ticks for the log scaling every ``base**i*subs[j]``. + """ + if subs is None: # consistency with previous bad API + self._subs = 'auto' + elif isinstance(subs, str): + _api.check_in_list(('all', 'auto'), subs=subs) + self._subs = subs + else: + try: + self._subs = np.asarray(subs, dtype=float) + except ValueError as e: + raise ValueError("subs must be None, 'all', 'auto' or " + "a sequence of floats, not " + f"{subs}.") from e + if self._subs.ndim != 1: + raise ValueError("A sequence passed to subs must be " + "1-dimensional, not " + f"{self._subs.ndim}-dimensional.") + + def __call__(self): + """Return the locations of the ticks.""" + vmin, vmax = self.axis.get_view_interval() + return self.tick_values(vmin, vmax) + + def tick_values(self, vmin, vmax): + if self.numticks == 'auto': + if self.axis is not None: + numticks = np.clip(self.axis.get_tick_space(), 2, 9) + else: + numticks = 9 + else: + numticks = self.numticks + + b = self._base + if vmin <= 0.0: + if self.axis is not None: + vmin = self.axis.get_minpos() + + if vmin <= 0.0 or not np.isfinite(vmin): + raise ValueError( + "Data has no positive values, and therefore cannot be log-scaled.") + + _log.debug('vmin %s vmax %s', vmin, vmax) + + if vmax < vmin: + vmin, vmax = vmax, vmin + log_vmin = math.log(vmin) / math.log(b) + log_vmax = math.log(vmax) / math.log(b) + + numdec = math.floor(log_vmax) - math.ceil(log_vmin) + + if isinstance(self._subs, str): + if numdec > 10 or b < 3: + if self._subs == 'auto': + return np.array([]) # no minor or major ticks + else: + subs = np.array([1.0]) # major ticks + else: + _first = 2.0 if self._subs == 'auto' else 1.0 + subs = np.arange(_first, b) + else: + subs = self._subs + + # Get decades between major ticks. + stride = (max(math.ceil(numdec / (numticks - 1)), 1) + if mpl.rcParams['_internal.classic_mode'] else + numdec // numticks + 1) + + # if we have decided that the stride is as big or bigger than + # the range, clip the stride back to the available range - 1 + # with a floor of 1. This prevents getting axis with only 1 tick + # visible. + if stride >= numdec: + stride = max(1, numdec - 1) + + # Does subs include anything other than 1? Essentially a hack to know + # whether we're a major or a minor locator. + have_subs = len(subs) > 1 or (len(subs) == 1 and subs[0] != 1.0) + + decades = np.arange(math.floor(log_vmin) - stride, + math.ceil(log_vmax) + 2 * stride, stride) + + if have_subs: + if stride == 1: + ticklocs = np.concatenate( + [subs * decade_start for decade_start in b ** decades]) + else: + ticklocs = np.array([]) + else: + ticklocs = b ** decades + + _log.debug('ticklocs %r', ticklocs) + if (len(subs) > 1 + and stride == 1 + and ((vmin <= ticklocs) & (ticklocs <= vmax)).sum() <= 1): + # If we're a minor locator *that expects at least two ticks per + # decade* and the major locator stride is 1 and there's no more + # than one minor tick, switch to AutoLocator. + return AutoLocator().tick_values(vmin, vmax) + else: + return self.raise_if_exceeds(ticklocs) + + def view_limits(self, vmin, vmax): + """Try to choose the view limits intelligently.""" + b = self._base + + vmin, vmax = self.nonsingular(vmin, vmax) + + if mpl.rcParams['axes.autolimit_mode'] == 'round_numbers': + vmin = _decade_less_equal(vmin, b) + vmax = _decade_greater_equal(vmax, b) + + return vmin, vmax + + def nonsingular(self, vmin, vmax): + if vmin > vmax: + vmin, vmax = vmax, vmin + if not np.isfinite(vmin) or not np.isfinite(vmax): + vmin, vmax = 1, 10 # Initial range, no data plotted yet. + elif vmax <= 0: + _api.warn_external( + "Data has no positive values, and therefore cannot be " + "log-scaled.") + vmin, vmax = 1, 10 + else: + # Consider shared axises + minpos = min(axis.get_minpos() for axis in self.axis._get_shared_axis()) + if not np.isfinite(minpos): + minpos = 1e-300 # This should never take effect. + if vmin <= 0: + vmin = minpos + if vmin == vmax: + vmin = _decade_less(vmin, self._base) + vmax = _decade_greater(vmax, self._base) + return vmin, vmax + + +class SymmetricalLogLocator(Locator): + """ + Place ticks spaced linearly near zero and spaced logarithmically beyond a threshold. + """ + + def __init__(self, transform=None, subs=None, linthresh=None, base=None): + """ + Parameters + ---------- + transform : `~.scale.SymmetricalLogTransform`, optional + If set, defines the *base* and *linthresh* of the symlog transform. + base, linthresh : float, optional + The *base* and *linthresh* of the symlog transform, as documented + for `.SymmetricalLogScale`. These parameters are only used if + *transform* is not set. + subs : sequence of float, default: [1] + The multiples of integer powers of the base where ticks are placed, + i.e., ticks are placed at + ``[sub * base**i for i in ... for sub in subs]``. + + Notes + ----- + Either *transform*, or both *base* and *linthresh*, must be given. + """ + if transform is not None: + self._base = transform.base + self._linthresh = transform.linthresh + elif linthresh is not None and base is not None: + self._base = base + self._linthresh = linthresh + else: + raise ValueError("Either transform, or both linthresh " + "and base, must be provided.") + if subs is None: + self._subs = [1.0] + else: + self._subs = subs + self.numticks = 15 + + def set_params(self, subs=None, numticks=None): + """Set parameters within this locator.""" + if numticks is not None: + self.numticks = numticks + if subs is not None: + self._subs = subs + + def __call__(self): + """Return the locations of the ticks.""" + # Note, these are untransformed coordinates + vmin, vmax = self.axis.get_view_interval() + return self.tick_values(vmin, vmax) + + def tick_values(self, vmin, vmax): + linthresh = self._linthresh + + if vmax < vmin: + vmin, vmax = vmax, vmin + + # The domain is divided into three sections, only some of + # which may actually be present. + # + # <======== -t ==0== t ========> + # aaaaaaaaa bbbbb ccccccccc + # + # a) and c) will have ticks at integral log positions. The + # number of ticks needs to be reduced if there are more + # than self.numticks of them. + # + # b) has a tick at 0 and only 0 (we assume t is a small + # number, and the linear segment is just an implementation + # detail and not interesting.) + # + # We could also add ticks at t, but that seems to usually be + # uninteresting. + # + # "simple" mode is when the range falls entirely within [-t, t] + # -- it should just display (vmin, 0, vmax) + if -linthresh <= vmin < vmax <= linthresh: + # only the linear range is present + return sorted({vmin, 0, vmax}) + + # Lower log range is present + has_a = (vmin < -linthresh) + # Upper log range is present + has_c = (vmax > linthresh) + + # Check if linear range is present + has_b = (has_a and vmax > -linthresh) or (has_c and vmin < linthresh) + + base = self._base + + def get_log_range(lo, hi): + lo = np.floor(np.log(lo) / np.log(base)) + hi = np.ceil(np.log(hi) / np.log(base)) + return lo, hi + + # Calculate all the ranges, so we can determine striding + a_lo, a_hi = (0, 0) + if has_a: + a_upper_lim = min(-linthresh, vmax) + a_lo, a_hi = get_log_range(abs(a_upper_lim), abs(vmin) + 1) + + c_lo, c_hi = (0, 0) + if has_c: + c_lower_lim = max(linthresh, vmin) + c_lo, c_hi = get_log_range(c_lower_lim, vmax + 1) + + # Calculate the total number of integer exponents in a and c ranges + total_ticks = (a_hi - a_lo) + (c_hi - c_lo) + if has_b: + total_ticks += 1 + stride = max(total_ticks // (self.numticks - 1), 1) + + decades = [] + if has_a: + decades.extend(-1 * (base ** (np.arange(a_lo, a_hi, + stride)[::-1]))) + + if has_b: + decades.append(0.0) + + if has_c: + decades.extend(base ** (np.arange(c_lo, c_hi, stride))) + + subs = np.asarray(self._subs) + + if len(subs) > 1 or subs[0] != 1.0: + ticklocs = [] + for decade in decades: + if decade == 0: + ticklocs.append(decade) + else: + ticklocs.extend(subs * decade) + else: + ticklocs = decades + + return self.raise_if_exceeds(np.array(ticklocs)) + + def view_limits(self, vmin, vmax): + """Try to choose the view limits intelligently.""" + b = self._base + if vmax < vmin: + vmin, vmax = vmax, vmin + + if mpl.rcParams['axes.autolimit_mode'] == 'round_numbers': + vmin = _decade_less_equal(vmin, b) + vmax = _decade_greater_equal(vmax, b) + if vmin == vmax: + vmin = _decade_less(vmin, b) + vmax = _decade_greater(vmax, b) + + return mtransforms.nonsingular(vmin, vmax) + + +class AsinhLocator(Locator): + """ + Place ticks spaced evenly on an inverse-sinh scale. + + Generally used with the `~.scale.AsinhScale` class. + + .. note:: + + This API is provisional and may be revised in the future + based on early user feedback. + """ + def __init__(self, linear_width, numticks=11, symthresh=0.2, + base=10, subs=None): + """ + Parameters + ---------- + linear_width : float + The scale parameter defining the extent + of the quasi-linear region. + numticks : int, default: 11 + The approximate number of major ticks that will fit + along the entire axis + symthresh : float, default: 0.2 + The fractional threshold beneath which data which covers + a range that is approximately symmetric about zero + will have ticks that are exactly symmetric. + base : int, default: 10 + The number base used for rounding tick locations + on a logarithmic scale. If this is less than one, + then rounding is to the nearest integer multiple + of powers of ten. + subs : tuple, default: None + Multiples of the number base, typically used + for the minor ticks, e.g. (2, 5) when base=10. + """ + super().__init__() + self.linear_width = linear_width + self.numticks = numticks + self.symthresh = symthresh + self.base = base + self.subs = subs + + def set_params(self, numticks=None, symthresh=None, + base=None, subs=None): + """Set parameters within this locator.""" + if numticks is not None: + self.numticks = numticks + if symthresh is not None: + self.symthresh = symthresh + if base is not None: + self.base = base + if subs is not None: + self.subs = subs if len(subs) > 0 else None + + def __call__(self): + vmin, vmax = self.axis.get_view_interval() + if (vmin * vmax) < 0 and abs(1 + vmax / vmin) < self.symthresh: + # Data-range appears to be almost symmetric, so round up: + bound = max(abs(vmin), abs(vmax)) + return self.tick_values(-bound, bound) + else: + return self.tick_values(vmin, vmax) + + def tick_values(self, vmin, vmax): + # Construct a set of uniformly-spaced "on-screen" locations. + ymin, ymax = self.linear_width * np.arcsinh(np.array([vmin, vmax]) + / self.linear_width) + ys = np.linspace(ymin, ymax, self.numticks) + zero_dev = abs(ys / (ymax - ymin)) + if ymin * ymax < 0: + # Ensure that the zero tick-mark is included, if the axis straddles zero. + ys = np.hstack([ys[(zero_dev > 0.5 / self.numticks)], 0.0]) + + # Transform the "on-screen" grid to the data space: + xs = self.linear_width * np.sinh(ys / self.linear_width) + zero_xs = (ys == 0) + + # Round the data-space values to be intuitive base-n numbers, keeping track of + # positive and negative values separately and carefully treating the zero value. + with np.errstate(divide="ignore"): # base ** log(0) = base ** -inf = 0. + if self.base > 1: + pows = (np.sign(xs) + * self.base ** np.floor(np.log(abs(xs)) / math.log(self.base))) + qs = np.outer(pows, self.subs).flatten() if self.subs else pows + else: # No need to adjust sign(pows), as it cancels out when computing qs. + pows = np.where(zero_xs, 1, 10**np.floor(np.log10(abs(xs)))) + qs = pows * np.round(xs / pows) + ticks = np.array(sorted(set(qs))) + + return ticks if len(ticks) >= 2 else np.linspace(vmin, vmax, self.numticks) + + +class LogitLocator(MaxNLocator): + """ + Place ticks spaced evenly on a logit scale. + """ + + def __init__(self, minor=False, *, nbins="auto"): + """ + Parameters + ---------- + nbins : int or 'auto', optional + Number of ticks. Only used if minor is False. + minor : bool, default: False + Indicate if this locator is for minor ticks or not. + """ + + self._minor = minor + super().__init__(nbins=nbins, steps=[1, 2, 5, 10]) + + def set_params(self, minor=None, **kwargs): + """Set parameters within this locator.""" + if minor is not None: + self._minor = minor + super().set_params(**kwargs) + + @property + def minor(self): + return self._minor + + @minor.setter + def minor(self, value): + self.set_params(minor=value) + + def tick_values(self, vmin, vmax): + # dummy axis has no axes attribute + if hasattr(self.axis, "axes") and self.axis.axes.name == "polar": + raise NotImplementedError("Polar axis cannot be logit scaled yet") + + if self._nbins == "auto": + if self.axis is not None: + nbins = self.axis.get_tick_space() + if nbins < 2: + nbins = 2 + else: + nbins = 9 + else: + nbins = self._nbins + + # We define ideal ticks with their index: + # linscale: ... 1e-3 1e-2 1e-1 1/2 1-1e-1 1-1e-2 1-1e-3 ... + # b-scale : ... -3 -2 -1 0 1 2 3 ... + def ideal_ticks(x): + return 10 ** x if x < 0 else 1 - (10 ** (-x)) if x > 0 else 0.5 + + vmin, vmax = self.nonsingular(vmin, vmax) + binf = int( + np.floor(np.log10(vmin)) + if vmin < 0.5 + else 0 + if vmin < 0.9 + else -np.ceil(np.log10(1 - vmin)) + ) + bsup = int( + np.ceil(np.log10(vmax)) + if vmax <= 0.5 + else 1 + if vmax <= 0.9 + else -np.floor(np.log10(1 - vmax)) + ) + numideal = bsup - binf - 1 + if numideal >= 2: + # have 2 or more wanted ideal ticks, so use them as major ticks + if numideal > nbins: + # to many ideal ticks, subsampling ideals for major ticks, and + # take others for minor ticks + subsampling_factor = math.ceil(numideal / nbins) + if self._minor: + ticklocs = [ + ideal_ticks(b) + for b in range(binf, bsup + 1) + if (b % subsampling_factor) != 0 + ] + else: + ticklocs = [ + ideal_ticks(b) + for b in range(binf, bsup + 1) + if (b % subsampling_factor) == 0 + ] + return self.raise_if_exceeds(np.array(ticklocs)) + if self._minor: + ticklocs = [] + for b in range(binf, bsup): + if b < -1: + ticklocs.extend(np.arange(2, 10) * 10 ** b) + elif b == -1: + ticklocs.extend(np.arange(2, 5) / 10) + elif b == 0: + ticklocs.extend(np.arange(6, 9) / 10) + else: + ticklocs.extend( + 1 - np.arange(2, 10)[::-1] * 10 ** (-b - 1) + ) + return self.raise_if_exceeds(np.array(ticklocs)) + ticklocs = [ideal_ticks(b) for b in range(binf, bsup + 1)] + return self.raise_if_exceeds(np.array(ticklocs)) + # the scale is zoomed so same ticks as linear scale can be used + if self._minor: + return [] + return super().tick_values(vmin, vmax) + + def nonsingular(self, vmin, vmax): + standard_minpos = 1e-7 + initial_range = (standard_minpos, 1 - standard_minpos) + if vmin > vmax: + vmin, vmax = vmax, vmin + if not np.isfinite(vmin) or not np.isfinite(vmax): + vmin, vmax = initial_range # Initial range, no data plotted yet. + elif vmax <= 0 or vmin >= 1: + # vmax <= 0 occurs when all values are negative + # vmin >= 1 occurs when all values are greater than one + _api.warn_external( + "Data has no values between 0 and 1, and therefore cannot be " + "logit-scaled." + ) + vmin, vmax = initial_range + else: + minpos = ( + self.axis.get_minpos() + if self.axis is not None + else standard_minpos + ) + if not np.isfinite(minpos): + minpos = standard_minpos # This should never take effect. + if vmin <= 0: + vmin = minpos + # NOTE: for vmax, we should query a property similar to get_minpos, + # but related to the maximal, less-than-one data point. + # Unfortunately, Bbox._minpos is defined very deep in the BBox and + # updated with data, so for now we use 1 - minpos as a substitute. + if vmax >= 1: + vmax = 1 - minpos + if vmin == vmax: + vmin, vmax = 0.1 * vmin, 1 - 0.1 * vmin + + return vmin, vmax + + +class AutoLocator(MaxNLocator): + """ + Place evenly spaced ticks, with the step size and maximum number of ticks chosen + automatically. + + This is a subclass of `~matplotlib.ticker.MaxNLocator`, with parameters + *nbins = 'auto'* and *steps = [1, 2, 2.5, 5, 10]*. + """ + def __init__(self): + """ + To know the values of the non-public parameters, please have a + look to the defaults of `~matplotlib.ticker.MaxNLocator`. + """ + if mpl.rcParams['_internal.classic_mode']: + nbins = 9 + steps = [1, 2, 5, 10] + else: + nbins = 'auto' + steps = [1, 2, 2.5, 5, 10] + super().__init__(nbins=nbins, steps=steps) + + +class AutoMinorLocator(Locator): + """ + Place evenly spaced minor ticks, with the step size and maximum number of ticks + chosen automatically. + + The Axis must use a linear scale and have evenly spaced major ticks. + """ + + def __init__(self, n=None): + """ + Parameters + ---------- + n : int or 'auto', default: :rc:`xtick.minor.ndivs` or :rc:`ytick.minor.ndivs` + The number of subdivisions of the interval between major ticks; + e.g., n=2 will place a single minor tick midway between major ticks. + + If *n* is 'auto', it will be set to 4 or 5: if the distance + between the major ticks equals 1, 2.5, 5 or 10 it can be perfectly + divided in 5 equidistant sub-intervals with a length multiple of + 0.05; otherwise, it is divided in 4 sub-intervals. + """ + self.ndivs = n + + def __call__(self): + # docstring inherited + if self.axis.get_scale() == 'log': + _api.warn_external('AutoMinorLocator does not work on logarithmic scales') + return [] + + majorlocs = np.unique(self.axis.get_majorticklocs()) + if len(majorlocs) < 2: + # Need at least two major ticks to find minor tick locations. + # TODO: Figure out a way to still be able to display minor ticks with less + # than two major ticks visible. For now, just display no ticks at all. + return [] + majorstep = majorlocs[1] - majorlocs[0] + + if self.ndivs is None: + self.ndivs = mpl.rcParams[ + 'ytick.minor.ndivs' if self.axis.axis_name == 'y' + else 'xtick.minor.ndivs'] # for x and z axis + + if self.ndivs == 'auto': + majorstep_mantissa = 10 ** (np.log10(majorstep) % 1) + ndivs = 5 if np.isclose(majorstep_mantissa, [1, 2.5, 5, 10]).any() else 4 + else: + ndivs = self.ndivs + + minorstep = majorstep / ndivs + + vmin, vmax = sorted(self.axis.get_view_interval()) + t0 = majorlocs[0] + tmin = round((vmin - t0) / minorstep) + tmax = round((vmax - t0) / minorstep) + 1 + locs = (np.arange(tmin, tmax) * minorstep) + t0 + + return self.raise_if_exceeds(locs) + + def tick_values(self, vmin, vmax): + raise NotImplementedError( + f"Cannot get tick locations for a {type(self).__name__}") diff --git a/infer_4_30_0/lib/python3.10/site-packages/matplotlib/typing.py b/infer_4_30_0/lib/python3.10/site-packages/matplotlib/typing.py new file mode 100644 index 0000000000000000000000000000000000000000..20e1022fa0a5a0487aa771da822ff481685f236f --- /dev/null +++ b/infer_4_30_0/lib/python3.10/site-packages/matplotlib/typing.py @@ -0,0 +1,78 @@ +""" +Typing support for Matplotlib + +This module contains Type aliases which are useful for Matplotlib and potentially +downstream libraries. + +.. admonition:: Provisional status of typing + + The ``typing`` module and type stub files are considered provisional and may change + at any time without a deprecation period. +""" +from collections.abc import Hashable, Sequence +import pathlib +from typing import Any, Callable, Literal, TypeAlias, TypeVar, Union + +from . import path +from ._enums import JoinStyle, CapStyle +from .artist import Artist +from .backend_bases import RendererBase +from .markers import MarkerStyle +from .transforms import Bbox, Transform + +RGBColorType: TypeAlias = tuple[float, float, float] | str +RGBAColorType: TypeAlias = ( + str | # "none" or "#RRGGBBAA"/"#RGBA" hex strings + tuple[float, float, float, float] | + # 2 tuple (color, alpha) representations, not infinitely recursive + # RGBColorType includes the (str, float) tuple, even for RGBA strings + tuple[RGBColorType, float] | + # (4-tuple, float) is odd, but accepted as the outer float overriding A of 4-tuple + tuple[tuple[float, float, float, float], float] +) + +ColorType: TypeAlias = RGBColorType | RGBAColorType + +RGBColourType: TypeAlias = RGBColorType +RGBAColourType: TypeAlias = RGBAColorType +ColourType: TypeAlias = ColorType + +LineStyleType: TypeAlias = str | tuple[float, Sequence[float]] +DrawStyleType: TypeAlias = Literal["default", "steps", "steps-pre", "steps-mid", + "steps-post"] +MarkEveryType: TypeAlias = ( + None | + int | tuple[int, int] | slice | list[int] | + float | tuple[float, float] | + list[bool] +) + +MarkerType: TypeAlias = str | path.Path | MarkerStyle +FillStyleType: TypeAlias = Literal["full", "left", "right", "bottom", "top", "none"] +JoinStyleType: TypeAlias = JoinStyle | Literal["miter", "round", "bevel"] +CapStyleType: TypeAlias = CapStyle | Literal["butt", "projecting", "round"] + +CoordsBaseType = Union[ + str, + Artist, + Transform, + Callable[ + [RendererBase], + Union[Bbox, Transform] + ] +] +CoordsType = Union[ + CoordsBaseType, + tuple[CoordsBaseType, CoordsBaseType] +] + +RcStyleType: TypeAlias = ( + str | + dict[str, Any] | + pathlib.Path | + Sequence[str | pathlib.Path | dict[str, Any]] +) + +_HT = TypeVar("_HT", bound=Hashable) +HashableList: TypeAlias = list[_HT | "HashableList[_HT]"] +"""A nested list of Hashable values.""" diff --git a/infer_4_30_0/lib/python3.10/site-packages/matplotlib/units.py b/infer_4_30_0/lib/python3.10/site-packages/matplotlib/units.py new file mode 100644 index 0000000000000000000000000000000000000000..e3480f228bb45cff45ed0566ceabdb1f3dcd53e1 --- /dev/null +++ b/infer_4_30_0/lib/python3.10/site-packages/matplotlib/units.py @@ -0,0 +1,195 @@ +""" +The classes here provide support for using custom classes with +Matplotlib, e.g., those that do not expose the array interface but know +how to convert themselves to arrays. It also supports classes with +units and units conversion. Use cases include converters for custom +objects, e.g., a list of datetime objects, as well as for objects that +are unit aware. We don't assume any particular units implementation; +rather a units implementation must register with the Registry converter +dictionary and provide a `ConversionInterface`. For example, +here is a complete implementation which supports plotting with native +datetime objects:: + + import matplotlib.units as units + import matplotlib.dates as dates + import matplotlib.ticker as ticker + import datetime + + class DateConverter(units.ConversionInterface): + + @staticmethod + def convert(value, unit, axis): + "Convert a datetime value to a scalar or array." + return dates.date2num(value) + + @staticmethod + def axisinfo(unit, axis): + "Return major and minor tick locators and formatters." + if unit != 'date': + return None + majloc = dates.AutoDateLocator() + majfmt = dates.AutoDateFormatter(majloc) + return units.AxisInfo(majloc=majloc, majfmt=majfmt, label='date') + + @staticmethod + def default_units(x, axis): + "Return the default unit for x or None." + return 'date' + + # Finally we register our object type with the Matplotlib units registry. + units.registry[datetime.date] = DateConverter() +""" + +from decimal import Decimal +from numbers import Number + +import numpy as np +from numpy import ma + +from matplotlib import cbook + + +class ConversionError(TypeError): + pass + + +def _is_natively_supported(x): + """ + Return whether *x* is of a type that Matplotlib natively supports or an + array of objects of such types. + """ + # Matplotlib natively supports all number types except Decimal. + if np.iterable(x): + # Assume lists are homogeneous as other functions in unit system. + for thisx in x: + if thisx is ma.masked: + continue + return isinstance(thisx, Number) and not isinstance(thisx, Decimal) + else: + return isinstance(x, Number) and not isinstance(x, Decimal) + + +class AxisInfo: + """ + Information to support default axis labeling, tick labeling, and limits. + + An instance of this class must be returned by + `ConversionInterface.axisinfo`. + """ + def __init__(self, majloc=None, minloc=None, + majfmt=None, minfmt=None, label=None, + default_limits=None): + """ + Parameters + ---------- + majloc, minloc : Locator, optional + Tick locators for the major and minor ticks. + majfmt, minfmt : Formatter, optional + Tick formatters for the major and minor ticks. + label : str, optional + The default axis label. + default_limits : optional + The default min and max limits of the axis if no data has + been plotted. + + Notes + ----- + If any of the above are ``None``, the axis will simply use the + default value. + """ + self.majloc = majloc + self.minloc = minloc + self.majfmt = majfmt + self.minfmt = minfmt + self.label = label + self.default_limits = default_limits + + +class ConversionInterface: + """ + The minimal interface for a converter to take custom data types (or + sequences) and convert them to values Matplotlib can use. + """ + + @staticmethod + def axisinfo(unit, axis): + """Return an `.AxisInfo` for the axis with the specified units.""" + return None + + @staticmethod + def default_units(x, axis): + """Return the default unit for *x* or ``None`` for the given axis.""" + return None + + @staticmethod + def convert(obj, unit, axis): + """ + Convert *obj* using *unit* for the specified *axis*. + + If *obj* is a sequence, return the converted sequence. The output must + be a sequence of scalars that can be used by the numpy array layer. + """ + return obj + + +class DecimalConverter(ConversionInterface): + """Converter for decimal.Decimal data to float.""" + + @staticmethod + def convert(value, unit, axis): + """ + Convert Decimals to floats. + + The *unit* and *axis* arguments are not used. + + Parameters + ---------- + value : decimal.Decimal or iterable + Decimal or list of Decimal need to be converted + """ + if isinstance(value, Decimal): + return float(value) + # value is Iterable[Decimal] + elif isinstance(value, ma.MaskedArray): + return ma.asarray(value, dtype=float) + else: + return np.asarray(value, dtype=float) + + # axisinfo and default_units can be inherited as Decimals are Numbers. + + +class Registry(dict): + """Register types with conversion interface.""" + + def get_converter(self, x): + """Get the converter interface instance for *x*, or None.""" + # Unpack in case of e.g. Pandas or xarray object + x = cbook._unpack_to_numpy(x) + + if isinstance(x, np.ndarray): + # In case x in a masked array, access the underlying data (only its + # type matters). If x is a regular ndarray, getdata() just returns + # the array itself. + x = np.ma.getdata(x).ravel() + # If there are no elements in x, infer the units from its dtype + if not x.size: + return self.get_converter(np.array([0], dtype=x.dtype)) + for cls in type(x).__mro__: # Look up in the cache. + try: + return self[cls] + except KeyError: + pass + try: # If cache lookup fails, look up based on first element... + first = cbook._safe_first_finite(x) + except (TypeError, StopIteration): + pass + else: + # ... and avoid infinite recursion for pathological iterables for + # which indexing returns instances of the same iterable class. + if type(first) is not type(x): + return self.get_converter(first) + return None + + +registry = Registry() +registry[Decimal] = DecimalConverter() diff --git a/infer_4_30_0/lib/python3.10/site-packages/narwhals-1.21.1.dist-info/licenses/LICENSE.md b/infer_4_30_0/lib/python3.10/site-packages/narwhals-1.21.1.dist-info/licenses/LICENSE.md new file mode 100644 index 0000000000000000000000000000000000000000..b9e2a9336ac1efccddbe91a123d45d8c490ebe74 --- /dev/null +++ b/infer_4_30_0/lib/python3.10/site-packages/narwhals-1.21.1.dist-info/licenses/LICENSE.md @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2024, Marco Gorelli + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/infer_4_30_0/lib/python3.10/site-packages/pkg_resources/__pycache__/__init__.cpython-310.pyc b/infer_4_30_0/lib/python3.10/site-packages/pkg_resources/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e8ca06e4b9dcb75c123723807d699de7fc438785 --- /dev/null +++ b/infer_4_30_0/lib/python3.10/site-packages/pkg_resources/__pycache__/__init__.cpython-310.pyc @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:5038415dcd05b856b4f50b67144679889ce40bbdf2089c1004e7e8a0e43204c5 +size 115499 diff --git a/infer_4_30_0/lib/python3.10/site-packages/pkg_resources/py.typed b/infer_4_30_0/lib/python3.10/site-packages/pkg_resources/py.typed new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/infer_4_30_0/lib/python3.10/site-packages/pkg_resources/tests/__init__.py b/infer_4_30_0/lib/python3.10/site-packages/pkg_resources/tests/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/infer_4_30_0/lib/python3.10/site-packages/pkg_resources/tests/test_find_distributions.py b/infer_4_30_0/lib/python3.10/site-packages/pkg_resources/tests/test_find_distributions.py new file mode 100644 index 0000000000000000000000000000000000000000..301b36d6cdbf128f839db473aa6b191eba694937 --- /dev/null +++ b/infer_4_30_0/lib/python3.10/site-packages/pkg_resources/tests/test_find_distributions.py @@ -0,0 +1,56 @@ +import shutil +from pathlib import Path + +import pytest + +import pkg_resources + +TESTS_DATA_DIR = Path(__file__).parent / 'data' + + +class TestFindDistributions: + @pytest.fixture + def target_dir(self, tmpdir): + target_dir = tmpdir.mkdir('target') + # place a .egg named directory in the target that is not an egg: + target_dir.mkdir('not.an.egg') + return target_dir + + def test_non_egg_dir_named_egg(self, target_dir): + dists = pkg_resources.find_distributions(str(target_dir)) + assert not list(dists) + + def test_standalone_egg_directory(self, target_dir): + shutil.copytree( + TESTS_DATA_DIR / 'my-test-package_unpacked-egg', + target_dir, + dirs_exist_ok=True, + ) + dists = pkg_resources.find_distributions(str(target_dir)) + assert [dist.project_name for dist in dists] == ['my-test-package'] + dists = pkg_resources.find_distributions(str(target_dir), only=True) + assert not list(dists) + + def test_zipped_egg(self, target_dir): + shutil.copytree( + TESTS_DATA_DIR / 'my-test-package_zipped-egg', + target_dir, + dirs_exist_ok=True, + ) + dists = pkg_resources.find_distributions(str(target_dir)) + assert [dist.project_name for dist in dists] == ['my-test-package'] + dists = pkg_resources.find_distributions(str(target_dir), only=True) + assert not list(dists) + + def test_zipped_sdist_one_level_removed(self, target_dir): + shutil.copytree( + TESTS_DATA_DIR / 'my-test-package-zip', target_dir, dirs_exist_ok=True + ) + dists = pkg_resources.find_distributions( + str(target_dir / "my-test-package.zip") + ) + assert [dist.project_name for dist in dists] == ['my-test-package'] + dists = pkg_resources.find_distributions( + str(target_dir / "my-test-package.zip"), only=True + ) + assert not list(dists) diff --git a/infer_4_30_0/lib/python3.10/site-packages/pkg_resources/tests/test_resources.py b/infer_4_30_0/lib/python3.10/site-packages/pkg_resources/tests/test_resources.py new file mode 100644 index 0000000000000000000000000000000000000000..f5e793fb90a309f6117e1dbe0b4b3f93f073bcb3 --- /dev/null +++ b/infer_4_30_0/lib/python3.10/site-packages/pkg_resources/tests/test_resources.py @@ -0,0 +1,869 @@ +import itertools +import os +import platform +import string +import sys + +import pytest +from packaging.specifiers import SpecifierSet + +import pkg_resources +from pkg_resources import ( + Distribution, + EntryPoint, + Requirement, + VersionConflict, + WorkingSet, + parse_requirements, + parse_version, + safe_name, + safe_version, +) + + +# from Python 3.6 docs. Available from itertools on Python 3.10 +def pairwise(iterable): + "s -> (s0,s1), (s1,s2), (s2, s3), ..." + a, b = itertools.tee(iterable) + next(b, None) + return zip(a, b) + + +class Metadata(pkg_resources.EmptyProvider): + """Mock object to return metadata as if from an on-disk distribution""" + + def __init__(self, *pairs): + self.metadata = dict(pairs) + + def has_metadata(self, name) -> bool: + return name in self.metadata + + def get_metadata(self, name): + return self.metadata[name] + + def get_metadata_lines(self, name): + return pkg_resources.yield_lines(self.get_metadata(name)) + + +dist_from_fn = pkg_resources.Distribution.from_filename + + +class TestDistro: + def testCollection(self): + # empty path should produce no distributions + ad = pkg_resources.Environment([], platform=None, python=None) + assert list(ad) == [] + assert ad['FooPkg'] == [] + ad.add(dist_from_fn("FooPkg-1.3_1.egg")) + ad.add(dist_from_fn("FooPkg-1.4-py2.4-win32.egg")) + ad.add(dist_from_fn("FooPkg-1.2-py2.4.egg")) + + # Name is in there now + assert ad['FooPkg'] + # But only 1 package + assert list(ad) == ['foopkg'] + + # Distributions sort by version + expected = ['1.4', '1.3-1', '1.2'] + assert [dist.version for dist in ad['FooPkg']] == expected + + # Removing a distribution leaves sequence alone + ad.remove(ad['FooPkg'][1]) + assert [dist.version for dist in ad['FooPkg']] == ['1.4', '1.2'] + + # And inserting adds them in order + ad.add(dist_from_fn("FooPkg-1.9.egg")) + assert [dist.version for dist in ad['FooPkg']] == ['1.9', '1.4', '1.2'] + + ws = WorkingSet([]) + foo12 = dist_from_fn("FooPkg-1.2-py2.4.egg") + foo14 = dist_from_fn("FooPkg-1.4-py2.4-win32.egg") + (req,) = parse_requirements("FooPkg>=1.3") + + # Nominal case: no distros on path, should yield all applicable + assert ad.best_match(req, ws).version == '1.9' + # If a matching distro is already installed, should return only that + ws.add(foo14) + assert ad.best_match(req, ws).version == '1.4' + + # If the first matching distro is unsuitable, it's a version conflict + ws = WorkingSet([]) + ws.add(foo12) + ws.add(foo14) + with pytest.raises(VersionConflict): + ad.best_match(req, ws) + + # If more than one match on the path, the first one takes precedence + ws = WorkingSet([]) + ws.add(foo14) + ws.add(foo12) + ws.add(foo14) + assert ad.best_match(req, ws).version == '1.4' + + def checkFooPkg(self, d): + assert d.project_name == "FooPkg" + assert d.key == "foopkg" + assert d.version == "1.3.post1" + assert d.py_version == "2.4" + assert d.platform == "win32" + assert d.parsed_version == parse_version("1.3-1") + + def testDistroBasics(self): + d = Distribution( + "/some/path", + project_name="FooPkg", + version="1.3-1", + py_version="2.4", + platform="win32", + ) + self.checkFooPkg(d) + + d = Distribution("/some/path") + assert d.py_version == '{}.{}'.format(*sys.version_info) + assert d.platform is None + + def testDistroParse(self): + d = dist_from_fn("FooPkg-1.3.post1-py2.4-win32.egg") + self.checkFooPkg(d) + d = dist_from_fn("FooPkg-1.3.post1-py2.4-win32.egg-info") + self.checkFooPkg(d) + + def testDistroMetadata(self): + d = Distribution( + "/some/path", + project_name="FooPkg", + py_version="2.4", + platform="win32", + metadata=Metadata(('PKG-INFO', "Metadata-Version: 1.0\nVersion: 1.3-1\n")), + ) + self.checkFooPkg(d) + + def distRequires(self, txt): + return Distribution("/foo", metadata=Metadata(('depends.txt', txt))) + + def checkRequires(self, dist, txt, extras=()): + assert list(dist.requires(extras)) == list(parse_requirements(txt)) + + def testDistroDependsSimple(self): + for v in "Twisted>=1.5", "Twisted>=1.5\nZConfig>=2.0": + self.checkRequires(self.distRequires(v), v) + + needs_object_dir = pytest.mark.skipif( + not hasattr(object, '__dir__'), + reason='object.__dir__ necessary for self.__dir__ implementation', + ) + + def test_distribution_dir(self): + d = pkg_resources.Distribution() + dir(d) + + @needs_object_dir + def test_distribution_dir_includes_provider_dir(self): + d = pkg_resources.Distribution() + before = d.__dir__() + assert 'test_attr' not in before + d._provider.test_attr = None + after = d.__dir__() + assert len(after) == len(before) + 1 + assert 'test_attr' in after + + @needs_object_dir + def test_distribution_dir_ignores_provider_dir_leading_underscore(self): + d = pkg_resources.Distribution() + before = d.__dir__() + assert '_test_attr' not in before + d._provider._test_attr = None + after = d.__dir__() + assert len(after) == len(before) + assert '_test_attr' not in after + + def testResolve(self): + ad = pkg_resources.Environment([]) + ws = WorkingSet([]) + # Resolving no requirements -> nothing to install + assert list(ws.resolve([], ad)) == [] + # Request something not in the collection -> DistributionNotFound + with pytest.raises(pkg_resources.DistributionNotFound): + ws.resolve(parse_requirements("Foo"), ad) + + Foo = Distribution.from_filename( + "/foo_dir/Foo-1.2.egg", + metadata=Metadata(('depends.txt', "[bar]\nBaz>=2.0")), + ) + ad.add(Foo) + ad.add(Distribution.from_filename("Foo-0.9.egg")) + + # Request thing(s) that are available -> list to activate + for i in range(3): + targets = list(ws.resolve(parse_requirements("Foo"), ad)) + assert targets == [Foo] + list(map(ws.add, targets)) + with pytest.raises(VersionConflict): + ws.resolve(parse_requirements("Foo==0.9"), ad) + ws = WorkingSet([]) # reset + + # Request an extra that causes an unresolved dependency for "Baz" + with pytest.raises(pkg_resources.DistributionNotFound): + ws.resolve(parse_requirements("Foo[bar]"), ad) + Baz = Distribution.from_filename( + "/foo_dir/Baz-2.1.egg", metadata=Metadata(('depends.txt', "Foo")) + ) + ad.add(Baz) + + # Activation list now includes resolved dependency + assert list(ws.resolve(parse_requirements("Foo[bar]"), ad)) == [Foo, Baz] + # Requests for conflicting versions produce VersionConflict + with pytest.raises(VersionConflict) as vc: + ws.resolve(parse_requirements("Foo==1.2\nFoo!=1.2"), ad) + + msg = 'Foo 0.9 is installed but Foo==1.2 is required' + assert vc.value.report() == msg + + def test_environment_marker_evaluation_negative(self): + """Environment markers are evaluated at resolution time.""" + ad = pkg_resources.Environment([]) + ws = WorkingSet([]) + res = ws.resolve(parse_requirements("Foo;python_version<'2'"), ad) + assert list(res) == [] + + def test_environment_marker_evaluation_positive(self): + ad = pkg_resources.Environment([]) + ws = WorkingSet([]) + Foo = Distribution.from_filename("/foo_dir/Foo-1.2.dist-info") + ad.add(Foo) + res = ws.resolve(parse_requirements("Foo;python_version>='2'"), ad) + assert list(res) == [Foo] + + def test_environment_marker_evaluation_called(self): + """ + If one package foo requires bar without any extras, + markers should pass for bar without extras. + """ + (parent_req,) = parse_requirements("foo") + (req,) = parse_requirements("bar;python_version>='2'") + req_extras = pkg_resources._ReqExtras({req: parent_req.extras}) + assert req_extras.markers_pass(req) + + (parent_req,) = parse_requirements("foo[]") + (req,) = parse_requirements("bar;python_version>='2'") + req_extras = pkg_resources._ReqExtras({req: parent_req.extras}) + assert req_extras.markers_pass(req) + + def test_marker_evaluation_with_extras(self): + """Extras are also evaluated as markers at resolution time.""" + ad = pkg_resources.Environment([]) + ws = WorkingSet([]) + Foo = Distribution.from_filename( + "/foo_dir/Foo-1.2.dist-info", + metadata=Metadata(( + "METADATA", + "Provides-Extra: baz\nRequires-Dist: quux; extra=='baz'", + )), + ) + ad.add(Foo) + assert list(ws.resolve(parse_requirements("Foo"), ad)) == [Foo] + quux = Distribution.from_filename("/foo_dir/quux-1.0.dist-info") + ad.add(quux) + res = list(ws.resolve(parse_requirements("Foo[baz]"), ad)) + assert res == [Foo, quux] + + def test_marker_evaluation_with_extras_normlized(self): + """Extras are also evaluated as markers at resolution time.""" + ad = pkg_resources.Environment([]) + ws = WorkingSet([]) + Foo = Distribution.from_filename( + "/foo_dir/Foo-1.2.dist-info", + metadata=Metadata(( + "METADATA", + "Provides-Extra: baz-lightyear\n" + "Requires-Dist: quux; extra=='baz-lightyear'", + )), + ) + ad.add(Foo) + assert list(ws.resolve(parse_requirements("Foo"), ad)) == [Foo] + quux = Distribution.from_filename("/foo_dir/quux-1.0.dist-info") + ad.add(quux) + res = list(ws.resolve(parse_requirements("Foo[baz-lightyear]"), ad)) + assert res == [Foo, quux] + + def test_marker_evaluation_with_multiple_extras(self): + ad = pkg_resources.Environment([]) + ws = WorkingSet([]) + Foo = Distribution.from_filename( + "/foo_dir/Foo-1.2.dist-info", + metadata=Metadata(( + "METADATA", + "Provides-Extra: baz\n" + "Requires-Dist: quux; extra=='baz'\n" + "Provides-Extra: bar\n" + "Requires-Dist: fred; extra=='bar'\n", + )), + ) + ad.add(Foo) + quux = Distribution.from_filename("/foo_dir/quux-1.0.dist-info") + ad.add(quux) + fred = Distribution.from_filename("/foo_dir/fred-0.1.dist-info") + ad.add(fred) + res = list(ws.resolve(parse_requirements("Foo[baz,bar]"), ad)) + assert sorted(res) == [fred, quux, Foo] + + def test_marker_evaluation_with_extras_loop(self): + ad = pkg_resources.Environment([]) + ws = WorkingSet([]) + a = Distribution.from_filename( + "/foo_dir/a-0.2.dist-info", + metadata=Metadata(("METADATA", "Requires-Dist: c[a]")), + ) + b = Distribution.from_filename( + "/foo_dir/b-0.3.dist-info", + metadata=Metadata(("METADATA", "Requires-Dist: c[b]")), + ) + c = Distribution.from_filename( + "/foo_dir/c-1.0.dist-info", + metadata=Metadata(( + "METADATA", + "Provides-Extra: a\n" + "Requires-Dist: b;extra=='a'\n" + "Provides-Extra: b\n" + "Requires-Dist: foo;extra=='b'", + )), + ) + foo = Distribution.from_filename("/foo_dir/foo-0.1.dist-info") + for dist in (a, b, c, foo): + ad.add(dist) + res = list(ws.resolve(parse_requirements("a"), ad)) + assert res == [a, c, b, foo] + + @pytest.mark.xfail( + sys.version_info[:2] == (3, 12) and sys.version_info.releaselevel != 'final', + reason="https://github.com/python/cpython/issues/103632", + ) + def testDistroDependsOptions(self): + d = self.distRequires( + """ + Twisted>=1.5 + [docgen] + ZConfig>=2.0 + docutils>=0.3 + [fastcgi] + fcgiapp>=0.1""" + ) + self.checkRequires(d, "Twisted>=1.5") + self.checkRequires( + d, "Twisted>=1.5 ZConfig>=2.0 docutils>=0.3".split(), ["docgen"] + ) + self.checkRequires(d, "Twisted>=1.5 fcgiapp>=0.1".split(), ["fastcgi"]) + self.checkRequires( + d, + "Twisted>=1.5 ZConfig>=2.0 docutils>=0.3 fcgiapp>=0.1".split(), + ["docgen", "fastcgi"], + ) + self.checkRequires( + d, + "Twisted>=1.5 fcgiapp>=0.1 ZConfig>=2.0 docutils>=0.3".split(), + ["fastcgi", "docgen"], + ) + with pytest.raises(pkg_resources.UnknownExtra): + d.requires(["foo"]) + + +class TestWorkingSet: + def test_find_conflicting(self): + ws = WorkingSet([]) + Foo = Distribution.from_filename("/foo_dir/Foo-1.2.egg") + ws.add(Foo) + + # create a requirement that conflicts with Foo 1.2 + req = next(parse_requirements("Foo<1.2")) + + with pytest.raises(VersionConflict) as vc: + ws.find(req) + + msg = 'Foo 1.2 is installed but Foo<1.2 is required' + assert vc.value.report() == msg + + def test_resolve_conflicts_with_prior(self): + """ + A ContextualVersionConflict should be raised when a requirement + conflicts with a prior requirement for a different package. + """ + # Create installation where Foo depends on Baz 1.0 and Bar depends on + # Baz 2.0. + ws = WorkingSet([]) + md = Metadata(('depends.txt', "Baz==1.0")) + Foo = Distribution.from_filename("/foo_dir/Foo-1.0.egg", metadata=md) + ws.add(Foo) + md = Metadata(('depends.txt', "Baz==2.0")) + Bar = Distribution.from_filename("/foo_dir/Bar-1.0.egg", metadata=md) + ws.add(Bar) + Baz = Distribution.from_filename("/foo_dir/Baz-1.0.egg") + ws.add(Baz) + Baz = Distribution.from_filename("/foo_dir/Baz-2.0.egg") + ws.add(Baz) + + with pytest.raises(VersionConflict) as vc: + ws.resolve(parse_requirements("Foo\nBar\n")) + + msg = "Baz 1.0 is installed but Baz==2.0 is required by " + msg += repr(set(['Bar'])) + assert vc.value.report() == msg + + +class TestEntryPoints: + def assertfields(self, ep): + assert ep.name == "foo" + assert ep.module_name == "pkg_resources.tests.test_resources" + assert ep.attrs == ("TestEntryPoints",) + assert ep.extras == ("x",) + assert ep.load() is TestEntryPoints + expect = "foo = pkg_resources.tests.test_resources:TestEntryPoints [x]" + assert str(ep) == expect + + def setup_method(self, method): + self.dist = Distribution.from_filename( + "FooPkg-1.2-py2.4.egg", metadata=Metadata(('requires.txt', '[x]')) + ) + + def testBasics(self): + ep = EntryPoint( + "foo", + "pkg_resources.tests.test_resources", + ["TestEntryPoints"], + ["x"], + self.dist, + ) + self.assertfields(ep) + + def testParse(self): + s = "foo = pkg_resources.tests.test_resources:TestEntryPoints [x]" + ep = EntryPoint.parse(s, self.dist) + self.assertfields(ep) + + ep = EntryPoint.parse("bar baz= spammity[PING]") + assert ep.name == "bar baz" + assert ep.module_name == "spammity" + assert ep.attrs == () + assert ep.extras == ("ping",) + + ep = EntryPoint.parse(" fizzly = wocka:foo") + assert ep.name == "fizzly" + assert ep.module_name == "wocka" + assert ep.attrs == ("foo",) + assert ep.extras == () + + # plus in the name + spec = "html+mako = mako.ext.pygmentplugin:MakoHtmlLexer" + ep = EntryPoint.parse(spec) + assert ep.name == 'html+mako' + + reject_specs = "foo", "x=a:b:c", "q=x/na", "fez=pish:tush-z", "x=f[a]>2" + + @pytest.mark.parametrize("reject_spec", reject_specs) + def test_reject_spec(self, reject_spec): + with pytest.raises(ValueError): + EntryPoint.parse(reject_spec) + + def test_printable_name(self): + """ + Allow any printable character in the name. + """ + # Create a name with all printable characters; strip the whitespace. + name = string.printable.strip() + spec = "{name} = module:attr".format(**locals()) + ep = EntryPoint.parse(spec) + assert ep.name == name + + def checkSubMap(self, m): + assert len(m) == len(self.submap_expect) + for key, ep in self.submap_expect.items(): + assert m.get(key).name == ep.name + assert m.get(key).module_name == ep.module_name + assert sorted(m.get(key).attrs) == sorted(ep.attrs) + assert sorted(m.get(key).extras) == sorted(ep.extras) + + submap_expect = dict( + feature1=EntryPoint('feature1', 'somemodule', ['somefunction']), + feature2=EntryPoint( + 'feature2', 'another.module', ['SomeClass'], ['extra1', 'extra2'] + ), + feature3=EntryPoint('feature3', 'this.module', extras=['something']), + ) + submap_str = """ + # define features for blah blah + feature1 = somemodule:somefunction + feature2 = another.module:SomeClass [extra1,extra2] + feature3 = this.module [something] + """ + + def testParseList(self): + self.checkSubMap(EntryPoint.parse_group("xyz", self.submap_str)) + with pytest.raises(ValueError): + EntryPoint.parse_group("x a", "foo=bar") + with pytest.raises(ValueError): + EntryPoint.parse_group("x", ["foo=baz", "foo=bar"]) + + def testParseMap(self): + m = EntryPoint.parse_map({'xyz': self.submap_str}) + self.checkSubMap(m['xyz']) + assert list(m.keys()) == ['xyz'] + m = EntryPoint.parse_map("[xyz]\n" + self.submap_str) + self.checkSubMap(m['xyz']) + assert list(m.keys()) == ['xyz'] + with pytest.raises(ValueError): + EntryPoint.parse_map(["[xyz]", "[xyz]"]) + with pytest.raises(ValueError): + EntryPoint.parse_map(self.submap_str) + + def testDeprecationWarnings(self): + ep = EntryPoint( + "foo", "pkg_resources.tests.test_resources", ["TestEntryPoints"], ["x"] + ) + with pytest.warns(pkg_resources.PkgResourcesDeprecationWarning): + ep.load(require=False) + + +class TestRequirements: + def testBasics(self): + r = Requirement.parse("Twisted>=1.2") + assert str(r) == "Twisted>=1.2" + assert repr(r) == "Requirement.parse('Twisted>=1.2')" + assert r == Requirement("Twisted>=1.2") + assert r == Requirement("twisTed>=1.2") + assert r != Requirement("Twisted>=2.0") + assert r != Requirement("Zope>=1.2") + assert r != Requirement("Zope>=3.0") + assert r != Requirement("Twisted[extras]>=1.2") + + def testOrdering(self): + r1 = Requirement("Twisted==1.2c1,>=1.2") + r2 = Requirement("Twisted>=1.2,==1.2c1") + assert r1 == r2 + assert str(r1) == str(r2) + assert str(r2) == "Twisted==1.2c1,>=1.2" + assert Requirement("Twisted") != Requirement( + "Twisted @ https://localhost/twisted.zip" + ) + + def testBasicContains(self): + r = Requirement("Twisted>=1.2") + foo_dist = Distribution.from_filename("FooPkg-1.3_1.egg") + twist11 = Distribution.from_filename("Twisted-1.1.egg") + twist12 = Distribution.from_filename("Twisted-1.2.egg") + assert parse_version('1.2') in r + assert parse_version('1.1') not in r + assert '1.2' in r + assert '1.1' not in r + assert foo_dist not in r + assert twist11 not in r + assert twist12 in r + + def testOptionsAndHashing(self): + r1 = Requirement.parse("Twisted[foo,bar]>=1.2") + r2 = Requirement.parse("Twisted[bar,FOO]>=1.2") + assert r1 == r2 + assert set(r1.extras) == set(("foo", "bar")) + assert set(r2.extras) == set(("foo", "bar")) + assert hash(r1) == hash(r2) + assert hash(r1) == hash(( + "twisted", + None, + SpecifierSet(">=1.2"), + frozenset(["foo", "bar"]), + None, + )) + assert hash( + Requirement.parse("Twisted @ https://localhost/twisted.zip") + ) == hash(( + "twisted", + "https://localhost/twisted.zip", + SpecifierSet(), + frozenset(), + None, + )) + + def testVersionEquality(self): + r1 = Requirement.parse("foo==0.3a2") + r2 = Requirement.parse("foo!=0.3a4") + d = Distribution.from_filename + + assert d("foo-0.3a4.egg") not in r1 + assert d("foo-0.3a1.egg") not in r1 + assert d("foo-0.3a4.egg") not in r2 + + assert d("foo-0.3a2.egg") in r1 + assert d("foo-0.3a2.egg") in r2 + assert d("foo-0.3a3.egg") in r2 + assert d("foo-0.3a5.egg") in r2 + + def testSetuptoolsProjectName(self): + """ + The setuptools project should implement the setuptools package. + """ + + assert Requirement.parse('setuptools').project_name == 'setuptools' + # setuptools 0.7 and higher means setuptools. + assert Requirement.parse('setuptools == 0.7').project_name == 'setuptools' + assert Requirement.parse('setuptools == 0.7a1').project_name == 'setuptools' + assert Requirement.parse('setuptools >= 0.7').project_name == 'setuptools' + + +class TestParsing: + def testEmptyParse(self): + assert list(parse_requirements('')) == [] + + def testYielding(self): + for inp, out in [ + ([], []), + ('x', ['x']), + ([[]], []), + (' x\n y', ['x', 'y']), + (['x\n\n', 'y'], ['x', 'y']), + ]: + assert list(pkg_resources.yield_lines(inp)) == out + + def testSplitting(self): + sample = """ + x + [Y] + z + + a + [b ] + # foo + c + [ d] + [q] + v + """ + assert list(pkg_resources.split_sections(sample)) == [ + (None, ["x"]), + ("Y", ["z", "a"]), + ("b", ["c"]), + ("d", []), + ("q", ["v"]), + ] + with pytest.raises(ValueError): + list(pkg_resources.split_sections("[foo")) + + def testSafeName(self): + assert safe_name("adns-python") == "adns-python" + assert safe_name("WSGI Utils") == "WSGI-Utils" + assert safe_name("WSGI Utils") == "WSGI-Utils" + assert safe_name("Money$$$Maker") == "Money-Maker" + assert safe_name("peak.web") != "peak-web" + + def testSafeVersion(self): + assert safe_version("1.2-1") == "1.2.post1" + assert safe_version("1.2 alpha") == "1.2.alpha" + assert safe_version("2.3.4 20050521") == "2.3.4.20050521" + assert safe_version("Money$$$Maker") == "Money-Maker" + assert safe_version("peak.web") == "peak.web" + + def testSimpleRequirements(self): + assert list(parse_requirements('Twis-Ted>=1.2-1')) == [ + Requirement('Twis-Ted>=1.2-1') + ] + assert list(parse_requirements('Twisted >=1.2, \\ # more\n<2.0')) == [ + Requirement('Twisted>=1.2,<2.0') + ] + assert Requirement.parse("FooBar==1.99a3") == Requirement("FooBar==1.99a3") + with pytest.raises(ValueError): + Requirement.parse(">=2.3") + with pytest.raises(ValueError): + Requirement.parse("x\\") + with pytest.raises(ValueError): + Requirement.parse("x==2 q") + with pytest.raises(ValueError): + Requirement.parse("X==1\nY==2") + with pytest.raises(ValueError): + Requirement.parse("#") + + def test_requirements_with_markers(self): + assert Requirement.parse("foobar;os_name=='a'") == Requirement.parse( + "foobar;os_name=='a'" + ) + assert Requirement.parse( + "name==1.1;python_version=='2.7'" + ) != Requirement.parse("name==1.1;python_version=='3.6'") + assert Requirement.parse( + "name==1.0;python_version=='2.7'" + ) != Requirement.parse("name==1.2;python_version=='2.7'") + assert Requirement.parse( + "name[foo]==1.0;python_version=='3.6'" + ) != Requirement.parse("name[foo,bar]==1.0;python_version=='3.6'") + + def test_local_version(self): + (req,) = parse_requirements('foo==1.0+org1') + + def test_spaces_between_multiple_versions(self): + (req,) = parse_requirements('foo>=1.0, <3') + (req,) = parse_requirements('foo >= 1.0, < 3') + + @pytest.mark.parametrize( + ['lower', 'upper'], + [ + ('1.2-rc1', '1.2rc1'), + ('0.4', '0.4.0'), + ('0.4.0.0', '0.4.0'), + ('0.4.0-0', '0.4-0'), + ('0post1', '0.0post1'), + ('0pre1', '0.0c1'), + ('0.0.0preview1', '0c1'), + ('0.0c1', '0-rc1'), + ('1.2a1', '1.2.a.1'), + ('1.2.a', '1.2a'), + ], + ) + def testVersionEquality(self, lower, upper): + assert parse_version(lower) == parse_version(upper) + + torture = """ + 0.80.1-3 0.80.1-2 0.80.1-1 0.79.9999+0.80.0pre4-1 + 0.79.9999+0.80.0pre2-3 0.79.9999+0.80.0pre2-2 + 0.77.2-1 0.77.1-1 0.77.0-1 + """ + + @pytest.mark.parametrize( + ['lower', 'upper'], + [ + ('2.1', '2.1.1'), + ('2a1', '2b0'), + ('2a1', '2.1'), + ('2.3a1', '2.3'), + ('2.1-1', '2.1-2'), + ('2.1-1', '2.1.1'), + ('2.1', '2.1post4'), + ('2.1a0-20040501', '2.1'), + ('1.1', '02.1'), + ('3.2', '3.2.post0'), + ('3.2post1', '3.2post2'), + ('0.4', '4.0'), + ('0.0.4', '0.4.0'), + ('0post1', '0.4post1'), + ('2.1.0-rc1', '2.1.0'), + ('2.1dev', '2.1a0'), + ] + + list(pairwise(reversed(torture.split()))), + ) + def testVersionOrdering(self, lower, upper): + assert parse_version(lower) < parse_version(upper) + + def testVersionHashable(self): + """ + Ensure that our versions stay hashable even though we've subclassed + them and added some shim code to them. + """ + assert hash(parse_version("1.0")) == hash(parse_version("1.0")) + + +class TestNamespaces: + ns_str = "__import__('pkg_resources').declare_namespace(__name__)\n" + + @pytest.fixture + def symlinked_tmpdir(self, tmpdir): + """ + Where available, return the tempdir as a symlink, + which as revealed in #231 is more fragile than + a natural tempdir. + """ + if not hasattr(os, 'symlink'): + yield str(tmpdir) + return + + link_name = str(tmpdir) + '-linked' + os.symlink(str(tmpdir), link_name) + try: + yield type(tmpdir)(link_name) + finally: + os.unlink(link_name) + + @pytest.fixture(autouse=True) + def patched_path(self, tmpdir): + """ + Patch sys.path to include the 'site-pkgs' dir. Also + restore pkg_resources._namespace_packages to its + former state. + """ + saved_ns_pkgs = pkg_resources._namespace_packages.copy() + saved_sys_path = sys.path[:] + site_pkgs = tmpdir.mkdir('site-pkgs') + sys.path.append(str(site_pkgs)) + try: + yield + finally: + pkg_resources._namespace_packages = saved_ns_pkgs + sys.path = saved_sys_path + + issue591 = pytest.mark.xfail(platform.system() == 'Windows', reason="#591") + + @issue591 + def test_two_levels_deep(self, symlinked_tmpdir): + """ + Test nested namespace packages + Create namespace packages in the following tree : + site-packages-1/pkg1/pkg2 + site-packages-2/pkg1/pkg2 + Check both are in the _namespace_packages dict and that their __path__ + is correct + """ + real_tmpdir = symlinked_tmpdir.realpath() + tmpdir = symlinked_tmpdir + sys.path.append(str(tmpdir / 'site-pkgs2')) + site_dirs = tmpdir / 'site-pkgs', tmpdir / 'site-pkgs2' + for site in site_dirs: + pkg1 = site / 'pkg1' + pkg2 = pkg1 / 'pkg2' + pkg2.ensure_dir() + (pkg1 / '__init__.py').write_text(self.ns_str, encoding='utf-8') + (pkg2 / '__init__.py').write_text(self.ns_str, encoding='utf-8') + with pytest.warns(DeprecationWarning, match="pkg_resources.declare_namespace"): + import pkg1 # pyright: ignore[reportMissingImports] # Temporary package for test + assert "pkg1" in pkg_resources._namespace_packages + # attempt to import pkg2 from site-pkgs2 + with pytest.warns(DeprecationWarning, match="pkg_resources.declare_namespace"): + import pkg1.pkg2 # pyright: ignore[reportMissingImports] # Temporary package for test + # check the _namespace_packages dict + assert "pkg1.pkg2" in pkg_resources._namespace_packages + assert pkg_resources._namespace_packages["pkg1"] == ["pkg1.pkg2"] + # check the __path__ attribute contains both paths + expected = [ + str(real_tmpdir / "site-pkgs" / "pkg1" / "pkg2"), + str(real_tmpdir / "site-pkgs2" / "pkg1" / "pkg2"), + ] + assert pkg1.pkg2.__path__ == expected + + @issue591 + def test_path_order(self, symlinked_tmpdir): + """ + Test that if multiple versions of the same namespace package subpackage + are on different sys.path entries, that only the one earliest on + sys.path is imported, and that the namespace package's __path__ is in + the correct order. + + Regression test for https://github.com/pypa/setuptools/issues/207 + """ + + tmpdir = symlinked_tmpdir + site_dirs = ( + tmpdir / "site-pkgs", + tmpdir / "site-pkgs2", + tmpdir / "site-pkgs3", + ) + + vers_str = "__version__ = %r" + + for number, site in enumerate(site_dirs, 1): + if number > 1: + sys.path.append(str(site)) + nspkg = site / 'nspkg' + subpkg = nspkg / 'subpkg' + subpkg.ensure_dir() + (nspkg / '__init__.py').write_text(self.ns_str, encoding='utf-8') + (subpkg / '__init__.py').write_text(vers_str % number, encoding='utf-8') + + with pytest.warns(DeprecationWarning, match="pkg_resources.declare_namespace"): + import nspkg # pyright: ignore[reportMissingImports] # Temporary package for test + import nspkg.subpkg # pyright: ignore[reportMissingImports] # Temporary package for test + expected = [str(site.realpath() / 'nspkg') for site in site_dirs] + assert nspkg.__path__ == expected + assert nspkg.subpkg.__version__ == 1 diff --git a/infer_4_30_0/lib/python3.10/site-packages/pybind11/include/pybind11/attr.h b/infer_4_30_0/lib/python3.10/site-packages/pybind11/include/pybind11/attr.h new file mode 100644 index 0000000000000000000000000000000000000000..1044db94d906ac5fcf6faab6ac7668187314598f --- /dev/null +++ b/infer_4_30_0/lib/python3.10/site-packages/pybind11/include/pybind11/attr.h @@ -0,0 +1,690 @@ +/* + pybind11/attr.h: Infrastructure for processing custom + type and function attributes + + Copyright (c) 2016 Wenzel Jakob + + All rights reserved. Use of this source code is governed by a + BSD-style license that can be found in the LICENSE file. +*/ + +#pragma once + +#include "detail/common.h" +#include "cast.h" + +#include + +PYBIND11_NAMESPACE_BEGIN(PYBIND11_NAMESPACE) + +/// \addtogroup annotations +/// @{ + +/// Annotation for methods +struct is_method { + handle class_; + explicit is_method(const handle &c) : class_(c) {} +}; + +/// Annotation for setters +struct is_setter {}; + +/// Annotation for operators +struct is_operator {}; + +/// Annotation for classes that cannot be subclassed +struct is_final {}; + +/// Annotation for parent scope +struct scope { + handle value; + explicit scope(const handle &s) : value(s) {} +}; + +/// Annotation for documentation +struct doc { + const char *value; + explicit doc(const char *value) : value(value) {} +}; + +/// Annotation for function names +struct name { + const char *value; + explicit name(const char *value) : value(value) {} +}; + +/// Annotation indicating that a function is an overload associated with a given "sibling" +struct sibling { + handle value; + explicit sibling(const handle &value) : value(value.ptr()) {} +}; + +/// Annotation indicating that a class derives from another given type +template +struct base { + + PYBIND11_DEPRECATED( + "base() was deprecated in favor of specifying 'T' as a template argument to class_") + base() = default; +}; + +/// Keep patient alive while nurse lives +template +struct keep_alive {}; + +/// Annotation indicating that a class is involved in a multiple inheritance relationship +struct multiple_inheritance {}; + +/// Annotation which enables dynamic attributes, i.e. adds `__dict__` to a class +struct dynamic_attr {}; + +/// Annotation which enables the buffer protocol for a type +struct buffer_protocol {}; + +/// Annotation which requests that a special metaclass is created for a type +struct metaclass { + handle value; + + PYBIND11_DEPRECATED("py::metaclass() is no longer required. It's turned on by default now.") + metaclass() = default; + + /// Override pybind11's default metaclass + explicit metaclass(handle value) : value(value) {} +}; + +/// Specifies a custom callback with signature `void (PyHeapTypeObject*)` that +/// may be used to customize the Python type. +/// +/// The callback is invoked immediately before `PyType_Ready`. +/// +/// Note: This is an advanced interface, and uses of it may require changes to +/// work with later versions of pybind11. You may wish to consult the +/// implementation of `make_new_python_type` in `detail/classes.h` to understand +/// the context in which the callback will be run. +struct custom_type_setup { + using callback = std::function; + + explicit custom_type_setup(callback value) : value(std::move(value)) {} + + callback value; +}; + +/// Annotation that marks a class as local to the module: +struct module_local { + const bool value; + constexpr explicit module_local(bool v = true) : value(v) {} +}; + +/// Annotation to mark enums as an arithmetic type +struct arithmetic {}; + +/// Mark a function for addition at the beginning of the existing overload chain instead of the end +struct prepend {}; + +/** \rst + A call policy which places one or more guard variables (``Ts...``) around the function call. + + For example, this definition: + + .. code-block:: cpp + + m.def("foo", foo, py::call_guard()); + + is equivalent to the following pseudocode: + + .. code-block:: cpp + + m.def("foo", [](args...) { + T scope_guard; + return foo(args...); // forwarded arguments + }); + \endrst */ +template +struct call_guard; + +template <> +struct call_guard<> { + using type = detail::void_type; +}; + +template +struct call_guard { + static_assert(std::is_default_constructible::value, + "The guard type must be default constructible"); + + using type = T; +}; + +template +struct call_guard { + struct type { + T guard{}; // Compose multiple guard types with left-to-right default-constructor order + typename call_guard::type next{}; + }; +}; + +/// @} annotations + +PYBIND11_NAMESPACE_BEGIN(detail) +/* Forward declarations */ +enum op_id : int; +enum op_type : int; +struct undefined_t; +template +struct op_; +void keep_alive_impl(size_t Nurse, size_t Patient, function_call &call, handle ret); + +/// Internal data structure which holds metadata about a keyword argument +struct argument_record { + const char *name; ///< Argument name + const char *descr; ///< Human-readable version of the argument value + handle value; ///< Associated Python object + bool convert : 1; ///< True if the argument is allowed to convert when loading + bool none : 1; ///< True if None is allowed when loading + + argument_record(const char *name, const char *descr, handle value, bool convert, bool none) + : name(name), descr(descr), value(value), convert(convert), none(none) {} +}; + +/// Internal data structure which holds metadata about a bound function (signature, overloads, +/// etc.) +struct function_record { + function_record() + : is_constructor(false), is_new_style_constructor(false), is_stateless(false), + is_operator(false), is_method(false), is_setter(false), has_args(false), + has_kwargs(false), prepend(false) {} + + /// Function name + char *name = nullptr; /* why no C++ strings? They generate heavier code.. */ + + // User-specified documentation string + char *doc = nullptr; + + /// Human-readable version of the function signature + char *signature = nullptr; + + /// List of registered keyword arguments + std::vector args; + + /// Pointer to lambda function which converts arguments and performs the actual call + handle (*impl)(function_call &) = nullptr; + + /// Storage for the wrapped function pointer and captured data, if any + void *data[3] = {}; + + /// Pointer to custom destructor for 'data' (if needed) + void (*free_data)(function_record *ptr) = nullptr; + + /// Return value policy associated with this function + return_value_policy policy = return_value_policy::automatic; + + /// True if name == '__init__' + bool is_constructor : 1; + + /// True if this is a new-style `__init__` defined in `detail/init.h` + bool is_new_style_constructor : 1; + + /// True if this is a stateless function pointer + bool is_stateless : 1; + + /// True if this is an operator (__add__), etc. + bool is_operator : 1; + + /// True if this is a method + bool is_method : 1; + + /// True if this is a setter + bool is_setter : 1; + + /// True if the function has a '*args' argument + bool has_args : 1; + + /// True if the function has a '**kwargs' argument + bool has_kwargs : 1; + + /// True if this function is to be inserted at the beginning of the overload resolution chain + bool prepend : 1; + + /// Number of arguments (including py::args and/or py::kwargs, if present) + std::uint16_t nargs; + + /// Number of leading positional arguments, which are terminated by a py::args or py::kwargs + /// argument or by a py::kw_only annotation. + std::uint16_t nargs_pos = 0; + + /// Number of leading arguments (counted in `nargs`) that are positional-only + std::uint16_t nargs_pos_only = 0; + + /// Python method object + PyMethodDef *def = nullptr; + + /// Python handle to the parent scope (a class or a module) + handle scope; + + /// Python handle to the sibling function representing an overload chain + handle sibling; + + /// Pointer to next overload + function_record *next = nullptr; +}; + +/// Special data structure which (temporarily) holds metadata about a bound class +struct type_record { + PYBIND11_NOINLINE type_record() + : multiple_inheritance(false), dynamic_attr(false), buffer_protocol(false), + default_holder(true), module_local(false), is_final(false) {} + + /// Handle to the parent scope + handle scope; + + /// Name of the class + const char *name = nullptr; + + // Pointer to RTTI type_info data structure + const std::type_info *type = nullptr; + + /// How large is the underlying C++ type? + size_t type_size = 0; + + /// What is the alignment of the underlying C++ type? + size_t type_align = 0; + + /// How large is the type's holder? + size_t holder_size = 0; + + /// The global operator new can be overridden with a class-specific variant + void *(*operator_new)(size_t) = nullptr; + + /// Function pointer to class_<..>::init_instance + void (*init_instance)(instance *, const void *) = nullptr; + + /// Function pointer to class_<..>::dealloc + void (*dealloc)(detail::value_and_holder &) = nullptr; + + /// List of base classes of the newly created type + list bases; + + /// Optional docstring + const char *doc = nullptr; + + /// Custom metaclass (optional) + handle metaclass; + + /// Custom type setup. + custom_type_setup::callback custom_type_setup_callback; + + /// Multiple inheritance marker + bool multiple_inheritance : 1; + + /// Does the class manage a __dict__? + bool dynamic_attr : 1; + + /// Does the class implement the buffer protocol? + bool buffer_protocol : 1; + + /// Is the default (unique_ptr) holder type used? + bool default_holder : 1; + + /// Is the class definition local to the module shared object? + bool module_local : 1; + + /// Is the class inheritable from python classes? + bool is_final : 1; + + PYBIND11_NOINLINE void add_base(const std::type_info &base, void *(*caster)(void *) ) { + auto *base_info = detail::get_type_info(base, false); + if (!base_info) { + std::string tname(base.name()); + detail::clean_type_id(tname); + pybind11_fail("generic_type: type \"" + std::string(name) + + "\" referenced unknown base type \"" + tname + "\""); + } + + if (default_holder != base_info->default_holder) { + std::string tname(base.name()); + detail::clean_type_id(tname); + pybind11_fail("generic_type: type \"" + std::string(name) + "\" " + + (default_holder ? "does not have" : "has") + + " a non-default holder type while its base \"" + tname + "\" " + + (base_info->default_holder ? "does not" : "does")); + } + + bases.append((PyObject *) base_info->type); + +#if PY_VERSION_HEX < 0x030B0000 + dynamic_attr |= base_info->type->tp_dictoffset != 0; +#else + dynamic_attr |= (base_info->type->tp_flags & Py_TPFLAGS_MANAGED_DICT) != 0; +#endif + + if (caster) { + base_info->implicit_casts.emplace_back(type, caster); + } + } +}; + +inline function_call::function_call(const function_record &f, handle p) : func(f), parent(p) { + args.reserve(f.nargs); + args_convert.reserve(f.nargs); +} + +/// Tag for a new-style `__init__` defined in `detail/init.h` +struct is_new_style_constructor {}; + +/** + * Partial template specializations to process custom attributes provided to + * cpp_function_ and class_. These are either used to initialize the respective + * fields in the type_record and function_record data structures or executed at + * runtime to deal with custom call policies (e.g. keep_alive). + */ +template +struct process_attribute; + +template +struct process_attribute_default { + /// Default implementation: do nothing + static void init(const T &, function_record *) {} + static void init(const T &, type_record *) {} + static void precall(function_call &) {} + static void postcall(function_call &, handle) {} +}; + +/// Process an attribute specifying the function's name +template <> +struct process_attribute : process_attribute_default { + static void init(const name &n, function_record *r) { r->name = const_cast(n.value); } +}; + +/// Process an attribute specifying the function's docstring +template <> +struct process_attribute : process_attribute_default { + static void init(const doc &n, function_record *r) { r->doc = const_cast(n.value); } +}; + +/// Process an attribute specifying the function's docstring (provided as a C-style string) +template <> +struct process_attribute : process_attribute_default { + static void init(const char *d, function_record *r) { r->doc = const_cast(d); } + static void init(const char *d, type_record *r) { r->doc = d; } +}; +template <> +struct process_attribute : process_attribute {}; + +/// Process an attribute indicating the function's return value policy +template <> +struct process_attribute : process_attribute_default { + static void init(const return_value_policy &p, function_record *r) { r->policy = p; } +}; + +/// Process an attribute which indicates that this is an overloaded function associated with a +/// given sibling +template <> +struct process_attribute : process_attribute_default { + static void init(const sibling &s, function_record *r) { r->sibling = s.value; } +}; + +/// Process an attribute which indicates that this function is a method +template <> +struct process_attribute : process_attribute_default { + static void init(const is_method &s, function_record *r) { + r->is_method = true; + r->scope = s.class_; + } +}; + +/// Process an attribute which indicates that this function is a setter +template <> +struct process_attribute : process_attribute_default { + static void init(const is_setter &, function_record *r) { r->is_setter = true; } +}; + +/// Process an attribute which indicates the parent scope of a method +template <> +struct process_attribute : process_attribute_default { + static void init(const scope &s, function_record *r) { r->scope = s.value; } +}; + +/// Process an attribute which indicates that this function is an operator +template <> +struct process_attribute : process_attribute_default { + static void init(const is_operator &, function_record *r) { r->is_operator = true; } +}; + +template <> +struct process_attribute + : process_attribute_default { + static void init(const is_new_style_constructor &, function_record *r) { + r->is_new_style_constructor = true; + } +}; + +inline void check_kw_only_arg(const arg &a, function_record *r) { + if (r->args.size() > r->nargs_pos && (!a.name || a.name[0] == '\0')) { + pybind11_fail("arg(): cannot specify an unnamed argument after a kw_only() annotation or " + "args() argument"); + } +} + +inline void append_self_arg_if_needed(function_record *r) { + if (r->is_method && r->args.empty()) { + r->args.emplace_back("self", nullptr, handle(), /*convert=*/true, /*none=*/false); + } +} + +/// Process a keyword argument attribute (*without* a default value) +template <> +struct process_attribute : process_attribute_default { + static void init(const arg &a, function_record *r) { + append_self_arg_if_needed(r); + r->args.emplace_back(a.name, nullptr, handle(), !a.flag_noconvert, a.flag_none); + + check_kw_only_arg(a, r); + } +}; + +/// Process a keyword argument attribute (*with* a default value) +template <> +struct process_attribute : process_attribute_default { + static void init(const arg_v &a, function_record *r) { + if (r->is_method && r->args.empty()) { + r->args.emplace_back( + "self", /*descr=*/nullptr, /*parent=*/handle(), /*convert=*/true, /*none=*/false); + } + + if (!a.value) { +#if defined(PYBIND11_DETAILED_ERROR_MESSAGES) + std::string descr("'"); + if (a.name) { + descr += std::string(a.name) + ": "; + } + descr += a.type + "'"; + if (r->is_method) { + if (r->name) { + descr += " in method '" + (std::string) str(r->scope) + "." + + (std::string) r->name + "'"; + } else { + descr += " in method of '" + (std::string) str(r->scope) + "'"; + } + } else if (r->name) { + descr += " in function '" + (std::string) r->name + "'"; + } + pybind11_fail("arg(): could not convert default argument " + descr + + " into a Python object (type not registered yet?)"); +#else + pybind11_fail("arg(): could not convert default argument " + "into a Python object (type not registered yet?). " + "#define PYBIND11_DETAILED_ERROR_MESSAGES or compile in debug mode for " + "more information."); +#endif + } + r->args.emplace_back(a.name, a.descr, a.value.inc_ref(), !a.flag_noconvert, a.flag_none); + + check_kw_only_arg(a, r); + } +}; + +/// Process a keyword-only-arguments-follow pseudo argument +template <> +struct process_attribute : process_attribute_default { + static void init(const kw_only &, function_record *r) { + append_self_arg_if_needed(r); + if (r->has_args && r->nargs_pos != static_cast(r->args.size())) { + pybind11_fail("Mismatched args() and kw_only(): they must occur at the same relative " + "argument location (or omit kw_only() entirely)"); + } + r->nargs_pos = static_cast(r->args.size()); + } +}; + +/// Process a positional-only-argument maker +template <> +struct process_attribute : process_attribute_default { + static void init(const pos_only &, function_record *r) { + append_self_arg_if_needed(r); + r->nargs_pos_only = static_cast(r->args.size()); + if (r->nargs_pos_only > r->nargs_pos) { + pybind11_fail("pos_only(): cannot follow a py::args() argument"); + } + // It also can't follow a kw_only, but a static_assert in pybind11.h checks that + } +}; + +/// Process a parent class attribute. Single inheritance only (class_ itself already guarantees +/// that) +template +struct process_attribute::value>> + : process_attribute_default { + static void init(const handle &h, type_record *r) { r->bases.append(h); } +}; + +/// Process a parent class attribute (deprecated, does not support multiple inheritance) +template +struct process_attribute> : process_attribute_default> { + static void init(const base &, type_record *r) { r->add_base(typeid(T), nullptr); } +}; + +/// Process a multiple inheritance attribute +template <> +struct process_attribute : process_attribute_default { + static void init(const multiple_inheritance &, type_record *r) { + r->multiple_inheritance = true; + } +}; + +template <> +struct process_attribute : process_attribute_default { + static void init(const dynamic_attr &, type_record *r) { r->dynamic_attr = true; } +}; + +template <> +struct process_attribute { + static void init(const custom_type_setup &value, type_record *r) { + r->custom_type_setup_callback = value.value; + } +}; + +template <> +struct process_attribute : process_attribute_default { + static void init(const is_final &, type_record *r) { r->is_final = true; } +}; + +template <> +struct process_attribute : process_attribute_default { + static void init(const buffer_protocol &, type_record *r) { r->buffer_protocol = true; } +}; + +template <> +struct process_attribute : process_attribute_default { + static void init(const metaclass &m, type_record *r) { r->metaclass = m.value; } +}; + +template <> +struct process_attribute : process_attribute_default { + static void init(const module_local &l, type_record *r) { r->module_local = l.value; } +}; + +/// Process a 'prepend' attribute, putting this at the beginning of the overload chain +template <> +struct process_attribute : process_attribute_default { + static void init(const prepend &, function_record *r) { r->prepend = true; } +}; + +/// Process an 'arithmetic' attribute for enums (does nothing here) +template <> +struct process_attribute : process_attribute_default {}; + +template +struct process_attribute> : process_attribute_default> {}; + +/** + * Process a keep_alive call policy -- invokes keep_alive_impl during the + * pre-call handler if both Nurse, Patient != 0 and use the post-call handler + * otherwise + */ +template +struct process_attribute> + : public process_attribute_default> { + template = 0> + static void precall(function_call &call) { + keep_alive_impl(Nurse, Patient, call, handle()); + } + template = 0> + static void postcall(function_call &, handle) {} + template = 0> + static void precall(function_call &) {} + template = 0> + static void postcall(function_call &call, handle ret) { + keep_alive_impl(Nurse, Patient, call, ret); + } +}; + +/// Recursively iterate over variadic template arguments +template +struct process_attributes { + static void init(const Args &...args, function_record *r) { + PYBIND11_WORKAROUND_INCORRECT_MSVC_C4100(r); + PYBIND11_WORKAROUND_INCORRECT_GCC_UNUSED_BUT_SET_PARAMETER(r); + using expander = int[]; + (void) expander{ + 0, ((void) process_attribute::type>::init(args, r), 0)...}; + } + static void init(const Args &...args, type_record *r) { + PYBIND11_WORKAROUND_INCORRECT_MSVC_C4100(r); + PYBIND11_WORKAROUND_INCORRECT_GCC_UNUSED_BUT_SET_PARAMETER(r); + using expander = int[]; + (void) expander{0, + (process_attribute::type>::init(args, r), 0)...}; + } + static void precall(function_call &call) { + PYBIND11_WORKAROUND_INCORRECT_MSVC_C4100(call); + using expander = int[]; + (void) expander{0, + (process_attribute::type>::precall(call), 0)...}; + } + static void postcall(function_call &call, handle fn_ret) { + PYBIND11_WORKAROUND_INCORRECT_MSVC_C4100(call, fn_ret); + PYBIND11_WORKAROUND_INCORRECT_GCC_UNUSED_BUT_SET_PARAMETER(fn_ret); + using expander = int[]; + (void) expander{ + 0, (process_attribute::type>::postcall(call, fn_ret), 0)...}; + } +}; + +template +using is_call_guard = is_instantiation; + +/// Extract the ``type`` from the first `call_guard` in `Extras...` (or `void_type` if none found) +template +using extract_guard_t = typename exactly_one_t, Extra...>::type; + +/// Check the number of named arguments at compile time +template ::value...), + size_t self = constexpr_sum(std::is_same::value...)> +constexpr bool expected_num_args(size_t nargs, bool has_args, bool has_kwargs) { + PYBIND11_WORKAROUND_INCORRECT_MSVC_C4100(nargs, has_args, has_kwargs); + return named == 0 || (self + named + size_t(has_args) + size_t(has_kwargs)) == nargs; +} + +PYBIND11_NAMESPACE_END(detail) +PYBIND11_NAMESPACE_END(PYBIND11_NAMESPACE) diff --git a/infer_4_30_0/lib/python3.10/site-packages/pybind11/include/pybind11/chrono.h b/infer_4_30_0/lib/python3.10/site-packages/pybind11/include/pybind11/chrono.h new file mode 100644 index 0000000000000000000000000000000000000000..167ea0e3d1057c54a469c8ecd656d49eec495fe7 --- /dev/null +++ b/infer_4_30_0/lib/python3.10/site-packages/pybind11/include/pybind11/chrono.h @@ -0,0 +1,225 @@ +/* + pybind11/chrono.h: Transparent conversion between std::chrono and python's datetime + + Copyright (c) 2016 Trent Houliston and + Wenzel Jakob + + All rights reserved. Use of this source code is governed by a + BSD-style license that can be found in the LICENSE file. +*/ + +#pragma once + +#include "pybind11.h" + +#include +#include +#include +#include +#include + +PYBIND11_NAMESPACE_BEGIN(PYBIND11_NAMESPACE) +PYBIND11_NAMESPACE_BEGIN(detail) + +template +class duration_caster { +public: + using rep = typename type::rep; + using period = typename type::period; + + // signed 25 bits required by the standard. + using days = std::chrono::duration>; + + bool load(handle src, bool) { + using namespace std::chrono; + + // Lazy initialise the PyDateTime import + if (!PyDateTimeAPI) { + PyDateTime_IMPORT; + } + + if (!src) { + return false; + } + // If invoked with datetime.delta object + if (PyDelta_Check(src.ptr())) { + value = type(duration_cast>( + days(PyDateTime_DELTA_GET_DAYS(src.ptr())) + + seconds(PyDateTime_DELTA_GET_SECONDS(src.ptr())) + + microseconds(PyDateTime_DELTA_GET_MICROSECONDS(src.ptr())))); + return true; + } + // If invoked with a float we assume it is seconds and convert + if (PyFloat_Check(src.ptr())) { + value = type(duration_cast>( + duration(PyFloat_AsDouble(src.ptr())))); + return true; + } + return false; + } + + // If this is a duration just return it back + static const std::chrono::duration & + get_duration(const std::chrono::duration &src) { + return src; + } + + // If this is a time_point get the time_since_epoch + template + static std::chrono::duration + get_duration(const std::chrono::time_point> &src) { + return src.time_since_epoch(); + } + + static handle cast(const type &src, return_value_policy /* policy */, handle /* parent */) { + using namespace std::chrono; + + // Use overloaded function to get our duration from our source + // Works out if it is a duration or time_point and get the duration + auto d = get_duration(src); + + // Lazy initialise the PyDateTime import + if (!PyDateTimeAPI) { + PyDateTime_IMPORT; + } + + // Declare these special duration types so the conversions happen with the correct + // primitive types (int) + using dd_t = duration>; + using ss_t = duration>; + using us_t = duration; + + auto dd = duration_cast(d); + auto subd = d - dd; + auto ss = duration_cast(subd); + auto us = duration_cast(subd - ss); + return PyDelta_FromDSU(dd.count(), ss.count(), us.count()); + } + + PYBIND11_TYPE_CASTER(type, const_name("datetime.timedelta")); +}; + +inline std::tm *localtime_thread_safe(const std::time_t *time, std::tm *buf) { +#if (defined(__STDC_LIB_EXT1__) && defined(__STDC_WANT_LIB_EXT1__)) || defined(_MSC_VER) + if (localtime_s(buf, time)) + return nullptr; + return buf; +#else + static std::mutex mtx; + std::lock_guard lock(mtx); + std::tm *tm_ptr = std::localtime(time); + if (tm_ptr != nullptr) { + *buf = *tm_ptr; + } + return tm_ptr; +#endif +} + +// This is for casting times on the system clock into datetime.datetime instances +template +class type_caster> { +public: + using type = std::chrono::time_point; + bool load(handle src, bool) { + using namespace std::chrono; + + // Lazy initialise the PyDateTime import + if (!PyDateTimeAPI) { + PyDateTime_IMPORT; + } + + if (!src) { + return false; + } + + std::tm cal; + microseconds msecs; + + if (PyDateTime_Check(src.ptr())) { + cal.tm_sec = PyDateTime_DATE_GET_SECOND(src.ptr()); + cal.tm_min = PyDateTime_DATE_GET_MINUTE(src.ptr()); + cal.tm_hour = PyDateTime_DATE_GET_HOUR(src.ptr()); + cal.tm_mday = PyDateTime_GET_DAY(src.ptr()); + cal.tm_mon = PyDateTime_GET_MONTH(src.ptr()) - 1; + cal.tm_year = PyDateTime_GET_YEAR(src.ptr()) - 1900; + cal.tm_isdst = -1; + msecs = microseconds(PyDateTime_DATE_GET_MICROSECOND(src.ptr())); + } else if (PyDate_Check(src.ptr())) { + cal.tm_sec = 0; + cal.tm_min = 0; + cal.tm_hour = 0; + cal.tm_mday = PyDateTime_GET_DAY(src.ptr()); + cal.tm_mon = PyDateTime_GET_MONTH(src.ptr()) - 1; + cal.tm_year = PyDateTime_GET_YEAR(src.ptr()) - 1900; + cal.tm_isdst = -1; + msecs = microseconds(0); + } else if (PyTime_Check(src.ptr())) { + cal.tm_sec = PyDateTime_TIME_GET_SECOND(src.ptr()); + cal.tm_min = PyDateTime_TIME_GET_MINUTE(src.ptr()); + cal.tm_hour = PyDateTime_TIME_GET_HOUR(src.ptr()); + cal.tm_mday = 1; // This date (day, month, year) = (1, 0, 70) + cal.tm_mon = 0; // represents 1-Jan-1970, which is the first + cal.tm_year = 70; // earliest available date for Python's datetime + cal.tm_isdst = -1; + msecs = microseconds(PyDateTime_TIME_GET_MICROSECOND(src.ptr())); + } else { + return false; + } + + value = time_point_cast(system_clock::from_time_t(std::mktime(&cal)) + msecs); + return true; + } + + static handle cast(const std::chrono::time_point &src, + return_value_policy /* policy */, + handle /* parent */) { + using namespace std::chrono; + + // Lazy initialise the PyDateTime import + if (!PyDateTimeAPI) { + PyDateTime_IMPORT; + } + + // Get out microseconds, and make sure they are positive, to avoid bug in eastern + // hemisphere time zones (cfr. https://github.com/pybind/pybind11/issues/2417) + using us_t = duration; + auto us = duration_cast(src.time_since_epoch() % seconds(1)); + if (us.count() < 0) { + us += seconds(1); + } + + // Subtract microseconds BEFORE `system_clock::to_time_t`, because: + // > If std::time_t has lower precision, it is implementation-defined whether the value is + // rounded or truncated. (https://en.cppreference.com/w/cpp/chrono/system_clock/to_time_t) + std::time_t tt + = system_clock::to_time_t(time_point_cast(src - us)); + + std::tm localtime; + std::tm *localtime_ptr = localtime_thread_safe(&tt, &localtime); + if (!localtime_ptr) { + throw cast_error("Unable to represent system_clock in local time"); + } + return PyDateTime_FromDateAndTime(localtime.tm_year + 1900, + localtime.tm_mon + 1, + localtime.tm_mday, + localtime.tm_hour, + localtime.tm_min, + localtime.tm_sec, + us.count()); + } + PYBIND11_TYPE_CASTER(type, const_name("datetime.datetime")); +}; + +// Other clocks that are not the system clock are not measured as datetime.datetime objects +// since they are not measured on calendar time. So instead we just make them timedeltas +// Or if they have passed us a time as a float we convert that +template +class type_caster> + : public duration_caster> {}; + +template +class type_caster> + : public duration_caster> {}; + +PYBIND11_NAMESPACE_END(detail) +PYBIND11_NAMESPACE_END(PYBIND11_NAMESPACE) diff --git a/infer_4_30_0/lib/python3.10/site-packages/pybind11/include/pybind11/common.h b/infer_4_30_0/lib/python3.10/site-packages/pybind11/include/pybind11/common.h new file mode 100644 index 0000000000000000000000000000000000000000..6c8a4f1e88e493ee08d24e668639c8d495fd49b1 --- /dev/null +++ b/infer_4_30_0/lib/python3.10/site-packages/pybind11/include/pybind11/common.h @@ -0,0 +1,2 @@ +#include "detail/common.h" +#warning "Including 'common.h' is deprecated. It will be removed in v3.0. Use 'pybind11.h'." diff --git a/infer_4_30_0/lib/python3.10/site-packages/pybind11/include/pybind11/embed.h b/infer_4_30_0/lib/python3.10/site-packages/pybind11/include/pybind11/embed.h new file mode 100644 index 0000000000000000000000000000000000000000..9d29eb824954629bbfcf7fbf8c298b4288141b0f --- /dev/null +++ b/infer_4_30_0/lib/python3.10/site-packages/pybind11/include/pybind11/embed.h @@ -0,0 +1,313 @@ +/* + pybind11/embed.h: Support for embedding the interpreter + + Copyright (c) 2017 Wenzel Jakob + + All rights reserved. Use of this source code is governed by a + BSD-style license that can be found in the LICENSE file. +*/ + +#pragma once + +#include "pybind11.h" +#include "eval.h" + +#include +#include + +#if defined(PYPY_VERSION) +# error Embedding the interpreter is not supported with PyPy +#endif + +#define PYBIND11_EMBEDDED_MODULE_IMPL(name) \ + extern "C" PyObject *pybind11_init_impl_##name(); \ + extern "C" PyObject *pybind11_init_impl_##name() { return pybind11_init_wrapper_##name(); } + +/** \rst + Add a new module to the table of builtins for the interpreter. Must be + defined in global scope. The first macro parameter is the name of the + module (without quotes). The second parameter is the variable which will + be used as the interface to add functions and classes to the module. + + .. code-block:: cpp + + PYBIND11_EMBEDDED_MODULE(example, m) { + // ... initialize functions and classes here + m.def("foo", []() { + return "Hello, World!"; + }); + } + \endrst */ +#define PYBIND11_EMBEDDED_MODULE(name, variable) \ + static ::pybind11::module_::module_def PYBIND11_CONCAT(pybind11_module_def_, name); \ + static void PYBIND11_CONCAT(pybind11_init_, name)(::pybind11::module_ &); \ + static PyObject PYBIND11_CONCAT(*pybind11_init_wrapper_, name)() { \ + auto m = ::pybind11::module_::create_extension_module( \ + PYBIND11_TOSTRING(name), nullptr, &PYBIND11_CONCAT(pybind11_module_def_, name)); \ + try { \ + PYBIND11_CONCAT(pybind11_init_, name)(m); \ + return m.ptr(); \ + } \ + PYBIND11_CATCH_INIT_EXCEPTIONS \ + } \ + PYBIND11_EMBEDDED_MODULE_IMPL(name) \ + ::pybind11::detail::embedded_module PYBIND11_CONCAT(pybind11_module_, name)( \ + PYBIND11_TOSTRING(name), PYBIND11_CONCAT(pybind11_init_impl_, name)); \ + void PYBIND11_CONCAT(pybind11_init_, name)(::pybind11::module_ \ + & variable) // NOLINT(bugprone-macro-parentheses) + +PYBIND11_NAMESPACE_BEGIN(PYBIND11_NAMESPACE) +PYBIND11_NAMESPACE_BEGIN(detail) + +/// Python 2.7/3.x compatible version of `PyImport_AppendInittab` and error checks. +struct embedded_module { + using init_t = PyObject *(*) (); + embedded_module(const char *name, init_t init) { + if (Py_IsInitialized() != 0) { + pybind11_fail("Can't add new modules after the interpreter has been initialized"); + } + + auto result = PyImport_AppendInittab(name, init); + if (result == -1) { + pybind11_fail("Insufficient memory to add a new module"); + } + } +}; + +struct wide_char_arg_deleter { + void operator()(wchar_t *ptr) const { + // API docs: https://docs.python.org/3/c-api/sys.html#c.Py_DecodeLocale + PyMem_RawFree(ptr); + } +}; + +inline wchar_t *widen_chars(const char *safe_arg) { + wchar_t *widened_arg = Py_DecodeLocale(safe_arg, nullptr); + return widened_arg; +} + +inline void precheck_interpreter() { + if (Py_IsInitialized() != 0) { + pybind11_fail("The interpreter is already running"); + } +} + +#if !defined(PYBIND11_PYCONFIG_SUPPORT_PY_VERSION_HEX) +# define PYBIND11_PYCONFIG_SUPPORT_PY_VERSION_HEX (0x03080000) +#endif + +#if PY_VERSION_HEX < PYBIND11_PYCONFIG_SUPPORT_PY_VERSION_HEX +inline void initialize_interpreter_pre_pyconfig(bool init_signal_handlers, + int argc, + const char *const *argv, + bool add_program_dir_to_path) { + detail::precheck_interpreter(); + Py_InitializeEx(init_signal_handlers ? 1 : 0); + + // Before it was special-cased in python 3.8, passing an empty or null argv + // caused a segfault, so we have to reimplement the special case ourselves. + bool special_case = (argv == nullptr || argc <= 0); + + const char *const empty_argv[]{"\0"}; + const char *const *safe_argv = special_case ? empty_argv : argv; + if (special_case) { + argc = 1; + } + + auto argv_size = static_cast(argc); + // SetArgv* on python 3 takes wchar_t, so we have to convert. + std::unique_ptr widened_argv(new wchar_t *[argv_size]); + std::vector> widened_argv_entries; + widened_argv_entries.reserve(argv_size); + for (size_t ii = 0; ii < argv_size; ++ii) { + widened_argv_entries.emplace_back(detail::widen_chars(safe_argv[ii])); + if (!widened_argv_entries.back()) { + // A null here indicates a character-encoding failure or the python + // interpreter out of memory. Give up. + return; + } + widened_argv[ii] = widened_argv_entries.back().get(); + } + + auto *pysys_argv = widened_argv.get(); + + PySys_SetArgvEx(argc, pysys_argv, static_cast(add_program_dir_to_path)); +} +#endif + +PYBIND11_NAMESPACE_END(detail) + +#if PY_VERSION_HEX >= PYBIND11_PYCONFIG_SUPPORT_PY_VERSION_HEX +inline void initialize_interpreter(PyConfig *config, + int argc = 0, + const char *const *argv = nullptr, + bool add_program_dir_to_path = true) { + detail::precheck_interpreter(); + PyStatus status = PyConfig_SetBytesArgv(config, argc, const_cast(argv)); + if (PyStatus_Exception(status) != 0) { + // A failure here indicates a character-encoding failure or the python + // interpreter out of memory. Give up. + PyConfig_Clear(config); + throw std::runtime_error(PyStatus_IsError(status) != 0 ? status.err_msg + : "Failed to prepare CPython"); + } + status = Py_InitializeFromConfig(config); + if (PyStatus_Exception(status) != 0) { + PyConfig_Clear(config); + throw std::runtime_error(PyStatus_IsError(status) != 0 ? status.err_msg + : "Failed to init CPython"); + } + if (add_program_dir_to_path) { + PyRun_SimpleString("import sys, os.path; " + "sys.path.insert(0, " + "os.path.abspath(os.path.dirname(sys.argv[0])) " + "if sys.argv and os.path.exists(sys.argv[0]) else '')"); + } + PyConfig_Clear(config); +} +#endif + +/** \rst + Initialize the Python interpreter. No other pybind11 or CPython API functions can be + called before this is done; with the exception of `PYBIND11_EMBEDDED_MODULE`. The + optional `init_signal_handlers` parameter can be used to skip the registration of + signal handlers (see the `Python documentation`_ for details). Calling this function + again after the interpreter has already been initialized is a fatal error. + + If initializing the Python interpreter fails, then the program is terminated. (This + is controlled by the CPython runtime and is an exception to pybind11's normal behavior + of throwing exceptions on errors.) + + The remaining optional parameters, `argc`, `argv`, and `add_program_dir_to_path` are + used to populate ``sys.argv`` and ``sys.path``. + See the |PySys_SetArgvEx documentation|_ for details. + + .. _Python documentation: https://docs.python.org/3/c-api/init.html#c.Py_InitializeEx + .. |PySys_SetArgvEx documentation| replace:: ``PySys_SetArgvEx`` documentation + .. _PySys_SetArgvEx documentation: https://docs.python.org/3/c-api/init.html#c.PySys_SetArgvEx + \endrst */ +inline void initialize_interpreter(bool init_signal_handlers = true, + int argc = 0, + const char *const *argv = nullptr, + bool add_program_dir_to_path = true) { +#if PY_VERSION_HEX < PYBIND11_PYCONFIG_SUPPORT_PY_VERSION_HEX + detail::initialize_interpreter_pre_pyconfig( + init_signal_handlers, argc, argv, add_program_dir_to_path); +#else + PyConfig config; + PyConfig_InitPythonConfig(&config); + // See PR #4473 for background + config.parse_argv = 0; + + config.install_signal_handlers = init_signal_handlers ? 1 : 0; + initialize_interpreter(&config, argc, argv, add_program_dir_to_path); +#endif +} + +/** \rst + Shut down the Python interpreter. No pybind11 or CPython API functions can be called + after this. In addition, pybind11 objects must not outlive the interpreter: + + .. code-block:: cpp + + { // BAD + py::initialize_interpreter(); + auto hello = py::str("Hello, World!"); + py::finalize_interpreter(); + } // <-- BOOM, hello's destructor is called after interpreter shutdown + + { // GOOD + py::initialize_interpreter(); + { // scoped + auto hello = py::str("Hello, World!"); + } // <-- OK, hello is cleaned up properly + py::finalize_interpreter(); + } + + { // BETTER + py::scoped_interpreter guard{}; + auto hello = py::str("Hello, World!"); + } + + .. warning:: + + The interpreter can be restarted by calling `initialize_interpreter` again. + Modules created using pybind11 can be safely re-initialized. However, Python + itself cannot completely unload binary extension modules and there are several + caveats with regard to interpreter restarting. All the details can be found + in the CPython documentation. In short, not all interpreter memory may be + freed, either due to reference cycles or user-created global data. + + \endrst */ +inline void finalize_interpreter() { + // Get the internals pointer (without creating it if it doesn't exist). It's possible for the + // internals to be created during Py_Finalize() (e.g. if a py::capsule calls `get_internals()` + // during destruction), so we get the pointer-pointer here and check it after Py_Finalize(). + detail::internals **internals_ptr_ptr = detail::get_internals_pp(); + // It could also be stashed in state_dict, so look there too: + if (object internals_obj + = get_internals_obj_from_state_dict(detail::get_python_state_dict())) { + internals_ptr_ptr = detail::get_internals_pp_from_capsule(internals_obj); + } + // Local internals contains data managed by the current interpreter, so we must clear them to + // avoid undefined behaviors when initializing another interpreter + detail::get_local_internals().registered_types_cpp.clear(); + detail::get_local_internals().registered_exception_translators.clear(); + + Py_Finalize(); + + if (internals_ptr_ptr) { + delete *internals_ptr_ptr; + *internals_ptr_ptr = nullptr; + } +} + +/** \rst + Scope guard version of `initialize_interpreter` and `finalize_interpreter`. + This a move-only guard and only a single instance can exist. + + See `initialize_interpreter` for a discussion of its constructor arguments. + + .. code-block:: cpp + + #include + + int main() { + py::scoped_interpreter guard{}; + py::print(Hello, World!); + } // <-- interpreter shutdown + \endrst */ +class scoped_interpreter { +public: + explicit scoped_interpreter(bool init_signal_handlers = true, + int argc = 0, + const char *const *argv = nullptr, + bool add_program_dir_to_path = true) { + initialize_interpreter(init_signal_handlers, argc, argv, add_program_dir_to_path); + } + +#if PY_VERSION_HEX >= PYBIND11_PYCONFIG_SUPPORT_PY_VERSION_HEX + explicit scoped_interpreter(PyConfig *config, + int argc = 0, + const char *const *argv = nullptr, + bool add_program_dir_to_path = true) { + initialize_interpreter(config, argc, argv, add_program_dir_to_path); + } +#endif + + scoped_interpreter(const scoped_interpreter &) = delete; + scoped_interpreter(scoped_interpreter &&other) noexcept { other.is_valid = false; } + scoped_interpreter &operator=(const scoped_interpreter &) = delete; + scoped_interpreter &operator=(scoped_interpreter &&) = delete; + + ~scoped_interpreter() { + if (is_valid) { + finalize_interpreter(); + } + } + +private: + bool is_valid = true; +}; + +PYBIND11_NAMESPACE_END(PYBIND11_NAMESPACE) diff --git a/infer_4_30_0/lib/python3.10/site-packages/pybind11/include/pybind11/functional.h b/infer_4_30_0/lib/python3.10/site-packages/pybind11/include/pybind11/functional.h new file mode 100644 index 0000000000000000000000000000000000000000..4b3610117c75dd569928c8c78aff275582e3b342 --- /dev/null +++ b/infer_4_30_0/lib/python3.10/site-packages/pybind11/include/pybind11/functional.h @@ -0,0 +1,149 @@ +/* + pybind11/functional.h: std::function<> support + + Copyright (c) 2016 Wenzel Jakob + + All rights reserved. Use of this source code is governed by a + BSD-style license that can be found in the LICENSE file. +*/ + +#pragma once + +#define PYBIND11_HAS_TYPE_CASTER_STD_FUNCTION_SPECIALIZATIONS + +#include "pybind11.h" + +#include + +PYBIND11_NAMESPACE_BEGIN(PYBIND11_NAMESPACE) +PYBIND11_NAMESPACE_BEGIN(detail) +PYBIND11_NAMESPACE_BEGIN(type_caster_std_function_specializations) + +// ensure GIL is held during functor destruction +struct func_handle { + function f; +#if !(defined(_MSC_VER) && _MSC_VER == 1916 && defined(PYBIND11_CPP17)) + // This triggers a syntax error under very special conditions (very weird indeed). + explicit +#endif + func_handle(function &&f_) noexcept + : f(std::move(f_)) { + } + func_handle(const func_handle &f_) { operator=(f_); } + func_handle &operator=(const func_handle &f_) { + gil_scoped_acquire acq; + f = f_.f; + return *this; + } + ~func_handle() { + gil_scoped_acquire acq; + function kill_f(std::move(f)); + } +}; + +// to emulate 'move initialization capture' in C++11 +struct func_wrapper_base { + func_handle hfunc; + explicit func_wrapper_base(func_handle &&hf) noexcept : hfunc(hf) {} +}; + +template +struct func_wrapper : func_wrapper_base { + using func_wrapper_base::func_wrapper_base; + Return operator()(Args... args) const { + gil_scoped_acquire acq; + // casts the returned object as a rvalue to the return type + return hfunc.f(std::forward(args)...).template cast(); + } +}; + +PYBIND11_NAMESPACE_END(type_caster_std_function_specializations) + +template +struct type_caster> { + using type = std::function; + using retval_type = conditional_t::value, void_type, Return>; + using function_type = Return (*)(Args...); + +public: + bool load(handle src, bool convert) { + if (src.is_none()) { + // Defer accepting None to other overloads (if we aren't in convert mode): + if (!convert) { + return false; + } + return true; + } + + if (!isinstance(src)) { + return false; + } + + auto func = reinterpret_borrow(src); + + /* + When passing a C++ function as an argument to another C++ + function via Python, every function call would normally involve + a full C++ -> Python -> C++ roundtrip, which can be prohibitive. + Here, we try to at least detect the case where the function is + stateless (i.e. function pointer or lambda function without + captured variables), in which case the roundtrip can be avoided. + */ + if (auto cfunc = func.cpp_function()) { + auto *cfunc_self = PyCFunction_GET_SELF(cfunc.ptr()); + if (cfunc_self == nullptr) { + PyErr_Clear(); + } else if (isinstance(cfunc_self)) { + auto c = reinterpret_borrow(cfunc_self); + + function_record *rec = nullptr; + // Check that we can safely reinterpret the capsule into a function_record + if (detail::is_function_record_capsule(c)) { + rec = c.get_pointer(); + } + + while (rec != nullptr) { + if (rec->is_stateless + && same_type(typeid(function_type), + *reinterpret_cast(rec->data[1]))) { + struct capture { + function_type f; + }; + value = ((capture *) &rec->data)->f; + return true; + } + rec = rec->next; + } + } + // PYPY segfaults here when passing builtin function like sum. + // Raising an fail exception here works to prevent the segfault, but only on gcc. + // See PR #1413 for full details + } + + value = type_caster_std_function_specializations::func_wrapper( + type_caster_std_function_specializations::func_handle(std::move(func))); + return true; + } + + template + static handle cast(Func &&f_, return_value_policy policy, handle /* parent */) { + if (!f_) { + return none().release(); + } + + auto result = f_.template target(); + if (result) { + return cpp_function(*result, policy).release(); + } + return cpp_function(std::forward(f_), policy).release(); + } + + PYBIND11_TYPE_CASTER(type, + const_name("Callable[[") + + ::pybind11::detail::concat(make_caster::name...) + + const_name("], ") + make_caster::name + + const_name("]")); +}; + +PYBIND11_NAMESPACE_END(detail) +PYBIND11_NAMESPACE_END(PYBIND11_NAMESPACE) diff --git a/infer_4_30_0/lib/python3.10/site-packages/pybind11/include/pybind11/gil_safe_call_once.h b/infer_4_30_0/lib/python3.10/site-packages/pybind11/include/pybind11/gil_safe_call_once.h new file mode 100644 index 0000000000000000000000000000000000000000..5f9e1b03c64bc18dd573708cd670df3a7b7bde66 --- /dev/null +++ b/infer_4_30_0/lib/python3.10/site-packages/pybind11/include/pybind11/gil_safe_call_once.h @@ -0,0 +1,100 @@ +// Copyright (c) 2023 The pybind Community. + +#pragma once + +#include "detail/common.h" +#include "gil.h" + +#include +#include + +#ifdef Py_GIL_DISABLED +# include +#endif + +PYBIND11_NAMESPACE_BEGIN(PYBIND11_NAMESPACE) + +// Use the `gil_safe_call_once_and_store` class below instead of the naive +// +// static auto imported_obj = py::module_::import("module_name"); // BAD, DO NOT USE! +// +// which has two serious issues: +// +// 1. Py_DECREF() calls potentially after the Python interpreter was finalized already, and +// 2. deadlocks in multi-threaded processes (because of missing lock ordering). +// +// The following alternative avoids both problems: +// +// PYBIND11_CONSTINIT static py::gil_safe_call_once_and_store storage; +// auto &imported_obj = storage // Do NOT make this `static`! +// .call_once_and_store_result([]() { +// return py::module_::import("module_name"); +// }) +// .get_stored(); +// +// The parameter of `call_once_and_store_result()` must be callable. It can make +// CPython API calls, and in particular, it can temporarily release the GIL. +// +// `T` can be any C++ type, it does not have to involve CPython API types. +// +// The behavior with regard to signals, e.g. `SIGINT` (`KeyboardInterrupt`), +// is not ideal. If the main thread is the one to actually run the `Callable`, +// then a `KeyboardInterrupt` will interrupt it if it is running normal Python +// code. The situation is different if a non-main thread runs the +// `Callable`, and then the main thread starts waiting for it to complete: +// a `KeyboardInterrupt` will not interrupt the non-main thread, but it will +// get processed only when it is the main thread's turn again and it is running +// normal Python code. However, this will be unnoticeable for quick call-once +// functions, which is usually the case. +template +class gil_safe_call_once_and_store { +public: + // PRECONDITION: The GIL must be held when `call_once_and_store_result()` is called. + template + gil_safe_call_once_and_store &call_once_and_store_result(Callable &&fn) { + if (!is_initialized_) { // This read is guarded by the GIL. + // Multiple threads may enter here, because the GIL is released in the next line and + // CPython API calls in the `fn()` call below may release and reacquire the GIL. + gil_scoped_release gil_rel; // Needed to establish lock ordering. + std::call_once(once_flag_, [&] { + // Only one thread will ever enter here. + gil_scoped_acquire gil_acq; + ::new (storage_) T(fn()); // fn may release, but will reacquire, the GIL. + is_initialized_ = true; // This write is guarded by the GIL. + }); + // All threads will observe `is_initialized_` as true here. + } + // Intentionally not returning `T &` to ensure the calling code is self-documenting. + return *this; + } + + // This must only be called after `call_once_and_store_result()` was called. + T &get_stored() { + assert(is_initialized_); + PYBIND11_WARNING_PUSH +#if !defined(__clang__) && defined(__GNUC__) && __GNUC__ < 5 + // Needed for gcc 4.8.5 + PYBIND11_WARNING_DISABLE_GCC("-Wstrict-aliasing") +#endif + return *reinterpret_cast(storage_); + PYBIND11_WARNING_POP + } + + constexpr gil_safe_call_once_and_store() = default; + PYBIND11_DTOR_CONSTEXPR ~gil_safe_call_once_and_store() = default; + +private: + alignas(T) char storage_[sizeof(T)] = {}; + std::once_flag once_flag_ = {}; +#ifdef Py_GIL_DISABLED + std::atomic_bool +#else + bool +#endif + is_initialized_{false}; + // The `is_initialized_`-`storage_` pair is very similar to `std::optional`, + // but the latter does not have the triviality properties of former, + // therefore `std::optional` is not a viable alternative here. +}; + +PYBIND11_NAMESPACE_END(PYBIND11_NAMESPACE) diff --git a/infer_4_30_0/lib/python3.10/site-packages/pybind11/include/pybind11/numpy.h b/infer_4_30_0/lib/python3.10/site-packages/pybind11/include/pybind11/numpy.h new file mode 100644 index 0000000000000000000000000000000000000000..09894cf74f4aef2b91f657f84ebfb6af3e7e8d0f --- /dev/null +++ b/infer_4_30_0/lib/python3.10/site-packages/pybind11/include/pybind11/numpy.h @@ -0,0 +1,2139 @@ +/* + pybind11/numpy.h: Basic NumPy support, vectorize() wrapper + + Copyright (c) 2016 Wenzel Jakob + + All rights reserved. Use of this source code is governed by a + BSD-style license that can be found in the LICENSE file. +*/ + +#pragma once + +#include "pybind11.h" +#include "detail/common.h" +#include "complex.h" +#include "gil_safe_call_once.h" +#include "pytypes.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#if defined(PYBIND11_NUMPY_1_ONLY) && !defined(PYBIND11_INTERNAL_NUMPY_1_ONLY_DETECTED) +# error PYBIND11_NUMPY_1_ONLY must be defined before any pybind11 header is included. +#endif + +/* This will be true on all flat address space platforms and allows us to reduce the + whole npy_intp / ssize_t / Py_intptr_t business down to just ssize_t for all size + and dimension types (e.g. shape, strides, indexing), instead of inflicting this + upon the library user. + Note that NumPy 2 now uses ssize_t for `npy_intp` to simplify this. */ +static_assert(sizeof(::pybind11::ssize_t) == sizeof(Py_intptr_t), "ssize_t != Py_intptr_t"); +static_assert(std::is_signed::value, "Py_intptr_t must be signed"); +// We now can reinterpret_cast between py::ssize_t and Py_intptr_t (MSVC + PyPy cares) + +PYBIND11_NAMESPACE_BEGIN(PYBIND11_NAMESPACE) + +PYBIND11_WARNING_DISABLE_MSVC(4127) + +class dtype; // Forward declaration +class array; // Forward declaration + +PYBIND11_NAMESPACE_BEGIN(detail) + +template <> +struct handle_type_name { + static constexpr auto name = const_name("numpy.dtype"); +}; + +template <> +struct handle_type_name { + static constexpr auto name = const_name("numpy.ndarray"); +}; + +template +struct npy_format_descriptor; + +/* NumPy 1 proxy (always includes legacy fields) */ +struct PyArrayDescr1_Proxy { + PyObject_HEAD + PyObject *typeobj; + char kind; + char type; + char byteorder; + char flags; + int type_num; + int elsize; + int alignment; + char *subarray; + PyObject *fields; + PyObject *names; +}; + +#ifndef PYBIND11_NUMPY_1_ONLY +struct PyArrayDescr_Proxy { + PyObject_HEAD + PyObject *typeobj; + char kind; + char type; + char byteorder; + char _former_flags; + int type_num; + /* Additional fields are NumPy version specific. */ +}; +#else +/* NumPy 1.x only, we can expose all fields */ +using PyArrayDescr_Proxy = PyArrayDescr1_Proxy; +#endif + +/* NumPy 2 proxy, including legacy fields */ +struct PyArrayDescr2_Proxy { + PyObject_HEAD + PyObject *typeobj; + char kind; + char type; + char byteorder; + char _former_flags; + int type_num; + std::uint64_t flags; + ssize_t elsize; + ssize_t alignment; + PyObject *metadata; + Py_hash_t hash; + void *reserved_null[2]; + /* The following fields only exist if 0 <= type_num < 2056 */ + char *subarray; + PyObject *fields; + PyObject *names; +}; + +struct PyArray_Proxy { + PyObject_HEAD + char *data; + int nd; + ssize_t *dimensions; + ssize_t *strides; + PyObject *base; + PyObject *descr; + int flags; +}; + +struct PyVoidScalarObject_Proxy { + PyObject_VAR_HEAD char *obval; + PyArrayDescr_Proxy *descr; + int flags; + PyObject *base; +}; + +struct numpy_type_info { + PyObject *dtype_ptr; + std::string format_str; +}; + +struct numpy_internals { + std::unordered_map registered_dtypes; + + numpy_type_info *get_type_info(const std::type_info &tinfo, bool throw_if_missing = true) { + auto it = registered_dtypes.find(std::type_index(tinfo)); + if (it != registered_dtypes.end()) { + return &(it->second); + } + if (throw_if_missing) { + pybind11_fail(std::string("NumPy type info missing for ") + tinfo.name()); + } + return nullptr; + } + + template + numpy_type_info *get_type_info(bool throw_if_missing = true) { + return get_type_info(typeid(typename std::remove_cv::type), throw_if_missing); + } +}; + +PYBIND11_NOINLINE void load_numpy_internals(numpy_internals *&ptr) { + ptr = &get_or_create_shared_data("_numpy_internals"); +} + +inline numpy_internals &get_numpy_internals() { + static numpy_internals *ptr = nullptr; + if (!ptr) { + load_numpy_internals(ptr); + } + return *ptr; +} + +PYBIND11_NOINLINE module_ import_numpy_core_submodule(const char *submodule_name) { + module_ numpy = module_::import("numpy"); + str version_string = numpy.attr("__version__"); + + module_ numpy_lib = module_::import("numpy.lib"); + object numpy_version = numpy_lib.attr("NumpyVersion")(version_string); + int major_version = numpy_version.attr("major").cast(); + +#ifdef PYBIND11_NUMPY_1_ONLY + if (major_version >= 2) { + throw std::runtime_error( + "This extension was built with PYBIND11_NUMPY_1_ONLY defined, " + "but NumPy 2 is used in this process. For NumPy2 compatibility, " + "this extension needs to be rebuilt without the PYBIND11_NUMPY_1_ONLY define."); + } +#endif + /* `numpy.core` was renamed to `numpy._core` in NumPy 2.0 as it officially + became a private module. */ + std::string numpy_core_path = major_version >= 2 ? "numpy._core" : "numpy.core"; + return module_::import((numpy_core_path + "." + submodule_name).c_str()); +} + +template +struct same_size { + template + using as = bool_constant; +}; + +template +constexpr int platform_lookup() { + return -1; +} + +// Lookup a type according to its size, and return a value corresponding to the NumPy typenum. +template +constexpr int platform_lookup(int I, Ints... Is) { + return sizeof(Concrete) == sizeof(T) ? I : platform_lookup(Is...); +} + +struct npy_api { + enum constants { + NPY_ARRAY_C_CONTIGUOUS_ = 0x0001, + NPY_ARRAY_F_CONTIGUOUS_ = 0x0002, + NPY_ARRAY_OWNDATA_ = 0x0004, + NPY_ARRAY_FORCECAST_ = 0x0010, + NPY_ARRAY_ENSUREARRAY_ = 0x0040, + NPY_ARRAY_ALIGNED_ = 0x0100, + NPY_ARRAY_WRITEABLE_ = 0x0400, + NPY_BOOL_ = 0, + NPY_BYTE_, + NPY_UBYTE_, + NPY_SHORT_, + NPY_USHORT_, + NPY_INT_, + NPY_UINT_, + NPY_LONG_, + NPY_ULONG_, + NPY_LONGLONG_, + NPY_ULONGLONG_, + NPY_FLOAT_, + NPY_DOUBLE_, + NPY_LONGDOUBLE_, + NPY_CFLOAT_, + NPY_CDOUBLE_, + NPY_CLONGDOUBLE_, + NPY_OBJECT_ = 17, + NPY_STRING_, + NPY_UNICODE_, + NPY_VOID_, + // Platform-dependent normalization + NPY_INT8_ = NPY_BYTE_, + NPY_UINT8_ = NPY_UBYTE_, + NPY_INT16_ = NPY_SHORT_, + NPY_UINT16_ = NPY_USHORT_, + // `npy_common.h` defines the integer aliases. In order, it checks: + // NPY_BITSOF_LONG, NPY_BITSOF_LONGLONG, NPY_BITSOF_INT, NPY_BITSOF_SHORT, NPY_BITSOF_CHAR + // and assigns the alias to the first matching size, so we should check in this order. + NPY_INT32_ + = platform_lookup(NPY_LONG_, NPY_INT_, NPY_SHORT_), + NPY_UINT32_ = platform_lookup( + NPY_ULONG_, NPY_UINT_, NPY_USHORT_), + NPY_INT64_ + = platform_lookup(NPY_LONG_, NPY_LONGLONG_, NPY_INT_), + NPY_UINT64_ + = platform_lookup( + NPY_ULONG_, NPY_ULONGLONG_, NPY_UINT_), + }; + + unsigned int PyArray_RUNTIME_VERSION_; + + struct PyArray_Dims { + Py_intptr_t *ptr; + int len; + }; + + static npy_api &get() { + PYBIND11_CONSTINIT static gil_safe_call_once_and_store storage; + return storage.call_once_and_store_result(lookup).get_stored(); + } + + bool PyArray_Check_(PyObject *obj) const { + return PyObject_TypeCheck(obj, PyArray_Type_) != 0; + } + bool PyArrayDescr_Check_(PyObject *obj) const { + return PyObject_TypeCheck(obj, PyArrayDescr_Type_) != 0; + } + + unsigned int (*PyArray_GetNDArrayCFeatureVersion_)(); + PyObject *(*PyArray_DescrFromType_)(int); + PyObject *(*PyArray_NewFromDescr_)(PyTypeObject *, + PyObject *, + int, + Py_intptr_t const *, + Py_intptr_t const *, + void *, + int, + PyObject *); + // Unused. Not removed because that affects ABI of the class. + PyObject *(*PyArray_DescrNewFromType_)(int); + int (*PyArray_CopyInto_)(PyObject *, PyObject *); + PyObject *(*PyArray_NewCopy_)(PyObject *, int); + PyTypeObject *PyArray_Type_; + PyTypeObject *PyVoidArrType_Type_; + PyTypeObject *PyArrayDescr_Type_; + PyObject *(*PyArray_DescrFromScalar_)(PyObject *); + PyObject *(*PyArray_FromAny_)(PyObject *, PyObject *, int, int, int, PyObject *); + int (*PyArray_DescrConverter_)(PyObject *, PyObject **); + bool (*PyArray_EquivTypes_)(PyObject *, PyObject *); +#ifdef PYBIND11_NUMPY_1_ONLY + int (*PyArray_GetArrayParamsFromObject_)(PyObject *, + PyObject *, + unsigned char, + PyObject **, + int *, + Py_intptr_t *, + PyObject **, + PyObject *); +#endif + PyObject *(*PyArray_Squeeze_)(PyObject *); + // Unused. Not removed because that affects ABI of the class. + int (*PyArray_SetBaseObject_)(PyObject *, PyObject *); + PyObject *(*PyArray_Resize_)(PyObject *, PyArray_Dims *, int, int); + PyObject *(*PyArray_Newshape_)(PyObject *, PyArray_Dims *, int); + PyObject *(*PyArray_View_)(PyObject *, PyObject *, PyObject *); + +private: + enum functions { + API_PyArray_GetNDArrayCFeatureVersion = 211, + API_PyArray_Type = 2, + API_PyArrayDescr_Type = 3, + API_PyVoidArrType_Type = 39, + API_PyArray_DescrFromType = 45, + API_PyArray_DescrFromScalar = 57, + API_PyArray_FromAny = 69, + API_PyArray_Resize = 80, + // CopyInto was slot 82 and 50 was effectively an alias. NumPy 2 removed 82. + API_PyArray_CopyInto = 50, + API_PyArray_NewCopy = 85, + API_PyArray_NewFromDescr = 94, + API_PyArray_DescrNewFromType = 96, + API_PyArray_Newshape = 135, + API_PyArray_Squeeze = 136, + API_PyArray_View = 137, + API_PyArray_DescrConverter = 174, + API_PyArray_EquivTypes = 182, +#ifdef PYBIND11_NUMPY_1_ONLY + API_PyArray_GetArrayParamsFromObject = 278, +#endif + API_PyArray_SetBaseObject = 282 + }; + + static npy_api lookup() { + module_ m = detail::import_numpy_core_submodule("multiarray"); + auto c = m.attr("_ARRAY_API"); + void **api_ptr = (void **) PyCapsule_GetPointer(c.ptr(), nullptr); + if (api_ptr == nullptr) { + raise_from(PyExc_SystemError, "FAILURE obtaining numpy _ARRAY_API pointer."); + throw error_already_set(); + } + npy_api api; +#define DECL_NPY_API(Func) api.Func##_ = (decltype(api.Func##_)) api_ptr[API_##Func]; + DECL_NPY_API(PyArray_GetNDArrayCFeatureVersion); + api.PyArray_RUNTIME_VERSION_ = api.PyArray_GetNDArrayCFeatureVersion_(); + if (api.PyArray_RUNTIME_VERSION_ < 0x7) { + pybind11_fail("pybind11 numpy support requires numpy >= 1.7.0"); + } + DECL_NPY_API(PyArray_Type); + DECL_NPY_API(PyVoidArrType_Type); + DECL_NPY_API(PyArrayDescr_Type); + DECL_NPY_API(PyArray_DescrFromType); + DECL_NPY_API(PyArray_DescrFromScalar); + DECL_NPY_API(PyArray_FromAny); + DECL_NPY_API(PyArray_Resize); + DECL_NPY_API(PyArray_CopyInto); + DECL_NPY_API(PyArray_NewCopy); + DECL_NPY_API(PyArray_NewFromDescr); + DECL_NPY_API(PyArray_DescrNewFromType); + DECL_NPY_API(PyArray_Newshape); + DECL_NPY_API(PyArray_Squeeze); + DECL_NPY_API(PyArray_View); + DECL_NPY_API(PyArray_DescrConverter); + DECL_NPY_API(PyArray_EquivTypes); +#ifdef PYBIND11_NUMPY_1_ONLY + DECL_NPY_API(PyArray_GetArrayParamsFromObject); +#endif + DECL_NPY_API(PyArray_SetBaseObject); + +#undef DECL_NPY_API + return api; + } +}; + +inline PyArray_Proxy *array_proxy(void *ptr) { return reinterpret_cast(ptr); } + +inline const PyArray_Proxy *array_proxy(const void *ptr) { + return reinterpret_cast(ptr); +} + +inline PyArrayDescr_Proxy *array_descriptor_proxy(PyObject *ptr) { + return reinterpret_cast(ptr); +} + +inline const PyArrayDescr_Proxy *array_descriptor_proxy(const PyObject *ptr) { + return reinterpret_cast(ptr); +} + +inline const PyArrayDescr1_Proxy *array_descriptor1_proxy(const PyObject *ptr) { + return reinterpret_cast(ptr); +} + +inline const PyArrayDescr2_Proxy *array_descriptor2_proxy(const PyObject *ptr) { + return reinterpret_cast(ptr); +} + +inline bool check_flags(const void *ptr, int flag) { + return (flag == (array_proxy(ptr)->flags & flag)); +} + +template +struct is_std_array : std::false_type {}; +template +struct is_std_array> : std::true_type {}; +template +struct is_complex : std::false_type {}; +template +struct is_complex> : std::true_type {}; + +template +struct array_info_scalar { + using type = T; + static constexpr bool is_array = false; + static constexpr bool is_empty = false; + static constexpr auto extents = const_name(""); + static void append_extents(list & /* shape */) {} +}; +// Computes underlying type and a comma-separated list of extents for array +// types (any mix of std::array and built-in arrays). An array of char is +// treated as scalar because it gets special handling. +template +struct array_info : array_info_scalar {}; +template +struct array_info> { + using type = typename array_info::type; + static constexpr bool is_array = true; + static constexpr bool is_empty = (N == 0) || array_info::is_empty; + static constexpr size_t extent = N; + + // appends the extents to shape + static void append_extents(list &shape) { + shape.append(N); + array_info::append_extents(shape); + } + + static constexpr auto extents = const_name::is_array>( + ::pybind11::detail::concat(const_name(), array_info::extents), const_name()); +}; +// For numpy we have special handling for arrays of characters, so we don't include +// the size in the array extents. +template +struct array_info : array_info_scalar {}; +template +struct array_info> : array_info_scalar> {}; +template +struct array_info : array_info> {}; +template +using remove_all_extents_t = typename array_info::type; + +template +using is_pod_struct + = all_of, // since we're accessing directly in memory + // we need a standard layout type +#if defined(__GLIBCXX__) \ + && (__GLIBCXX__ < 20150422 || __GLIBCXX__ == 20150426 || __GLIBCXX__ == 20150623 \ + || __GLIBCXX__ == 20150626 || __GLIBCXX__ == 20160803) + // libstdc++ < 5 (including versions 4.8.5, 4.9.3 and 4.9.4 which were released after + // 5) don't implement is_trivially_copyable, so approximate it + std::is_trivially_destructible, + satisfies_any_of, +#else + std::is_trivially_copyable, +#endif + satisfies_none_of>; + +// Replacement for std::is_pod (deprecated in C++20) +template +using is_pod = all_of, std::is_trivial>; + +template +ssize_t byte_offset_unsafe(const Strides &) { + return 0; +} +template +ssize_t byte_offset_unsafe(const Strides &strides, ssize_t i, Ix... index) { + return i * strides[Dim] + byte_offset_unsafe(strides, index...); +} + +/** + * Proxy class providing unsafe, unchecked const access to array data. This is constructed through + * the `unchecked()` method of `array` or the `unchecked()` method of `array_t`. `Dims` + * will be -1 for dimensions determined at runtime. + */ +template +class unchecked_reference { +protected: + static constexpr bool Dynamic = Dims < 0; + const unsigned char *data_; + // Storing the shape & strides in local variables (i.e. these arrays) allows the compiler to + // make large performance gains on big, nested loops, but requires compile-time dimensions + conditional_t> shape_, strides_; + const ssize_t dims_; + + friend class pybind11::array; + // Constructor for compile-time dimensions: + template + unchecked_reference(const void *data, + const ssize_t *shape, + const ssize_t *strides, + enable_if_t) + : data_{reinterpret_cast(data)}, dims_{Dims} { + for (size_t i = 0; i < (size_t) dims_; i++) { + shape_[i] = shape[i]; + strides_[i] = strides[i]; + } + } + // Constructor for runtime dimensions: + template + unchecked_reference(const void *data, + const ssize_t *shape, + const ssize_t *strides, + enable_if_t dims) + : data_{reinterpret_cast(data)}, shape_{shape}, strides_{strides}, + dims_{dims} {} + +public: + /** + * Unchecked const reference access to data at the given indices. For a compile-time known + * number of dimensions, this requires the correct number of arguments; for run-time + * dimensionality, this is not checked (and so is up to the caller to use safely). + */ + template + const T &operator()(Ix... index) const { + static_assert(ssize_t{sizeof...(Ix)} == Dims || Dynamic, + "Invalid number of indices for unchecked array reference"); + return *reinterpret_cast(data_ + + byte_offset_unsafe(strides_, ssize_t(index)...)); + } + /** + * Unchecked const reference access to data; this operator only participates if the reference + * is to a 1-dimensional array. When present, this is exactly equivalent to `obj(index)`. + */ + template > + const T &operator[](ssize_t index) const { + return operator()(index); + } + + /// Pointer access to the data at the given indices. + template + const T *data(Ix... ix) const { + return &operator()(ssize_t(ix)...); + } + + /// Returns the item size, i.e. sizeof(T) + constexpr static ssize_t itemsize() { return sizeof(T); } + + /// Returns the shape (i.e. size) of dimension `dim` + ssize_t shape(ssize_t dim) const { return shape_[(size_t) dim]; } + + /// Returns the number of dimensions of the array + ssize_t ndim() const { return dims_; } + + /// Returns the total number of elements in the referenced array, i.e. the product of the + /// shapes + template + enable_if_t size() const { + return std::accumulate( + shape_.begin(), shape_.end(), (ssize_t) 1, std::multiplies()); + } + template + enable_if_t size() const { + return std::accumulate(shape_, shape_ + ndim(), (ssize_t) 1, std::multiplies()); + } + + /// Returns the total number of bytes used by the referenced data. Note that the actual span + /// in memory may be larger if the referenced array has non-contiguous strides (e.g. for a + /// slice). + ssize_t nbytes() const { return size() * itemsize(); } +}; + +template +class unchecked_mutable_reference : public unchecked_reference { + friend class pybind11::array; + using ConstBase = unchecked_reference; + using ConstBase::ConstBase; + using ConstBase::Dynamic; + +public: + // Bring in const-qualified versions from base class + using ConstBase::operator(); + using ConstBase::operator[]; + + /// Mutable, unchecked access to data at the given indices. + template + T &operator()(Ix... index) { + static_assert(ssize_t{sizeof...(Ix)} == Dims || Dynamic, + "Invalid number of indices for unchecked array reference"); + return const_cast(ConstBase::operator()(index...)); + } + /** + * Mutable, unchecked access data at the given index; this operator only participates if the + * reference is to a 1-dimensional array (or has runtime dimensions). When present, this is + * exactly equivalent to `obj(index)`. + */ + template > + T &operator[](ssize_t index) { + return operator()(index); + } + + /// Mutable pointer access to the data at the given indices. + template + T *mutable_data(Ix... ix) { + return &operator()(ssize_t(ix)...); + } +}; + +template +struct type_caster> { + static_assert(Dim == 0 && Dim > 0 /* always fail */, + "unchecked array proxy object is not castable"); +}; +template +struct type_caster> + : type_caster> {}; + +PYBIND11_NAMESPACE_END(detail) + +class dtype : public object { +public: + PYBIND11_OBJECT_DEFAULT(dtype, object, detail::npy_api::get().PyArrayDescr_Check_) + + explicit dtype(const buffer_info &info) { + dtype descr(_dtype_from_pep3118()(pybind11::str(info.format))); + // If info.itemsize == 0, use the value calculated from the format string + m_ptr = descr.strip_padding(info.itemsize != 0 ? info.itemsize : descr.itemsize()) + .release() + .ptr(); + } + + explicit dtype(const pybind11::str &format) : dtype(from_args(format)) {} + + explicit dtype(const std::string &format) : dtype(pybind11::str(format)) {} + + explicit dtype(const char *format) : dtype(pybind11::str(format)) {} + + dtype(list names, list formats, list offsets, ssize_t itemsize) { + dict args; + args["names"] = std::move(names); + args["formats"] = std::move(formats); + args["offsets"] = std::move(offsets); + args["itemsize"] = pybind11::int_(itemsize); + m_ptr = from_args(args).release().ptr(); + } + + /// Return dtype for the given typenum (one of the NPY_TYPES). + /// https://numpy.org/devdocs/reference/c-api/array.html#c.PyArray_DescrFromType + explicit dtype(int typenum) + : object(detail::npy_api::get().PyArray_DescrFromType_(typenum), stolen_t{}) { + if (m_ptr == nullptr) { + throw error_already_set(); + } + } + + /// This is essentially the same as calling numpy.dtype(args) in Python. + static dtype from_args(const object &args) { + PyObject *ptr = nullptr; + if ((detail::npy_api::get().PyArray_DescrConverter_(args.ptr(), &ptr) == 0) || !ptr) { + throw error_already_set(); + } + return reinterpret_steal(ptr); + } + + /// Return dtype associated with a C++ type. + template + static dtype of() { + return detail::npy_format_descriptor::type>::dtype(); + } + + /// Size of the data type in bytes. +#ifdef PYBIND11_NUMPY_1_ONLY + ssize_t itemsize() const { return detail::array_descriptor_proxy(m_ptr)->elsize; } +#else + ssize_t itemsize() const { + if (detail::npy_api::get().PyArray_RUNTIME_VERSION_ < 0x12) { + return detail::array_descriptor1_proxy(m_ptr)->elsize; + } + return detail::array_descriptor2_proxy(m_ptr)->elsize; + } +#endif + + /// Returns true for structured data types. +#ifdef PYBIND11_NUMPY_1_ONLY + bool has_fields() const { return detail::array_descriptor_proxy(m_ptr)->names != nullptr; } +#else + bool has_fields() const { + if (detail::npy_api::get().PyArray_RUNTIME_VERSION_ < 0x12) { + return detail::array_descriptor1_proxy(m_ptr)->names != nullptr; + } + const auto *proxy = detail::array_descriptor2_proxy(m_ptr); + if (proxy->type_num < 0 || proxy->type_num >= 2056) { + return false; + } + return proxy->names != nullptr; + } +#endif + + /// Single-character code for dtype's kind. + /// For example, floating point types are 'f' and integral types are 'i'. + char kind() const { return detail::array_descriptor_proxy(m_ptr)->kind; } + + /// Single-character for dtype's type. + /// For example, ``float`` is 'f', ``double`` 'd', ``int`` 'i', and ``long`` 'l'. + char char_() const { + // Note: The signature, `dtype::char_` follows the naming of NumPy's + // public Python API (i.e., ``dtype.char``), rather than its internal + // C API (``PyArray_Descr::type``). + return detail::array_descriptor_proxy(m_ptr)->type; + } + + /// type number of dtype. + int num() const { + // Note: The signature, `dtype::num` follows the naming of NumPy's public + // Python API (i.e., ``dtype.num``), rather than its internal + // C API (``PyArray_Descr::type_num``). + return detail::array_descriptor_proxy(m_ptr)->type_num; + } + + /// Single character for byteorder + char byteorder() const { return detail::array_descriptor_proxy(m_ptr)->byteorder; } + +/// Alignment of the data type +#ifdef PYBIND11_NUMPY_1_ONLY + int alignment() const { return detail::array_descriptor_proxy(m_ptr)->alignment; } +#else + ssize_t alignment() const { + if (detail::npy_api::get().PyArray_RUNTIME_VERSION_ < 0x12) { + return detail::array_descriptor1_proxy(m_ptr)->alignment; + } + return detail::array_descriptor2_proxy(m_ptr)->alignment; + } +#endif + +/// Flags for the array descriptor +#ifdef PYBIND11_NUMPY_1_ONLY + char flags() const { return detail::array_descriptor_proxy(m_ptr)->flags; } +#else + std::uint64_t flags() const { + if (detail::npy_api::get().PyArray_RUNTIME_VERSION_ < 0x12) { + return (unsigned char) detail::array_descriptor1_proxy(m_ptr)->flags; + } + return detail::array_descriptor2_proxy(m_ptr)->flags; + } +#endif + +private: + static object &_dtype_from_pep3118() { + PYBIND11_CONSTINIT static gil_safe_call_once_and_store storage; + return storage + .call_once_and_store_result([]() { + return detail::import_numpy_core_submodule("_internal") + .attr("_dtype_from_pep3118"); + }) + .get_stored(); + } + + dtype strip_padding(ssize_t itemsize) { + // Recursively strip all void fields with empty names that are generated for + // padding fields (as of NumPy v1.11). + if (!has_fields()) { + return *this; + } + + struct field_descr { + pybind11::str name; + object format; + pybind11::int_ offset; + field_descr(pybind11::str &&name, object &&format, pybind11::int_ &&offset) + : name{std::move(name)}, format{std::move(format)}, offset{std::move(offset)} {}; + }; + auto field_dict = attr("fields").cast(); + std::vector field_descriptors; + field_descriptors.reserve(field_dict.size()); + + for (auto field : field_dict.attr("items")()) { + auto spec = field.cast(); + auto name = spec[0].cast(); + auto spec_fo = spec[1].cast(); + auto format = spec_fo[0].cast(); + auto offset = spec_fo[1].cast(); + if ((len(name) == 0u) && format.kind() == 'V') { + continue; + } + field_descriptors.emplace_back( + std::move(name), format.strip_padding(format.itemsize()), std::move(offset)); + } + + std::sort(field_descriptors.begin(), + field_descriptors.end(), + [](const field_descr &a, const field_descr &b) { + return a.offset.cast() < b.offset.cast(); + }); + + list names, formats, offsets; + for (auto &descr : field_descriptors) { + names.append(std::move(descr.name)); + formats.append(std::move(descr.format)); + offsets.append(std::move(descr.offset)); + } + return dtype(std::move(names), std::move(formats), std::move(offsets), itemsize); + } +}; + +class array : public buffer { +public: + PYBIND11_OBJECT_CVT(array, buffer, detail::npy_api::get().PyArray_Check_, raw_array) + + enum { + c_style = detail::npy_api::NPY_ARRAY_C_CONTIGUOUS_, + f_style = detail::npy_api::NPY_ARRAY_F_CONTIGUOUS_, + forcecast = detail::npy_api::NPY_ARRAY_FORCECAST_ + }; + + array() : array(0, static_cast(nullptr)) {} + + using ShapeContainer = detail::any_container; + using StridesContainer = detail::any_container; + + // Constructs an array taking shape/strides from arbitrary container types + array(const pybind11::dtype &dt, + ShapeContainer shape, + StridesContainer strides, + const void *ptr = nullptr, + handle base = handle()) { + + if (strides->empty()) { + *strides = detail::c_strides(*shape, dt.itemsize()); + } + + auto ndim = shape->size(); + if (ndim != strides->size()) { + pybind11_fail("NumPy: shape ndim doesn't match strides ndim"); + } + auto descr = dt; + + int flags = 0; + if (base && ptr) { + if (isinstance(base)) { + /* Copy flags from base (except ownership bit) */ + flags = reinterpret_borrow(base).flags() + & ~detail::npy_api::NPY_ARRAY_OWNDATA_; + } else { + /* Writable by default, easy to downgrade later on if needed */ + flags = detail::npy_api::NPY_ARRAY_WRITEABLE_; + } + } + + auto &api = detail::npy_api::get(); + auto tmp = reinterpret_steal(api.PyArray_NewFromDescr_( + api.PyArray_Type_, + descr.release().ptr(), + (int) ndim, + // Use reinterpret_cast for PyPy on Windows (remove if fixed, checked on 7.3.1) + reinterpret_cast(shape->data()), + reinterpret_cast(strides->data()), + const_cast(ptr), + flags, + nullptr)); + if (!tmp) { + throw error_already_set(); + } + if (ptr) { + if (base) { + api.PyArray_SetBaseObject_(tmp.ptr(), base.inc_ref().ptr()); + } else { + tmp = reinterpret_steal( + api.PyArray_NewCopy_(tmp.ptr(), -1 /* any order */)); + } + } + m_ptr = tmp.release().ptr(); + } + + array(const pybind11::dtype &dt, + ShapeContainer shape, + const void *ptr = nullptr, + handle base = handle()) + : array(dt, std::move(shape), {}, ptr, base) {} + + template ::value && !std::is_same::value>> + array(const pybind11::dtype &dt, T count, const void *ptr = nullptr, handle base = handle()) + : array(dt, {{count}}, ptr, base) {} + + template + array(ShapeContainer shape, StridesContainer strides, const T *ptr, handle base = handle()) + : array(pybind11::dtype::of(), + std::move(shape), + std::move(strides), + reinterpret_cast(ptr), + base) {} + + template + array(ShapeContainer shape, const T *ptr, handle base = handle()) + : array(std::move(shape), {}, ptr, base) {} + + template + explicit array(ssize_t count, const T *ptr, handle base = handle()) + : array({count}, {}, ptr, base) {} + + explicit array(const buffer_info &info, handle base = handle()) + : array(pybind11::dtype(info), info.shape, info.strides, info.ptr, base) {} + + /// Array descriptor (dtype) + pybind11::dtype dtype() const { + return reinterpret_borrow(detail::array_proxy(m_ptr)->descr); + } + + /// Total number of elements + ssize_t size() const { + return std::accumulate(shape(), shape() + ndim(), (ssize_t) 1, std::multiplies()); + } + + /// Byte size of a single element + ssize_t itemsize() const { return dtype().itemsize(); } + + /// Total number of bytes + ssize_t nbytes() const { return size() * itemsize(); } + + /// Number of dimensions + ssize_t ndim() const { return detail::array_proxy(m_ptr)->nd; } + + /// Base object + object base() const { return reinterpret_borrow(detail::array_proxy(m_ptr)->base); } + + /// Dimensions of the array + const ssize_t *shape() const { return detail::array_proxy(m_ptr)->dimensions; } + + /// Dimension along a given axis + ssize_t shape(ssize_t dim) const { + if (dim >= ndim()) { + fail_dim_check(dim, "invalid axis"); + } + return shape()[dim]; + } + + /// Strides of the array + const ssize_t *strides() const { return detail::array_proxy(m_ptr)->strides; } + + /// Stride along a given axis + ssize_t strides(ssize_t dim) const { + if (dim >= ndim()) { + fail_dim_check(dim, "invalid axis"); + } + return strides()[dim]; + } + + /// Return the NumPy array flags + int flags() const { return detail::array_proxy(m_ptr)->flags; } + + /// If set, the array is writeable (otherwise the buffer is read-only) + bool writeable() const { + return detail::check_flags(m_ptr, detail::npy_api::NPY_ARRAY_WRITEABLE_); + } + + /// If set, the array owns the data (will be freed when the array is deleted) + bool owndata() const { + return detail::check_flags(m_ptr, detail::npy_api::NPY_ARRAY_OWNDATA_); + } + + /// Pointer to the contained data. If index is not provided, points to the + /// beginning of the buffer. May throw if the index would lead to out of bounds access. + template + const void *data(Ix... index) const { + return static_cast(detail::array_proxy(m_ptr)->data + offset_at(index...)); + } + + /// Mutable pointer to the contained data. If index is not provided, points to the + /// beginning of the buffer. May throw if the index would lead to out of bounds access. + /// May throw if the array is not writeable. + template + void *mutable_data(Ix... index) { + check_writeable(); + return static_cast(detail::array_proxy(m_ptr)->data + offset_at(index...)); + } + + /// Byte offset from beginning of the array to a given index (full or partial). + /// May throw if the index would lead to out of bounds access. + template + ssize_t offset_at(Ix... index) const { + if ((ssize_t) sizeof...(index) > ndim()) { + fail_dim_check(sizeof...(index), "too many indices for an array"); + } + return byte_offset(ssize_t(index)...); + } + + ssize_t offset_at() const { return 0; } + + /// Item count from beginning of the array to a given index (full or partial). + /// May throw if the index would lead to out of bounds access. + template + ssize_t index_at(Ix... index) const { + return offset_at(index...) / itemsize(); + } + + /** + * Returns a proxy object that provides access to the array's data without bounds or + * dimensionality checking. Will throw if the array is missing the `writeable` flag. Use with + * care: the array must not be destroyed or reshaped for the duration of the returned object, + * and the caller must take care not to access invalid dimensions or dimension indices. + */ + template + detail::unchecked_mutable_reference mutable_unchecked() & { + if (Dims >= 0 && ndim() != Dims) { + throw std::domain_error("array has incorrect number of dimensions: " + + std::to_string(ndim()) + "; expected " + + std::to_string(Dims)); + } + return detail::unchecked_mutable_reference( + mutable_data(), shape(), strides(), ndim()); + } + + /** + * Returns a proxy object that provides const access to the array's data without bounds or + * dimensionality checking. Unlike `mutable_unchecked()`, this does not require that the + * underlying array have the `writable` flag. Use with care: the array must not be destroyed + * or reshaped for the duration of the returned object, and the caller must take care not to + * access invalid dimensions or dimension indices. + */ + template + detail::unchecked_reference unchecked() const & { + if (Dims >= 0 && ndim() != Dims) { + throw std::domain_error("array has incorrect number of dimensions: " + + std::to_string(ndim()) + "; expected " + + std::to_string(Dims)); + } + return detail::unchecked_reference(data(), shape(), strides(), ndim()); + } + + /// Return a new view with all of the dimensions of length 1 removed + array squeeze() { + auto &api = detail::npy_api::get(); + return reinterpret_steal(api.PyArray_Squeeze_(m_ptr)); + } + + /// Resize array to given shape + /// If refcheck is true and more that one reference exist to this array + /// then resize will succeed only if it makes a reshape, i.e. original size doesn't change + void resize(ShapeContainer new_shape, bool refcheck = true) { + detail::npy_api::PyArray_Dims d + = {// Use reinterpret_cast for PyPy on Windows (remove if fixed, checked on 7.3.1) + reinterpret_cast(new_shape->data()), + int(new_shape->size())}; + // try to resize, set ordering param to -1 cause it's not used anyway + auto new_array = reinterpret_steal( + detail::npy_api::get().PyArray_Resize_(m_ptr, &d, int(refcheck), -1)); + if (!new_array) { + throw error_already_set(); + } + if (isinstance(new_array)) { + *this = std::move(new_array); + } + } + + /// Optional `order` parameter omitted, to be added as needed. + array reshape(ShapeContainer new_shape) { + detail::npy_api::PyArray_Dims d + = {reinterpret_cast(new_shape->data()), int(new_shape->size())}; + auto new_array + = reinterpret_steal(detail::npy_api::get().PyArray_Newshape_(m_ptr, &d, 0)); + if (!new_array) { + throw error_already_set(); + } + return new_array; + } + + /// Create a view of an array in a different data type. + /// This function may fundamentally reinterpret the data in the array. + /// It is the responsibility of the caller to ensure that this is safe. + /// Only supports the `dtype` argument, the `type` argument is omitted, + /// to be added as needed. + array view(const std::string &dtype) { + auto &api = detail::npy_api::get(); + auto new_view = reinterpret_steal(api.PyArray_View_( + m_ptr, dtype::from_args(pybind11::str(dtype)).release().ptr(), nullptr)); + if (!new_view) { + throw error_already_set(); + } + return new_view; + } + + /// Ensure that the argument is a NumPy array + /// In case of an error, nullptr is returned and the Python error is cleared. + static array ensure(handle h, int ExtraFlags = 0) { + auto result = reinterpret_steal(raw_array(h.ptr(), ExtraFlags)); + if (!result) { + PyErr_Clear(); + } + return result; + } + +protected: + template + friend struct detail::npy_format_descriptor; + + void fail_dim_check(ssize_t dim, const std::string &msg) const { + throw index_error(msg + ": " + std::to_string(dim) + " (ndim = " + std::to_string(ndim()) + + ')'); + } + + template + ssize_t byte_offset(Ix... index) const { + check_dimensions(index...); + return detail::byte_offset_unsafe(strides(), ssize_t(index)...); + } + + void check_writeable() const { + if (!writeable()) { + throw std::domain_error("array is not writeable"); + } + } + + template + void check_dimensions(Ix... index) const { + check_dimensions_impl(ssize_t(0), shape(), ssize_t(index)...); + } + + void check_dimensions_impl(ssize_t, const ssize_t *) const {} + + template + void check_dimensions_impl(ssize_t axis, const ssize_t *shape, ssize_t i, Ix... index) const { + if (i >= *shape) { + throw index_error(std::string("index ") + std::to_string(i) + + " is out of bounds for axis " + std::to_string(axis) + + " with size " + std::to_string(*shape)); + } + check_dimensions_impl(axis + 1, shape + 1, index...); + } + + /// Create array from any object -- always returns a new reference + static PyObject *raw_array(PyObject *ptr, int ExtraFlags = 0) { + if (ptr == nullptr) { + set_error(PyExc_ValueError, "cannot create a pybind11::array from a nullptr"); + return nullptr; + } + return detail::npy_api::get().PyArray_FromAny_( + ptr, nullptr, 0, 0, detail::npy_api::NPY_ARRAY_ENSUREARRAY_ | ExtraFlags, nullptr); + } +}; + +template +class array_t : public array { +private: + struct private_ctor {}; + // Delegating constructor needed when both moving and accessing in the same constructor + array_t(private_ctor, + ShapeContainer &&shape, + StridesContainer &&strides, + const T *ptr, + handle base) + : array(std::move(shape), std::move(strides), ptr, base) {} + +public: + static_assert(!detail::array_info::is_array, "Array types cannot be used with array_t"); + + using value_type = T; + + array_t() : array(0, static_cast(nullptr)) {} + array_t(handle h, borrowed_t) : array(h, borrowed_t{}) {} + array_t(handle h, stolen_t) : array(h, stolen_t{}) {} + + PYBIND11_DEPRECATED("Use array_t::ensure() instead") + array_t(handle h, bool is_borrowed) : array(raw_array_t(h.ptr()), stolen_t{}) { + if (!m_ptr) { + PyErr_Clear(); + } + if (!is_borrowed) { + Py_XDECREF(h.ptr()); + } + } + + // NOLINTNEXTLINE(google-explicit-constructor) + array_t(const object &o) : array(raw_array_t(o.ptr()), stolen_t{}) { + if (!m_ptr) { + throw error_already_set(); + } + } + + explicit array_t(const buffer_info &info, handle base = handle()) : array(info, base) {} + + array_t(ShapeContainer shape, + StridesContainer strides, + const T *ptr = nullptr, + handle base = handle()) + : array(std::move(shape), std::move(strides), ptr, base) {} + + explicit array_t(ShapeContainer shape, const T *ptr = nullptr, handle base = handle()) + : array_t(private_ctor{}, + std::move(shape), + (ExtraFlags & f_style) != 0 ? detail::f_strides(*shape, itemsize()) + : detail::c_strides(*shape, itemsize()), + ptr, + base) {} + + explicit array_t(ssize_t count, const T *ptr = nullptr, handle base = handle()) + : array({count}, {}, ptr, base) {} + + constexpr ssize_t itemsize() const { return sizeof(T); } + + template + ssize_t index_at(Ix... index) const { + return offset_at(index...) / itemsize(); + } + + template + const T *data(Ix... index) const { + return static_cast(array::data(index...)); + } + + template + T *mutable_data(Ix... index) { + return static_cast(array::mutable_data(index...)); + } + + // Reference to element at a given index + template + const T &at(Ix... index) const { + if ((ssize_t) sizeof...(index) != ndim()) { + fail_dim_check(sizeof...(index), "index dimension mismatch"); + } + return *(static_cast(array::data()) + + byte_offset(ssize_t(index)...) / itemsize()); + } + + // Mutable reference to element at a given index + template + T &mutable_at(Ix... index) { + if ((ssize_t) sizeof...(index) != ndim()) { + fail_dim_check(sizeof...(index), "index dimension mismatch"); + } + return *(static_cast(array::mutable_data()) + + byte_offset(ssize_t(index)...) / itemsize()); + } + + /** + * Returns a proxy object that provides access to the array's data without bounds or + * dimensionality checking. Will throw if the array is missing the `writeable` flag. Use with + * care: the array must not be destroyed or reshaped for the duration of the returned object, + * and the caller must take care not to access invalid dimensions or dimension indices. + */ + template + detail::unchecked_mutable_reference mutable_unchecked() & { + return array::mutable_unchecked(); + } + + /** + * Returns a proxy object that provides const access to the array's data without bounds or + * dimensionality checking. Unlike `mutable_unchecked()`, this does not require that the + * underlying array have the `writable` flag. Use with care: the array must not be destroyed + * or reshaped for the duration of the returned object, and the caller must take care not to + * access invalid dimensions or dimension indices. + */ + template + detail::unchecked_reference unchecked() const & { + return array::unchecked(); + } + + /// Ensure that the argument is a NumPy array of the correct dtype (and if not, try to convert + /// it). In case of an error, nullptr is returned and the Python error is cleared. + static array_t ensure(handle h) { + auto result = reinterpret_steal(raw_array_t(h.ptr())); + if (!result) { + PyErr_Clear(); + } + return result; + } + + static bool check_(handle h) { + const auto &api = detail::npy_api::get(); + return api.PyArray_Check_(h.ptr()) + && api.PyArray_EquivTypes_(detail::array_proxy(h.ptr())->descr, + dtype::of().ptr()) + && detail::check_flags(h.ptr(), ExtraFlags & (array::c_style | array::f_style)); + } + +protected: + /// Create array from any object -- always returns a new reference + static PyObject *raw_array_t(PyObject *ptr) { + if (ptr == nullptr) { + set_error(PyExc_ValueError, "cannot create a pybind11::array_t from a nullptr"); + return nullptr; + } + return detail::npy_api::get().PyArray_FromAny_(ptr, + dtype::of().release().ptr(), + 0, + 0, + detail::npy_api::NPY_ARRAY_ENSUREARRAY_ + | ExtraFlags, + nullptr); + } +}; + +template +struct format_descriptor::value>> { + static std::string format() { + return detail::npy_format_descriptor::type>::format(); + } +}; + +template +struct format_descriptor { + static std::string format() { return std::to_string(N) + 's'; } +}; +template +struct format_descriptor> { + static std::string format() { return std::to_string(N) + 's'; } +}; + +template +struct format_descriptor::value>> { + static std::string format() { + return format_descriptor< + typename std::remove_cv::type>::type>::format(); + } +}; + +template +struct format_descriptor::is_array>> { + static std::string format() { + using namespace detail; + static constexpr auto extents = const_name("(") + array_info::extents + const_name(")"); + return extents.text + format_descriptor>::format(); + } +}; + +PYBIND11_NAMESPACE_BEGIN(detail) +template +struct pyobject_caster> { + using type = array_t; + + bool load(handle src, bool convert) { + if (!convert && !type::check_(src)) { + return false; + } + value = type::ensure(src); + return static_cast(value); + } + + static handle cast(const handle &src, return_value_policy /* policy */, handle /* parent */) { + return src.inc_ref(); + } + PYBIND11_TYPE_CASTER(type, handle_type_name::name); +}; + +template +struct compare_buffer_info::value>> { + static bool compare(const buffer_info &b) { + return npy_api::get().PyArray_EquivTypes_(dtype::of().ptr(), dtype(b).ptr()); + } +}; + +template +struct npy_format_descriptor_name; + +template +struct npy_format_descriptor_name::value>> { + static constexpr auto name = const_name::value>( + const_name("bool"), + const_name::value>("numpy.int", "numpy.uint") + + const_name()); +}; + +template +struct npy_format_descriptor_name::value>> { + static constexpr auto name = const_name < std::is_same::value + || std::is_same::value + || std::is_same::value + || std::is_same::value + > (const_name("numpy.float") + const_name(), + const_name("numpy.longdouble")); +}; + +template +struct npy_format_descriptor_name::value>> { + static constexpr auto name = const_name < std::is_same::value + || std::is_same::value + || std::is_same::value + || std::is_same::value + > (const_name("numpy.complex") + + const_name(), + const_name("numpy.longcomplex")); +}; + +template +struct npy_format_descriptor< + T, + enable_if_t::value>> + : npy_format_descriptor_name { +private: + // NB: the order here must match the one in common.h + constexpr static const int values[15] = {npy_api::NPY_BOOL_, + npy_api::NPY_BYTE_, + npy_api::NPY_UBYTE_, + npy_api::NPY_INT16_, + npy_api::NPY_UINT16_, + npy_api::NPY_INT32_, + npy_api::NPY_UINT32_, + npy_api::NPY_INT64_, + npy_api::NPY_UINT64_, + npy_api::NPY_FLOAT_, + npy_api::NPY_DOUBLE_, + npy_api::NPY_LONGDOUBLE_, + npy_api::NPY_CFLOAT_, + npy_api::NPY_CDOUBLE_, + npy_api::NPY_CLONGDOUBLE_}; + +public: + static constexpr int value = values[detail::is_fmt_numeric::index]; + + static pybind11::dtype dtype() { return pybind11::dtype(/*typenum*/ value); } +}; + +template +struct npy_format_descriptor::value>> { + static constexpr auto name = const_name("object"); + + static constexpr int value = npy_api::NPY_OBJECT_; + + static pybind11::dtype dtype() { return pybind11::dtype(/*typenum*/ value); } +}; + +#define PYBIND11_DECL_CHAR_FMT \ + static constexpr auto name = const_name("S") + const_name(); \ + static pybind11::dtype dtype() { \ + return pybind11::dtype(std::string("S") + std::to_string(N)); \ + } +template +struct npy_format_descriptor { + PYBIND11_DECL_CHAR_FMT +}; +template +struct npy_format_descriptor> { + PYBIND11_DECL_CHAR_FMT +}; +#undef PYBIND11_DECL_CHAR_FMT + +template +struct npy_format_descriptor::is_array>> { +private: + using base_descr = npy_format_descriptor::type>; + +public: + static_assert(!array_info::is_empty, "Zero-sized arrays are not supported"); + + static constexpr auto name + = const_name("(") + array_info::extents + const_name(")") + base_descr::name; + static pybind11::dtype dtype() { + list shape; + array_info::append_extents(shape); + return pybind11::dtype::from_args( + pybind11::make_tuple(base_descr::dtype(), std::move(shape))); + } +}; + +template +struct npy_format_descriptor::value>> { +private: + using base_descr = npy_format_descriptor::type>; + +public: + static constexpr auto name = base_descr::name; + static pybind11::dtype dtype() { return base_descr::dtype(); } +}; + +struct field_descriptor { + const char *name; + ssize_t offset; + ssize_t size; + std::string format; + dtype descr; +}; + +PYBIND11_NOINLINE void register_structured_dtype(any_container fields, + const std::type_info &tinfo, + ssize_t itemsize, + bool (*direct_converter)(PyObject *, void *&)) { + + auto &numpy_internals = get_numpy_internals(); + if (numpy_internals.get_type_info(tinfo, false)) { + pybind11_fail("NumPy: dtype is already registered"); + } + + // Use ordered fields because order matters as of NumPy 1.14: + // https://docs.scipy.org/doc/numpy/release.html#multiple-field-indexing-assignment-of-structured-arrays + std::vector ordered_fields(std::move(fields)); + std::sort( + ordered_fields.begin(), + ordered_fields.end(), + [](const field_descriptor &a, const field_descriptor &b) { return a.offset < b.offset; }); + + list names, formats, offsets; + for (auto &field : ordered_fields) { + if (!field.descr) { + pybind11_fail(std::string("NumPy: unsupported field dtype: `") + field.name + "` @ " + + tinfo.name()); + } + names.append(pybind11::str(field.name)); + formats.append(field.descr); + offsets.append(pybind11::int_(field.offset)); + } + auto *dtype_ptr + = pybind11::dtype(std::move(names), std::move(formats), std::move(offsets), itemsize) + .release() + .ptr(); + + // There is an existing bug in NumPy (as of v1.11): trailing bytes are + // not encoded explicitly into the format string. This will supposedly + // get fixed in v1.12; for further details, see these: + // - https://github.com/numpy/numpy/issues/7797 + // - https://github.com/numpy/numpy/pull/7798 + // Because of this, we won't use numpy's logic to generate buffer format + // strings and will just do it ourselves. + ssize_t offset = 0; + std::ostringstream oss; + // mark the structure as unaligned with '^', because numpy and C++ don't + // always agree about alignment (particularly for complex), and we're + // explicitly listing all our padding. This depends on none of the fields + // overriding the endianness. Putting the ^ in front of individual fields + // isn't guaranteed to work due to https://github.com/numpy/numpy/issues/9049 + oss << "^T{"; + for (auto &field : ordered_fields) { + if (field.offset > offset) { + oss << (field.offset - offset) << 'x'; + } + oss << field.format << ':' << field.name << ':'; + offset = field.offset + field.size; + } + if (itemsize > offset) { + oss << (itemsize - offset) << 'x'; + } + oss << '}'; + auto format_str = oss.str(); + + // Smoke test: verify that NumPy properly parses our buffer format string + auto &api = npy_api::get(); + auto arr = array(buffer_info(nullptr, itemsize, format_str, 1)); + if (!api.PyArray_EquivTypes_(dtype_ptr, arr.dtype().ptr())) { + pybind11_fail("NumPy: invalid buffer descriptor!"); + } + + auto tindex = std::type_index(tinfo); + numpy_internals.registered_dtypes[tindex] = {dtype_ptr, std::move(format_str)}; + with_internals([tindex, &direct_converter](internals &internals) { + internals.direct_conversions[tindex].push_back(direct_converter); + }); +} + +template +struct npy_format_descriptor { + static_assert(is_pod_struct::value, + "Attempt to use a non-POD or unimplemented POD type as a numpy dtype"); + + static constexpr auto name = make_caster::name; + + static pybind11::dtype dtype() { return reinterpret_borrow(dtype_ptr()); } + + static std::string format() { + static auto format_str = get_numpy_internals().get_type_info(true)->format_str; + return format_str; + } + + static void register_dtype(any_container fields) { + register_structured_dtype(std::move(fields), + typeid(typename std::remove_cv::type), + sizeof(T), + &direct_converter); + } + +private: + static PyObject *dtype_ptr() { + static PyObject *ptr = get_numpy_internals().get_type_info(true)->dtype_ptr; + return ptr; + } + + static bool direct_converter(PyObject *obj, void *&value) { + auto &api = npy_api::get(); + if (!PyObject_TypeCheck(obj, api.PyVoidArrType_Type_)) { + return false; + } + if (auto descr = reinterpret_steal(api.PyArray_DescrFromScalar_(obj))) { + if (api.PyArray_EquivTypes_(dtype_ptr(), descr.ptr())) { + value = ((PyVoidScalarObject_Proxy *) obj)->obval; + return true; + } + } + return false; + } +}; + +#ifdef __CLION_IDE__ // replace heavy macro with dummy code for the IDE (doesn't affect code) +# define PYBIND11_NUMPY_DTYPE(Type, ...) ((void) 0) +# define PYBIND11_NUMPY_DTYPE_EX(Type, ...) ((void) 0) +#else + +# define PYBIND11_FIELD_DESCRIPTOR_EX(T, Field, Name) \ + ::pybind11::detail::field_descriptor { \ + Name, offsetof(T, Field), sizeof(decltype(std::declval().Field)), \ + ::pybind11::format_descriptor().Field)>::format(), \ + ::pybind11::detail::npy_format_descriptor< \ + decltype(std::declval().Field)>::dtype() \ + } + +// Extract name, offset and format descriptor for a struct field +# define PYBIND11_FIELD_DESCRIPTOR(T, Field) PYBIND11_FIELD_DESCRIPTOR_EX(T, Field, #Field) + +// The main idea of this macro is borrowed from https://github.com/swansontec/map-macro +// (C) William Swanson, Paul Fultz +# define PYBIND11_EVAL0(...) __VA_ARGS__ +# define PYBIND11_EVAL1(...) PYBIND11_EVAL0(PYBIND11_EVAL0(PYBIND11_EVAL0(__VA_ARGS__))) +# define PYBIND11_EVAL2(...) PYBIND11_EVAL1(PYBIND11_EVAL1(PYBIND11_EVAL1(__VA_ARGS__))) +# define PYBIND11_EVAL3(...) PYBIND11_EVAL2(PYBIND11_EVAL2(PYBIND11_EVAL2(__VA_ARGS__))) +# define PYBIND11_EVAL4(...) PYBIND11_EVAL3(PYBIND11_EVAL3(PYBIND11_EVAL3(__VA_ARGS__))) +# define PYBIND11_EVAL(...) PYBIND11_EVAL4(PYBIND11_EVAL4(PYBIND11_EVAL4(__VA_ARGS__))) +# define PYBIND11_MAP_END(...) +# define PYBIND11_MAP_OUT +# define PYBIND11_MAP_COMMA , +# define PYBIND11_MAP_GET_END() 0, PYBIND11_MAP_END +# define PYBIND11_MAP_NEXT0(test, next, ...) next PYBIND11_MAP_OUT +# define PYBIND11_MAP_NEXT1(test, next) PYBIND11_MAP_NEXT0(test, next, 0) +# define PYBIND11_MAP_NEXT(test, next) PYBIND11_MAP_NEXT1(PYBIND11_MAP_GET_END test, next) +# if defined(_MSC_VER) \ + && !defined(__clang__) // MSVC is not as eager to expand macros, hence this workaround +# define PYBIND11_MAP_LIST_NEXT1(test, next) \ + PYBIND11_EVAL0(PYBIND11_MAP_NEXT0(test, PYBIND11_MAP_COMMA next, 0)) +# else +# define PYBIND11_MAP_LIST_NEXT1(test, next) \ + PYBIND11_MAP_NEXT0(test, PYBIND11_MAP_COMMA next, 0) +# endif +# define PYBIND11_MAP_LIST_NEXT(test, next) \ + PYBIND11_MAP_LIST_NEXT1(PYBIND11_MAP_GET_END test, next) +# define PYBIND11_MAP_LIST0(f, t, x, peek, ...) \ + f(t, x) PYBIND11_MAP_LIST_NEXT(peek, PYBIND11_MAP_LIST1)(f, t, peek, __VA_ARGS__) +# define PYBIND11_MAP_LIST1(f, t, x, peek, ...) \ + f(t, x) PYBIND11_MAP_LIST_NEXT(peek, PYBIND11_MAP_LIST0)(f, t, peek, __VA_ARGS__) +// PYBIND11_MAP_LIST(f, t, a1, a2, ...) expands to f(t, a1), f(t, a2), ... +# define PYBIND11_MAP_LIST(f, t, ...) \ + PYBIND11_EVAL(PYBIND11_MAP_LIST1(f, t, __VA_ARGS__, (), 0)) + +# define PYBIND11_NUMPY_DTYPE(Type, ...) \ + ::pybind11::detail::npy_format_descriptor::register_dtype( \ + ::std::vector<::pybind11::detail::field_descriptor>{ \ + PYBIND11_MAP_LIST(PYBIND11_FIELD_DESCRIPTOR, Type, __VA_ARGS__)}) + +# if defined(_MSC_VER) && !defined(__clang__) +# define PYBIND11_MAP2_LIST_NEXT1(test, next) \ + PYBIND11_EVAL0(PYBIND11_MAP_NEXT0(test, PYBIND11_MAP_COMMA next, 0)) +# else +# define PYBIND11_MAP2_LIST_NEXT1(test, next) \ + PYBIND11_MAP_NEXT0(test, PYBIND11_MAP_COMMA next, 0) +# endif +# define PYBIND11_MAP2_LIST_NEXT(test, next) \ + PYBIND11_MAP2_LIST_NEXT1(PYBIND11_MAP_GET_END test, next) +# define PYBIND11_MAP2_LIST0(f, t, x1, x2, peek, ...) \ + f(t, x1, x2) PYBIND11_MAP2_LIST_NEXT(peek, PYBIND11_MAP2_LIST1)(f, t, peek, __VA_ARGS__) +# define PYBIND11_MAP2_LIST1(f, t, x1, x2, peek, ...) \ + f(t, x1, x2) PYBIND11_MAP2_LIST_NEXT(peek, PYBIND11_MAP2_LIST0)(f, t, peek, __VA_ARGS__) +// PYBIND11_MAP2_LIST(f, t, a1, a2, ...) expands to f(t, a1, a2), f(t, a3, a4), ... +# define PYBIND11_MAP2_LIST(f, t, ...) \ + PYBIND11_EVAL(PYBIND11_MAP2_LIST1(f, t, __VA_ARGS__, (), 0)) + +# define PYBIND11_NUMPY_DTYPE_EX(Type, ...) \ + ::pybind11::detail::npy_format_descriptor::register_dtype( \ + ::std::vector<::pybind11::detail::field_descriptor>{ \ + PYBIND11_MAP2_LIST(PYBIND11_FIELD_DESCRIPTOR_EX, Type, __VA_ARGS__)}) + +#endif // __CLION_IDE__ + +class common_iterator { +public: + using container_type = std::vector; + using value_type = container_type::value_type; + using size_type = container_type::size_type; + + common_iterator() : m_strides() {} + + common_iterator(void *ptr, const container_type &strides, const container_type &shape) + : p_ptr(reinterpret_cast(ptr)), m_strides(strides.size()) { + m_strides.back() = static_cast(strides.back()); + for (size_type i = m_strides.size() - 1; i != 0; --i) { + size_type j = i - 1; + auto s = static_cast(shape[i]); + m_strides[j] = strides[j] + m_strides[i] - strides[i] * s; + } + } + + void increment(size_type dim) { p_ptr += m_strides[dim]; } + + void *data() const { return p_ptr; } + +private: + char *p_ptr{nullptr}; + container_type m_strides; +}; + +template +class multi_array_iterator { +public: + using container_type = std::vector; + + multi_array_iterator(const std::array &buffers, const container_type &shape) + : m_shape(shape.size()), m_index(shape.size(), 0), m_common_iterator() { + + // Manual copy to avoid conversion warning if using std::copy + for (size_t i = 0; i < shape.size(); ++i) { + m_shape[i] = shape[i]; + } + + container_type strides(shape.size()); + for (size_t i = 0; i < N; ++i) { + init_common_iterator(buffers[i], shape, m_common_iterator[i], strides); + } + } + + multi_array_iterator &operator++() { + for (size_t j = m_index.size(); j != 0; --j) { + size_t i = j - 1; + if (++m_index[i] != m_shape[i]) { + increment_common_iterator(i); + break; + } + m_index[i] = 0; + } + return *this; + } + + template + T *data() const { + return reinterpret_cast(m_common_iterator[K].data()); + } + +private: + using common_iter = common_iterator; + + void init_common_iterator(const buffer_info &buffer, + const container_type &shape, + common_iter &iterator, + container_type &strides) { + auto buffer_shape_iter = buffer.shape.rbegin(); + auto buffer_strides_iter = buffer.strides.rbegin(); + auto shape_iter = shape.rbegin(); + auto strides_iter = strides.rbegin(); + + while (buffer_shape_iter != buffer.shape.rend()) { + if (*shape_iter == *buffer_shape_iter) { + *strides_iter = *buffer_strides_iter; + } else { + *strides_iter = 0; + } + + ++buffer_shape_iter; + ++buffer_strides_iter; + ++shape_iter; + ++strides_iter; + } + + std::fill(strides_iter, strides.rend(), 0); + iterator = common_iter(buffer.ptr, strides, shape); + } + + void increment_common_iterator(size_t dim) { + for (auto &iter : m_common_iterator) { + iter.increment(dim); + } + } + + container_type m_shape; + container_type m_index; + std::array m_common_iterator; +}; + +enum class broadcast_trivial { non_trivial, c_trivial, f_trivial }; + +// Populates the shape and number of dimensions for the set of buffers. Returns a +// broadcast_trivial enum value indicating whether the broadcast is "trivial"--that is, has each +// buffer being either a singleton or a full-size, C-contiguous (`c_trivial`) or Fortran-contiguous +// (`f_trivial`) storage buffer; returns `non_trivial` otherwise. +template +broadcast_trivial +broadcast(const std::array &buffers, ssize_t &ndim, std::vector &shape) { + ndim = std::accumulate( + buffers.begin(), buffers.end(), ssize_t(0), [](ssize_t res, const buffer_info &buf) { + return std::max(res, buf.ndim); + }); + + shape.clear(); + shape.resize((size_t) ndim, 1); + + // Figure out the output size, and make sure all input arrays conform (i.e. are either size 1 + // or the full size). + for (size_t i = 0; i < N; ++i) { + auto res_iter = shape.rbegin(); + auto end = buffers[i].shape.rend(); + for (auto shape_iter = buffers[i].shape.rbegin(); shape_iter != end; + ++shape_iter, ++res_iter) { + const auto &dim_size_in = *shape_iter; + auto &dim_size_out = *res_iter; + + // Each input dimension can either be 1 or `n`, but `n` values must match across + // buffers + if (dim_size_out == 1) { + dim_size_out = dim_size_in; + } else if (dim_size_in != 1 && dim_size_in != dim_size_out) { + pybind11_fail("pybind11::vectorize: incompatible size/dimension of inputs!"); + } + } + } + + bool trivial_broadcast_c = true; + bool trivial_broadcast_f = true; + for (size_t i = 0; i < N && (trivial_broadcast_c || trivial_broadcast_f); ++i) { + if (buffers[i].size == 1) { + continue; + } + + // Require the same number of dimensions: + if (buffers[i].ndim != ndim) { + return broadcast_trivial::non_trivial; + } + + // Require all dimensions be full-size: + if (!std::equal(buffers[i].shape.cbegin(), buffers[i].shape.cend(), shape.cbegin())) { + return broadcast_trivial::non_trivial; + } + + // Check for C contiguity (but only if previous inputs were also C contiguous) + if (trivial_broadcast_c) { + ssize_t expect_stride = buffers[i].itemsize; + auto end = buffers[i].shape.crend(); + for (auto shape_iter = buffers[i].shape.crbegin(), + stride_iter = buffers[i].strides.crbegin(); + trivial_broadcast_c && shape_iter != end; + ++shape_iter, ++stride_iter) { + if (expect_stride == *stride_iter) { + expect_stride *= *shape_iter; + } else { + trivial_broadcast_c = false; + } + } + } + + // Check for Fortran contiguity (if previous inputs were also F contiguous) + if (trivial_broadcast_f) { + ssize_t expect_stride = buffers[i].itemsize; + auto end = buffers[i].shape.cend(); + for (auto shape_iter = buffers[i].shape.cbegin(), + stride_iter = buffers[i].strides.cbegin(); + trivial_broadcast_f && shape_iter != end; + ++shape_iter, ++stride_iter) { + if (expect_stride == *stride_iter) { + expect_stride *= *shape_iter; + } else { + trivial_broadcast_f = false; + } + } + } + } + + return trivial_broadcast_c ? broadcast_trivial::c_trivial + : trivial_broadcast_f ? broadcast_trivial::f_trivial + : broadcast_trivial::non_trivial; +} + +template +struct vectorize_arg { + static_assert(!std::is_rvalue_reference::value, + "Functions with rvalue reference arguments cannot be vectorized"); + // The wrapped function gets called with this type: + using call_type = remove_reference_t; + // Is this a vectorized argument? + static constexpr bool vectorize + = satisfies_any_of::value + && satisfies_none_of::value + && (!std::is_reference::value + || (std::is_lvalue_reference::value && std::is_const::value)); + // Accept this type: an array for vectorized types, otherwise the type as-is: + using type = conditional_t, array::forcecast>, T>; +}; + +// py::vectorize when a return type is present +template +struct vectorize_returned_array { + using Type = array_t; + + static Type create(broadcast_trivial trivial, const std::vector &shape) { + if (trivial == broadcast_trivial::f_trivial) { + return array_t(shape); + } + return array_t(shape); + } + + static Return *mutable_data(Type &array) { return array.mutable_data(); } + + static Return call(Func &f, Args &...args) { return f(args...); } + + static void call(Return *out, size_t i, Func &f, Args &...args) { out[i] = f(args...); } +}; + +// py::vectorize when a return type is not present +template +struct vectorize_returned_array { + using Type = none; + + static Type create(broadcast_trivial, const std::vector &) { return none(); } + + static void *mutable_data(Type &) { return nullptr; } + + static detail::void_type call(Func &f, Args &...args) { + f(args...); + return {}; + } + + static void call(void *, size_t, Func &f, Args &...args) { f(args...); } +}; + +template +struct vectorize_helper { + +// NVCC for some reason breaks if NVectorized is private +#ifdef __CUDACC__ +public: +#else +private: +#endif + + static constexpr size_t N = sizeof...(Args); + static constexpr size_t NVectorized = constexpr_sum(vectorize_arg::vectorize...); + static_assert( + NVectorized >= 1, + "pybind11::vectorize(...) requires a function with at least one vectorizable argument"); + +public: + template ::type>::value>> + explicit vectorize_helper(T &&f) : f(std::forward(f)) {} + + object operator()(typename vectorize_arg::type... args) { + return run(args..., + make_index_sequence(), + select_indices::vectorize...>(), + make_index_sequence()); + } + +private: + remove_reference_t f; + + // Internal compiler error in MSVC 19.16.27025.1 (Visual Studio 2017 15.9.4), when compiling + // with "/permissive-" flag when arg_call_types is manually inlined. + using arg_call_types = std::tuple::call_type...>; + template + using param_n_t = typename std::tuple_element::type; + + using returned_array = vectorize_returned_array; + + // Runs a vectorized function given arguments tuple and three index sequences: + // - Index is the full set of 0 ... (N-1) argument indices; + // - VIndex is the subset of argument indices with vectorized parameters, letting us access + // vectorized arguments (anything not in this sequence is passed through) + // - BIndex is a incremental sequence (beginning at 0) of the same size as VIndex, so that + // we can store vectorized buffer_infos in an array (argument VIndex has its buffer at + // index BIndex in the array). + template + object run(typename vectorize_arg::type &...args, + index_sequence i_seq, + index_sequence vi_seq, + index_sequence bi_seq) { + + // Pointers to values the function was called with; the vectorized ones set here will start + // out as array_t pointers, but they will be changed them to T pointers before we make + // call the wrapped function. Non-vectorized pointers are left as-is. + std::array params{{reinterpret_cast(&args)...}}; + + // The array of `buffer_info`s of vectorized arguments: + std::array buffers{ + {reinterpret_cast(params[VIndex])->request()...}}; + + /* Determine dimensions parameters of output array */ + ssize_t nd = 0; + std::vector shape(0); + auto trivial = broadcast(buffers, nd, shape); + auto ndim = (size_t) nd; + + size_t size + = std::accumulate(shape.begin(), shape.end(), (size_t) 1, std::multiplies()); + + // If all arguments are 0-dimension arrays (i.e. single values) return a plain value (i.e. + // not wrapped in an array). + if (size == 1 && ndim == 0) { + PYBIND11_EXPAND_SIDE_EFFECTS(params[VIndex] = buffers[BIndex].ptr); + return cast( + returned_array::call(f, *reinterpret_cast *>(params[Index])...)); + } + + auto result = returned_array::create(trivial, shape); + + PYBIND11_WARNING_PUSH +#ifdef PYBIND11_DETECTED_CLANG_WITH_MISLEADING_CALL_STD_MOVE_EXPLICITLY_WARNING + PYBIND11_WARNING_DISABLE_CLANG("-Wreturn-std-move") +#endif + + if (size == 0) { + return result; + } + + /* Call the function */ + auto *mutable_data = returned_array::mutable_data(result); + if (trivial == broadcast_trivial::non_trivial) { + apply_broadcast(buffers, params, mutable_data, size, shape, i_seq, vi_seq, bi_seq); + } else { + apply_trivial(buffers, params, mutable_data, size, i_seq, vi_seq, bi_seq); + } + + return result; + PYBIND11_WARNING_POP + } + + template + void apply_trivial(std::array &buffers, + std::array ¶ms, + Return *out, + size_t size, + index_sequence, + index_sequence, + index_sequence) { + + // Initialize an array of mutable byte references and sizes with references set to the + // appropriate pointer in `params`; as we iterate, we'll increment each pointer by its size + // (except for singletons, which get an increment of 0). + std::array, NVectorized> vecparams{ + {std::pair( + reinterpret_cast(params[VIndex] = buffers[BIndex].ptr), + buffers[BIndex].size == 1 ? 0 : sizeof(param_n_t))...}}; + + for (size_t i = 0; i < size; ++i) { + returned_array::call( + out, i, f, *reinterpret_cast *>(params[Index])...); + for (auto &x : vecparams) { + x.first += x.second; + } + } + } + + template + void apply_broadcast(std::array &buffers, + std::array ¶ms, + Return *out, + size_t size, + const std::vector &output_shape, + index_sequence, + index_sequence, + index_sequence) { + + multi_array_iterator input_iter(buffers, output_shape); + + for (size_t i = 0; i < size; ++i, ++input_iter) { + PYBIND11_EXPAND_SIDE_EFFECTS((params[VIndex] = input_iter.template data())); + returned_array::call( + out, i, f, *reinterpret_cast *>(std::get(params))...); + } + } +}; + +template +vectorize_helper vectorize_extractor(const Func &f, Return (*)(Args...)) { + return detail::vectorize_helper(f); +} + +template +struct handle_type_name> { + static constexpr auto name + = const_name("numpy.ndarray[") + npy_format_descriptor::name + const_name("]"); +}; + +PYBIND11_NAMESPACE_END(detail) + +// Vanilla pointer vectorizer: +template +detail::vectorize_helper vectorize(Return (*f)(Args...)) { + return detail::vectorize_helper(f); +} + +// lambda vectorizer: +template ::value, int> = 0> +auto vectorize(Func &&f) + -> decltype(detail::vectorize_extractor(std::forward(f), + (detail::function_signature_t *) nullptr)) { + return detail::vectorize_extractor(std::forward(f), + (detail::function_signature_t *) nullptr); +} + +// Vectorize a class method (non-const): +template ())), + Return, + Class *, + Args...>> +Helper vectorize(Return (Class::*f)(Args...)) { + return Helper(std::mem_fn(f)); +} + +// Vectorize a class method (const): +template ())), + Return, + const Class *, + Args...>> +Helper vectorize(Return (Class::*f)(Args...) const) { + return Helper(std::mem_fn(f)); +} + +PYBIND11_NAMESPACE_END(PYBIND11_NAMESPACE) diff --git a/infer_4_30_0/lib/python3.10/site-packages/pybind11/include/pybind11/pytypes.h b/infer_4_30_0/lib/python3.10/site-packages/pybind11/include/pybind11/pytypes.h new file mode 100644 index 0000000000000000000000000000000000000000..1e76d7bc136c6e3de2ec693161dc9328eda52cd6 --- /dev/null +++ b/infer_4_30_0/lib/python3.10/site-packages/pybind11/include/pybind11/pytypes.h @@ -0,0 +1,2606 @@ +/* + pybind11/pytypes.h: Convenience wrapper classes for basic Python types + + Copyright (c) 2016 Wenzel Jakob + + All rights reserved. Use of this source code is governed by a + BSD-style license that can be found in the LICENSE file. +*/ + +#pragma once + +#include "detail/common.h" +#include "buffer_info.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#if defined(PYBIND11_HAS_OPTIONAL) +# include +#endif + +#ifdef PYBIND11_HAS_STRING_VIEW +# include +#endif + +PYBIND11_NAMESPACE_BEGIN(PYBIND11_NAMESPACE) + +PYBIND11_WARNING_DISABLE_MSVC(4127) + +/* A few forward declarations */ +class handle; +class object; +class str; +class iterator; +class type; +struct arg; +struct arg_v; + +PYBIND11_NAMESPACE_BEGIN(detail) +class args_proxy; +bool isinstance_generic(handle obj, const std::type_info &tp); + +// Accessor forward declarations +template +class accessor; +namespace accessor_policies { +struct obj_attr; +struct str_attr; +struct generic_item; +struct sequence_item; +struct list_item; +struct tuple_item; +} // namespace accessor_policies +// PLEASE KEEP handle_type_name SPECIALIZATIONS IN SYNC. +using obj_attr_accessor = accessor; +using str_attr_accessor = accessor; +using item_accessor = accessor; +using sequence_accessor = accessor; +using list_accessor = accessor; +using tuple_accessor = accessor; + +/// Tag and check to identify a class which implements the Python object API +class pyobject_tag {}; +template +using is_pyobject = std::is_base_of>; + +/** \rst + A mixin class which adds common functions to `handle`, `object` and various accessors. + The only requirement for `Derived` is to implement ``PyObject *Derived::ptr() const``. +\endrst */ +template +class object_api : public pyobject_tag { + const Derived &derived() const { return static_cast(*this); } + +public: + /** \rst + Return an iterator equivalent to calling ``iter()`` in Python. The object + must be a collection which supports the iteration protocol. + \endrst */ + iterator begin() const; + /// Return a sentinel which ends iteration. + iterator end() const; + + /** \rst + Return an internal functor to invoke the object's sequence protocol. Casting + the returned ``detail::item_accessor`` instance to a `handle` or `object` + subclass causes a corresponding call to ``__getitem__``. Assigning a `handle` + or `object` subclass causes a call to ``__setitem__``. + \endrst */ + item_accessor operator[](handle key) const; + /// See above (the only difference is that the key's reference is stolen) + item_accessor operator[](object &&key) const; + /// See above (the only difference is that the key is provided as a string literal) + item_accessor operator[](const char *key) const; + + /** \rst + Return an internal functor to access the object's attributes. Casting the + returned ``detail::obj_attr_accessor`` instance to a `handle` or `object` + subclass causes a corresponding call to ``getattr``. Assigning a `handle` + or `object` subclass causes a call to ``setattr``. + \endrst */ + obj_attr_accessor attr(handle key) const; + /// See above (the only difference is that the key's reference is stolen) + obj_attr_accessor attr(object &&key) const; + /// See above (the only difference is that the key is provided as a string literal) + str_attr_accessor attr(const char *key) const; + + /** \rst + Matches * unpacking in Python, e.g. to unpack arguments out of a ``tuple`` + or ``list`` for a function call. Applying another * to the result yields + ** unpacking, e.g. to unpack a dict as function keyword arguments. + See :ref:`calling_python_functions`. + \endrst */ + args_proxy operator*() const; + + /// Check if the given item is contained within this object, i.e. ``item in obj``. + template + bool contains(T &&item) const; + + /** \rst + Assuming the Python object is a function or implements the ``__call__`` + protocol, ``operator()`` invokes the underlying function, passing an + arbitrary set of parameters. The result is returned as a `object` and + may need to be converted back into a Python object using `handle::cast()`. + + When some of the arguments cannot be converted to Python objects, the + function will throw a `cast_error` exception. When the Python function + call fails, a `error_already_set` exception is thrown. + \endrst */ + template + object operator()(Args &&...args) const; + template + PYBIND11_DEPRECATED("call(...) was deprecated in favor of operator()(...)") + object call(Args &&...args) const; + + /// Equivalent to ``obj is other`` in Python. + bool is(object_api const &other) const { return derived().ptr() == other.derived().ptr(); } + /// Equivalent to ``obj is None`` in Python. + bool is_none() const { return derived().ptr() == Py_None; } + /// Equivalent to obj == other in Python + bool equal(object_api const &other) const { return rich_compare(other, Py_EQ); } + bool not_equal(object_api const &other) const { return rich_compare(other, Py_NE); } + bool operator<(object_api const &other) const { return rich_compare(other, Py_LT); } + bool operator<=(object_api const &other) const { return rich_compare(other, Py_LE); } + bool operator>(object_api const &other) const { return rich_compare(other, Py_GT); } + bool operator>=(object_api const &other) const { return rich_compare(other, Py_GE); } + + object operator-() const; + object operator~() const; + object operator+(object_api const &other) const; + object operator+=(object_api const &other); + object operator-(object_api const &other) const; + object operator-=(object_api const &other); + object operator*(object_api const &other) const; + object operator*=(object_api const &other); + object operator/(object_api const &other) const; + object operator/=(object_api const &other); + object operator|(object_api const &other) const; + object operator|=(object_api const &other); + object operator&(object_api const &other) const; + object operator&=(object_api const &other); + object operator^(object_api const &other) const; + object operator^=(object_api const &other); + object operator<<(object_api const &other) const; + object operator<<=(object_api const &other); + object operator>>(object_api const &other) const; + object operator>>=(object_api const &other); + + PYBIND11_DEPRECATED("Use py::str(obj) instead") + pybind11::str str() const; + + /// Get or set the object's docstring, i.e. ``obj.__doc__``. + str_attr_accessor doc() const; + + /// Return the object's current reference count + ssize_t ref_count() const { +#ifdef PYPY_VERSION + // PyPy uses the top few bits for REFCNT_FROM_PYPY & REFCNT_FROM_PYPY_LIGHT + // Following pybind11 2.12.1 and older behavior and removing this part + return static_cast(static_cast(Py_REFCNT(derived().ptr()))); +#else + return Py_REFCNT(derived().ptr()); +#endif + } + + // TODO PYBIND11_DEPRECATED( + // "Call py::type::handle_of(h) or py::type::of(h) instead of h.get_type()") + handle get_type() const; + +private: + bool rich_compare(object_api const &other, int value) const; +}; + +template +using is_pyobj_ptr_or_nullptr_t = detail::any_of, + std::is_same, + std::is_same>; + +PYBIND11_NAMESPACE_END(detail) + +#if !defined(PYBIND11_HANDLE_REF_DEBUG) && !defined(NDEBUG) +# define PYBIND11_HANDLE_REF_DEBUG +#endif + +/** \rst + Holds a reference to a Python object (no reference counting) + + The `handle` class is a thin wrapper around an arbitrary Python object (i.e. a + ``PyObject *`` in Python's C API). It does not perform any automatic reference + counting and merely provides a basic C++ interface to various Python API functions. + + .. seealso:: + The `object` class inherits from `handle` and adds automatic reference + counting features. +\endrst */ +class handle : public detail::object_api { +public: + /// The default constructor creates a handle with a ``nullptr``-valued pointer + handle() = default; + + /// Enable implicit conversion from ``PyObject *`` and ``nullptr``. + /// Not using ``handle(PyObject *ptr)`` to avoid implicit conversion from ``0``. + template ::value, int> = 0> + // NOLINTNEXTLINE(google-explicit-constructor) + handle(T ptr) : m_ptr(ptr) {} + + /// Enable implicit conversion through ``T::operator PyObject *()``. + template < + typename T, + detail::enable_if_t, + detail::is_pyobj_ptr_or_nullptr_t>, + std::is_convertible>::value, + int> + = 0> + // NOLINTNEXTLINE(google-explicit-constructor) + handle(T &obj) : m_ptr(obj) {} + + /// Return the underlying ``PyObject *`` pointer + PyObject *ptr() const { return m_ptr; } + PyObject *&ptr() { return m_ptr; } + + /** \rst + Manually increase the reference count of the Python object. Usually, it is + preferable to use the `object` class which derives from `handle` and calls + this function automatically. Returns a reference to itself. + \endrst */ + const handle &inc_ref() const & { +#ifdef PYBIND11_HANDLE_REF_DEBUG + inc_ref_counter(1); +#endif +#ifdef PYBIND11_ASSERT_GIL_HELD_INCREF_DECREF + if (m_ptr != nullptr && !PyGILState_Check()) { + throw_gilstate_error("pybind11::handle::inc_ref()"); + } +#endif + Py_XINCREF(m_ptr); + return *this; + } + + /** \rst + Manually decrease the reference count of the Python object. Usually, it is + preferable to use the `object` class which derives from `handle` and calls + this function automatically. Returns a reference to itself. + \endrst */ + const handle &dec_ref() const & { +#ifdef PYBIND11_ASSERT_GIL_HELD_INCREF_DECREF + if (m_ptr != nullptr && !PyGILState_Check()) { + throw_gilstate_error("pybind11::handle::dec_ref()"); + } +#endif + Py_XDECREF(m_ptr); + return *this; + } + + /** \rst + Attempt to cast the Python object into the given C++ type. A `cast_error` + will be throw upon failure. + \endrst */ + template + T cast() const; + /// Return ``true`` when the `handle` wraps a valid Python object + explicit operator bool() const { return m_ptr != nullptr; } + /** \rst + Deprecated: Check that the underlying pointers are the same. + Equivalent to ``obj1 is obj2`` in Python. + \endrst */ + PYBIND11_DEPRECATED("Use obj1.is(obj2) instead") + bool operator==(const handle &h) const { return m_ptr == h.m_ptr; } + PYBIND11_DEPRECATED("Use !obj1.is(obj2) instead") + bool operator!=(const handle &h) const { return m_ptr != h.m_ptr; } + PYBIND11_DEPRECATED("Use handle::operator bool() instead") + bool check() const { return m_ptr != nullptr; } + +protected: + PyObject *m_ptr = nullptr; + +private: +#ifdef PYBIND11_ASSERT_GIL_HELD_INCREF_DECREF + void throw_gilstate_error(const std::string &function_name) const { + fprintf( + stderr, + "%s is being called while the GIL is either not held or invalid. Please see " + "https://pybind11.readthedocs.io/en/stable/advanced/" + "misc.html#common-sources-of-global-interpreter-lock-errors for debugging advice.\n" + "If you are convinced there is no bug in your code, you can #define " + "PYBIND11_NO_ASSERT_GIL_HELD_INCREF_DECREF " + "to disable this check. In that case you have to ensure this #define is consistently " + "used for all translation units linked into a given pybind11 extension, otherwise " + "there will be ODR violations.", + function_name.c_str()); + if (Py_TYPE(m_ptr)->tp_name != nullptr) { + fprintf(stderr, + " The failing %s call was triggered on a %s object.", + function_name.c_str(), + Py_TYPE(m_ptr)->tp_name); + } + fprintf(stderr, "\n"); + fflush(stderr); + throw std::runtime_error(function_name + " PyGILState_Check() failure."); + } +#endif + +#ifdef PYBIND11_HANDLE_REF_DEBUG + static std::size_t inc_ref_counter(std::size_t add) { + thread_local std::size_t counter = 0; + counter += add; + return counter; + } + +public: + static std::size_t inc_ref_counter() { return inc_ref_counter(0); } +#endif +}; + +inline void set_error(const handle &type, const char *message) { + PyErr_SetString(type.ptr(), message); +} + +inline void set_error(const handle &type, const handle &value) { + PyErr_SetObject(type.ptr(), value.ptr()); +} + +/** \rst + Holds a reference to a Python object (with reference counting) + + Like `handle`, the `object` class is a thin wrapper around an arbitrary Python + object (i.e. a ``PyObject *`` in Python's C API). In contrast to `handle`, it + optionally increases the object's reference count upon construction, and it + *always* decreases the reference count when the `object` instance goes out of + scope and is destructed. When using `object` instances consistently, it is much + easier to get reference counting right at the first attempt. +\endrst */ +class object : public handle { +public: + object() = default; + PYBIND11_DEPRECATED("Use reinterpret_borrow() or reinterpret_steal()") + object(handle h, bool is_borrowed) : handle(h) { + if (is_borrowed) { + inc_ref(); + } + } + /// Copy constructor; always increases the reference count + object(const object &o) : handle(o) { inc_ref(); } + /// Move constructor; steals the object from ``other`` and preserves its reference count + object(object &&other) noexcept : handle(other) { other.m_ptr = nullptr; } + /// Destructor; automatically calls `handle::dec_ref()` + ~object() { dec_ref(); } + + /** \rst + Resets the internal pointer to ``nullptr`` without decreasing the + object's reference count. The function returns a raw handle to the original + Python object. + \endrst */ + handle release() { + PyObject *tmp = m_ptr; + m_ptr = nullptr; + return handle(tmp); + } + + object &operator=(const object &other) { + // Skip inc_ref and dec_ref if both objects are the same + if (!this->is(other)) { + other.inc_ref(); + // Use temporary variable to ensure `*this` remains valid while + // `Py_XDECREF` executes, in case `*this` is accessible from Python. + handle temp(m_ptr); + m_ptr = other.m_ptr; + temp.dec_ref(); + } + return *this; + } + + object &operator=(object &&other) noexcept { + if (this != &other) { + handle temp(m_ptr); + m_ptr = other.m_ptr; + other.m_ptr = nullptr; + temp.dec_ref(); + } + return *this; + } + +#define PYBIND11_INPLACE_OP(iop) \ + object iop(object_api const &other) { return operator=(handle::iop(other)); } + + PYBIND11_INPLACE_OP(operator+=) + PYBIND11_INPLACE_OP(operator-=) + PYBIND11_INPLACE_OP(operator*=) + PYBIND11_INPLACE_OP(operator/=) + PYBIND11_INPLACE_OP(operator|=) + PYBIND11_INPLACE_OP(operator&=) + PYBIND11_INPLACE_OP(operator^=) + PYBIND11_INPLACE_OP(operator<<=) + PYBIND11_INPLACE_OP(operator>>=) +#undef PYBIND11_INPLACE_OP + + // Calling cast() on an object lvalue just copies (via handle::cast) + template + T cast() const &; + // Calling on an object rvalue does a move, if needed and/or possible + template + T cast() &&; + +protected: + // Tags for choosing constructors from raw PyObject * + struct borrowed_t {}; + struct stolen_t {}; + + /// @cond BROKEN + template + friend T reinterpret_borrow(handle); + template + friend T reinterpret_steal(handle); + /// @endcond + +public: + // Only accessible from derived classes and the reinterpret_* functions + object(handle h, borrowed_t) : handle(h) { inc_ref(); } + object(handle h, stolen_t) : handle(h) {} +}; + +/** \rst + Declare that a `handle` or ``PyObject *`` is a certain type and borrow the reference. + The target type ``T`` must be `object` or one of its derived classes. The function + doesn't do any conversions or checks. It's up to the user to make sure that the + target type is correct. + + .. code-block:: cpp + + PyObject *p = PyList_GetItem(obj, index); + py::object o = reinterpret_borrow(p); + // or + py::tuple t = reinterpret_borrow(p); // <-- `p` must be already be a `tuple` +\endrst */ +template +T reinterpret_borrow(handle h) { + return {h, object::borrowed_t{}}; +} + +/** \rst + Like `reinterpret_borrow`, but steals the reference. + + .. code-block:: cpp + + PyObject *p = PyObject_Str(obj); + py::str s = reinterpret_steal(p); // <-- `p` must be already be a `str` +\endrst */ +template +T reinterpret_steal(handle h) { + return {h, object::stolen_t{}}; +} + +PYBIND11_NAMESPACE_BEGIN(detail) + +// Equivalent to obj.__class__.__name__ (or obj.__name__ if obj is a class). +inline const char *obj_class_name(PyObject *obj) { + if (PyType_Check(obj)) { + return reinterpret_cast(obj)->tp_name; + } + return Py_TYPE(obj)->tp_name; +} + +std::string error_string(); + +// The code in this struct is very unusual, to minimize the chances of +// masking bugs (elsewhere) by errors during the error handling (here). +// This is meant to be a lifeline for troubleshooting long-running processes +// that crash under conditions that are virtually impossible to reproduce. +// Low-level implementation alternatives are preferred to higher-level ones +// that might raise cascading exceptions. Last-ditch-kind-of attempts are made +// to report as much of the original error as possible, even if there are +// secondary issues obtaining some of the details. +struct error_fetch_and_normalize { + // This comment only applies to Python <= 3.11: + // Immediate normalization is long-established behavior (starting with + // https://github.com/pybind/pybind11/commit/135ba8deafb8bf64a15b24d1513899eb600e2011 + // from Sep 2016) and safest. Normalization could be deferred, but this could mask + // errors elsewhere, the performance gain is very minor in typical situations + // (usually the dominant bottleneck is EH unwinding), and the implementation here + // would be more complex. + // Starting with Python 3.12, PyErr_Fetch() normalizes exceptions immediately. + // Any errors during normalization are tracked under __notes__. + explicit error_fetch_and_normalize(const char *called) { + PyErr_Fetch(&m_type.ptr(), &m_value.ptr(), &m_trace.ptr()); + if (!m_type) { + pybind11_fail("Internal error: " + std::string(called) + + " called while " + "Python error indicator not set."); + } + const char *exc_type_name_orig = detail::obj_class_name(m_type.ptr()); + if (exc_type_name_orig == nullptr) { + pybind11_fail("Internal error: " + std::string(called) + + " failed to obtain the name " + "of the original active exception type."); + } + m_lazy_error_string = exc_type_name_orig; +#if PY_VERSION_HEX >= 0x030C0000 + // The presence of __notes__ is likely due to exception normalization + // errors, although that is not necessarily true, therefore insert a + // hint only: + if (PyObject_HasAttrString(m_value.ptr(), "__notes__")) { + m_lazy_error_string += "[WITH __notes__]"; + } +#else + // PyErr_NormalizeException() may change the exception type if there are cascading + // failures. This can potentially be extremely confusing. + PyErr_NormalizeException(&m_type.ptr(), &m_value.ptr(), &m_trace.ptr()); + if (m_type.ptr() == nullptr) { + pybind11_fail("Internal error: " + std::string(called) + + " failed to normalize the " + "active exception."); + } + const char *exc_type_name_norm = detail::obj_class_name(m_type.ptr()); + if (exc_type_name_norm == nullptr) { + pybind11_fail("Internal error: " + std::string(called) + + " failed to obtain the name " + "of the normalized active exception type."); + } +# if defined(PYPY_VERSION_NUM) && PYPY_VERSION_NUM < 0x07030a00 + // This behavior runs the risk of masking errors in the error handling, but avoids a + // conflict with PyPy, which relies on the normalization here to change OSError to + // FileNotFoundError (https://github.com/pybind/pybind11/issues/4075). + m_lazy_error_string = exc_type_name_norm; +# else + if (exc_type_name_norm != m_lazy_error_string) { + std::string msg = std::string(called) + + ": MISMATCH of original and normalized " + "active exception types: "; + msg += "ORIGINAL "; + msg += m_lazy_error_string; + msg += " REPLACED BY "; + msg += exc_type_name_norm; + msg += ": " + format_value_and_trace(); + pybind11_fail(msg); + } +# endif +#endif + } + + error_fetch_and_normalize(const error_fetch_and_normalize &) = delete; + error_fetch_and_normalize(error_fetch_and_normalize &&) = delete; + + std::string format_value_and_trace() const { + std::string result; + std::string message_error_string; + if (m_value) { + auto value_str = reinterpret_steal(PyObject_Str(m_value.ptr())); + constexpr const char *message_unavailable_exc + = ""; + if (!value_str) { + message_error_string = detail::error_string(); + result = message_unavailable_exc; + } else { + // Not using `value_str.cast()`, to not potentially throw a secondary + // error_already_set that will then result in process termination (#4288). + auto value_bytes = reinterpret_steal( + PyUnicode_AsEncodedString(value_str.ptr(), "utf-8", "backslashreplace")); + if (!value_bytes) { + message_error_string = detail::error_string(); + result = message_unavailable_exc; + } else { + char *buffer = nullptr; + Py_ssize_t length = 0; + if (PyBytes_AsStringAndSize(value_bytes.ptr(), &buffer, &length) == -1) { + message_error_string = detail::error_string(); + result = message_unavailable_exc; + } else { + result = std::string(buffer, static_cast(length)); + } + } + } +#if PY_VERSION_HEX >= 0x030B0000 + auto notes + = reinterpret_steal(PyObject_GetAttrString(m_value.ptr(), "__notes__")); + if (!notes) { + PyErr_Clear(); // No notes is good news. + } else { + auto len_notes = PyList_Size(notes.ptr()); + if (len_notes < 0) { + result += "\nFAILURE obtaining len(__notes__): " + detail::error_string(); + } else { + result += "\n__notes__ (len=" + std::to_string(len_notes) + "):"; + for (ssize_t i = 0; i < len_notes; i++) { + PyObject *note = PyList_GET_ITEM(notes.ptr(), i); + auto note_bytes = reinterpret_steal( + PyUnicode_AsEncodedString(note, "utf-8", "backslashreplace")); + if (!note_bytes) { + result += "\nFAILURE obtaining __notes__[" + std::to_string(i) + + "]: " + detail::error_string(); + } else { + char *buffer = nullptr; + Py_ssize_t length = 0; + if (PyBytes_AsStringAndSize(note_bytes.ptr(), &buffer, &length) + == -1) { + result += "\nFAILURE formatting __notes__[" + std::to_string(i) + + "]: " + detail::error_string(); + } else { + result += '\n'; + result += std::string(buffer, static_cast(length)); + } + } + } + } + } +#endif + } else { + result = ""; + } + if (result.empty()) { + result = ""; + } + + bool have_trace = false; + if (m_trace) { +#if !defined(PYPY_VERSION) + auto *tb = reinterpret_cast(m_trace.ptr()); + + // Get the deepest trace possible. + while (tb->tb_next) { + tb = tb->tb_next; + } + + PyFrameObject *frame = tb->tb_frame; + Py_XINCREF(frame); + result += "\n\nAt:\n"; + while (frame) { +# if PY_VERSION_HEX >= 0x030900B1 + PyCodeObject *f_code = PyFrame_GetCode(frame); +# else + PyCodeObject *f_code = frame->f_code; + Py_INCREF(f_code); +# endif + int lineno = PyFrame_GetLineNumber(frame); + result += " "; + result += handle(f_code->co_filename).cast(); + result += '('; + result += std::to_string(lineno); + result += "): "; + result += handle(f_code->co_name).cast(); + result += '\n'; + Py_DECREF(f_code); +# if PY_VERSION_HEX >= 0x030900B1 + auto *b_frame = PyFrame_GetBack(frame); +# else + auto *b_frame = frame->f_back; + Py_XINCREF(b_frame); +# endif + Py_DECREF(frame); + frame = b_frame; + } + + have_trace = true; +#endif //! defined(PYPY_VERSION) + } + + if (!message_error_string.empty()) { + if (!have_trace) { + result += '\n'; + } + result += "\nMESSAGE UNAVAILABLE DUE TO EXCEPTION: " + message_error_string; + } + + return result; + } + + std::string const &error_string() const { + if (!m_lazy_error_string_completed) { + m_lazy_error_string += ": " + format_value_and_trace(); + m_lazy_error_string_completed = true; + } + return m_lazy_error_string; + } + + void restore() { + if (m_restore_called) { + pybind11_fail("Internal error: pybind11::detail::error_fetch_and_normalize::restore() " + "called a second time. ORIGINAL ERROR: " + + error_string()); + } + PyErr_Restore(m_type.inc_ref().ptr(), m_value.inc_ref().ptr(), m_trace.inc_ref().ptr()); + m_restore_called = true; + } + + bool matches(handle exc) const { + return (PyErr_GivenExceptionMatches(m_type.ptr(), exc.ptr()) != 0); + } + + // Not protecting these for simplicity. + object m_type, m_value, m_trace; + +private: + // Only protecting invariants. + mutable std::string m_lazy_error_string; + mutable bool m_lazy_error_string_completed = false; + mutable bool m_restore_called = false; +}; + +inline std::string error_string() { + return error_fetch_and_normalize("pybind11::detail::error_string").error_string(); +} + +PYBIND11_NAMESPACE_END(detail) + +/// Fetch and hold an error which was already set in Python. An instance of this is typically +/// thrown to propagate python-side errors back through C++ which can either be caught manually or +/// else falls back to the function dispatcher (which then raises the captured error back to +/// python). +class PYBIND11_EXPORT_EXCEPTION error_already_set : public std::exception { +public: + /// Fetches the current Python exception (using PyErr_Fetch()), which will clear the + /// current Python error indicator. + error_already_set() + : m_fetched_error{new detail::error_fetch_and_normalize("pybind11::error_already_set"), + m_fetched_error_deleter} {} + + /// The what() result is built lazily on demand. + /// WARNING: This member function needs to acquire the Python GIL. This can lead to + /// crashes (undefined behavior) if the Python interpreter is finalizing. + const char *what() const noexcept override; + + /// Restores the currently-held Python error (which will clear the Python error indicator first + /// if already set). + /// NOTE: This member function will always restore the normalized exception, which may or may + /// not be the original Python exception. + /// WARNING: The GIL must be held when this member function is called! + void restore() { m_fetched_error->restore(); } + + /// If it is impossible to raise the currently-held error, such as in a destructor, we can + /// write it out using Python's unraisable hook (`sys.unraisablehook`). The error context + /// should be some object whose `repr()` helps identify the location of the error. Python + /// already knows the type and value of the error, so there is no need to repeat that. + void discard_as_unraisable(object err_context) { + restore(); + PyErr_WriteUnraisable(err_context.ptr()); + } + /// An alternate version of `discard_as_unraisable()`, where a string provides information on + /// the location of the error. For example, `__func__` could be helpful. + /// WARNING: The GIL must be held when this member function is called! + void discard_as_unraisable(const char *err_context) { + discard_as_unraisable(reinterpret_steal(PYBIND11_FROM_STRING(err_context))); + } + + // Does nothing; provided for backwards compatibility. + PYBIND11_DEPRECATED("Use of error_already_set.clear() is deprecated") + void clear() {} + + /// Check if the currently trapped error type matches the given Python exception class (or a + /// subclass thereof). May also be passed a tuple to search for any exception class matches in + /// the given tuple. + bool matches(handle exc) const { return m_fetched_error->matches(exc); } + + const object &type() const { return m_fetched_error->m_type; } + const object &value() const { return m_fetched_error->m_value; } + const object &trace() const { return m_fetched_error->m_trace; } + +private: + std::shared_ptr m_fetched_error; + + /// WARNING: This custom deleter needs to acquire the Python GIL. This can lead to + /// crashes (undefined behavior) if the Python interpreter is finalizing. + static void m_fetched_error_deleter(detail::error_fetch_and_normalize *raw_ptr); +}; + +/// Replaces the current Python error indicator with the chosen error, performing a +/// 'raise from' to indicate that the chosen error was caused by the original error. +inline void raise_from(PyObject *type, const char *message) { + // Based on _PyErr_FormatVFromCause: + // https://github.com/python/cpython/blob/467ab194fc6189d9f7310c89937c51abeac56839/Python/errors.c#L405 + // See https://github.com/pybind/pybind11/pull/2112 for details. + PyObject *exc = nullptr, *val = nullptr, *val2 = nullptr, *tb = nullptr; + + assert(PyErr_Occurred()); + PyErr_Fetch(&exc, &val, &tb); + PyErr_NormalizeException(&exc, &val, &tb); + if (tb != nullptr) { + PyException_SetTraceback(val, tb); + Py_DECREF(tb); + } + Py_DECREF(exc); + assert(!PyErr_Occurred()); + + PyErr_SetString(type, message); + + PyErr_Fetch(&exc, &val2, &tb); + PyErr_NormalizeException(&exc, &val2, &tb); + Py_INCREF(val); + PyException_SetCause(val2, val); + PyException_SetContext(val2, val); + PyErr_Restore(exc, val2, tb); +} + +/// Sets the current Python error indicator with the chosen error, performing a 'raise from' +/// from the error contained in error_already_set to indicate that the chosen error was +/// caused by the original error. +inline void raise_from(error_already_set &err, PyObject *type, const char *message) { + err.restore(); + raise_from(type, message); +} + +/** \defgroup python_builtins const_name + Unless stated otherwise, the following C++ functions behave the same + as their Python counterparts. + */ + +/** \ingroup python_builtins + \rst + Return true if ``obj`` is an instance of ``T``. Type ``T`` must be a subclass of + `object` or a class which was exposed to Python as ``py::class_``. +\endrst */ +template ::value, int> = 0> +bool isinstance(handle obj) { + return T::check_(obj); +} + +template ::value, int> = 0> +bool isinstance(handle obj) { + return detail::isinstance_generic(obj, typeid(T)); +} + +template <> +inline bool isinstance(handle) = delete; +template <> +inline bool isinstance(handle obj) { + return obj.ptr() != nullptr; +} + +/// \ingroup python_builtins +/// Return true if ``obj`` is an instance of the ``type``. +inline bool isinstance(handle obj, handle type) { + const auto result = PyObject_IsInstance(obj.ptr(), type.ptr()); + if (result == -1) { + throw error_already_set(); + } + return result != 0; +} + +/// \addtogroup python_builtins +/// @{ +inline bool hasattr(handle obj, handle name) { + return PyObject_HasAttr(obj.ptr(), name.ptr()) == 1; +} + +inline bool hasattr(handle obj, const char *name) { + return PyObject_HasAttrString(obj.ptr(), name) == 1; +} + +inline void delattr(handle obj, handle name) { + if (PyObject_DelAttr(obj.ptr(), name.ptr()) != 0) { + throw error_already_set(); + } +} + +inline void delattr(handle obj, const char *name) { + if (PyObject_DelAttrString(obj.ptr(), name) != 0) { + throw error_already_set(); + } +} + +inline object getattr(handle obj, handle name) { + PyObject *result = PyObject_GetAttr(obj.ptr(), name.ptr()); + if (!result) { + throw error_already_set(); + } + return reinterpret_steal(result); +} + +inline object getattr(handle obj, const char *name) { + PyObject *result = PyObject_GetAttrString(obj.ptr(), name); + if (!result) { + throw error_already_set(); + } + return reinterpret_steal(result); +} + +inline object getattr(handle obj, handle name, handle default_) { + if (PyObject *result = PyObject_GetAttr(obj.ptr(), name.ptr())) { + return reinterpret_steal(result); + } + PyErr_Clear(); + return reinterpret_borrow(default_); +} + +inline object getattr(handle obj, const char *name, handle default_) { + if (PyObject *result = PyObject_GetAttrString(obj.ptr(), name)) { + return reinterpret_steal(result); + } + PyErr_Clear(); + return reinterpret_borrow(default_); +} + +inline void setattr(handle obj, handle name, handle value) { + if (PyObject_SetAttr(obj.ptr(), name.ptr(), value.ptr()) != 0) { + throw error_already_set(); + } +} + +inline void setattr(handle obj, const char *name, handle value) { + if (PyObject_SetAttrString(obj.ptr(), name, value.ptr()) != 0) { + throw error_already_set(); + } +} + +inline ssize_t hash(handle obj) { + auto h = PyObject_Hash(obj.ptr()); + if (h == -1) { + throw error_already_set(); + } + return h; +} + +/// @} python_builtins + +PYBIND11_NAMESPACE_BEGIN(detail) +inline handle get_function(handle value) { + if (value) { + if (PyInstanceMethod_Check(value.ptr())) { + value = PyInstanceMethod_GET_FUNCTION(value.ptr()); + } else if (PyMethod_Check(value.ptr())) { + value = PyMethod_GET_FUNCTION(value.ptr()); + } + } + return value; +} + +// Reimplementation of python's dict helper functions to ensure that exceptions +// aren't swallowed (see #2862) + +// copied from cpython _PyDict_GetItemStringWithError +inline PyObject *dict_getitemstring(PyObject *v, const char *key) { + PyObject *kv = nullptr, *rv = nullptr; + kv = PyUnicode_FromString(key); + if (kv == nullptr) { + throw error_already_set(); + } + + rv = PyDict_GetItemWithError(v, kv); + Py_DECREF(kv); + if (rv == nullptr && PyErr_Occurred()) { + throw error_already_set(); + } + return rv; +} + +inline PyObject *dict_getitem(PyObject *v, PyObject *key) { + PyObject *rv = PyDict_GetItemWithError(v, key); + if (rv == nullptr && PyErr_Occurred()) { + throw error_already_set(); + } + return rv; +} + +inline PyObject *dict_getitemstringref(PyObject *v, const char *key) { +#if PY_VERSION_HEX >= 0x030D0000 + PyObject *rv; + if (PyDict_GetItemStringRef(v, key, &rv) < 0) { + throw error_already_set(); + } + return rv; +#else + PyObject *rv = dict_getitemstring(v, key); + if (rv == nullptr && PyErr_Occurred()) { + throw error_already_set(); + } + Py_XINCREF(rv); + return rv; +#endif +} + +// Helper aliases/functions to support implicit casting of values given to python +// accessors/methods. When given a pyobject, this simply returns the pyobject as-is; for other C++ +// type, the value goes through pybind11::cast(obj) to convert it to an `object`. +template ::value, int> = 0> +auto object_or_cast(T &&o) -> decltype(std::forward(o)) { + return std::forward(o); +} +// The following casting version is implemented in cast.h: +template ::value, int> = 0> +object object_or_cast(T &&o); +// Match a PyObject*, which we want to convert directly to handle via its converting constructor +inline handle object_or_cast(PyObject *ptr) { return ptr; } + +PYBIND11_WARNING_PUSH +PYBIND11_WARNING_DISABLE_MSVC(4522) // warning C4522: multiple assignment operators specified +template +class accessor : public object_api> { + using key_type = typename Policy::key_type; + +public: + accessor(handle obj, key_type key) : obj(obj), key(std::move(key)) {} + accessor(const accessor &) = default; + accessor(accessor &&) noexcept = default; + + // accessor overload required to override default assignment operator (templates are not + // allowed to replace default compiler-generated assignments). + void operator=(const accessor &a) && { std::move(*this).operator=(handle(a)); } + void operator=(const accessor &a) & { operator=(handle(a)); } + + template + void operator=(T &&value) && { + Policy::set(obj, key, object_or_cast(std::forward(value))); + } + template + void operator=(T &&value) & { + get_cache() = ensure_object(object_or_cast(std::forward(value))); + } + + template + PYBIND11_DEPRECATED( + "Use of obj.attr(...) as bool is deprecated in favor of pybind11::hasattr(obj, ...)") + explicit + operator enable_if_t::value + || std::is_same::value, + bool>() const { + return hasattr(obj, key); + } + template + PYBIND11_DEPRECATED("Use of obj[key] as bool is deprecated in favor of obj.contains(key)") + explicit + operator enable_if_t::value, bool>() const { + return obj.contains(key); + } + + // NOLINTNEXTLINE(google-explicit-constructor) + operator object() const { return get_cache(); } + PyObject *ptr() const { return get_cache().ptr(); } + template + T cast() const { + return get_cache().template cast(); + } + +private: + static object ensure_object(object &&o) { return std::move(o); } + static object ensure_object(handle h) { return reinterpret_borrow(h); } + + object &get_cache() const { + if (!cache) { + cache = Policy::get(obj, key); + } + return cache; + } + +private: + handle obj; + key_type key; + mutable object cache; +}; +PYBIND11_WARNING_POP + +PYBIND11_NAMESPACE_BEGIN(accessor_policies) +struct obj_attr { + using key_type = object; + static object get(handle obj, handle key) { return getattr(obj, key); } + static void set(handle obj, handle key, handle val) { setattr(obj, key, val); } +}; + +struct str_attr { + using key_type = const char *; + static object get(handle obj, const char *key) { return getattr(obj, key); } + static void set(handle obj, const char *key, handle val) { setattr(obj, key, val); } +}; + +struct generic_item { + using key_type = object; + + static object get(handle obj, handle key) { + PyObject *result = PyObject_GetItem(obj.ptr(), key.ptr()); + if (!result) { + throw error_already_set(); + } + return reinterpret_steal(result); + } + + static void set(handle obj, handle key, handle val) { + if (PyObject_SetItem(obj.ptr(), key.ptr(), val.ptr()) != 0) { + throw error_already_set(); + } + } +}; + +struct sequence_item { + using key_type = size_t; + + template ::value, int> = 0> + static object get(handle obj, const IdxType &index) { + PyObject *result = PySequence_GetItem(obj.ptr(), ssize_t_cast(index)); + if (!result) { + throw error_already_set(); + } + return reinterpret_steal(result); + } + + template ::value, int> = 0> + static void set(handle obj, const IdxType &index, handle val) { + // PySequence_SetItem does not steal a reference to 'val' + if (PySequence_SetItem(obj.ptr(), ssize_t_cast(index), val.ptr()) != 0) { + throw error_already_set(); + } + } +}; + +struct list_item { + using key_type = size_t; + + template ::value, int> = 0> + static object get(handle obj, const IdxType &index) { + PyObject *result = PyList_GetItem(obj.ptr(), ssize_t_cast(index)); + if (!result) { + throw error_already_set(); + } + return reinterpret_borrow(result); + } + + template ::value, int> = 0> + static void set(handle obj, const IdxType &index, handle val) { + // PyList_SetItem steals a reference to 'val' + if (PyList_SetItem(obj.ptr(), ssize_t_cast(index), val.inc_ref().ptr()) != 0) { + throw error_already_set(); + } + } +}; + +struct tuple_item { + using key_type = size_t; + + template ::value, int> = 0> + static object get(handle obj, const IdxType &index) { + PyObject *result = PyTuple_GetItem(obj.ptr(), ssize_t_cast(index)); + if (!result) { + throw error_already_set(); + } + return reinterpret_borrow(result); + } + + template ::value, int> = 0> + static void set(handle obj, const IdxType &index, handle val) { + // PyTuple_SetItem steals a reference to 'val' + if (PyTuple_SetItem(obj.ptr(), ssize_t_cast(index), val.inc_ref().ptr()) != 0) { + throw error_already_set(); + } + } +}; +PYBIND11_NAMESPACE_END(accessor_policies) + +/// STL iterator template used for tuple, list, sequence and dict +template +class generic_iterator : public Policy { + using It = generic_iterator; + +public: + using difference_type = ssize_t; + using iterator_category = typename Policy::iterator_category; + using value_type = typename Policy::value_type; + using reference = typename Policy::reference; + using pointer = typename Policy::pointer; + + generic_iterator() = default; + generic_iterator(handle seq, ssize_t index) : Policy(seq, index) {} + + // NOLINTNEXTLINE(readability-const-return-type) // PR #3263 + reference operator*() const { return Policy::dereference(); } + // NOLINTNEXTLINE(readability-const-return-type) // PR #3263 + reference operator[](difference_type n) const { return *(*this + n); } + pointer operator->() const { return **this; } + + It &operator++() { + Policy::increment(); + return *this; + } + It operator++(int) { + auto copy = *this; + Policy::increment(); + return copy; + } + It &operator--() { + Policy::decrement(); + return *this; + } + It operator--(int) { + auto copy = *this; + Policy::decrement(); + return copy; + } + It &operator+=(difference_type n) { + Policy::advance(n); + return *this; + } + It &operator-=(difference_type n) { + Policy::advance(-n); + return *this; + } + + friend It operator+(const It &a, difference_type n) { + auto copy = a; + return copy += n; + } + friend It operator+(difference_type n, const It &b) { return b + n; } + friend It operator-(const It &a, difference_type n) { + auto copy = a; + return copy -= n; + } + friend difference_type operator-(const It &a, const It &b) { return a.distance_to(b); } + + friend bool operator==(const It &a, const It &b) { return a.equal(b); } + friend bool operator!=(const It &a, const It &b) { return !(a == b); } + friend bool operator<(const It &a, const It &b) { return b - a > 0; } + friend bool operator>(const It &a, const It &b) { return b < a; } + friend bool operator>=(const It &a, const It &b) { return !(a < b); } + friend bool operator<=(const It &a, const It &b) { return !(a > b); } +}; + +PYBIND11_NAMESPACE_BEGIN(iterator_policies) +/// Quick proxy class needed to implement ``operator->`` for iterators which can't return pointers +template +struct arrow_proxy { + T value; + + // NOLINTNEXTLINE(google-explicit-constructor) + arrow_proxy(T &&value) noexcept : value(std::move(value)) {} + T *operator->() const { return &value; } +}; + +/// Lightweight iterator policy using just a simple pointer: see ``PySequence_Fast_ITEMS`` +class sequence_fast_readonly { +protected: + using iterator_category = std::random_access_iterator_tag; + using value_type = handle; + using reference = const handle; // PR #3263 + using pointer = arrow_proxy; + + sequence_fast_readonly(handle obj, ssize_t n) : ptr(PySequence_Fast_ITEMS(obj.ptr()) + n) {} + sequence_fast_readonly() = default; + + // NOLINTNEXTLINE(readability-const-return-type) // PR #3263 + reference dereference() const { return *ptr; } + void increment() { ++ptr; } + void decrement() { --ptr; } + void advance(ssize_t n) { ptr += n; } + bool equal(const sequence_fast_readonly &b) const { return ptr == b.ptr; } + ssize_t distance_to(const sequence_fast_readonly &b) const { return ptr - b.ptr; } + +private: + PyObject **ptr; +}; + +/// Full read and write access using the sequence protocol: see ``detail::sequence_accessor`` +class sequence_slow_readwrite { +protected: + using iterator_category = std::random_access_iterator_tag; + using value_type = object; + using reference = sequence_accessor; + using pointer = arrow_proxy; + + sequence_slow_readwrite(handle obj, ssize_t index) : obj(obj), index(index) {} + sequence_slow_readwrite() = default; + + reference dereference() const { return {obj, static_cast(index)}; } + void increment() { ++index; } + void decrement() { --index; } + void advance(ssize_t n) { index += n; } + bool equal(const sequence_slow_readwrite &b) const { return index == b.index; } + ssize_t distance_to(const sequence_slow_readwrite &b) const { return index - b.index; } + +private: + handle obj; + ssize_t index; +}; + +/// Python's dictionary protocol permits this to be a forward iterator +class dict_readonly { +protected: + using iterator_category = std::forward_iterator_tag; + using value_type = std::pair; + using reference = const value_type; // PR #3263 + using pointer = arrow_proxy; + + dict_readonly() = default; + dict_readonly(handle obj, ssize_t pos) : obj(obj), pos(pos) { increment(); } + + // NOLINTNEXTLINE(readability-const-return-type) // PR #3263 + reference dereference() const { return {key, value}; } + void increment() { + if (PyDict_Next(obj.ptr(), &pos, &key, &value) == 0) { + pos = -1; + } + } + bool equal(const dict_readonly &b) const { return pos == b.pos; } + +private: + handle obj; + PyObject *key = nullptr, *value = nullptr; + ssize_t pos = -1; +}; +PYBIND11_NAMESPACE_END(iterator_policies) + +#if !defined(PYPY_VERSION) +using tuple_iterator = generic_iterator; +using list_iterator = generic_iterator; +#else +using tuple_iterator = generic_iterator; +using list_iterator = generic_iterator; +#endif + +using sequence_iterator = generic_iterator; +using dict_iterator = generic_iterator; + +inline bool PyIterable_Check(PyObject *obj) { + PyObject *iter = PyObject_GetIter(obj); + if (iter) { + Py_DECREF(iter); + return true; + } + PyErr_Clear(); + return false; +} + +inline bool PyNone_Check(PyObject *o) { return o == Py_None; } +inline bool PyEllipsis_Check(PyObject *o) { return o == Py_Ellipsis; } + +#ifdef PYBIND11_STR_LEGACY_PERMISSIVE +inline bool PyUnicode_Check_Permissive(PyObject *o) { + return PyUnicode_Check(o) || PYBIND11_BYTES_CHECK(o); +} +# define PYBIND11_STR_CHECK_FUN detail::PyUnicode_Check_Permissive +#else +# define PYBIND11_STR_CHECK_FUN PyUnicode_Check +#endif + +inline bool PyStaticMethod_Check(PyObject *o) { return o->ob_type == &PyStaticMethod_Type; } + +class kwargs_proxy : public handle { +public: + explicit kwargs_proxy(handle h) : handle(h) {} +}; + +class args_proxy : public handle { +public: + explicit args_proxy(handle h) : handle(h) {} + kwargs_proxy operator*() const { return kwargs_proxy(*this); } +}; + +/// Python argument categories (using PEP 448 terms) +template +using is_keyword = std::is_base_of; +template +using is_s_unpacking = std::is_same; // * unpacking +template +using is_ds_unpacking = std::is_same; // ** unpacking +template +using is_positional = satisfies_none_of; +template +using is_keyword_or_ds = satisfies_any_of; + +// Call argument collector forward declarations +template +class simple_collector; +template +class unpacking_collector; + +PYBIND11_NAMESPACE_END(detail) + +// TODO: After the deprecated constructors are removed, this macro can be simplified by +// inheriting ctors: `using Parent::Parent`. It's not an option right now because +// the `using` statement triggers the parent deprecation warning even if the ctor +// isn't even used. +#define PYBIND11_OBJECT_COMMON(Name, Parent, CheckFun) \ +public: \ + PYBIND11_DEPRECATED("Use reinterpret_borrow<" #Name ">() or reinterpret_steal<" #Name ">()") \ + Name(handle h, bool is_borrowed) \ + : Parent(is_borrowed ? Parent(h, borrowed_t{}) : Parent(h, stolen_t{})) {} \ + Name(handle h, borrowed_t) : Parent(h, borrowed_t{}) {} \ + Name(handle h, stolen_t) : Parent(h, stolen_t{}) {} \ + PYBIND11_DEPRECATED("Use py::isinstance(obj) instead") \ + bool check() const { return m_ptr != nullptr && (CheckFun(m_ptr) != 0); } \ + static bool check_(handle h) { return h.ptr() != nullptr && CheckFun(h.ptr()); } \ + template /* NOLINTNEXTLINE(google-explicit-constructor) */ \ + Name(const ::pybind11::detail::accessor &a) : Name(object(a)) {} + +#define PYBIND11_OBJECT_CVT(Name, Parent, CheckFun, ConvertFun) \ + PYBIND11_OBJECT_COMMON(Name, Parent, CheckFun) \ + /* This is deliberately not 'explicit' to allow implicit conversion from object: */ \ + /* NOLINTNEXTLINE(google-explicit-constructor) */ \ + Name(const object &o) \ + : Parent(check_(o) ? o.inc_ref().ptr() : ConvertFun(o.ptr()), stolen_t{}) { \ + if (!m_ptr) \ + throw ::pybind11::error_already_set(); \ + } \ + /* NOLINTNEXTLINE(google-explicit-constructor) */ \ + Name(object &&o) : Parent(check_(o) ? o.release().ptr() : ConvertFun(o.ptr()), stolen_t{}) { \ + if (!m_ptr) \ + throw ::pybind11::error_already_set(); \ + } + +#define PYBIND11_OBJECT_CVT_DEFAULT(Name, Parent, CheckFun, ConvertFun) \ + PYBIND11_OBJECT_CVT(Name, Parent, CheckFun, ConvertFun) \ + Name() = default; + +#define PYBIND11_OBJECT_CHECK_FAILED(Name, o_ptr) \ + ::pybind11::type_error("Object of type '" \ + + ::pybind11::detail::get_fully_qualified_tp_name(Py_TYPE(o_ptr)) \ + + "' is not an instance of '" #Name "'") + +#define PYBIND11_OBJECT(Name, Parent, CheckFun) \ + PYBIND11_OBJECT_COMMON(Name, Parent, CheckFun) \ + /* This is deliberately not 'explicit' to allow implicit conversion from object: */ \ + /* NOLINTNEXTLINE(google-explicit-constructor) */ \ + Name(const object &o) : Parent(o) { \ + if (m_ptr && !check_(m_ptr)) \ + throw PYBIND11_OBJECT_CHECK_FAILED(Name, m_ptr); \ + } \ + /* NOLINTNEXTLINE(google-explicit-constructor) */ \ + Name(object &&o) : Parent(std::move(o)) { \ + if (m_ptr && !check_(m_ptr)) \ + throw PYBIND11_OBJECT_CHECK_FAILED(Name, m_ptr); \ + } + +#define PYBIND11_OBJECT_DEFAULT(Name, Parent, CheckFun) \ + PYBIND11_OBJECT(Name, Parent, CheckFun) \ + Name() = default; + +/// \addtogroup pytypes +/// @{ + +/** \rst + Wraps a Python iterator so that it can also be used as a C++ input iterator + + Caveat: copying an iterator does not (and cannot) clone the internal + state of the Python iterable. This also applies to the post-increment + operator. This iterator should only be used to retrieve the current + value using ``operator*()``. +\endrst */ +class iterator : public object { +public: + using iterator_category = std::input_iterator_tag; + using difference_type = ssize_t; + using value_type = handle; + using reference = const handle; // PR #3263 + using pointer = const handle *; + + PYBIND11_OBJECT_DEFAULT(iterator, object, PyIter_Check) + + iterator &operator++() { + advance(); + return *this; + } + + iterator operator++(int) { + auto rv = *this; + advance(); + return rv; + } + + // NOLINTNEXTLINE(readability-const-return-type) // PR #3263 + reference operator*() const { + if (m_ptr && !value.ptr()) { + auto &self = const_cast(*this); + self.advance(); + } + return value; + } + + pointer operator->() const { + operator*(); + return &value; + } + + /** \rst + The value which marks the end of the iteration. ``it == iterator::sentinel()`` + is equivalent to catching ``StopIteration`` in Python. + + .. code-block:: cpp + + void foo(py::iterator it) { + while (it != py::iterator::sentinel()) { + // use `*it` + ++it; + } + } + \endrst */ + static iterator sentinel() { return {}; } + + friend bool operator==(const iterator &a, const iterator &b) { return a->ptr() == b->ptr(); } + friend bool operator!=(const iterator &a, const iterator &b) { return a->ptr() != b->ptr(); } + +private: + void advance() { + value = reinterpret_steal(PyIter_Next(m_ptr)); + if (value.ptr() == nullptr && PyErr_Occurred()) { + throw error_already_set(); + } + } + +private: + object value = {}; +}; + +class type : public object { +public: + PYBIND11_OBJECT(type, object, PyType_Check) + + /// Return a type handle from a handle or an object + static handle handle_of(handle h) { return handle((PyObject *) Py_TYPE(h.ptr())); } + + /// Return a type object from a handle or an object + static type of(handle h) { return type(type::handle_of(h), borrowed_t{}); } + + // Defined in pybind11/cast.h + /// Convert C++ type to handle if previously registered. Does not convert + /// standard types, like int, float. etc. yet. + /// See https://github.com/pybind/pybind11/issues/2486 + template + static handle handle_of(); + + /// Convert C++ type to type if previously registered. Does not convert + /// standard types, like int, float. etc. yet. + /// See https://github.com/pybind/pybind11/issues/2486 + template + static type of() { + return type(type::handle_of(), borrowed_t{}); + } +}; + +class iterable : public object { +public: + PYBIND11_OBJECT_DEFAULT(iterable, object, detail::PyIterable_Check) +}; + +class bytes; + +class str : public object { +public: + PYBIND11_OBJECT_CVT(str, object, PYBIND11_STR_CHECK_FUN, raw_str) + + template ::value, int> = 0> + str(const char *c, const SzType &n) + : object(PyUnicode_FromStringAndSize(c, ssize_t_cast(n)), stolen_t{}) { + if (!m_ptr) { + if (PyErr_Occurred()) { + throw error_already_set(); + } + pybind11_fail("Could not allocate string object!"); + } + } + + // 'explicit' is explicitly omitted from the following constructors to allow implicit + // conversion to py::str from C++ string-like objects + // NOLINTNEXTLINE(google-explicit-constructor) + str(const char *c = "") : object(PyUnicode_FromString(c), stolen_t{}) { + if (!m_ptr) { + if (PyErr_Occurred()) { + throw error_already_set(); + } + pybind11_fail("Could not allocate string object!"); + } + } + + // NOLINTNEXTLINE(google-explicit-constructor) + str(const std::string &s) : str(s.data(), s.size()) {} + +#ifdef PYBIND11_HAS_STRING_VIEW + // enable_if is needed to avoid "ambiguous conversion" errors (see PR #3521). + template ::value, int> = 0> + // NOLINTNEXTLINE(google-explicit-constructor) + str(T s) : str(s.data(), s.size()) {} + +# ifdef PYBIND11_HAS_U8STRING + // reinterpret_cast here is safe (C++20 guarantees char8_t has the same size/alignment as char) + // NOLINTNEXTLINE(google-explicit-constructor) + str(std::u8string_view s) : str(reinterpret_cast(s.data()), s.size()) {} +# endif + +#endif + + explicit str(const bytes &b); + + /** \rst + Return a string representation of the object. This is analogous to + the ``str()`` function in Python. + \endrst */ + explicit str(handle h) : object(raw_str(h.ptr()), stolen_t{}) { + if (!m_ptr) { + throw error_already_set(); + } + } + + // NOLINTNEXTLINE(google-explicit-constructor) + operator std::string() const { + object temp = *this; + if (PyUnicode_Check(m_ptr)) { + temp = reinterpret_steal(PyUnicode_AsUTF8String(m_ptr)); + if (!temp) { + throw error_already_set(); + } + } + char *buffer = nullptr; + ssize_t length = 0; + if (PyBytes_AsStringAndSize(temp.ptr(), &buffer, &length) != 0) { + throw error_already_set(); + } + return std::string(buffer, (size_t) length); + } + + template + str format(Args &&...args) const { + return attr("format")(std::forward(args)...); + } + +private: + /// Return string representation -- always returns a new reference, even if already a str + static PyObject *raw_str(PyObject *op) { + PyObject *str_value = PyObject_Str(op); + return str_value; + } +}; +/// @} pytypes + +inline namespace literals { +/** \rst + String literal version of `str` + \endrst */ +inline str +#if !defined(__clang__) && defined(__GNUC__) && __GNUC__ < 5 +operator"" _s // gcc 4.8.5 insists on having a space (hard error). +#else +operator""_s // clang 17 generates a deprecation warning if there is a space. +#endif + (const char *s, size_t size) { + return {s, size}; +} +} // namespace literals + +/// \addtogroup pytypes +/// @{ +class bytes : public object { +public: + PYBIND11_OBJECT(bytes, object, PYBIND11_BYTES_CHECK) + + // Allow implicit conversion: + // NOLINTNEXTLINE(google-explicit-constructor) + bytes(const char *c = "") : object(PYBIND11_BYTES_FROM_STRING(c), stolen_t{}) { + if (!m_ptr) { + pybind11_fail("Could not allocate bytes object!"); + } + } + + template ::value, int> = 0> + bytes(const char *c, const SzType &n) + : object(PYBIND11_BYTES_FROM_STRING_AND_SIZE(c, ssize_t_cast(n)), stolen_t{}) { + if (!m_ptr) { + pybind11_fail("Could not allocate bytes object!"); + } + } + + // Allow implicit conversion: + // NOLINTNEXTLINE(google-explicit-constructor) + bytes(const std::string &s) : bytes(s.data(), s.size()) {} + + explicit bytes(const pybind11::str &s); + + // NOLINTNEXTLINE(google-explicit-constructor) + operator std::string() const { return string_op(); } + +#ifdef PYBIND11_HAS_STRING_VIEW + // enable_if is needed to avoid "ambiguous conversion" errors (see PR #3521). + template ::value, int> = 0> + // NOLINTNEXTLINE(google-explicit-constructor) + bytes(T s) : bytes(s.data(), s.size()) {} + + // Obtain a string view that views the current `bytes` buffer value. Note that this is only + // valid so long as the `bytes` instance remains alive and so generally should not outlive the + // lifetime of the `bytes` instance. + // NOLINTNEXTLINE(google-explicit-constructor) + operator std::string_view() const { return string_op(); } +#endif +private: + template + T string_op() const { + char *buffer = nullptr; + ssize_t length = 0; + if (PyBytes_AsStringAndSize(m_ptr, &buffer, &length) != 0) { + throw error_already_set(); + } + return {buffer, static_cast(length)}; + } +}; +// Note: breathe >= 4.17.0 will fail to build docs if the below two constructors +// are included in the doxygen group; close here and reopen after as a workaround +/// @} pytypes + +inline bytes::bytes(const pybind11::str &s) { + object temp = s; + if (PyUnicode_Check(s.ptr())) { + temp = reinterpret_steal(PyUnicode_AsUTF8String(s.ptr())); + if (!temp) { + throw error_already_set(); + } + } + char *buffer = nullptr; + ssize_t length = 0; + if (PyBytes_AsStringAndSize(temp.ptr(), &buffer, &length) != 0) { + throw error_already_set(); + } + auto obj = reinterpret_steal(PYBIND11_BYTES_FROM_STRING_AND_SIZE(buffer, length)); + if (!obj) { + pybind11_fail("Could not allocate bytes object!"); + } + m_ptr = obj.release().ptr(); +} + +inline str::str(const bytes &b) { + char *buffer = nullptr; + ssize_t length = 0; + if (PyBytes_AsStringAndSize(b.ptr(), &buffer, &length) != 0) { + throw error_already_set(); + } + auto obj = reinterpret_steal(PyUnicode_FromStringAndSize(buffer, length)); + if (!obj) { + if (PyErr_Occurred()) { + throw error_already_set(); + } + pybind11_fail("Could not allocate string object!"); + } + m_ptr = obj.release().ptr(); +} + +/// \addtogroup pytypes +/// @{ +class bytearray : public object { +public: + PYBIND11_OBJECT_CVT(bytearray, object, PyByteArray_Check, PyByteArray_FromObject) + + template ::value, int> = 0> + bytearray(const char *c, const SzType &n) + : object(PyByteArray_FromStringAndSize(c, ssize_t_cast(n)), stolen_t{}) { + if (!m_ptr) { + pybind11_fail("Could not allocate bytearray object!"); + } + } + + bytearray() : bytearray("", 0) {} + + explicit bytearray(const std::string &s) : bytearray(s.data(), s.size()) {} + + size_t size() const { return static_cast(PyByteArray_Size(m_ptr)); } + + explicit operator std::string() const { + char *buffer = PyByteArray_AS_STRING(m_ptr); + ssize_t size = PyByteArray_GET_SIZE(m_ptr); + return std::string(buffer, static_cast(size)); + } +}; +// Note: breathe >= 4.17.0 will fail to build docs if the below two constructors +// are included in the doxygen group; close here and reopen after as a workaround +/// @} pytypes + +/// \addtogroup pytypes +/// @{ +class none : public object { +public: + PYBIND11_OBJECT(none, object, detail::PyNone_Check) + none() : object(Py_None, borrowed_t{}) {} +}; + +class ellipsis : public object { +public: + PYBIND11_OBJECT(ellipsis, object, detail::PyEllipsis_Check) + ellipsis() : object(Py_Ellipsis, borrowed_t{}) {} +}; + +class bool_ : public object { +public: + PYBIND11_OBJECT_CVT(bool_, object, PyBool_Check, raw_bool) + bool_() : object(Py_False, borrowed_t{}) {} + // Allow implicit conversion from and to `bool`: + // NOLINTNEXTLINE(google-explicit-constructor) + bool_(bool value) : object(value ? Py_True : Py_False, borrowed_t{}) {} + // NOLINTNEXTLINE(google-explicit-constructor) + operator bool() const { return (m_ptr != nullptr) && PyLong_AsLong(m_ptr) != 0; } + +private: + /// Return the truth value of an object -- always returns a new reference + static PyObject *raw_bool(PyObject *op) { + const auto value = PyObject_IsTrue(op); + if (value == -1) { + return nullptr; + } + return handle(value != 0 ? Py_True : Py_False).inc_ref().ptr(); + } +}; + +PYBIND11_NAMESPACE_BEGIN(detail) +// Converts a value to the given unsigned type. If an error occurs, you get back (Unsigned) -1; +// otherwise you get back the unsigned long or unsigned long long value cast to (Unsigned). +// (The distinction is critically important when casting a returned -1 error value to some other +// unsigned type: (A)-1 != (B)-1 when A and B are unsigned types of different sizes). +template +Unsigned as_unsigned(PyObject *o) { + if (sizeof(Unsigned) <= sizeof(unsigned long)) { + unsigned long v = PyLong_AsUnsignedLong(o); + return v == (unsigned long) -1 && PyErr_Occurred() ? (Unsigned) -1 : (Unsigned) v; + } + unsigned long long v = PyLong_AsUnsignedLongLong(o); + return v == (unsigned long long) -1 && PyErr_Occurred() ? (Unsigned) -1 : (Unsigned) v; +} +PYBIND11_NAMESPACE_END(detail) + +class int_ : public object { +public: + PYBIND11_OBJECT_CVT(int_, object, PYBIND11_LONG_CHECK, PyNumber_Long) + int_() : object(PyLong_FromLong(0), stolen_t{}) {} + // Allow implicit conversion from C++ integral types: + template ::value, int> = 0> + // NOLINTNEXTLINE(google-explicit-constructor) + int_(T value) { + if (sizeof(T) <= sizeof(long)) { + if (std::is_signed::value) { + m_ptr = PyLong_FromLong((long) value); + } else { + m_ptr = PyLong_FromUnsignedLong((unsigned long) value); + } + } else { + if (std::is_signed::value) { + m_ptr = PyLong_FromLongLong((long long) value); + } else { + m_ptr = PyLong_FromUnsignedLongLong((unsigned long long) value); + } + } + if (!m_ptr) { + pybind11_fail("Could not allocate int object!"); + } + } + + template ::value, int> = 0> + // NOLINTNEXTLINE(google-explicit-constructor) + operator T() const { + return std::is_unsigned::value ? detail::as_unsigned(m_ptr) + : sizeof(T) <= sizeof(long) ? (T) PyLong_AsLong(m_ptr) + : (T) PYBIND11_LONG_AS_LONGLONG(m_ptr); + } +}; + +class float_ : public object { +public: + PYBIND11_OBJECT_CVT(float_, object, PyFloat_Check, PyNumber_Float) + // Allow implicit conversion from float/double: + // NOLINTNEXTLINE(google-explicit-constructor) + float_(float value) : object(PyFloat_FromDouble((double) value), stolen_t{}) { + if (!m_ptr) { + pybind11_fail("Could not allocate float object!"); + } + } + // NOLINTNEXTLINE(google-explicit-constructor) + float_(double value = .0) : object(PyFloat_FromDouble((double) value), stolen_t{}) { + if (!m_ptr) { + pybind11_fail("Could not allocate float object!"); + } + } + // NOLINTNEXTLINE(google-explicit-constructor) + operator float() const { return (float) PyFloat_AsDouble(m_ptr); } + // NOLINTNEXTLINE(google-explicit-constructor) + operator double() const { return (double) PyFloat_AsDouble(m_ptr); } +}; + +class weakref : public object { +public: + PYBIND11_OBJECT_CVT_DEFAULT(weakref, object, PyWeakref_Check, raw_weakref) + explicit weakref(handle obj, handle callback = {}) + : object(PyWeakref_NewRef(obj.ptr(), callback.ptr()), stolen_t{}) { + if (!m_ptr) { + if (PyErr_Occurred()) { + throw error_already_set(); + } + pybind11_fail("Could not allocate weak reference!"); + } + } + +private: + static PyObject *raw_weakref(PyObject *o) { return PyWeakref_NewRef(o, nullptr); } +}; + +class slice : public object { +public: + PYBIND11_OBJECT_DEFAULT(slice, object, PySlice_Check) + slice(handle start, handle stop, handle step) + : object(PySlice_New(start.ptr(), stop.ptr(), step.ptr()), stolen_t{}) { + if (!m_ptr) { + pybind11_fail("Could not allocate slice object!"); + } + } + +#ifdef PYBIND11_HAS_OPTIONAL + slice(std::optional start, std::optional stop, std::optional step) + : slice(index_to_object(start), index_to_object(stop), index_to_object(step)) {} +#else + slice(ssize_t start_, ssize_t stop_, ssize_t step_) + : slice(int_(start_), int_(stop_), int_(step_)) {} +#endif + + bool + compute(size_t length, size_t *start, size_t *stop, size_t *step, size_t *slicelength) const { + return PySlice_GetIndicesEx((PYBIND11_SLICE_OBJECT *) m_ptr, + (ssize_t) length, + (ssize_t *) start, + (ssize_t *) stop, + (ssize_t *) step, + (ssize_t *) slicelength) + == 0; + } + bool compute( + ssize_t length, ssize_t *start, ssize_t *stop, ssize_t *step, ssize_t *slicelength) const { + return PySlice_GetIndicesEx( + (PYBIND11_SLICE_OBJECT *) m_ptr, length, start, stop, step, slicelength) + == 0; + } + +private: + template + static object index_to_object(T index) { + return index ? object(int_(*index)) : object(none()); + } +}; + +class capsule : public object { +public: + PYBIND11_OBJECT_DEFAULT(capsule, object, PyCapsule_CheckExact) + PYBIND11_DEPRECATED("Use reinterpret_borrow() or reinterpret_steal()") + capsule(PyObject *ptr, bool is_borrowed) + : object(is_borrowed ? object(ptr, borrowed_t{}) : object(ptr, stolen_t{})) {} + + explicit capsule(const void *value, + const char *name = nullptr, + PyCapsule_Destructor destructor = nullptr) + : object(PyCapsule_New(const_cast(value), name, destructor), stolen_t{}) { + if (!m_ptr) { + throw error_already_set(); + } + } + + PYBIND11_DEPRECATED("Please use the ctor with value, name, destructor args") + capsule(const void *value, PyCapsule_Destructor destructor) + : object(PyCapsule_New(const_cast(value), nullptr, destructor), stolen_t{}) { + if (!m_ptr) { + throw error_already_set(); + } + } + + /// Capsule name is nullptr. + capsule(const void *value, void (*destructor)(void *)) { + initialize_with_void_ptr_destructor(value, nullptr, destructor); + } + + capsule(const void *value, const char *name, void (*destructor)(void *)) { + initialize_with_void_ptr_destructor(value, name, destructor); + } + + explicit capsule(void (*destructor)()) { + m_ptr = PyCapsule_New(reinterpret_cast(destructor), nullptr, [](PyObject *o) { + const char *name = get_name_in_error_scope(o); + auto destructor = reinterpret_cast(PyCapsule_GetPointer(o, name)); + if (destructor == nullptr) { + throw error_already_set(); + } + destructor(); + }); + + if (!m_ptr) { + throw error_already_set(); + } + } + + template + operator T *() const { // NOLINT(google-explicit-constructor) + return get_pointer(); + } + + /// Get the pointer the capsule holds. + template + T *get_pointer() const { + const auto *name = this->name(); + T *result = static_cast(PyCapsule_GetPointer(m_ptr, name)); + if (!result) { + throw error_already_set(); + } + return result; + } + + /// Replaces a capsule's pointer *without* calling the destructor on the existing one. + void set_pointer(const void *value) { + if (PyCapsule_SetPointer(m_ptr, const_cast(value)) != 0) { + throw error_already_set(); + } + } + + const char *name() const { + const char *name = PyCapsule_GetName(m_ptr); + if ((name == nullptr) && PyErr_Occurred()) { + throw error_already_set(); + } + return name; + } + + /// Replaces a capsule's name *without* calling the destructor on the existing one. + void set_name(const char *new_name) { + if (PyCapsule_SetName(m_ptr, new_name) != 0) { + throw error_already_set(); + } + } + +private: + static const char *get_name_in_error_scope(PyObject *o) { + error_scope error_guard; + + const char *name = PyCapsule_GetName(o); + if ((name == nullptr) && PyErr_Occurred()) { + // write out and consume error raised by call to PyCapsule_GetName + PyErr_WriteUnraisable(o); + } + + return name; + } + + void initialize_with_void_ptr_destructor(const void *value, + const char *name, + void (*destructor)(void *)) { + m_ptr = PyCapsule_New(const_cast(value), name, [](PyObject *o) { + // guard if destructor called while err indicator is set + error_scope error_guard; + auto destructor = reinterpret_cast(PyCapsule_GetContext(o)); + if (destructor == nullptr && PyErr_Occurred()) { + throw error_already_set(); + } + const char *name = get_name_in_error_scope(o); + void *ptr = PyCapsule_GetPointer(o, name); + if (ptr == nullptr) { + throw error_already_set(); + } + + if (destructor != nullptr) { + destructor(ptr); + } + }); + + if (!m_ptr || PyCapsule_SetContext(m_ptr, reinterpret_cast(destructor)) != 0) { + throw error_already_set(); + } + } +}; + +class tuple : public object { +public: + PYBIND11_OBJECT_CVT(tuple, object, PyTuple_Check, PySequence_Tuple) + template ::value, int> = 0> + // Some compilers generate link errors when using `const SzType &` here: + explicit tuple(SzType size = 0) : object(PyTuple_New(ssize_t_cast(size)), stolen_t{}) { + if (!m_ptr) { + pybind11_fail("Could not allocate tuple object!"); + } + } + size_t size() const { return (size_t) PyTuple_Size(m_ptr); } + bool empty() const { return size() == 0; } + detail::tuple_accessor operator[](size_t index) const { return {*this, index}; } + template ::value, int> = 0> + detail::item_accessor operator[](T &&o) const { + return object::operator[](std::forward(o)); + } + detail::tuple_iterator begin() const { return {*this, 0}; } + detail::tuple_iterator end() const { return {*this, PyTuple_GET_SIZE(m_ptr)}; } +}; + +// We need to put this into a separate function because the Intel compiler +// fails to compile enable_if_t...>::value> part below +// (tested with ICC 2021.1 Beta 20200827). +template +constexpr bool args_are_all_keyword_or_ds() { + return detail::all_of...>::value; +} + +class dict : public object { +public: + PYBIND11_OBJECT_CVT(dict, object, PyDict_Check, raw_dict) + dict() : object(PyDict_New(), stolen_t{}) { + if (!m_ptr) { + pybind11_fail("Could not allocate dict object!"); + } + } + template ()>, + // MSVC workaround: it can't compile an out-of-line definition, so defer the + // collector + typename collector = detail::deferred_t, Args...>> + explicit dict(Args &&...args) : dict(collector(std::forward(args)...).kwargs()) {} + + size_t size() const { return (size_t) PyDict_Size(m_ptr); } + bool empty() const { return size() == 0; } + detail::dict_iterator begin() const { return {*this, 0}; } + detail::dict_iterator end() const { return {}; } + void clear() /* py-non-const */ { PyDict_Clear(ptr()); } + template + bool contains(T &&key) const { + auto result = PyDict_Contains(m_ptr, detail::object_or_cast(std::forward(key)).ptr()); + if (result == -1) { + throw error_already_set(); + } + return result == 1; + } + +private: + /// Call the `dict` Python type -- always returns a new reference + static PyObject *raw_dict(PyObject *op) { + if (PyDict_Check(op)) { + return handle(op).inc_ref().ptr(); + } + return PyObject_CallFunctionObjArgs((PyObject *) &PyDict_Type, op, nullptr); + } +}; + +class sequence : public object { +public: + PYBIND11_OBJECT_DEFAULT(sequence, object, PySequence_Check) + size_t size() const { + ssize_t result = PySequence_Size(m_ptr); + if (result == -1) { + throw error_already_set(); + } + return (size_t) result; + } + bool empty() const { return size() == 0; } + detail::sequence_accessor operator[](size_t index) const { return {*this, index}; } + template ::value, int> = 0> + detail::item_accessor operator[](T &&o) const { + return object::operator[](std::forward(o)); + } + detail::sequence_iterator begin() const { return {*this, 0}; } + detail::sequence_iterator end() const { return {*this, PySequence_Size(m_ptr)}; } +}; + +class list : public object { +public: + PYBIND11_OBJECT_CVT(list, object, PyList_Check, PySequence_List) + template ::value, int> = 0> + // Some compilers generate link errors when using `const SzType &` here: + explicit list(SzType size = 0) : object(PyList_New(ssize_t_cast(size)), stolen_t{}) { + if (!m_ptr) { + pybind11_fail("Could not allocate list object!"); + } + } + size_t size() const { return (size_t) PyList_Size(m_ptr); } + bool empty() const { return size() == 0; } + detail::list_accessor operator[](size_t index) const { return {*this, index}; } + template ::value, int> = 0> + detail::item_accessor operator[](T &&o) const { + return object::operator[](std::forward(o)); + } + detail::list_iterator begin() const { return {*this, 0}; } + detail::list_iterator end() const { return {*this, PyList_GET_SIZE(m_ptr)}; } + template + void append(T &&val) /* py-non-const */ { + if (PyList_Append(m_ptr, detail::object_or_cast(std::forward(val)).ptr()) != 0) { + throw error_already_set(); + } + } + template ::value, int> = 0> + void insert(const IdxType &index, ValType &&val) /* py-non-const */ { + if (PyList_Insert(m_ptr, + ssize_t_cast(index), + detail::object_or_cast(std::forward(val)).ptr()) + != 0) { + throw error_already_set(); + } + } + void clear() /* py-non-const */ { + if (PyList_SetSlice(m_ptr, 0, PyList_Size(m_ptr), nullptr) == -1) { + throw error_already_set(); + } + } +}; + +class args : public tuple { + PYBIND11_OBJECT_DEFAULT(args, tuple, PyTuple_Check) +}; +class kwargs : public dict { + PYBIND11_OBJECT_DEFAULT(kwargs, dict, PyDict_Check) +}; + +class anyset : public object { +public: + PYBIND11_OBJECT(anyset, object, PyAnySet_Check) + size_t size() const { return static_cast(PySet_Size(m_ptr)); } + bool empty() const { return size() == 0; } + template + bool contains(T &&val) const { + auto result = PySet_Contains(m_ptr, detail::object_or_cast(std::forward(val)).ptr()); + if (result == -1) { + throw error_already_set(); + } + return result == 1; + } +}; + +class set : public anyset { +public: + PYBIND11_OBJECT_CVT(set, anyset, PySet_Check, PySet_New) + set() : anyset(PySet_New(nullptr), stolen_t{}) { + if (!m_ptr) { + pybind11_fail("Could not allocate set object!"); + } + } + template + bool add(T &&val) /* py-non-const */ { + return PySet_Add(m_ptr, detail::object_or_cast(std::forward(val)).ptr()) == 0; + } + void clear() /* py-non-const */ { PySet_Clear(m_ptr); } +}; + +class frozenset : public anyset { +public: + PYBIND11_OBJECT_CVT(frozenset, anyset, PyFrozenSet_Check, PyFrozenSet_New) +}; + +class function : public object { +public: + PYBIND11_OBJECT_DEFAULT(function, object, PyCallable_Check) + handle cpp_function() const { + handle fun = detail::get_function(m_ptr); + if (fun && PyCFunction_Check(fun.ptr())) { + return fun; + } + return handle(); + } + bool is_cpp_function() const { return (bool) cpp_function(); } +}; + +class staticmethod : public object { +public: + PYBIND11_OBJECT_CVT(staticmethod, object, detail::PyStaticMethod_Check, PyStaticMethod_New) +}; + +class buffer : public object { +public: + PYBIND11_OBJECT_DEFAULT(buffer, object, PyObject_CheckBuffer) + + buffer_info request(bool writable = false) const { + int flags = PyBUF_STRIDES | PyBUF_FORMAT; + if (writable) { + flags |= PyBUF_WRITABLE; + } + auto *view = new Py_buffer(); + if (PyObject_GetBuffer(m_ptr, view, flags) != 0) { + delete view; + throw error_already_set(); + } + return buffer_info(view); + } +}; + +class memoryview : public object { +public: + PYBIND11_OBJECT_CVT(memoryview, object, PyMemoryView_Check, PyMemoryView_FromObject) + + /** \rst + Creates ``memoryview`` from ``buffer_info``. + + ``buffer_info`` must be created from ``buffer::request()``. Otherwise + throws an exception. + + For creating a ``memoryview`` from objects that support buffer protocol, + use ``memoryview(const object& obj)`` instead of this constructor. + \endrst */ + explicit memoryview(const buffer_info &info) { + if (!info.view()) { + pybind11_fail("Prohibited to create memoryview without Py_buffer"); + } + // Note: PyMemoryView_FromBuffer never increments obj reference. + m_ptr = (info.view()->obj) ? PyMemoryView_FromObject(info.view()->obj) + : PyMemoryView_FromBuffer(info.view()); + if (!m_ptr) { + pybind11_fail("Unable to create memoryview from buffer descriptor"); + } + } + + /** \rst + Creates ``memoryview`` from static buffer. + + This method is meant for providing a ``memoryview`` for C/C++ buffer not + managed by Python. The caller is responsible for managing the lifetime + of ``ptr`` and ``format``, which MUST outlive the memoryview constructed + here. + + See also: Python C API documentation for `PyMemoryView_FromBuffer`_. + + .. _PyMemoryView_FromBuffer: + https://docs.python.org/c-api/memoryview.html#c.PyMemoryView_FromBuffer + + :param ptr: Pointer to the buffer. + :param itemsize: Byte size of an element. + :param format: Pointer to the null-terminated format string. For + homogeneous Buffers, this should be set to + ``format_descriptor::value``. + :param shape: Shape of the tensor (1 entry per dimension). + :param strides: Number of bytes between adjacent entries (for each + per dimension). + :param readonly: Flag to indicate if the underlying storage may be + written to. + \endrst */ + static memoryview from_buffer(void *ptr, + ssize_t itemsize, + const char *format, + detail::any_container shape, + detail::any_container strides, + bool readonly = false); + + static memoryview from_buffer(const void *ptr, + ssize_t itemsize, + const char *format, + detail::any_container shape, + detail::any_container strides) { + return memoryview::from_buffer( + const_cast(ptr), itemsize, format, std::move(shape), std::move(strides), true); + } + + template + static memoryview from_buffer(T *ptr, + detail::any_container shape, + detail::any_container strides, + bool readonly = false) { + return memoryview::from_buffer(reinterpret_cast(ptr), + sizeof(T), + format_descriptor::value, + std::move(shape), + std::move(strides), + readonly); + } + + template + static memoryview from_buffer(const T *ptr, + detail::any_container shape, + detail::any_container strides) { + return memoryview::from_buffer( + const_cast(ptr), std::move(shape), std::move(strides), true); + } + + /** \rst + Creates ``memoryview`` from static memory. + + This method is meant for providing a ``memoryview`` for C/C++ buffer not + managed by Python. The caller is responsible for managing the lifetime + of ``mem``, which MUST outlive the memoryview constructed here. + + See also: Python C API documentation for `PyMemoryView_FromBuffer`_. + + .. _PyMemoryView_FromMemory: + https://docs.python.org/c-api/memoryview.html#c.PyMemoryView_FromMemory + \endrst */ + static memoryview from_memory(void *mem, ssize_t size, bool readonly = false) { + PyObject *ptr = PyMemoryView_FromMemory( + reinterpret_cast(mem), size, (readonly) ? PyBUF_READ : PyBUF_WRITE); + if (!ptr) { + pybind11_fail("Could not allocate memoryview object!"); + } + return memoryview(object(ptr, stolen_t{})); + } + + static memoryview from_memory(const void *mem, ssize_t size) { + return memoryview::from_memory(const_cast(mem), size, true); + } + +#ifdef PYBIND11_HAS_STRING_VIEW + static memoryview from_memory(std::string_view mem) { + return from_memory(const_cast(mem.data()), static_cast(mem.size()), true); + } +#endif +}; + +/// @cond DUPLICATE +inline memoryview memoryview::from_buffer(void *ptr, + ssize_t itemsize, + const char *format, + detail::any_container shape, + detail::any_container strides, + bool readonly) { + size_t ndim = shape->size(); + if (ndim != strides->size()) { + pybind11_fail("memoryview: shape length doesn't match strides length"); + } + ssize_t size = ndim != 0u ? 1 : 0; + for (size_t i = 0; i < ndim; ++i) { + size *= (*shape)[i]; + } + Py_buffer view; + view.buf = ptr; + view.obj = nullptr; + view.len = size * itemsize; + view.readonly = static_cast(readonly); + view.itemsize = itemsize; + view.format = const_cast(format); + view.ndim = static_cast(ndim); + view.shape = shape->data(); + view.strides = strides->data(); + view.suboffsets = nullptr; + view.internal = nullptr; + PyObject *obj = PyMemoryView_FromBuffer(&view); + if (!obj) { + throw error_already_set(); + } + return memoryview(object(obj, stolen_t{})); +} +/// @endcond +/// @} pytypes + +/// \addtogroup python_builtins +/// @{ + +/// Get the length of a Python object. +inline size_t len(handle h) { + ssize_t result = PyObject_Length(h.ptr()); + if (result < 0) { + throw error_already_set(); + } + return (size_t) result; +} + +/// Get the length hint of a Python object. +/// Returns 0 when this cannot be determined. +inline size_t len_hint(handle h) { + ssize_t result = PyObject_LengthHint(h.ptr(), 0); + if (result < 0) { + // Sometimes a length can't be determined at all (eg generators) + // In which case simply return 0 + PyErr_Clear(); + return 0; + } + return (size_t) result; +} + +inline str repr(handle h) { + PyObject *str_value = PyObject_Repr(h.ptr()); + if (!str_value) { + throw error_already_set(); + } + return reinterpret_steal(str_value); +} + +inline iterator iter(handle obj) { + PyObject *result = PyObject_GetIter(obj.ptr()); + if (!result) { + throw error_already_set(); + } + return reinterpret_steal(result); +} +/// @} python_builtins + +PYBIND11_NAMESPACE_BEGIN(detail) +template +iterator object_api::begin() const { + return iter(derived()); +} +template +iterator object_api::end() const { + return iterator::sentinel(); +} +template +item_accessor object_api::operator[](handle key) const { + return {derived(), reinterpret_borrow(key)}; +} +template +item_accessor object_api::operator[](object &&key) const { + return {derived(), std::move(key)}; +} +template +item_accessor object_api::operator[](const char *key) const { + return {derived(), pybind11::str(key)}; +} +template +obj_attr_accessor object_api::attr(handle key) const { + return {derived(), reinterpret_borrow(key)}; +} +template +obj_attr_accessor object_api::attr(object &&key) const { + return {derived(), std::move(key)}; +} +template +str_attr_accessor object_api::attr(const char *key) const { + return {derived(), key}; +} +template +args_proxy object_api::operator*() const { + return args_proxy(derived().ptr()); +} +template +template +bool object_api::contains(T &&item) const { + return attr("__contains__")(std::forward(item)).template cast(); +} + +template +pybind11::str object_api::str() const { + return pybind11::str(derived()); +} + +template +str_attr_accessor object_api::doc() const { + return attr("__doc__"); +} + +template +handle object_api::get_type() const { + return type::handle_of(derived()); +} + +template +bool object_api::rich_compare(object_api const &other, int value) const { + int rv = PyObject_RichCompareBool(derived().ptr(), other.derived().ptr(), value); + if (rv == -1) { + throw error_already_set(); + } + return rv == 1; +} + +#define PYBIND11_MATH_OPERATOR_UNARY(op, fn) \ + template \ + object object_api::op() const { \ + object result = reinterpret_steal(fn(derived().ptr())); \ + if (!result.ptr()) \ + throw error_already_set(); \ + return result; \ + } + +#define PYBIND11_MATH_OPERATOR_BINARY(op, fn) \ + template \ + object object_api::op(object_api const &other) const { \ + object result = reinterpret_steal(fn(derived().ptr(), other.derived().ptr())); \ + if (!result.ptr()) \ + throw error_already_set(); \ + return result; \ + } + +#define PYBIND11_MATH_OPERATOR_BINARY_INPLACE(iop, fn) \ + template \ + object object_api::iop(object_api const &other) { \ + object result = reinterpret_steal(fn(derived().ptr(), other.derived().ptr())); \ + if (!result.ptr()) \ + throw error_already_set(); \ + return result; \ + } + +PYBIND11_MATH_OPERATOR_UNARY(operator~, PyNumber_Invert) +PYBIND11_MATH_OPERATOR_UNARY(operator-, PyNumber_Negative) +PYBIND11_MATH_OPERATOR_BINARY(operator+, PyNumber_Add) +PYBIND11_MATH_OPERATOR_BINARY_INPLACE(operator+=, PyNumber_InPlaceAdd) +PYBIND11_MATH_OPERATOR_BINARY(operator-, PyNumber_Subtract) +PYBIND11_MATH_OPERATOR_BINARY_INPLACE(operator-=, PyNumber_InPlaceSubtract) +PYBIND11_MATH_OPERATOR_BINARY(operator*, PyNumber_Multiply) +PYBIND11_MATH_OPERATOR_BINARY_INPLACE(operator*=, PyNumber_InPlaceMultiply) +PYBIND11_MATH_OPERATOR_BINARY(operator/, PyNumber_TrueDivide) +PYBIND11_MATH_OPERATOR_BINARY_INPLACE(operator/=, PyNumber_InPlaceTrueDivide) +PYBIND11_MATH_OPERATOR_BINARY(operator|, PyNumber_Or) +PYBIND11_MATH_OPERATOR_BINARY_INPLACE(operator|=, PyNumber_InPlaceOr) +PYBIND11_MATH_OPERATOR_BINARY(operator&, PyNumber_And) +PYBIND11_MATH_OPERATOR_BINARY_INPLACE(operator&=, PyNumber_InPlaceAnd) +PYBIND11_MATH_OPERATOR_BINARY(operator^, PyNumber_Xor) +PYBIND11_MATH_OPERATOR_BINARY_INPLACE(operator^=, PyNumber_InPlaceXor) +PYBIND11_MATH_OPERATOR_BINARY(operator<<, PyNumber_Lshift) +PYBIND11_MATH_OPERATOR_BINARY_INPLACE(operator<<=, PyNumber_InPlaceLshift) +PYBIND11_MATH_OPERATOR_BINARY(operator>>, PyNumber_Rshift) +PYBIND11_MATH_OPERATOR_BINARY_INPLACE(operator>>=, PyNumber_InPlaceRshift) + +#undef PYBIND11_MATH_OPERATOR_UNARY +#undef PYBIND11_MATH_OPERATOR_BINARY +#undef PYBIND11_MATH_OPERATOR_BINARY_INPLACE + +PYBIND11_NAMESPACE_END(detail) +PYBIND11_NAMESPACE_END(PYBIND11_NAMESPACE) diff --git a/infer_4_30_0/lib/python3.10/site-packages/pybind11/include/pybind11/stl_bind.h b/infer_4_30_0/lib/python3.10/site-packages/pybind11/include/pybind11/stl_bind.h new file mode 100644 index 0000000000000000000000000000000000000000..fcb48dea3396435fb6321a376d4cbfc099f8542a --- /dev/null +++ b/infer_4_30_0/lib/python3.10/site-packages/pybind11/include/pybind11/stl_bind.h @@ -0,0 +1,822 @@ +/* + pybind11/std_bind.h: Binding generators for STL data types + + Copyright (c) 2016 Sergey Lyskov and Wenzel Jakob + + All rights reserved. Use of this source code is governed by a + BSD-style license that can be found in the LICENSE file. +*/ + +#pragma once + +#include "detail/common.h" +#include "detail/type_caster_base.h" +#include "cast.h" +#include "operators.h" + +#include +#include +#include + +PYBIND11_NAMESPACE_BEGIN(PYBIND11_NAMESPACE) +PYBIND11_NAMESPACE_BEGIN(detail) + +/* SFINAE helper class used by 'is_comparable */ +template +struct container_traits { + template + static std::true_type + test_comparable(decltype(std::declval() == std::declval()) *); + template + static std::false_type test_comparable(...); + template + static std::true_type test_value(typename T2::value_type *); + template + static std::false_type test_value(...); + template + static std::true_type test_pair(typename T2::first_type *, typename T2::second_type *); + template + static std::false_type test_pair(...); + + static constexpr const bool is_comparable + = std::is_same(nullptr))>::value; + static constexpr const bool is_pair + = std::is_same(nullptr, nullptr))>::value; + static constexpr const bool is_vector + = std::is_same(nullptr))>::value; + static constexpr const bool is_element = !is_pair && !is_vector; +}; + +/* Default: is_comparable -> std::false_type */ +template +struct is_comparable : std::false_type {}; + +/* For non-map data structures, check whether operator== can be instantiated */ +template +struct is_comparable< + T, + enable_if_t::is_element && container_traits::is_comparable>> + : std::true_type {}; + +/* For a vector/map data structure, recursively check the value type + (which is std::pair for maps) */ +template +struct is_comparable::is_vector>> + : is_comparable::type_to_check_recursively> {}; + +template <> +struct is_comparable : std::true_type {}; + +/* For pairs, recursively check the two data types */ +template +struct is_comparable::is_pair>> { + static constexpr const bool value = is_comparable::value + && is_comparable::value; +}; + +/* Fallback functions */ +template +void vector_if_copy_constructible(const Args &...) {} +template +void vector_if_equal_operator(const Args &...) {} +template +void vector_if_insertion_operator(const Args &...) {} +template +void vector_modifiers(const Args &...) {} + +template +void vector_if_copy_constructible(enable_if_t::value, Class_> &cl) { + cl.def(init(), "Copy constructor"); +} + +template +void vector_if_equal_operator(enable_if_t::value, Class_> &cl) { + using T = typename Vector::value_type; + + cl.def(self == self); + cl.def(self != self); + + cl.def( + "count", + [](const Vector &v, const T &x) { return std::count(v.begin(), v.end(), x); }, + arg("x"), + "Return the number of times ``x`` appears in the list"); + + cl.def( + "remove", + [](Vector &v, const T &x) { + auto p = std::find(v.begin(), v.end(), x); + if (p != v.end()) { + v.erase(p); + } else { + throw value_error(); + } + }, + arg("x"), + "Remove the first item from the list whose value is x. " + "It is an error if there is no such item."); + + cl.def( + "__contains__", + [](const Vector &v, const T &x) { return std::find(v.begin(), v.end(), x) != v.end(); }, + arg("x"), + "Return true the container contains ``x``"); +} + +// Vector modifiers -- requires a copyable vector_type: +// (Technically, some of these (pop and __delitem__) don't actually require copyability, but it +// seems silly to allow deletion but not insertion, so include them here too.) +template +void vector_modifiers( + enable_if_t::value, Class_> &cl) { + using T = typename Vector::value_type; + using SizeType = typename Vector::size_type; + using DiffType = typename Vector::difference_type; + + auto wrap_i = [](DiffType i, SizeType n) { + if (i < 0) { + i += n; + } + if (i < 0 || (SizeType) i >= n) { + throw index_error(); + } + return i; + }; + + cl.def( + "append", + [](Vector &v, const T &value) { v.push_back(value); }, + arg("x"), + "Add an item to the end of the list"); + + cl.def(init([](const iterable &it) { + auto v = std::unique_ptr(new Vector()); + v->reserve(len_hint(it)); + for (handle h : it) { + v->push_back(h.cast()); + } + return v.release(); + })); + + cl.def("clear", [](Vector &v) { v.clear(); }, "Clear the contents"); + + cl.def( + "extend", + [](Vector &v, const Vector &src) { v.insert(v.end(), src.begin(), src.end()); }, + arg("L"), + "Extend the list by appending all the items in the given list"); + + cl.def( + "extend", + [](Vector &v, const iterable &it) { + const size_t old_size = v.size(); + v.reserve(old_size + len_hint(it)); + try { + for (handle h : it) { + v.push_back(h.cast()); + } + } catch (const cast_error &) { + v.erase(v.begin() + static_cast(old_size), + v.end()); + try { + v.shrink_to_fit(); + } catch (const std::exception &) { // NOLINT(bugprone-empty-catch) + // Do nothing + } + throw; + } + }, + arg("L"), + "Extend the list by appending all the items in the given list"); + + cl.def( + "insert", + [](Vector &v, DiffType i, const T &x) { + // Can't use wrap_i; i == v.size() is OK + if (i < 0) { + i += v.size(); + } + if (i < 0 || (SizeType) i > v.size()) { + throw index_error(); + } + v.insert(v.begin() + i, x); + }, + arg("i"), + arg("x"), + "Insert an item at a given position."); + + cl.def( + "pop", + [](Vector &v) { + if (v.empty()) { + throw index_error(); + } + T t = std::move(v.back()); + v.pop_back(); + return t; + }, + "Remove and return the last item"); + + cl.def( + "pop", + [wrap_i](Vector &v, DiffType i) { + i = wrap_i(i, v.size()); + T t = std::move(v[(SizeType) i]); + v.erase(std::next(v.begin(), i)); + return t; + }, + arg("i"), + "Remove and return the item at index ``i``"); + + cl.def("__setitem__", [wrap_i](Vector &v, DiffType i, const T &t) { + i = wrap_i(i, v.size()); + v[(SizeType) i] = t; + }); + + /// Slicing protocol + cl.def( + "__getitem__", + [](const Vector &v, const slice &slice) -> Vector * { + size_t start = 0, stop = 0, step = 0, slicelength = 0; + + if (!slice.compute(v.size(), &start, &stop, &step, &slicelength)) { + throw error_already_set(); + } + + auto *seq = new Vector(); + seq->reserve((size_t) slicelength); + + for (size_t i = 0; i < slicelength; ++i) { + seq->push_back(v[start]); + start += step; + } + return seq; + }, + arg("s"), + "Retrieve list elements using a slice object"); + + cl.def( + "__setitem__", + [](Vector &v, const slice &slice, const Vector &value) { + size_t start = 0, stop = 0, step = 0, slicelength = 0; + if (!slice.compute(v.size(), &start, &stop, &step, &slicelength)) { + throw error_already_set(); + } + + if (slicelength != value.size()) { + throw std::runtime_error( + "Left and right hand size of slice assignment have different sizes!"); + } + + for (size_t i = 0; i < slicelength; ++i) { + v[start] = value[i]; + start += step; + } + }, + "Assign list elements using a slice object"); + + cl.def( + "__delitem__", + [wrap_i](Vector &v, DiffType i) { + i = wrap_i(i, v.size()); + v.erase(v.begin() + i); + }, + "Delete the list elements at index ``i``"); + + cl.def( + "__delitem__", + [](Vector &v, const slice &slice) { + size_t start = 0, stop = 0, step = 0, slicelength = 0; + + if (!slice.compute(v.size(), &start, &stop, &step, &slicelength)) { + throw error_already_set(); + } + + if (step == 1 && false) { + v.erase(v.begin() + (DiffType) start, v.begin() + DiffType(start + slicelength)); + } else { + for (size_t i = 0; i < slicelength; ++i) { + v.erase(v.begin() + DiffType(start)); + start += step - 1; + } + } + }, + "Delete list elements using a slice object"); +} + +// If the type has an operator[] that doesn't return a reference (most notably std::vector), +// we have to access by copying; otherwise we return by reference. +template +using vector_needs_copy + = negation()[typename Vector::size_type()]), + typename Vector::value_type &>>; + +// The usual case: access and iterate by reference +template +void vector_accessor(enable_if_t::value, Class_> &cl) { + using T = typename Vector::value_type; + using SizeType = typename Vector::size_type; + using DiffType = typename Vector::difference_type; + using ItType = typename Vector::iterator; + + auto wrap_i = [](DiffType i, SizeType n) { + if (i < 0) { + i += n; + } + if (i < 0 || (SizeType) i >= n) { + throw index_error(); + } + return i; + }; + + cl.def( + "__getitem__", + [wrap_i](Vector &v, DiffType i) -> T & { + i = wrap_i(i, v.size()); + return v[(SizeType) i]; + }, + return_value_policy::reference_internal // ref + keepalive + ); + + cl.def( + "__iter__", + [](Vector &v) { + return make_iterator( + v.begin(), v.end()); + }, + keep_alive<0, 1>() /* Essential: keep list alive while iterator exists */ + ); +} + +// The case for special objects, like std::vector, that have to be returned-by-copy: +template +void vector_accessor(enable_if_t::value, Class_> &cl) { + using T = typename Vector::value_type; + using SizeType = typename Vector::size_type; + using DiffType = typename Vector::difference_type; + using ItType = typename Vector::iterator; + cl.def("__getitem__", [](const Vector &v, DiffType i) -> T { + if (i < 0) { + i += v.size(); + if (i < 0) { + throw index_error(); + } + } + auto i_st = static_cast(i); + if (i_st >= v.size()) { + throw index_error(); + } + return v[i_st]; + }); + + cl.def( + "__iter__", + [](Vector &v) { + return make_iterator(v.begin(), v.end()); + }, + keep_alive<0, 1>() /* Essential: keep list alive while iterator exists */ + ); +} + +template +auto vector_if_insertion_operator(Class_ &cl, std::string const &name) + -> decltype(std::declval() << std::declval(), + void()) { + using size_type = typename Vector::size_type; + + cl.def( + "__repr__", + [name](Vector &v) { + std::ostringstream s; + s << name << '['; + for (size_type i = 0; i < v.size(); ++i) { + s << v[i]; + if (i != v.size() - 1) { + s << ", "; + } + } + s << ']'; + return s.str(); + }, + "Return the canonical string representation of this list."); +} + +// Provide the buffer interface for vectors if we have data() and we have a format for it +// GCC seems to have "void std::vector::data()" - doing SFINAE on the existence of data() +// is insufficient, we need to check it returns an appropriate pointer +template +struct vector_has_data_and_format : std::false_type {}; +template +struct vector_has_data_and_format< + Vector, + enable_if_t::format(), + std::declval().data()), + typename Vector::value_type *>::value>> : std::true_type {}; + +// [workaround(intel)] Separate function required here +// Workaround as the Intel compiler does not compile the enable_if_t part below +// (tested with icc (ICC) 2021.1 Beta 20200827) +template +constexpr bool args_any_are_buffer() { + return detail::any_of...>::value; +} + +// [workaround(intel)] Separate function required here +// [workaround(msvc)] Can't use constexpr bool in return type + +// Add the buffer interface to a vector +template +void vector_buffer_impl(Class_ &cl, std::true_type) { + using T = typename Vector::value_type; + + static_assert(vector_has_data_and_format::value, + "There is not an appropriate format descriptor for this vector"); + + // numpy.h declares this for arbitrary types, but it may raise an exception and crash hard + // at runtime if PYBIND11_NUMPY_DTYPE hasn't been called, so check here + format_descriptor::format(); + + cl.def_buffer([](Vector &v) -> buffer_info { + return buffer_info(v.data(), + static_cast(sizeof(T)), + format_descriptor::format(), + 1, + {v.size()}, + {sizeof(T)}); + }); + + cl.def(init([](const buffer &buf) { + auto info = buf.request(); + if (info.ndim != 1 || info.strides[0] % static_cast(sizeof(T))) { + throw type_error("Only valid 1D buffers can be copied to a vector"); + } + if (!detail::compare_buffer_info::compare(info) + || (ssize_t) sizeof(T) != info.itemsize) { + throw type_error("Format mismatch (Python: " + info.format + + " C++: " + format_descriptor::format() + ")"); + } + + T *p = static_cast(info.ptr); + ssize_t step = info.strides[0] / static_cast(sizeof(T)); + T *end = p + info.shape[0] * step; + if (step == 1) { + return Vector(p, end); + } + Vector vec; + vec.reserve((size_t) info.shape[0]); + for (; p != end; p += step) { + vec.push_back(*p); + } + return vec; + })); + + return; +} + +template +void vector_buffer_impl(Class_ &, std::false_type) {} + +template +void vector_buffer(Class_ &cl) { + vector_buffer_impl( + cl, detail::any_of...>{}); +} + +PYBIND11_NAMESPACE_END(detail) + +// +// std::vector +// +template , typename... Args> +class_ bind_vector(handle scope, std::string const &name, Args &&...args) { + using Class_ = class_; + + // If the value_type is unregistered (e.g. a converting type) or is itself registered + // module-local then make the vector binding module-local as well: + using vtype = typename Vector::value_type; + auto *vtype_info = detail::get_type_info(typeid(vtype)); + bool local = !vtype_info || vtype_info->module_local; + + Class_ cl(scope, name.c_str(), pybind11::module_local(local), std::forward(args)...); + + // Declare the buffer interface if a buffer_protocol() is passed in + detail::vector_buffer(cl); + + cl.def(init<>()); + + // Register copy constructor (if possible) + detail::vector_if_copy_constructible(cl); + + // Register comparison-related operators and functions (if possible) + detail::vector_if_equal_operator(cl); + + // Register stream insertion operator (if possible) + detail::vector_if_insertion_operator(cl, name); + + // Modifiers require copyable vector value type + detail::vector_modifiers(cl); + + // Accessor and iterator; return by value if copyable, otherwise we return by ref + keep-alive + detail::vector_accessor(cl); + + cl.def( + "__bool__", + [](const Vector &v) -> bool { return !v.empty(); }, + "Check whether the list is nonempty"); + + cl.def("__len__", [](const Vector &vec) { return vec.size(); }); + +#if 0 + // C++ style functions deprecated, leaving it here as an example + cl.def(init()); + + cl.def("resize", + (void (Vector::*) (size_type count)) & Vector::resize, + "changes the number of elements stored"); + + cl.def("erase", + [](Vector &v, SizeType i) { + if (i >= v.size()) + throw index_error(); + v.erase(v.begin() + i); + }, "erases element at index ``i``"); + + cl.def("empty", &Vector::empty, "checks whether the container is empty"); + cl.def("size", &Vector::size, "returns the number of elements"); + cl.def("push_back", (void (Vector::*)(const T&)) &Vector::push_back, "adds an element to the end"); + cl.def("pop_back", &Vector::pop_back, "removes the last element"); + + cl.def("max_size", &Vector::max_size, "returns the maximum possible number of elements"); + cl.def("reserve", &Vector::reserve, "reserves storage"); + cl.def("capacity", &Vector::capacity, "returns the number of elements that can be held in currently allocated storage"); + cl.def("shrink_to_fit", &Vector::shrink_to_fit, "reduces memory usage by freeing unused memory"); + + cl.def("clear", &Vector::clear, "clears the contents"); + cl.def("swap", &Vector::swap, "swaps the contents"); + + cl.def("front", [](Vector &v) { + if (v.size()) return v.front(); + else throw index_error(); + }, "access the first element"); + + cl.def("back", [](Vector &v) { + if (v.size()) return v.back(); + else throw index_error(); + }, "access the last element "); + +#endif + + return cl; +} + +// +// std::map, std::unordered_map +// + +PYBIND11_NAMESPACE_BEGIN(detail) + +/* Fallback functions */ +template +void map_if_insertion_operator(const Args &...) {} +template +void map_assignment(const Args &...) {} + +// Map assignment when copy-assignable: just copy the value +template +void map_assignment( + enable_if_t::value, Class_> &cl) { + using KeyType = typename Map::key_type; + using MappedType = typename Map::mapped_type; + + cl.def("__setitem__", [](Map &m, const KeyType &k, const MappedType &v) { + auto it = m.find(k); + if (it != m.end()) { + it->second = v; + } else { + m.emplace(k, v); + } + }); +} + +// Not copy-assignable, but still copy-constructible: we can update the value by erasing and +// reinserting +template +void map_assignment(enable_if_t::value + && is_copy_constructible::value, + Class_> &cl) { + using KeyType = typename Map::key_type; + using MappedType = typename Map::mapped_type; + + cl.def("__setitem__", [](Map &m, const KeyType &k, const MappedType &v) { + // We can't use m[k] = v; because value type might not be default constructable + auto r = m.emplace(k, v); + if (!r.second) { + // value type is not copy assignable so the only way to insert it is to erase it + // first... + m.erase(r.first); + m.emplace(k, v); + } + }); +} + +template +auto map_if_insertion_operator(Class_ &cl, std::string const &name) + -> decltype(std::declval() << std::declval() + << std::declval(), + void()) { + + cl.def( + "__repr__", + [name](Map &m) { + std::ostringstream s; + s << name << '{'; + bool f = false; + for (auto const &kv : m) { + if (f) { + s << ", "; + } + s << kv.first << ": " << kv.second; + f = true; + } + s << '}'; + return s.str(); + }, + "Return the canonical string representation of this map."); +} + +struct keys_view { + virtual size_t len() = 0; + virtual iterator iter() = 0; + virtual bool contains(const handle &k) = 0; + virtual ~keys_view() = default; +}; + +struct values_view { + virtual size_t len() = 0; + virtual iterator iter() = 0; + virtual ~values_view() = default; +}; + +struct items_view { + virtual size_t len() = 0; + virtual iterator iter() = 0; + virtual ~items_view() = default; +}; + +template +struct KeysViewImpl : public detail::keys_view { + explicit KeysViewImpl(Map &map) : map(map) {} + size_t len() override { return map.size(); } + iterator iter() override { return make_key_iterator(map.begin(), map.end()); } + bool contains(const handle &k) override { + try { + return map.find(k.template cast()) != map.end(); + } catch (const cast_error &) { + return false; + } + } + Map ↦ +}; + +template +struct ValuesViewImpl : public detail::values_view { + explicit ValuesViewImpl(Map &map) : map(map) {} + size_t len() override { return map.size(); } + iterator iter() override { return make_value_iterator(map.begin(), map.end()); } + Map ↦ +}; + +template +struct ItemsViewImpl : public detail::items_view { + explicit ItemsViewImpl(Map &map) : map(map) {} + size_t len() override { return map.size(); } + iterator iter() override { return make_iterator(map.begin(), map.end()); } + Map ↦ +}; + +PYBIND11_NAMESPACE_END(detail) + +template , typename... Args> +class_ bind_map(handle scope, const std::string &name, Args &&...args) { + using KeyType = typename Map::key_type; + using MappedType = typename Map::mapped_type; + using KeysView = detail::keys_view; + using ValuesView = detail::values_view; + using ItemsView = detail::items_view; + using Class_ = class_; + + // If either type is a non-module-local bound type then make the map binding non-local as well; + // otherwise (e.g. both types are either module-local or converting) the map will be + // module-local. + auto *tinfo = detail::get_type_info(typeid(MappedType)); + bool local = !tinfo || tinfo->module_local; + if (local) { + tinfo = detail::get_type_info(typeid(KeyType)); + local = !tinfo || tinfo->module_local; + } + + Class_ cl(scope, name.c_str(), pybind11::module_local(local), std::forward(args)...); + + // Wrap KeysView if it wasn't already wrapped + if (!detail::get_type_info(typeid(KeysView))) { + class_ keys_view(scope, "KeysView", pybind11::module_local(local)); + keys_view.def("__len__", &KeysView::len); + keys_view.def("__iter__", + &KeysView::iter, + keep_alive<0, 1>() /* Essential: keep view alive while iterator exists */ + ); + keys_view.def("__contains__", &KeysView::contains); + } + // Similarly for ValuesView: + if (!detail::get_type_info(typeid(ValuesView))) { + class_ values_view(scope, "ValuesView", pybind11::module_local(local)); + values_view.def("__len__", &ValuesView::len); + values_view.def("__iter__", + &ValuesView::iter, + keep_alive<0, 1>() /* Essential: keep view alive while iterator exists */ + ); + } + // Similarly for ItemsView: + if (!detail::get_type_info(typeid(ItemsView))) { + class_ items_view(scope, "ItemsView", pybind11::module_local(local)); + items_view.def("__len__", &ItemsView::len); + items_view.def("__iter__", + &ItemsView::iter, + keep_alive<0, 1>() /* Essential: keep view alive while iterator exists */ + ); + } + + cl.def(init<>()); + + // Register stream insertion operator (if possible) + detail::map_if_insertion_operator(cl, name); + + cl.def( + "__bool__", + [](const Map &m) -> bool { return !m.empty(); }, + "Check whether the map is nonempty"); + + cl.def( + "__iter__", + [](Map &m) { return make_key_iterator(m.begin(), m.end()); }, + keep_alive<0, 1>() /* Essential: keep map alive while iterator exists */ + ); + + cl.def( + "keys", + [](Map &m) { return std::unique_ptr(new detail::KeysViewImpl(m)); }, + keep_alive<0, 1>() /* Essential: keep map alive while view exists */ + ); + + cl.def( + "values", + [](Map &m) { return std::unique_ptr(new detail::ValuesViewImpl(m)); }, + keep_alive<0, 1>() /* Essential: keep map alive while view exists */ + ); + + cl.def( + "items", + [](Map &m) { return std::unique_ptr(new detail::ItemsViewImpl(m)); }, + keep_alive<0, 1>() /* Essential: keep map alive while view exists */ + ); + + cl.def( + "__getitem__", + [](Map &m, const KeyType &k) -> MappedType & { + auto it = m.find(k); + if (it == m.end()) { + throw key_error(); + } + return it->second; + }, + return_value_policy::reference_internal // ref + keepalive + ); + + cl.def("__contains__", [](Map &m, const KeyType &k) -> bool { + auto it = m.find(k); + if (it == m.end()) { + return false; + } + return true; + }); + // Fallback for when the object is not of the key type + cl.def("__contains__", [](Map &, const object &) -> bool { return false; }); + + // Assignment provided only if the type is copyable + detail::map_assignment(cl); + + cl.def("__delitem__", [](Map &m, const KeyType &k) { + auto it = m.find(k); + if (it == m.end()) { + throw key_error(); + } + m.erase(it); + }); + + // Always use a lambda in case of `using` declaration + cl.def("__len__", [](const Map &m) { return m.size(); }); + + return cl; +} + +PYBIND11_NAMESPACE_END(PYBIND11_NAMESPACE) diff --git a/infer_4_30_0/lib/python3.10/site-packages/pybind11/include/pybind11/typing.h b/infer_4_30_0/lib/python3.10/site-packages/pybind11/include/pybind11/typing.h new file mode 100644 index 0000000000000000000000000000000000000000..84aaf9f702d780b1415b806f4efc7ebfd3d2675d --- /dev/null +++ b/infer_4_30_0/lib/python3.10/site-packages/pybind11/include/pybind11/typing.h @@ -0,0 +1,242 @@ +/* + pybind11/typing.h: Convenience wrapper classes for basic Python types + with more explicit annotations. + + Copyright (c) 2023 Dustin Spicuzza + + All rights reserved. Use of this source code is governed by a + BSD-style license that can be found in the LICENSE file. +*/ + +#pragma once + +#include "detail/common.h" +#include "cast.h" +#include "pytypes.h" + +#include + +PYBIND11_NAMESPACE_BEGIN(PYBIND11_NAMESPACE) +PYBIND11_NAMESPACE_BEGIN(typing) + +/* + The following types can be used to direct pybind11-generated docstrings + to have have more explicit types (e.g., `list[str]` instead of `list`). + Just use these in place of existing types. + + There is no additional enforcement of types at runtime. +*/ + +template +class Tuple : public tuple { + using tuple::tuple; +}; + +template +class Dict : public dict { + using dict::dict; +}; + +template +class List : public list { + using list::list; +}; + +template +class Set : public set { + using set::set; +}; + +template +class Iterable : public iterable { + using iterable::iterable; +}; + +template +class Iterator : public iterator { + using iterator::iterator; +}; + +template +class Callable; + +template +class Callable : public function { + using function::function; +}; + +template +class Type : public type { + using type::type; +}; + +template +class Union : public object { + PYBIND11_OBJECT_DEFAULT(Union, object, PyObject_Type) + using object::object; +}; + +template +class Optional : public object { + PYBIND11_OBJECT_DEFAULT(Optional, object, PyObject_Type) + using object::object; +}; + +template +class TypeGuard : public bool_ { + using bool_::bool_; +}; + +template +class TypeIs : public bool_ { + using bool_::bool_; +}; + +class NoReturn : public none { + using none::none; +}; + +class Never : public none { + using none::none; +}; + +#if defined(__cpp_nontype_template_args) && __cpp_nontype_template_args >= 201911L +# define PYBIND11_TYPING_H_HAS_STRING_LITERAL +template +struct StringLiteral { + constexpr StringLiteral(const char (&str)[N]) { std::copy_n(str, N, name); } + char name[N]; +}; + +template +class Literal : public object { + PYBIND11_OBJECT_DEFAULT(Literal, object, PyObject_Type) +}; + +// Example syntax for creating a TypeVar. +// typedef typing::TypeVar<"T"> TypeVarT; +template +class TypeVar : public object { + PYBIND11_OBJECT_DEFAULT(TypeVar, object, PyObject_Type) + using object::object; +}; +#endif + +PYBIND11_NAMESPACE_END(typing) + +PYBIND11_NAMESPACE_BEGIN(detail) + +template +struct handle_type_name> { + static constexpr auto name = const_name("tuple[") + + ::pybind11::detail::concat(make_caster::name...) + + const_name("]"); +}; + +template <> +struct handle_type_name> { + // PEP 484 specifies this syntax for an empty tuple + static constexpr auto name = const_name("tuple[()]"); +}; + +template +struct handle_type_name> { + // PEP 484 specifies this syntax for a variable-length tuple + static constexpr auto name + = const_name("tuple[") + make_caster::name + const_name(", ...]"); +}; + +template +struct handle_type_name> { + static constexpr auto name = const_name("dict[") + make_caster::name + const_name(", ") + + make_caster::name + const_name("]"); +}; + +template +struct handle_type_name> { + static constexpr auto name = const_name("list[") + make_caster::name + const_name("]"); +}; + +template +struct handle_type_name> { + static constexpr auto name = const_name("set[") + make_caster::name + const_name("]"); +}; + +template +struct handle_type_name> { + static constexpr auto name = const_name("Iterable[") + make_caster::name + const_name("]"); +}; + +template +struct handle_type_name> { + static constexpr auto name = const_name("Iterator[") + make_caster::name + const_name("]"); +}; + +template +struct handle_type_name> { + using retval_type = conditional_t::value, void_type, Return>; + static constexpr auto name + = const_name("Callable[[") + ::pybind11::detail::concat(make_caster::name...) + + const_name("], ") + make_caster::name + const_name("]"); +}; + +template +struct handle_type_name> { + // PEP 484 specifies this syntax for defining only return types of callables + using retval_type = conditional_t::value, void_type, Return>; + static constexpr auto name + = const_name("Callable[..., ") + make_caster::name + const_name("]"); +}; + +template +struct handle_type_name> { + static constexpr auto name = const_name("type[") + make_caster::name + const_name("]"); +}; + +template +struct handle_type_name> { + static constexpr auto name = const_name("Union[") + + ::pybind11::detail::concat(make_caster::name...) + + const_name("]"); +}; + +template +struct handle_type_name> { + static constexpr auto name = const_name("Optional[") + make_caster::name + const_name("]"); +}; + +template +struct handle_type_name> { + static constexpr auto name = const_name("TypeGuard[") + make_caster::name + const_name("]"); +}; + +template +struct handle_type_name> { + static constexpr auto name = const_name("TypeIs[") + make_caster::name + const_name("]"); +}; + +template <> +struct handle_type_name { + static constexpr auto name = const_name("NoReturn"); +}; + +template <> +struct handle_type_name { + static constexpr auto name = const_name("Never"); +}; + +#if defined(PYBIND11_TYPING_H_HAS_STRING_LITERAL) +template +struct handle_type_name> { + static constexpr auto name = const_name("Literal[") + + pybind11::detail::concat(const_name(Literals.name)...) + + const_name("]"); +}; +template +struct handle_type_name> { + static constexpr auto name = const_name(StrLit.name); +}; +#endif + +PYBIND11_NAMESPACE_END(detail) +PYBIND11_NAMESPACE_END(PYBIND11_NAMESPACE)